diff --git a/lib/analyze-action-post.js b/lib/analyze-action-post.js index 5a82f9ae1a..294cdc9a94 100644 --- a/lib/analyze-action-post.js +++ b/lib/analyze-action-post.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -19875,9 +19875,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -19934,737 +20016,826 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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 (isPlainObject(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+)|(?:(? a.concat(b), []); - } - function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - } - function encodeReserved(str2) { - return str2.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(str2) { - return encodeURIComponent(str2).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; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - function isDefined2(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context2, operator, key, modifier) { - var value = context2[key], result = []; - if (isDefined2(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)); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - result.push(encodeValue(operator, value[k], k)); + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; } - }); + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } } - }); + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - } else { - if (operator === ";") { - if (isDefined2(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; - } - function expand(template, context2) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_2, 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(context2, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); } - } else { - return encodeReserved(literal); + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } - } - function parse(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 = omit(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 = omit(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(","); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + req.end(); } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); - } - function endpointWithDefaults(defaults, route, options) { - return parse(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 - }); - } - var endpoint = withDefaults(null, DEFAULTS); - } -}); - -// node_modules/deprecation/dist-node/index.js -var require_dist_node3 = __commonJS({ - "node_modules/deprecation/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var Deprecation = class extends Error { - constructor(message) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; } - this.name = "Deprecation"; + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; } - }; - exports2.Deprecation = Deprecation; - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - return ret; + return additionalHeaders[header] || clientHeader || _default2; } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; + var httpClient = __importStar4(require_lib2()); + var undici_1 = require_undici(); + function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error("Parameter token or opts.auth is required"); + } else if (token && options.auth) { + throw new Error("Parameters token and opts.auth may not both be specified"); + } + return typeof options.auth === "string" ? options.auth : `token ${token}`; + } + exports2.getAuthString = getAuthString; + function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + exports2.getProxyAgent = getProxyAgent; + function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); + } + exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; + function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; + return proxyFetch; } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; } + exports2.getApiBaseUrl = getApiBaseUrl; } }); -// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node4 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { "use strict"; - var __create2 = Object.create; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - RequestError: () => RequestError - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_deprecation = require_dist_node3(); - var import_once = __toESM2(require_once()); - var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - request: () => request - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node2(); - var import_universal_user_agent = require_dist_node(); - var VERSION = "8.4.1"; - function isPlainObject(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); - } - var import_request_error = require_dist_node4(); - function getBufferResponse(response) { - return response.arrayBuffer(); - } - function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - 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" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } - }).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error4; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error4) => { - if (error4 instanceof import_request_error.RequestError) - throw error4; - else if (error4.name === "AbortError") - throw error4; - let message = error4.message; - if (error4.name === "TypeError" && "cause" in error4) { - if (error4.cause instanceof Error) { - message = error4.cause.message; - } else if (typeof error4.cause === "string") { - message = error4.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); - } - 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 getBufferResponse(response); - } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; - } - function withDefaults(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: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - } - var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } - }); - } -}); - -// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node6 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint + endpoint: () => endpoint }); module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); @@ -21218,9 +21179,101 @@ var require_dist_node6 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node7 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/deprecation/dist-node/index.js +var require_dist_node3 = __commonJS({ + "node_modules/deprecation/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var Deprecation = class extends Error { + constructor(message) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "Deprecation"; + } + }; + exports2.Deprecation = Deprecation; + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node4 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; var __create2 = Object.create; var __defProp2 = Object.defineProperty; @@ -21310,9 +21363,9 @@ var require_dist_node7 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js -var require_dist_node8 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js +var require_dist_node5 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21336,7 +21389,7 @@ var require_dist_node8 = __commonJS({ request: () => request }); module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node6(); + var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; function isPlainObject(value) { @@ -21350,7 +21403,7 @@ var require_dist_node8 = __commonJS({ 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); } - var import_request_error = require_dist_node7(); + var import_request_error = require_dist_node4(); function getBufferResponse(response) { return response.arrayBuffer(); } @@ -21520,9 +21573,9 @@ var require_dist_node8 = __commonJS({ } }); -// node_modules/@octokit/graphql/dist-node/index.js -var require_dist_node9 = __commonJS({ - "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node6 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21541,129 +21594,340 @@ var require_dist_node9 = __commonJS({ return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export2(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint }); - module2.exports = __toCommonJS2(index_exports); - var import_request3 = require_dist_node8(); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); - var VERSION = "7.1.1"; - var import_request2 = require_dist_node8(); - var import_request = require_dist_node8(); - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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; + }, {}); } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + function isPlainObject(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 (isPlainObject(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]; } } - }; - 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`) - ); + 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); } - 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` - ) - ); + 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+)|(?:(? { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } + function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; } - if (!result.variables) { - result.variables = {}; + } + return result; + } + function encodeReserved(str2) { + return str2.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, "]"); } - 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 part; + }).join(""); + } + function encodeUnreserved(str2) { + return encodeURIComponent(str2).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; } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; + } + function isDefined2(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context2, operator, key, modifier) { + var value = context2[key], result = []; + if (isDefined2(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)); } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(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(",")); + } + } } - return response.data.data; - }); + } else { + if (operator === ";") { + if (isDefined2(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; } - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); + function parseUrl(template) { + return { + expand: expand.bind(null, template) }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); } - var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" - }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" + function expand(template, context2) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_2, 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(context2, 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 parse(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 = omit(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 = omit(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(/(? { + 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 parse(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 }); } + var endpoint = withDefaults(null, DEFAULTS); } }); -// node_modules/@octokit/auth-token/dist-node/index.js -var require_dist_node10 = __commonJS({ - "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node7 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; + var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) @@ -21677,53 +21941,490 @@ var require_dist_node10 = __commonJS({ } return to; }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - createTokenAuth: () => createTokenAuth + RequestError: () => RequestError }); module2.exports = __toCommonJS2(dist_src_exports); - 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, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); - } - 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" - ); + var import_deprecation = require_dist_node3(); + var import_once = __toESM2(require_once()); + var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + request: () => request + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_endpoint = require_dist_node6(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "8.4.1"; + function isPlainObject(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); + } + var import_request_error = require_dist_node7(); + function getBufferResponse(response) { + return response.arrayBuffer(); + } + function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + 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" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error4; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error4) => { + if (error4 instanceof import_request_error.RequestError) + throw error4; + else if (error4.name === "AbortError") + throw error4; + let message = error4.message; + if (error4.name === "TypeError" && "cause" in error4) { + if (error4.cause instanceof Error) { + message = error4.cause.message; + } else if (typeof error4.cause === "string") { + message = error4.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); + } + 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 getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; + } + function withDefaults(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: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + } + var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }); + } +}); + +// node_modules/@octokit/graphql/dist-node/index.js +var require_dist_node9 = __commonJS({ + "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export2(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest + }); + module2.exports = __toCommonJS2(index_exports); + var import_request3 = require_dist_node8(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "7.1.1"; + var import_request2 = require_dist_node8(); + var import_request = require_dist_node8(); + 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.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + }; + 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 withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); + } + } +}); + +// node_modules/@octokit/auth-token/dist-node/index.js +var require_dist_node10 = __commonJS({ + "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + createTokenAuth: () => createTokenAuth + }); + module2.exports = __toCommonJS2(dist_src_exports); + 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, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + 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) + }); }; } }); @@ -26499,7 +27200,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -29372,7 +30073,7 @@ var require_validator = __commonJS({ }); // node_modules/jsonschema/lib/index.js -var require_lib2 = __commonJS({ +var require_lib3 = __commonJS({ "node_modules/jsonschema/lib/index.js"(exports2, module2) { "use strict"; var Validator2 = module2.exports.Validator = require_validator(); @@ -32511,5019 +33212,5824 @@ var require_cacheUtils = __commonJS({ } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); - var HttpPipeline = class _HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = void 0; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - this._policies.push({ - policy, - options - }); - this._orderedPolicies = void 0; + } else { + return void 0; } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { - removedPolicies.push(policyDescriptor.policy); - return false; - } else { - return true; - } - }); - this._orderedPolicies = void 0; - return removedPolicies; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - clone() { - return new _HttpPipeline(this._policies); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - static create() { - return new _HttpPipeline(); + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - orderPolicies() { - const result = []; - const policyMap = /* @__PURE__ */ new Map(); - function createPhase(name) { - return { - name, - policies: /* @__PURE__ */ new Set(), - hasRun: false, - hasAfterPolicies: false - }; - } - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } else if (phase === "Serialize") { - return serializePhase; - } else if (phase === "Deserialize") { - return deserializePhase; - } else if (phase === "Sign") { - return signPhase; - } else { - return noPhase; - } - } - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: /* @__PURE__ */ new Set(), - dependants: /* @__PURE__ */ new Set() - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); - } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); - } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); - } - } - } - } - function walkPhase(phase) { - phase.hasRun = true; - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - continue; - } - if (node.dependsOn.size === 0) { - result.push(node.policy); - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); - } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - walkPhase(noPhase); - } - return; - } - if (phase.hasAfterPolicies) { - walkPhase(noPhase); - } - } - } - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - walkPhases(); - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return result; } - }; - function createEmptyPipeline() { - return HttpPipeline.create(); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@azure/logger/dist/index.js -var require_dist = __commonJS({ - "node_modules/@azure/logger/dist/index.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var os = require("os"); - var util = require("util"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); - function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); - } - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; - var enabledString; - var enabledNamespaces = []; - var skippedNamespaces = []; - var debuggers = []; - if (debugEnvVariable) { - enable(debugEnvVariable); - } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log - }); - function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); - } else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); - } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - } - function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - } - return false; - } - function disable() { - const result = enabledString || ""; - enable(""); - return result; - } - function createDebugger(namespace) { - const newDebugger = Object.assign(debug5, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend: extend3 - }); - function debug5(...args) { - if (!newDebugger.enabled) { - return; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } - newDebugger.log(...args); - } - debuggers.push(newDebugger); - return newDebugger; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return false; - } - function extend3(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; - } - var debug4 = debugObj; - var registeredLoggers = /* @__PURE__ */ new Set(); - var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; - var azureLogLevel; - var AzureLogger = debug4("azure"); - AzureLogger.log = (...args) => { - debug4.log(...args); }; - var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; - if (logLevelFromEnv) { - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); - } else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - } - function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); + }); } - azureLogLevel = level; - const enabledNamespaces2 = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces2.push(logger.namespace); - } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); + }); } - debug4.enable(enabledNamespaces2.join(",")); - } - function getLogLevel() { - return azureLogLevel; - } - var levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 }; - function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") - }; - } - function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); - }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces2 = debug4.disable(); - debug4.enable(enabledNamespaces2 + "," + logger.namespace); + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - registeredLoggers.add(logger); - return logger; - } - function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); - } - function isAzureLogLevel(logLevel) { - return AZURE_LOG_LEVELS.includes(logLevel); - } - exports2.AzureLogger = AzureLogger; - exports2.createClientLogger = createClientLogger; - exports2.getLogLevel = getLogLevel; - exports2.setLogLevel = setLogLevel; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js -var require_log = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_dist(); - exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - } -}); - -// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js -var require_createAbortablePromise = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createAbortablePromise = createAbortablePromise; - var abort_controller_1 = require_commonjs(); - function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve5, reject) => { - function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - function removeListeners() { - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - function onAbort() { - cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); - removeListeners(); - rejectOnAbort(); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { - return rejectOnAbort(); + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - try { - buildPromise((x) => { - removeListeners(); - resolve5(x); - }, (x) => { - removeListeners(); - reject(x); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); }); - } catch (err) { - reject(err); + data.pipe(req); + } else { + req.end(); } - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); - }); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/random.js -var require_random = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - function getRandomIntegerInclusive(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - const offset = Math.floor(Math.random() * (max - min + 1)); - return offset + min; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/delay.js -var require_delay = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay; - exports2.calculateRetryDelay = calculateRetryDelay; - var createAbortablePromise_js_1 = require_createAbortablePromise(); - var random_js_1 = require_random(); - var StandardAbortMessage = "The delay was aborted."; - function delay(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve5) => { - token = setTimeout(resolve5, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage - }); - } - function calculateRetryDelay(retryAttempt, config) { - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); - return { retryAfterInMs }; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js -var require_aborterUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cancelablePromiseRace = cancelablePromiseRace; - async function cancelablePromiseRace(abortablePromiseBuilders, options) { - var _a, _b; - const aborter = new AbortController(); - function abortHandler() { - aborter.abort(); } - (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); - try { - return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); - } finally { - aborter.abort(); - (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/object.js -var require_object = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isObject = isObject2; - function isObject2(input) { - return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/error.js -var require_error = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isError = isError; - exports2.getErrorMessage = getErrorMessage2; - var object_js_1 = require_object(); - function isError(e) { - if ((0, object_js_1.isObject)(e)) { - const hasName = typeof e.name === "string"; - const hasMessage = typeof e.message === "string"; - return hasName && hasMessage; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return false; - } - function getErrorMessage2(e) { - if (isError(e)) { - return e.message; - } else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } else { - stringified = String(e); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); } - } catch (err) { - stringified = "[unable to stringify input]"; } - return `Unknown error ${stringified}`; + return info7; } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.computeSha256Hash = computeSha256Hash; - var crypto_1 = require("crypto"); - async function computeSha256Hmac(key, stringToSign, encoding) { - const decodedKey = Buffer.from(key, "base64"); - return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); - } - async function computeSha256Hash(content, encoding) { - return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/typeGuards.js -var require_typeGuards = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isDefined = isDefined2; - exports2.isObjectWithProperties = isObjectWithProperties; - exports2.objectHasProperty = objectHasProperty; - function isDefined2(thing) { - return typeof thing !== "undefined" && thing !== null; - } - function isObjectWithProperties(thing, properties) { - if (!isDefined2(thing) || typeof thing !== "object") { - return false; - } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - return true; - } - function objectHasProperty(thing, property) { - return isDefined2(thing) && typeof thing === "object" && property in thing; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js -var require_uuidUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomUUID = randomUUID; - var crypto_1 = require("crypto"); - var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; - function randomUUID() { - return uuidFunction(); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js -var require_checkEnvironment = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { - "use strict"; - var _a; - var _b; - var _c; - var _d; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; - exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; - exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); - exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; - exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; - exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); - exports2.isNode = exports2.isNodeLike; - exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; - exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; - } -}); - -// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js -var require_bytesEncoding = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - function uint8ArrayToString(bytes, format) { - return Buffer.from(bytes).toString(format); - } - function stringToUint8Array(value, format) { - return Buffer.from(value, format); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/index.js -var require_commonjs2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; - var delay_js_1 = require_delay(); - Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { - return delay_js_1.delay; - } }); - Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { - return delay_js_1.calculateRetryDelay; - } }); - var aborterUtils_js_1 = require_aborterUtils(); - Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { - return aborterUtils_js_1.cancelablePromiseRace; - } }); - var createAbortablePromise_js_1 = require_createAbortablePromise(); - Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { - return createAbortablePromise_js_1.createAbortablePromise; - } }); - var random_js_1 = require_random(); - Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { - return random_js_1.getRandomIntegerInclusive; - } }); - var object_js_1 = require_object(); - Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { - return object_js_1.isObject; - } }); - var error_js_1 = require_error(); - Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { - return error_js_1.isError; - } }); - Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { - return error_js_1.getErrorMessage; - } }); - var sha256_js_1 = require_sha256(); - Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hash; - } }); - Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hmac; - } }); - var typeGuards_js_1 = require_typeGuards(); - Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { - return typeGuards_js_1.isDefined; - } }); - Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { - return typeGuards_js_1.isObjectWithProperties; - } }); - Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { - return typeGuards_js_1.objectHasProperty; - } }); - var uuidUtils_js_1 = require_uuidUtils(); - Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { - return uuidUtils_js_1.randomUUID; - } }); - var checkEnvironment_js_1 = require_checkEnvironment(); - Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBrowser; - } }); - Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBun; - } }); - Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNode; - } }); - Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeLike; - } }); - Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeRuntime; - } }); - Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { - return checkEnvironment_js_1.isDeno; - } }); - Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { - return checkEnvironment_js_1.isReactNative; - } }); - Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { - return checkEnvironment_js_1.isWebWorker; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js -var require_sanitizer = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = void 0; - var core_util_1 = require_commonjs2(); - var RedactedString = "REDACTED"; - var defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate" - ]; - var defaultAllowedQueryParameters = ["api-version"]; - var Sanitizer = class { - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { - allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); - allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); - } - sanitize(obj) { - const seen = /* @__PURE__ */ new Set(); - return JSON.stringify(obj, (key, value) => { - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); - } - if (key === "headers") { - return this.sanitizeHeaders(value); - } else if (key === "url") { - return this.sanitizeUrl(value); - } else if (key === "query") { - return this.sanitizeQuery(value); - } else if (key === "body") { - return void 0; - } else if (key === "response") { - return void 0; - } else if (key === "operationSpec") { - return void 0; - } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - } - return value; - }, 2); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - sanitizeUrl(value) { - if (typeof value !== "string" || value === null || value === "") { - return value; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const url = new URL(value); - if (!url.search) { - return value; + if (!useProxy) { + agent = this._agent; } - for (const [key] of url.searchParams) { - if (!this.allowedQueryParameters.has(key.toLowerCase())) { - url.searchParams.set(key, RedactedString); - } + if (agent) { + return agent; } - return url.toString(); - } - sanitizeHeaders(obj) { - const sanitized = {}; - for (const key of Object.keys(obj)) { - if (this.allowedHeaderNames.has(key.toLowerCase())) { - sanitized[key] = obj[key]; + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - sanitized[key] = RedactedString; + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - return sanitized; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - sanitizeQuery(value) { - if (typeof value !== "object" || value === null) { - return value; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (this.allowedQueryParameters.has(k.toLowerCase())) { - sanitized[k] = value[k]; - } else { - sanitized[k] = RedactedString; - } + if (proxyAgent) { + return proxyAgent; } - return sanitized; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); + } + })); + }); } }; - exports2.Sanitizer = Sanitizer; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js -var require_logPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log(); - var sanitizer_js_1 = require_sanitizer(); - exports2.logPolicyName = "logPolicy"; - function logPolicy(options = {}) { - var _a; - const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - return { - name: exports2.logPolicyName, - async sendRequest(request, next) { - if (!logger.enabled) { - return next(request); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - logger(`Request: ${sanitizer.sanitize(request)}`); - const response = await next(request); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); - return response; } - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js -var require_redirectPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - exports2.redirectPolicyName = "redirectPolicy"; - var allowedRedirect = ["GET", "HEAD"]; - function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: exports2.redirectPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return handleRedirect(next, response, maxRetries); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - }; - } - async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { - const url = new URL(locationHeader, request.url); - request.url = url.toString(); - if (status === 303) { - request.method = "GET"; - request.headers.delete("Content-Length"); - delete request.body; + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } - request.headers.delete("Authorization"); - const res = await next(request); - return handleRedirect(next, res, maxRetries, currentRetries + 1); - } - return response; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs -var tslib_es6_exports = {}; -__export(tslib_es6_exports, { - __addDisposableResource: () => __addDisposableResource, - __assign: () => __assign, - __asyncDelegator: () => __asyncDelegator, - __asyncGenerator: () => __asyncGenerator, - __asyncValues: () => __asyncValues, - __await: () => __await, - __awaiter: () => __awaiter, - __classPrivateFieldGet: () => __classPrivateFieldGet, - __classPrivateFieldIn: () => __classPrivateFieldIn, - __classPrivateFieldSet: () => __classPrivateFieldSet, - __createBinding: () => __createBinding, - __decorate: () => __decorate, - __disposeResources: () => __disposeResources, - __esDecorate: () => __esDecorate, - __exportStar: () => __exportStar, - __extends: () => __extends, - __generator: () => __generator, - __importDefault: () => __importDefault, - __importStar: () => __importStar, - __makeTemplateObject: () => __makeTemplateObject, - __metadata: () => __metadata, - __param: () => __param, - __propKey: () => __propKey, - __read: () => __read, - __rest: () => __rest, - __runInitializers: () => __runInitializers, - __setFunctionName: () => __setFunctionName, - __spread: () => __spread, - __spreadArray: () => __spreadArray, - __spreadArrays: () => __spreadArrays, - __values: () => __values2, - default: () => tslib_es6_default -}); -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _2, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context2 = {}; - for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; - context2.addInitializer = function(f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_2 = accept(result.get)) descriptor.get = _2; - if (_2 = accept(result.set)) descriptor.set = _2; - if (_2 = accept(result.init)) initializers.unshift(_2); - } else if (_2 = accept(result)) { - if (kind === "field") initializers.unshift(_2); - else descriptor[key] = _2; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} -function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -} -function __propKey(x) { - return typeof x === "symbol" ? x : "".concat(x); -} -function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); -} -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _2 = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_2 = 0)), _2) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _2.label++; - return { value: op[1], done: false }; - case 5: - _2.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _2.ops.pop(); - _2.trys.pop(); - continue; - default: - if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _2 = 0; - continue; +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _2.label = op[1]; - break; + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; } - if (op[0] === 6 && _2.label < t[1]) { - _2.label = t[1]; - t = op; - break; + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); } - if (t && _2.label < t[2]) { - _2.label = t[2]; - _2.ops.push(op); - break; + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; } - if (t[2]) _2.ops.pop(); - _2.trys.pop(); - continue; + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; } - op = body.call(thisArg, _2); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; + }; + function createEmptyPipeline() { + return HttpPipeline.create(); } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; } -} -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} -function __values2(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function() { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; +}); + +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error4) { - e = { error: error4 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); } - } - return ar; -} -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - if (f) i[n] = f(i[n]); + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log + }); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function(e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function() { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function(v) { - return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; - } : f; - } -} -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve5, reject) { - v = o[n](v), settle(resolve5, reject, v.done, v.value); - }); - }; - } - function settle(resolve5, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve5({ value: v2, done: d }); - }, reject); - } -} -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - } - __setModuleDefault(result, mod); - return result; -} -function __importDefault(mod) { - return mod && mod.__esModule ? mod : { default: mod }; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldIn(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} -function __addDisposableResource(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; + function disable() { + const result = enabledString || ""; + enable(""); + return result; } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; + function createDebugger(namespace) { + const newDebugger = Object.assign(debug5, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug5(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { - try { - inner.call(this); - } catch (e) { - return Promise.reject(e); + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; } + return false; + } + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; + } + var debug4 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug4("azure"); + AzureLogger.log = (...args) => { + debug4.log(...args); }; - env.stack.push({ value, dispose, async }); - } else if (async) { - env.stack.push({ async: true }); - } - return value; -} -function __disposeResources(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { - fail(e); - return next(); - }); - } else s |= 1; - } catch (e) { - fail(e); + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); } } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; - } - return next(); -} -var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; -var init_tslib_es6 = __esm({ - "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() { - extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics(d, b); - }; - __assign = function() { - __assign = Object.assign || function __assign4(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); } - return t; - }; - return __assign.apply(this, arguments); - }; - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - }); - __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; - }; - tslib_es6_default = { - __extends, - __assign, - __rest, - __decorate, - __param, - __metadata, - __awaiter, - __generator, - __createBinding, - __exportStar, - __values: __values2, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn, - __addDisposableResource, - __disposeResources + debug4.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 }; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js -var require_userAgentPlatform = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getHeaderName = getHeaderName; - exports2.setPlatformSpecificData = setPlatformSpecificData; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var os = tslib_1.__importStar(require("node:os")); - var process2 = tslib_1.__importStar(require("node:process")); - function getHeaderName() { - return "User-Agent"; + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; } - async function setPlatformSpecificData(map2) { - if (process2 && process2.versions) { - const versions = process2.versions; - if (versions.bun) { - map2.set("Bun", versions.bun); - } else if (versions.deno) { - map2.set("Deno", versions.deno); - } else if (versions.node) { - map2.set("Node", versions.node); - } + function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; + } + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces2 = debug4.disable(); + debug4.enable(enabledNamespaces2 + "," + logger.namespace); } - map2.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`); + registeredLoggers.add(logger); + return logger; + } + function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + } + function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); } + exports2.AzureLogger = AzureLogger; + exports2.createClientLogger = createClientLogger; + exports2.getLogLevel = getLogLevel; + exports2.setLogLevel = setLogLevel; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js -var require_constants8 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js +var require_log = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; - exports2.SDK_VERSION = "1.17.0"; - exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js -var require_userAgent = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUserAgentHeaderName = getUserAgentHeaderName; - exports2.getUserAgentValue = getUserAgentValue; - var userAgentPlatform_js_1 = require_userAgentPlatform(); - var constants_js_1 = require_constants8(); - function getUserAgentString(telemetryInfo) { - const parts = []; - for (const [key, value] of telemetryInfo) { - const token = value ? `${key}/${value}` : key; - parts.push(token); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } - return parts.join(" "); - } - function getUserAgentHeaderName() { - return (0, userAgentPlatform_js_1.getHeaderName)(); - } - async function getUserAgentValue(prefix) { - const runtimeInfo = /* @__PURE__ */ new Map(); - runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); - await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); - const defaultAgent = getUserAgentString(runtimeInfo); - const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; - return userAgentValue; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js -var require_userAgentPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.userAgentPolicyName = void 0; - exports2.userAgentPolicy = userAgentPolicy; - var userAgent_js_1 = require_userAgent(); - var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); - exports2.userAgentPolicyName = "userAgentPolicy"; - function userAgentPolicy(options = {}) { - const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); - return { - name: exports2.userAgentPolicyName, - async sendRequest(request, next) { - if (!request.headers.has(UserAgentHeaderName)) { - request.headers.set(UserAgentHeaderName, await userAgentValue); - } - return next(request); - } - }; - } + }; + exports2.AbortError = AbortError; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js -var require_typeGuards2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) { +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isNodeReadableStream = isNodeReadableStream; - exports2.isWebReadableStream = isWebReadableStream; - exports2.isReadableStream = isReadableStream; - exports2.isBlob = isBlob; - function isNodeReadableStream(x) { - return Boolean(x && typeof x["pipe"] === "function"); - } - function isWebReadableStream(x) { - return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); - } - function isReadableStream(x) { - return isNodeReadableStream(x) || isWebReadableStream(x); - } - function isBlob(x) { - return typeof x.stream === "function"; - } + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js -var require_file2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRawContent = getRawContent; - exports2.createFileFromStream = createFileFromStream; - exports2.createFile = createFile; - var core_util_1 = require_commonjs2(); - var typeGuards_js_1 = require_typeGuards2(); - var unimplementedMethods = { - arrayBuffer: () => { - throw new Error("Not implemented"); - }, - slice: () => { - throw new Error("Not implemented"); - }, - text: () => { - throw new Error("Not implemented"); - } - }; - var rawContent = Symbol("rawContent"); - function hasRawContent(x) { - return typeof x[rawContent] === "function"; - } - function getRawContent(blob) { - if (hasRawContent(blob)) { - return blob[rawContent](); - } else { - return blob.stream(); - } - } - function createFileFromStream(stream, name, options = {}) { - var _a, _b, _c, _d; - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { - const s = stream(); - if ((0, typeGuards_js_1.isNodeReadableStream)(s)) { - throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve5, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); } - return s; - }, [rawContent]: stream }); + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve5(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); } - function createFile(content, name, options = {}) { - var _a, _b, _c; - if (core_util_1.isNodeLike) { - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); - } else { - return new File([content], name, options); - } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/random.js +var require_random = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; + function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js -var require_concat = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.concat = concat; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var node_stream_1 = require("node:stream"); - var typeGuards_js_1 = require_typeGuards2(); - var file_js_1 = require_file2(); - function streamAsyncIterator() { - return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { - const reader = this.getReader(); - try { - while (true) { - const { done, value } = yield tslib_1.__await(reader.read()); - if (done) { - return yield tslib_1.__await(void 0); - } - yield yield tslib_1.__await(value); - } - } finally { - reader.releaseLock(); - } + exports2.delay = delay; + exports2.calculateRetryDelay = calculateRetryDelay; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var random_js_1 = require_random(); + var StandardAbortMessage = "The delay was aborted."; + function delay(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve5) => { + token = setTimeout(resolve5, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage }); } - function makeAsyncIterable(webStream) { - if (!webStream[Symbol.asyncIterator]) { - webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); - } - if (!webStream.values) { - webStream.values = streamAsyncIterator.bind(webStream); - } + function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; } - function ensureNodeStream(stream) { - if (stream instanceof ReadableStream) { - makeAsyncIterable(stream); - return node_stream_1.Readable.fromWeb(stream); - } else { - return stream; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); } - } - function toStream(source) { - if (source instanceof Uint8Array) { - return node_stream_1.Readable.from(Buffer.from(source)); - } else if ((0, typeGuards_js_1.isBlob)(source)) { - return toStream((0, file_js_1.getRawContent)(source)); - } else { - return ensureNodeStream(source); + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); } } - async function concat(sources) { - return function() { - const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); - return node_stream_1.Readable.from((function() { - return tslib_1.__asyncGenerator(this, arguments, function* () { - var _a, e_1, _b, _c; - for (const stream of streams) { - try { - for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { - _c = stream_1_1.value; - _d = false; - const chunk = _c; - yield yield tslib_1.__await(chunk); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1)); - } finally { - if (e_1) throw e_1.error; - } - } - } - }); - })()); - }; - } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js -var require_multipartPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/object.js +var require_object = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.multipartPolicyName = void 0; - exports2.multipartPolicy = multipartPolicy; - var core_util_1 = require_commonjs2(); - var concat_js_1 = require_concat(); - var typeGuards_js_1 = require_typeGuards2(); - function generateBoundary() { - return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; + exports2.isObject = isObject2; + function isObject2(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); } - function encodeHeaders(headers) { - let result = ""; - for (const [key, value] of headers) { - result += `${key}: ${value}\r -`; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isError = isError; + exports2.getErrorMessage = getErrorMessage2; + var object_js_1 = require_object(); + function isError(e) { + if ((0, object_js_1.isObject)(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; } - return result; + return false; } - function getLength(source) { - if (source instanceof Uint8Array) { - return source.byteLength; - } else if ((0, typeGuards_js_1.isBlob)(source)) { - return source.size === -1 ? void 0 : source.size; + function getErrorMessage2(e) { + if (isError(e)) { + return e.message; } else { - return void 0; - } - } - function getTotalLength(sources) { - let total = 0; - for (const source of sources) { - const partLength = getLength(source); - if (partLength === void 0) { - return void 0; - } else { - total += partLength; + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } else { + stringified = String(e); + } + } catch (err) { + stringified = "[unable to stringify input]"; } + return `Unknown error ${stringified}`; } - return total; - } - async function buildRequestBody(request, parts, boundary) { - const sources = [ - (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"), - ...parts.flatMap((part) => [ - (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), - (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), - (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), - part.body, - (0, core_util_1.stringToUint8Array)(`\r ---${boundary}`, "utf-8") - ]), - (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8") - ]; - const contentLength = getTotalLength(sources); - if (contentLength) { - request.headers.set("Content-Length", contentLength); - } - request.body = await (0, concat_js_1.concat)(sources); } - exports2.multipartPolicyName = "multipartPolicy"; - var maxBoundaryLength = 70; - var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); - function assertValidBoundary(boundary) { - if (boundary.length > maxBoundaryLength) { - throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); - } - if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { - throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); - } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.computeSha256Hmac = computeSha256Hmac; + exports2.computeSha256Hash = computeSha256Hash; + var crypto_1 = require("crypto"); + async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); } - function multipartPolicy() { - return { - name: exports2.multipartPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.multipartBody) { - return next(request); - } - if (request.body) { - throw new Error("multipartBody and regular body cannot be set at the same time"); - } - let boundary = request.multipartBody.boundary; - const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; - const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); - if (!parsedHeader) { - throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); - } - const [, contentType, parsedBoundary] = parsedHeader; - if (parsedBoundary && boundary && parsedBoundary !== boundary) { - throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); - } - boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary; - if (boundary) { - assertValidBoundary(boundary); - } else { - boundary = generateBoundary(); - } - request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); - await buildRequestBody(request, request.multipartBody.parts, boundary); - request.multipartBody = void 0; - return next(request); - } - }; + async function computeSha256Hash(content, encoding) { + return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js -var require_decompressResponsePolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decompressResponsePolicyName = void 0; - exports2.decompressResponsePolicy = decompressResponsePolicy; - exports2.decompressResponsePolicyName = "decompressResponsePolicy"; - function decompressResponsePolicy() { - return { - name: exports2.decompressResponsePolicyName, - async sendRequest(request, next) { - if (request.method !== "HEAD") { - request.headers.set("Accept-Encoding", "gzip,deflate"); - } - return next(request); + exports2.isDefined = isDefined2; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined2(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined2(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; } - }; + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined2(thing) && typeof thing === "object" && property in thing; } } }); -// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js +var require_uuidUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { "use strict"; + var _a; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; - } - }; - exports2.AbortError = AbortError; + exports2.randomUUID = randomUUID; + var crypto_1 = require("crypto"); + var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; + function randomUUID() { + return uuidFunction(); + } } }); -// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs3 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js +var require_checkEnvironment = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { "use strict"; + var _a; + var _b; + var _c; + var _d; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError2(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); + exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; + exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; + exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); + exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; + exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; + exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); + exports2.isNode = exports2.isNodeLike; + exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; + exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js -var require_helpers2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js +var require_bytesEncoding = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay; - exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; - var abort_controller_1 = require_commonjs3(); - var StandardAbortMessage = "The operation was aborted."; - function delay(delayInMs, value, options) { - return new Promise((resolve5, reject) => { - let timer = void 0; - let onAborted = void 0; - const rejectOnAbort = () => { - return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); - }; - const removeListeners = () => { - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { - options.abortSignal.removeEventListener("abort", onAborted); - } - }; - onAborted = () => { - if (timer) { - clearTimeout(timer); - } - removeListeners(); - return rejectOnAbort(); - }; - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { - return rejectOnAbort(); - } - timer = setTimeout(() => { - removeListeners(); - resolve5(value); - }, delayInMs); - if (options === null || options === void 0 ? void 0 : options.abortSignal) { - options.abortSignal.addEventListener("abort", onAborted); - } - }); + exports2.uint8ArrayToString = uint8ArrayToString; + exports2.stringToUint8Array = stringToUint8Array; + function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); } - function parseHeaderValueAsNumber(response, headerName) { - const value = response.headers.get(headerName); - if (!value) - return; - const valueAsNum = Number(value); - if (Number.isNaN(valueAsNum)) - return; - return valueAsNum; + function stringToUint8Array(value, format) { + return Buffer.from(value, format); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js -var require_throttlingRetryStrategy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; - exports2.throttlingRetryStrategy = throttlingRetryStrategy; - var helpers_js_1 = require_helpers2(); - var RetryAfterHeader = "Retry-After"; - var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; - function getRetryAfterInMs(response) { - if (!(response && [429, 503].includes(response.status))) - return void 0; - try { - for (const header of AllRetryAfterHeaders) { - const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); - if (retryAfterValue === 0 || retryAfterValue) { - const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; - return retryAfterValue * multiplyingFactor; - } - } - const retryAfterHeader = response.headers.get(RetryAfterHeader); - if (!retryAfterHeader) - return; - const date = Date.parse(retryAfterHeader); - const diff = date - Date.now(); - return Number.isFinite(diff) ? Math.max(0, diff) : void 0; - } catch (_a) { - return void 0; - } - } - function isThrottlingRetryResponse(response) { - return Number.isFinite(getRetryAfterInMs(response)); - } - function throttlingRetryStrategy() { - return { - name: "throttlingRetryStrategy", - retry({ response }) { - const retryAfterInMs = getRetryAfterInMs(response); - if (!Number.isFinite(retryAfterInMs)) { - return { skipStrategy: true }; - } - return { - retryAfterInMs - }; - } - }; - } + exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; + var delay_js_1 = require_delay(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { + return delay_js_1.calculateRetryDelay; + } }); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var random_js_1 = require_random(); + Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { + return random_js_1.getRandomIntegerInclusive; + } }); + var object_js_1 = require_object(); + Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { + return object_js_1.isObject; + } }); + var error_js_1 = require_error(); + Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { + return error_js_1.isError; + } }); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var sha256_js_1 = require_sha256(); + Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hash; + } }); + Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hmac; + } }); + var typeGuards_js_1 = require_typeGuards(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + var uuidUtils_js_1 = require_uuidUtils(); + Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { + return uuidUtils_js_1.randomUUID; + } }); + var checkEnvironment_js_1 = require_checkEnvironment(); + Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBrowser; + } }); + Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBun; + } }); + Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNode; + } }); + Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeLike; + } }); + Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeRuntime; + } }); + Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { + return checkEnvironment_js_1.isDeno; + } }); + Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { + return checkEnvironment_js_1.isReactNative; + } }); + Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { + return checkEnvironment_js_1.isWebWorker; + } }); + var bytesEncoding_js_1 = require_bytesEncoding(); + Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { + return bytesEncoding_js_1.uint8ArrayToString; + } }); + Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { + return bytesEncoding_js_1.stringToUint8Array; + } }); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js -var require_exponentialRetryStrategy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js +var require_sanitizer = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryStrategy = exponentialRetryStrategy; - exports2.isExponentialRetryResponse = isExponentialRetryResponse; - exports2.isSystemError = isSystemError; + exports2.Sanitizer = void 0; var core_util_1 = require_commonjs2(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; - var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; - function exponentialRetryStrategy(options = {}) { - var _a, _b; - const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; - const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - let retryAfterInMs = retryInterval; - return { - name: "exponentialRetryStrategy", - retry({ retryCount, response, responseError }) { - const matchedSystemError = isSystemError(responseError); - const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; - const isExponential = isExponentialRetryResponse(response); - const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; - const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); - if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { - return { skipStrategy: true }; + var RedactedString = "REDACTED"; + var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" + ]; + var defaultAllowedQueryParameters = ["api-version"]; + var Sanitizer = class { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); } - if (responseError && !matchedSystemError && !isExponential) { - return { errorToThrow: responseError }; + if (key === "headers") { + return this.sanitizeHeaders(value); + } else if (key === "url") { + return this.sanitizeUrl(value); + } else if (key === "query") { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); } - const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); - const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); - retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2); - return { retryAfterInMs }; + return value; + }, 2); + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; } - }; - } - function isExponentialRetryResponse(response) { - return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); - } - function isSystemError(err) { - if (!err) { - return false; + const url = new URL(value); + if (!url.search) { + return value; + } + for (const [key] of url.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url.searchParams.set(key, RedactedString); + } + } + return url.toString(); } - return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; - } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } + }; + exports2.Sanitizer = Sanitizer; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js -var require_retryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js +var require_logPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.retryPolicy = retryPolicy; - var helpers_js_1 = require_helpers2(); - var logger_1 = require_dist(); - var abort_controller_1 = require_commonjs3(); - var constants_js_1 = require_constants8(); - var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); - var retryPolicyName = "retryPolicy"; - function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { - const logger = options.logger || retryPolicyLogger; + exports2.logPolicyName = void 0; + exports2.logPolicy = logPolicy; + var log_js_1 = require_log(); + var sanitizer_js_1 = require_sanitizer(); + exports2.logPolicyName = "logPolicy"; + function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); return { - name: retryPolicyName, + name: exports2.logPolicyName, async sendRequest(request, next) { - var _a, _b; - let response; - let responseError; - let retryCount = -1; - retryRequest: while (true) { - retryCount += 1; - response = void 0; - responseError = void 0; - try { - logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); - response = await next(request); - logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); - } catch (e) { - logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); - responseError = e; - if (!e || responseError.name !== "RestError") { - throw e; - } - response = responseError.response; - } - if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - logger.error(`Retry ${retryCount}: Request aborted.`); - const abortError = new abort_controller_1.AbortError(); - throw abortError; - } - if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { - logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); - if (responseError) { - throw responseError; - } else if (response) { - return response; - } else { - throw new Error("Maximum retries reached with no response or error to throw"); - } - } - logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); - strategiesLoop: for (const strategy of strategies) { - const strategyLogger = strategy.logger || retryPolicyLogger; - strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); - const modifiers = strategy.retry({ - retryCount, - response, - responseError - }); - if (modifiers.skipStrategy) { - strategyLogger.info(`Retry ${retryCount}: Skipped.`); - continue strategiesLoop; - } - const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; - if (errorToThrow) { - strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); - throw errorToThrow; - } - if (retryAfterInMs || retryAfterInMs === 0) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); - await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); - continue retryRequest; - } - if (redirectTo) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); - request.url = redirectTo; - continue retryRequest; - } - } - if (responseError) { - logger.info(`None of the retry strategies could work with the received error. Throwing it.`); - throw responseError; - } - if (response) { - logger.info(`None of the retry strategies could work with the received response. Returning it.`); - return response; - } + if (!logger.enabled) { + return next(request); } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; } }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js -var require_defaultRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.defaultRetryPolicyName = void 0; - exports2.defaultRetryPolicy = defaultRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.defaultRetryPolicyName = "defaultRetryPolicy"; - function defaultRetryPolicy(options = {}) { - var _a; + exports2.redirectPolicyName = void 0; + exports2.redirectPolicy = redirectPolicy; + exports2.redirectPolicyName = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; return { - name: exports2.defaultRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest + name: exports2.redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + } }; } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js -var require_httpHeaders = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createHttpHeaders = createHttpHeaders; - function normalizeName(name) { - return name.toLowerCase(); - } - function* headerIterator(map2) { - for (const entry of map2.values()) { - yield [entry.name, entry.value]; - } - } - var HttpHeadersImpl = class { - constructor(rawHeaders) { - this._headersMap = /* @__PURE__ */ new Map(); - if (rawHeaders) { - for (const headerName of Object.keys(rawHeaders)) { - this.set(headerName, rawHeaders[headerName]); - } - } - } - /** - * Set a header in this collection with the provided name and value. The name is - * case-insensitive. - * @param name - The name of the header to set. This value is case-insensitive. - * @param value - The value of the header to set. - */ - set(name, value) { - this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); - } - /** - * Get the header value for the provided header name, or undefined if no header exists in this - * collection with the provided name. - * @param name - The name of the header. This value is case-insensitive. - */ - get(name) { - var _a; - return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; - } - /** - * Get whether or not this header collection contains a header entry for the provided header name. - * @param name - The name of the header to set. This value is case-insensitive. - */ - has(name) { - return this._headersMap.has(normalizeName(name)); - } - /** - * Remove the header with the provided headerName. - * @param name - The name of the header to remove. - */ - delete(name) { - this._headersMap.delete(normalizeName(name)); - } - /** - * Get the JSON object representation of this HTTP header collection. - */ - toJSON(options = {}) { - const result = {}; - if (options.preserveCase) { - for (const entry of this._headersMap.values()) { - result[entry.name] = entry.value; - } - } else { - for (const [normalizedName, entry] of this._headersMap) { - result[normalizedName] = entry.value; - } + async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url = new URL(locationHeader, request.url); + request.url = url.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; } - return result; - } - /** - * Get the string representation of this HTTP header collection. - */ - toString() { - return JSON.stringify(this.toJSON({ preserveCase: true })); - } - /** - * Iterate over tuples of header [name, value] pairs. - */ - [Symbol.iterator]() { - return headerIterator(this._headersMap); + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); } - }; - function createHttpHeaders(rawHeaders) { - return new HttpHeadersImpl(rawHeaders); + return response; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js -var require_formDataPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.formDataPolicyName = void 0; - exports2.formDataPolicy = formDataPolicy; - var core_util_1 = require_commonjs2(); - var httpHeaders_js_1 = require_httpHeaders(); - exports2.formDataPolicyName = "formDataPolicy"; - function formDataToFormDataMap(formData) { - var _a; - const formDataMap = {}; - for (const [key, value] of formData.entries()) { - (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = []; - formDataMap[key].push(value); - } - return formDataMap; - } - function formDataPolicy() { - return { - name: exports2.formDataPolicyName, - async sendRequest(request, next) { - if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { - request.formData = formDataToFormDataMap(request.body); - request.body = void 0; - } - if (request.formData) { - const contentType = request.headers.get("Content-Type"); - if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { - request.body = wwwFormUrlEncode(request.formData); - } else { - await prepareFormData(request.formData, request); - } - request.formData = void 0; - } - return next(request); - } - }; - } - function wwwFormUrlEncode(formData) { - const urlSearchParams = new URLSearchParams(); - for (const [key, value] of Object.entries(formData)) { - if (Array.isArray(value)) { - for (const subValue of value) { - urlSearchParams.append(key, subValue.toString()); - } - } else { - urlSearchParams.append(key, value.toString()); - } - } - return urlSearchParams.toString(); - } - async function prepareFormData(formData, request) { - const contentType = request.headers.get("Content-Type"); - if (contentType && !contentType.startsWith("multipart/form-data")) { - return; - } - request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); - const parts = []; - for (const [fieldName, values] of Object.entries(formData)) { - for (const value of Array.isArray(values) ? values : [values]) { - if (typeof value === "string") { - parts.push({ - headers: (0, httpHeaders_js_1.createHttpHeaders)({ - "Content-Disposition": `form-data; name="${fieldName}"` - }), - body: (0, core_util_1.stringToUint8Array)(value, "utf-8") - }); - } else if (value === void 0 || value === null || typeof value !== "object") { - throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); - } else { - const fileName = value.name || "blob"; - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); - headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); - headers.set("Content-Type", value.type || "application/octet-stream"); - parts.push({ - headers, - body: value - }); - } - } - } - request.multipartBody = { parts }; +// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __addDisposableResource: () => __addDisposableResource, + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __disposeResources: () => __disposeResources, + __esDecorate: () => __esDecorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __propKey: () => __propKey, + __read: () => __read, + __rest: () => __rest, + __runInitializers: () => __runInitializers, + __setFunctionName: () => __setFunctionName, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values2, + default: () => tslib_es6_default +}); +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; } + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; } -}); - -// node_modules/ms/index.js -var require_ms = __commonJS({ - "node_modules/ms/index.js"(exports2, module2) { - var s = 1e3; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - module2.exports = function(val2, options) { - options = options || {}; - var type2 = typeof val2; - if (type2 === "string" && val2.length > 0) { - return parse(val2); - } else if (type2 === "number" && isFinite(val2)) { - return options.long ? fmtLong(val2) : fmtShort(val2); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2) - ); + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _2, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context2 = {}; + for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; + context2.addInitializer = function(f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); }; - function parse(str2) { - str2 = String(str2); - if (str2.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str2 - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type2 = (match[2] || "ms").toLowerCase(); - switch (type2) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "weeks": - case "week": - case "w": - return n * w; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return void 0; - } + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_2 = accept(result.get)) descriptor.get = _2; + if (_2 = accept(result.set)) descriptor.set = _2; + if (_2 = accept(result.init)) initializers.unshift(_2); + } else if (_2 = accept(result)) { + if (kind === "field") initializers.unshift(_2); + else descriptor[key] = _2; } - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; - } - if (msAbs >= m) { - return Math.round(ms / m) + "m"; - } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - return ms + "ms"; } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, "minute"); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return ms + " ms"; } - function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _2 = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n) { + return function(v) { + return step([n, v]); + }; } -}); - -// node_modules/debug/src/common.js -var require_common = __commonJS({ - "node_modules/debug/src/common.js"(exports2, module2) { - function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce3; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require_ms(); - createDebug.destroy = destroy; - Object.keys(env).forEach((key) => { - createDebug[key] = env[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash = 0; - for (let i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; - } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug4(...args) { - if (!debug4.enabled) { - return; - } - const self2 = debug4; - const curr = Number(/* @__PURE__ */ new Date()); - const ms = curr - (prevTime || curr); - self2.diff = ms; - self2.prev = prevTime; - self2.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_2 = 0)), _2) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _2.label++; + return { value: op[1], done: false }; + case 5: + _2.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; + continue; } - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - if (match === "%%") { - return "%"; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === "function") { - const val2 = args[index]; - match = formatter.call(self2, val2); - args.splice(index, 1); - index--; - } - return match; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); - } - debug4.namespace = namespace; - debug4.useColors = createDebug.useColors(); - debug4.color = createDebug.selectColor(namespace); - debug4.extend = extend3; - debug4.destroy = createDebug.destroy; - Object.defineProperty(debug4, "enabled", { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, - set: (v) => { - enableOverride = v; + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _2.label = op[1]; + break; } - }); - if (typeof createDebug.init === "function") { - createDebug.init(debug4); - } - return debug4; - } - function extend3(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns of split) { - if (ns[0] === "-") { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); + if (op[0] === 6 && _2.label < t[1]) { + _2.label = t[1]; + t = op; + break; } - } - } - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { - if (template[templateIndex] === "*") { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; + if (t && _2.label < t[2]) { + _2.label = t[2]; + _2.ops.push(op); + break; } - } - while (templateIndex < template.length && template[templateIndex] === "*") { - templateIndex++; - } - return templateIndex === template.length; - } - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; + if (t[2]) _2.ops.pop(); + _2.trys.pop(); + continue; } - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; - } - } - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; - } - } - return false; - } - function coerce3(val2) { - if (val2 instanceof Error) { - return val2.stack || val2.message; - } - return val2; - } - function destroy() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - createDebug.enable(createDebug.load()); - return createDebug; + op = body.call(thisArg, _2); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; } - module2.exports = setup; + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; } -}); - -// node_modules/debug/src/browser.js -var require_browser = __commonJS({ - "node_modules/debug/src/browser.js"(exports2, module2) { - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load2; - exports2.useColors = useColors; - exports2.storage = localstorage(); - exports2.destroy = /* @__PURE__ */ (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } +} +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} +function __values2(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function() { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error4) { + e = { error: error4 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); }; - })(); - exports2.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - let m; - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 - typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker - typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + if (f) i[n] = f(i[n]); } - function formatArgs(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; - } - index++; - if (match === "%c") { - lastC = index; - } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function(e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function() { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function(v) { + return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; + } : f; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve5, reject) { + v = o[n](v), settle(resolve5, reject, v.done, v.value); }); - args.splice(lastC, 0, c); + }; + } + function settle(resolve5, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve5({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; } - exports2.log = console.debug || console.log || (() => { - }); - function save(namespaces) { - try { - if (namespaces) { - exports2.storage.setItem("debug", namespaces); - } else { - exports2.storage.removeItem("debug"); - } - } catch (error4) { - } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; } - function load2() { - let r; + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { - r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); - } catch (error4) { - } - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; + inner.call(this); + } catch (e) { + return Promise.reject(e); } - return r; - } - function localstorage() { + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { try { - return localStorage; - } catch (error4) { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); } } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error4) { - return "[UnexpectedJSONParseError]: " + error4.message; + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; +var init_tslib_es6 = __esm({ + "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() { + extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + __assign = function() { + __assign = Object.assign || function __assign4(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; + }; + tslib_es6_default = { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values: __values2, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources }; } }); -// node_modules/has-flag/index.js -var require_has_flag = __commonJS({ - "node_modules/has-flag/index.js"(exports2, module2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js +var require_userAgentPlatform = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { "use strict"; - module2.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf("--"); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); - }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getHeaderName = getHeaderName; + exports2.setPlatformSpecificData = setPlatformSpecificData; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var os = tslib_1.__importStar(require("node:os")); + var process2 = tslib_1.__importStar(require("node:process")); + function getHeaderName() { + return "User-Agent"; + } + async function setPlatformSpecificData(map2) { + if (process2 && process2.versions) { + const versions = process2.versions; + if (versions.bun) { + map2.set("Bun", versions.bun); + } else if (versions.deno) { + map2.set("Deno", versions.deno); + } else if (versions.node) { + map2.set("Node", versions.node); + } + } + map2.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`); + } } }); -// node_modules/supports-color/index.js -var require_supports_color = __commonJS({ - "node_modules/supports-color/index.js"(exports2, module2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js +var require_constants8 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { "use strict"; - var os = require("os"); - var tty = require("tty"); - var hasFlag = require_has_flag(); - var { env } = process; - var forceColor; - if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { - forceColor = 0; - } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { - forceColor = 1; - } - if ("FORCE_COLOR" in env) { - if (env.FORCE_COLOR === "true") { - forceColor = 1; - } else if (env.FORCE_COLOR === "false") { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; + exports2.SDK_VERSION = "1.17.0"; + exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js +var require_userAgent = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getUserAgentHeaderName = getUserAgentHeaderName; + exports2.getUserAgentValue = getUserAgentValue; + var userAgentPlatform_js_1 = require_userAgentPlatform(); + var constants_js_1 = require_constants8(); + function getUserAgentString(telemetryInfo) { + const parts = []; + for (const [key, value] of telemetryInfo) { + const token = value ? `${key}/${value}` : key; + parts.push(token); } + return parts.join(" "); } - function translateLevel(level) { - if (level === 0) { - return false; - } + function getUserAgentHeaderName() { + return (0, userAgentPlatform_js_1.getHeaderName)(); + } + async function getUserAgentValue(prefix) { + const runtimeInfo = /* @__PURE__ */ new Map(); + runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); + await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); + const defaultAgent = getUserAgentString(runtimeInfo); + const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; + return userAgentValue; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js +var require_userAgentPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.userAgentPolicyName = void 0; + exports2.userAgentPolicy = userAgentPolicy; + var userAgent_js_1 = require_userAgent(); + var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); + exports2.userAgentPolicyName = "userAgentPolicy"; + function userAgentPolicy(options = {}) { + const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 + name: exports2.userAgentPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(UserAgentHeaderName)) { + request.headers.set(UserAgentHeaderName, await userAgentValue); + } + return next(request); + } }; } - function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } - if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { - return 3; - } - if (hasFlag("color=256")) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === void 0) { - return 0; - } - const min = forceColor || 0; - if (env.TERM === "dumb") { - return min; - } - if (process.platform === "win32") { - const osRelease = os.release().split("."); - if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - return 1; - } - if ("CI" in env) { - if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { - return 1; - } - return min; - } - if ("TEAMCITY_VERSION" in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - if (env.COLORTERM === "truecolor") { - return 3; - } - if ("TERM_PROGRAM" in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (env.TERM_PROGRAM) { - case "iTerm.app": - return version >= 3 ? 3 : 2; - case "Apple_Terminal": - return 2; - } - } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - if ("COLORTERM" in env) { - return 1; - } - return min; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js +var require_typeGuards2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isNodeReadableStream = isNodeReadableStream; + exports2.isWebReadableStream = isWebReadableStream; + exports2.isReadableStream = isReadableStream; + exports2.isBlob = isBlob; + function isNodeReadableStream(x) { + return Boolean(x && typeof x["pipe"] === "function"); } - function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); + function isWebReadableStream(x) { + return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); + } + function isReadableStream(x) { + return isNodeReadableStream(x) || isWebReadableStream(x); + } + function isBlob(x) { + return typeof x.stream === "function"; } - module2.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) - }; } }); -// node_modules/debug/src/node.js -var require_node = __commonJS({ - "node_modules/debug/src/node.js"(exports2, module2) { - var tty = require("tty"); - var util = require("util"); - exports2.init = init; - exports2.log = log; - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load2; - exports2.useColors = useColors; - exports2.destroy = util.deprecate( - () => { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js +var require_file2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRawContent = getRawContent; + exports2.createFileFromStream = createFileFromStream; + exports2.createFile = createFile; + var core_util_1 = require_commonjs2(); + var typeGuards_js_1 = require_typeGuards2(); + var unimplementedMethods = { + arrayBuffer: () => { + throw new Error("Not implemented"); }, - "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." - ); - exports2.colors = [6, 2, 3, 4, 5, 1]; - try { - const supportsColor = require_supports_color(); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports2.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; + slice: () => { + throw new Error("Not implemented"); + }, + text: () => { + throw new Error("Not implemented"); } - } catch (error4) { + }; + var rawContent = Symbol("rawContent"); + function hasRawContent(x) { + return typeof x[rawContent] === "function"; } - exports2.inspectOpts = Object.keys(process.env).filter((key) => { - return /^debug_/i.test(key); - }).reduce((obj, key) => { - const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_2, k) => { - return k.toUpperCase(); - }); - let val2 = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val2)) { - val2 = true; - } else if (/^(no|off|false|disabled)$/i.test(val2)) { - val2 = false; - } else if (val2 === "null") { - val2 = null; + function getRawContent(blob) { + if (hasRawContent(blob)) { + return blob[rawContent](); } else { - val2 = Number(val2); + return blob.stream(); } - obj[prop] = val2; - return obj; - }, {}); - function useColors() { - return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); } - function formatArgs(args) { - const { namespace: name, useColors: useColors2 } = this; - if (useColors2) { - const c = this.color; - const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); - const prefix = ` ${colorCode};1m${name} \x1B[0m`; - args[0] = prefix + args[0].split("\n").join("\n" + prefix); - args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + function createFileFromStream(stream, name, options = {}) { + var _a, _b, _c, _d; + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { + const s = stream(); + if ((0, typeGuards_js_1.isNodeReadableStream)(s)) { + throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); + } + return s; + }, [rawContent]: stream }); + } + function createFile(content, name, options = {}) { + var _a, _b, _c; + if (core_util_1.isNodeLike) { + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); } else { - args[0] = getDate() + name + " " + args[0]; + return new File([content], name, options); } } - function getDate() { - if (exports2.inspectOpts.hideDate) { - return ""; - } - return (/* @__PURE__ */ new Date()).toISOString() + " "; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js +var require_concat = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.concat = concat; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var node_stream_1 = require("node:stream"); + var typeGuards_js_1 = require_typeGuards2(); + var file_js_1 = require_file2(); + function streamAsyncIterator() { + return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { + const reader = this.getReader(); + try { + while (true) { + const { done, value } = yield tslib_1.__await(reader.read()); + if (done) { + return yield tslib_1.__await(void 0); + } + yield yield tslib_1.__await(value); + } + } finally { + reader.releaseLock(); + } + }); } - function log(...args) { - return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + function makeAsyncIterable(webStream) { + if (!webStream[Symbol.asyncIterator]) { + webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); + } + if (!webStream.values) { + webStream.values = streamAsyncIterator.bind(webStream); + } } - function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; + function ensureNodeStream(stream) { + if (stream instanceof ReadableStream) { + makeAsyncIterable(stream); + return node_stream_1.Readable.fromWeb(stream); } else { - delete process.env.DEBUG; + return stream; } } - function load2() { - return process.env.DEBUG; - } - function init(debug4) { - debug4.inspectOpts = {}; - const keys = Object.keys(exports2.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug4.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + function toStream(source) { + if (source instanceof Uint8Array) { + return node_stream_1.Readable.from(Buffer.from(source)); + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return toStream((0, file_js_1.getRawContent)(source)); + } else { + return ensureNodeStream(source); } } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" "); - }; - formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); - }; - } -}); - -// node_modules/debug/src/index.js -var require_src = __commonJS({ - "node_modules/debug/src/index.js"(exports2, module2) { - if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { - module2.exports = require_browser(); - } else { - module2.exports = require_node(); + async function concat(sources) { + return function() { + const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); + return node_stream_1.Readable.from((function() { + return tslib_1.__asyncGenerator(this, arguments, function* () { + var _a, e_1, _b, _c; + for (const stream of streams) { + try { + for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { + _c = stream_1_1.value; + _d = false; + const chunk = _c; + yield yield tslib_1.__await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1)); + } finally { + if (e_1) throw e_1.error; + } + } + } + }); + })()); + }; } } }); -// node_modules/agent-base/dist/helpers.js -var require_helpers3 = __commonJS({ - "node_modules/agent-base/dist/helpers.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js +var require_multipartPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.req = exports2.json = exports2.toBuffer = void 0; - var http = __importStar4(require("http")); - var https2 = __importStar4(require("https")); - async function toBuffer(stream) { - let length = 0; - const chunks = []; - for await (const chunk of stream) { - length += chunk.length; - chunks.push(chunk); + exports2.multipartPolicyName = void 0; + exports2.multipartPolicy = multipartPolicy; + var core_util_1 = require_commonjs2(); + var concat_js_1 = require_concat(); + var typeGuards_js_1 = require_typeGuards2(); + function generateBoundary() { + return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; + } + function encodeHeaders(headers) { + let result = ""; + for (const [key, value] of headers) { + result += `${key}: ${value}\r +`; } - return Buffer.concat(chunks, length); + return result; } - exports2.toBuffer = toBuffer; - async function json2(stream) { - const buf = await toBuffer(stream); - const str2 = buf.toString("utf8"); - try { - return JSON.parse(str2); - } catch (_err) { - const err = _err; - err.message += ` (input: ${str2})`; - throw err; + function getLength(source) { + if (source instanceof Uint8Array) { + return source.byteLength; + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return source.size === -1 ? void 0 : source.size; + } else { + return void 0; } } - exports2.json = json2; - function req(url, opts = {}) { - const href = typeof url === "string" ? url : url.href; - const req2 = (href.startsWith("https:") ? https2 : http).request(url, opts); - const promise = new Promise((resolve5, reject) => { - req2.once("response", resolve5).once("error", reject).end(); - }); - req2.then = promise.then.bind(promise); - return req2; + function getTotalLength(sources) { + let total = 0; + for (const source of sources) { + const partLength = getLength(source); + if (partLength === void 0) { + return void 0; + } else { + total += partLength; + } + } + return total; } - exports2.req = req; - } -}); - -// node_modules/agent-base/dist/index.js -var require_dist2 = __commonJS({ - "node_modules/agent-base/dist/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + async function buildRequestBody(request, parts, boundary) { + const sources = [ + (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"), + ...parts.flatMap((part) => [ + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + part.body, + (0, core_util_1.stringToUint8Array)(`\r +--${boundary}`, "utf-8") + ]), + (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8") + ]; + const contentLength = getTotalLength(sources); + if (contentLength) { + request.headers.set("Content-Length", contentLength); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + request.body = await (0, concat_js_1.concat)(sources); + } + exports2.multipartPolicyName = "multipartPolicy"; + var maxBoundaryLength = 70; + var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); + function assertValidBoundary(boundary) { + if (boundary.length > maxBoundaryLength) { + throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); } - __setModuleDefault4(result, mod); - return result; - }; - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Agent = void 0; - var net = __importStar4(require("net")); - var http = __importStar4(require("http")); - var https_1 = require("https"); - __exportStar4(require_helpers3(), exports2); - var INTERNAL = Symbol("AgentBaseInternalState"); - var Agent = class extends http.Agent { - constructor(opts) { - super(opts); - this[INTERNAL] = {}; + if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { + throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); } - /** - * Determine whether this is an `http` or `https` request. - */ - isSecureEndpoint(options) { - if (options) { - if (typeof options.secureEndpoint === "boolean") { - return options.secureEndpoint; + } + function multipartPolicy() { + return { + name: exports2.multipartPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.multipartBody) { + return next(request); } - if (typeof options.protocol === "string") { - return options.protocol === "https:"; + if (request.body) { + throw new Error("multipartBody and regular body cannot be set at the same time"); } - } - const { stack } = new Error(); - if (typeof stack !== "string") - return false; - return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); - } - // In order to support async signatures in `connect()` and Node's native - // connection pooling in `http.Agent`, the array of sockets for each origin - // has to be updated synchronously. This is so the length of the array is - // accurate when `addRequest()` is next called. We achieve this by creating a - // fake socket and adding it to `sockets[origin]` and incrementing - // `totalSocketCount`. - incrementSockets(name) { - if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { - return null; - } - if (!this.sockets[name]) { - this.sockets[name] = []; - } - const fakeSocket = new net.Socket({ writable: false }); - this.sockets[name].push(fakeSocket); - this.totalSocketCount++; - return fakeSocket; - } - decrementSockets(name, socket) { - if (!this.sockets[name] || socket === null) { - return; - } - const sockets = this.sockets[name]; - const index = sockets.indexOf(socket); - if (index !== -1) { - sockets.splice(index, 1); - this.totalSocketCount--; - if (sockets.length === 0) { - delete this.sockets[name]; + let boundary = request.multipartBody.boundary; + const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; + const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); + if (!parsedHeader) { + throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); } - } - } - // In order to properly update the socket pool, we need to call `getName()` on - // the core `https.Agent` if it is a secureEndpoint. - getName(options) { - const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options); - if (secureEndpoint) { - return https_1.Agent.prototype.getName.call(this, options); - } - return super.getName(options); - } - createSocket(req, options, cb) { - const connectOpts = { - ...options, - secureEndpoint: this.isSecureEndpoint(options) - }; - const name = this.getName(connectOpts); - const fakeSocket = this.incrementSockets(name); - Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { - this.decrementSockets(name, fakeSocket); - if (socket instanceof http.Agent) { - try { - return socket.addRequest(req, connectOpts); - } catch (err) { - return cb(err); - } + const [, contentType, parsedBoundary] = parsedHeader; + if (parsedBoundary && boundary && parsedBoundary !== boundary) { + throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); } - this[INTERNAL].currentSocket = socket; - super.createSocket(req, options, cb); - }, (err) => { - this.decrementSockets(name, fakeSocket); - cb(err); - }); - } - createConnection() { - const socket = this[INTERNAL].currentSocket; - this[INTERNAL].currentSocket = void 0; - if (!socket) { - throw new Error("No socket was returned in the `connect()` function"); - } - return socket; - } - get defaultPort() { - return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); - } - set defaultPort(v) { - if (this[INTERNAL]) { - this[INTERNAL].defaultPort = v; + boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary; + if (boundary) { + assertValidBoundary(boundary); + } else { + boundary = generateBoundary(); + } + request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); + await buildRequestBody(request, request.multipartBody.parts, boundary); + request.multipartBody = void 0; + return next(request); } - } - get protocol() { - return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); - } - set protocol(v) { - if (this[INTERNAL]) { - this[INTERNAL].protocol = v; + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js +var require_decompressResponsePolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.decompressResponsePolicyName = void 0; + exports2.decompressResponsePolicy = decompressResponsePolicy; + exports2.decompressResponsePolicyName = "decompressResponsePolicy"; + function decompressResponsePolicy() { + return { + name: exports2.decompressResponsePolicyName, + async sendRequest(request, next) { + if (request.method !== "HEAD") { + request.headers.set("Accept-Encoding", "gzip,deflate"); + } + return next(request); } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } }; - exports2.Agent = Agent; + exports2.AbortError = AbortError; } }); -// node_modules/https-proxy-agent/dist/parse-proxy-response.js -var require_parse_proxy_response = __commonJS({ - "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs3 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { "use strict"; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.parseProxyResponse = void 0; - var debug_1 = __importDefault4(require_src()); - var debug4 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); - function parseProxyResponse(socket) { + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError2(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js +var require_helpers2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay; + exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; + var abort_controller_1 = require_commonjs3(); + var StandardAbortMessage = "The operation was aborted."; + function delay(delayInMs, value, options) { return new Promise((resolve5, reject) => { - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once("readable", read); - } - function cleanup() { - socket.removeListener("end", onend); - socket.removeListener("error", onerror); - socket.removeListener("readable", read); - } - function onend() { - cleanup(); - debug4("onend"); - reject(new Error("Proxy connection ended before receiving CONNECT response")); - } - function onerror(err) { - cleanup(); - debug4("onerror %o", err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf("\r\n\r\n"); - if (endOfHeaders === -1) { - debug4("have not received end of HTTP headers yet..."); - read(); - return; - } - const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); - const firstLine = headerParts.shift(); - if (!firstLine) { - socket.destroy(); - return reject(new Error("No header received from proxy CONNECT response")); + let timer = void 0; + let onAborted = void 0; + const rejectOnAbort = () => { + return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); } - const firstLineParts = firstLine.split(" "); - const statusCode = +firstLineParts[1]; - const statusText = firstLineParts.slice(2).join(" "); - const headers = {}; - for (const header of headerParts) { - if (!header) - continue; - const firstColon = header.indexOf(":"); - if (firstColon === -1) { - socket.destroy(); - return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); - } - const key = header.slice(0, firstColon).toLowerCase(); - const value = header.slice(firstColon + 1).trimStart(); - const current = headers[key]; - if (typeof current === "string") { - headers[key] = [current, value]; - } else if (Array.isArray(current)) { - current.push(value); - } else { - headers[key] = value; - } + }; + onAborted = () => { + if (timer) { + clearTimeout(timer); } - debug4("got proxy server response: %o %o", firstLine, headers); - cleanup(); - resolve5({ - connect: { - statusCode, - statusText, - headers - }, - buffered - }); + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve5(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); } - socket.on("error", onerror); - socket.on("end", onend); - read(); }); } - exports2.parseProxyResponse = parseProxyResponse; + function parseHeaderValueAsNumber(response, headerName) { + const value = response.headers.get(headerName); + if (!value) + return; + const valueAsNum = Number(value); + if (Number.isNaN(valueAsNum)) + return; + return valueAsNum; + } } }); -// node_modules/https-proxy-agent/dist/index.js -var require_dist3 = __commonJS({ - "node_modules/https-proxy-agent/dist/index.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js +var require_throttlingRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpsProxyAgent = void 0; - var net = __importStar4(require("net")); - var tls = __importStar4(require("tls")); - var assert_1 = __importDefault4(require("assert")); - var debug_1 = __importDefault4(require_src()); - var agent_base_1 = require_dist2(); - var url_1 = require("url"); - var parse_proxy_response_1 = require_parse_proxy_response(); - var debug4 = (0, debug_1.default)("https-proxy-agent"); - var setServernameFromNonIpHost = (options) => { - if (options.servername === void 0 && options.host && !net.isIP(options.host)) { - return { - ...options, - servername: options.host - }; - } - return options; - }; - var HttpsProxyAgent = class extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.options = { path: void 0 }; - this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug4("Creating new HttpsProxyAgent instance: %o", this.proxy.href); - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); - const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; - this.connectOpts = { - // Attempt to negotiate http/1.1 for proxy servers that support http/2 - ALPNProtocols: ["http/1.1"], - ...opts ? omit(opts, "headers") : null, - host, - port - }; + exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; + exports2.throttlingRetryStrategy = throttlingRetryStrategy; + var helpers_js_1 = require_helpers2(); + var RetryAfterHeader = "Retry-After"; + var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; + function getRetryAfterInMs(response) { + if (!(response && [429, 503].includes(response.status))) + return void 0; + try { + for (const header of AllRetryAfterHeaders) { + const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); + if (retryAfterValue === 0 || retryAfterValue) { + const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; + return retryAfterValue * multiplyingFactor; + } + } + const retryAfterHeader = response.headers.get(RetryAfterHeader); + if (!retryAfterHeader) + return; + const date = Date.parse(retryAfterHeader); + const diff = date - Date.now(); + return Number.isFinite(diff) ? Math.max(0, diff) : void 0; + } catch (_a) { + return void 0; } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - */ - async connect(req, opts) { - const { proxy } = this; - if (!opts.host) { - throw new TypeError('No "host" provided'); + } + function isThrottlingRetryResponse(response) { + return Number.isFinite(getRetryAfterInMs(response)); + } + function throttlingRetryStrategy() { + return { + name: "throttlingRetryStrategy", + retry({ response }) { + const retryAfterInMs = getRetryAfterInMs(response); + if (!Number.isFinite(retryAfterInMs)) { + return { skipStrategy: true }; + } + return { + retryAfterInMs + }; } - let socket; - if (proxy.protocol === "https:") { - debug4("Creating `tls.Socket`: %o", this.connectOpts); - socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); - } else { - debug4("Creating `net.Socket`: %o", this.connectOpts); - socket = net.connect(this.connectOpts); - } - const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; - const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; - let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r -`; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; - } - headers.Host = `${host}:${opts.port}`; - if (!headers["Proxy-Connection"]) { - headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; - } - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r -`; - } - const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); - socket.write(`${payload}\r -`); - const { connect, buffered } = await proxyResponsePromise; - req.emit("proxyConnect", connect); - this.emit("proxyConnect", connect, req); - if (connect.statusCode === 200) { - req.once("socket", resume); - if (opts.secureEndpoint) { - debug4("Upgrading socket connection to TLS"); - return tls.connect({ - ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), - socket - }); - } - return socket; - } - socket.destroy(); - const fakeSocket = new net.Socket({ writable: false }); - fakeSocket.readable = true; - req.once("socket", (s) => { - debug4("Replaying proxy buffer for failed request"); - (0, assert_1.default)(s.listenerCount("data") > 0); - s.push(buffered); - s.push(null); - }); - return fakeSocket; - } - }; - HttpsProxyAgent.protocols = ["http", "https"]; - exports2.HttpsProxyAgent = HttpsProxyAgent; - function resume(socket) { - socket.resume(); - } - function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - } -}); - -// node_modules/http-proxy-agent/dist/index.js -var require_dist4 = __commonJS({ - "node_modules/http-proxy-agent/dist/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpProxyAgent = void 0; - var net = __importStar4(require("net")); - var tls = __importStar4(require("tls")); - var debug_1 = __importDefault4(require_src()); - var events_1 = require("events"); - var agent_base_1 = require_dist2(); - var url_1 = require("url"); - var debug4 = (0, debug_1.default)("http-proxy-agent"); - var HttpProxyAgent = class extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug4("Creating new HttpProxyAgent instance: %o", this.proxy.href); - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); - const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; - this.connectOpts = { - ...opts ? omit(opts, "headers") : null, - host, - port - }; - } - addRequest(req, opts) { - req._header = null; - this.setRequestProps(req, opts); - super.addRequest(req, opts); - } - setRequestProps(req, opts) { - const { proxy } = this; - const protocol = opts.secureEndpoint ? "https:" : "http:"; - const hostname = req.getHeader("host") || "localhost"; - const base = `${protocol}//${hostname}`; - const url = new url_1.URL(req.path, base); - if (opts.port !== 80) { - url.port = String(opts.port); - } - req.path = String(url); - const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; - } - if (!headers["Proxy-Connection"]) { - headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; - } - for (const name of Object.keys(headers)) { - const value = headers[name]; - if (value) { - req.setHeader(name, value); - } - } - } - async connect(req, opts) { - req._header = null; - if (!req.path.includes("://")) { - this.setRequestProps(req, opts); - } - let first; - let endOfHeaders; - debug4("Regenerating stored HTTP header string for request"); - req._implicitHeader(); - if (req.outputData && req.outputData.length > 0) { - debug4("Patching connection write() output buffer with updated header"); - first = req.outputData[0].data; - endOfHeaders = first.indexOf("\r\n\r\n") + 4; - req.outputData[0].data = req._header + first.substring(endOfHeaders); - debug4("Output buffer: %o", req.outputData[0].data); - } - let socket; - if (this.proxy.protocol === "https:") { - debug4("Creating `tls.Socket`: %o", this.connectOpts); - socket = tls.connect(this.connectOpts); - } else { - debug4("Creating `net.Socket`: %o", this.connectOpts); - socket = net.connect(this.connectOpts); - } - await (0, events_1.once)(socket, "connect"); - return socket; - } - }; - HttpProxyAgent.protocols = ["http", "https"]; - exports2.HttpProxyAgent = HttpProxyAgent; - function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; + }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js -var require_proxyPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js +var require_exponentialRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; - exports2.loadNoProxy = loadNoProxy; - exports2.getDefaultProxySettings = getDefaultProxySettings; - exports2.proxyPolicy = proxyPolicy; - var https_proxy_agent_1 = require_dist3(); - var http_proxy_agent_1 = require_dist4(); - var log_js_1 = require_log(); - var HTTPS_PROXY = "HTTPS_PROXY"; - var HTTP_PROXY = "HTTP_PROXY"; - var ALL_PROXY = "ALL_PROXY"; - var NO_PROXY = "NO_PROXY"; - exports2.proxyPolicyName = "proxyPolicy"; - exports2.globalNoProxyList = []; - var noProxyListLoaded = false; - var globalBypassedMap = /* @__PURE__ */ new Map(); - function getEnvironmentValue(name) { - if (process.env[name]) { - return process.env[name]; - } else if (process.env[name.toLowerCase()]) { - return process.env[name.toLowerCase()]; - } - return void 0; - } - function loadEnvironmentProxyValue() { - if (!process) { - return void 0; - } - const httpsProxy = getEnvironmentValue(HTTPS_PROXY); - const allProxy = getEnvironmentValue(ALL_PROXY); - const httpProxy = getEnvironmentValue(HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; - } - function isBypassed(uri, noProxyList, bypassedMap) { - if (noProxyList.length === 0) { - return false; - } - const host = new URL(uri).hostname; - if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { - return bypassedMap.get(host); - } - let isBypassedFlag = false; - for (const pattern of noProxyList) { - if (pattern[0] === ".") { - if (host.endsWith(pattern)) { - isBypassedFlag = true; - } else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } + exports2.exponentialRetryStrategy = exponentialRetryStrategy; + exports2.isExponentialRetryResponse = isExponentialRetryResponse; + exports2.isSystemError = isSystemError; + var core_util_1 = require_commonjs2(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; + var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; + function exponentialRetryStrategy(options = {}) { + var _a, _b; + const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; + const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + let retryAfterInMs = retryInterval; + return { + name: "exponentialRetryStrategy", + retry({ retryCount, response, responseError }) { + const matchedSystemError = isSystemError(responseError); + const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; + const isExponential = isExponentialRetryResponse(response); + const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; + const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); + if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { + return { skipStrategy: true }; } - } else { - if (host === pattern) { - isBypassedFlag = true; + if (responseError && !matchedSystemError && !isExponential) { + return { errorToThrow: responseError }; } + const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); + const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); + retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2); + return { retryAfterInMs }; } - } - bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); - return isBypassedFlag; - } - function loadNoProxy() { - const noProxy = getEnvironmentValue(NO_PROXY); - noProxyListLoaded = true; - if (noProxy) { - return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); - } - return []; - } - function getDefaultProxySettings(proxyUrl) { - if (!proxyUrl) { - proxyUrl = loadEnvironmentProxyValue(); - if (!proxyUrl) { - return void 0; - } - } - const parsedUrl = new URL(proxyUrl); - const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; - return { - host: schema2 + parsedUrl.hostname, - port: Number.parseInt(parsedUrl.port || "80"), - username: parsedUrl.username, - password: parsedUrl.password }; } - function getDefaultProxySettingsInternal() { - const envProxy = loadEnvironmentProxyValue(); - return envProxy ? new URL(envProxy) : void 0; - } - function getUrlFromProxySettings(settings) { - let parsedProxyUrl; - try { - parsedProxyUrl = new URL(settings.host); - } catch (_a) { - throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); - } - parsedProxyUrl.port = String(settings.port); - if (settings.username) { - parsedProxyUrl.username = settings.username; - } - if (settings.password) { - parsedProxyUrl.password = settings.password; - } - return parsedProxyUrl; - } - function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { - if (request.agent) { - return; - } - const url = new URL(request.url); - const isInsecure = url.protocol !== "https:"; - if (request.tlsSettings) { - log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); - } - const headers = request.headers.toJSON(); - if (isInsecure) { - if (!cachedAgents.httpProxyAgent) { - cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpProxyAgent; - } else { - if (!cachedAgents.httpsProxyAgent) { - cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpsProxyAgent; - } + function isExponentialRetryResponse(response) { + return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); } - function proxyPolicy(proxySettings, options) { - if (!noProxyListLoaded) { - exports2.globalNoProxyList.push(...loadNoProxy()); + function isSystemError(err) { + if (!err) { + return false; } - const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); - const cachedAgents = {}; - return { - name: exports2.proxyPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) { - setProxyAgentOnRequest(request, cachedAgents, defaultProxy); - } else if (request.proxySettings) { - setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); - } - return next(request); - } - }; + return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js -var require_setClientRequestIdPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js +var require_retryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.setClientRequestIdPolicyName = void 0; - exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; - exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; - function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + exports2.retryPolicy = retryPolicy; + var helpers_js_1 = require_helpers2(); + var logger_1 = require_dist(); + var abort_controller_1 = require_commonjs3(); + var constants_js_1 = require_constants8(); + var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); + var retryPolicyName = "retryPolicy"; + function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { + const logger = options.logger || retryPolicyLogger; return { - name: exports2.setClientRequestIdPolicyName, + name: retryPolicyName, async sendRequest(request, next) { - if (!request.headers.has(requestIdHeaderName)) { - request.headers.set(requestIdHeaderName, request.requestId); + var _a, _b; + let response; + let responseError; + let retryCount = -1; + retryRequest: while (true) { + retryCount += 1; + response = void 0; + responseError = void 0; + try { + logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); + response = await next(request); + logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); + } catch (e) { + logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); + responseError = e; + if (!e || responseError.name !== "RestError") { + throw e; + } + response = responseError.response; + } + if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + logger.error(`Retry ${retryCount}: Request aborted.`); + const abortError = new abort_controller_1.AbortError(); + throw abortError; + } + if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { + logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + if (responseError) { + throw responseError; + } else if (response) { + return response; + } else { + throw new Error("Maximum retries reached with no response or error to throw"); + } + } + logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + strategiesLoop: for (const strategy of strategies) { + const strategyLogger = strategy.logger || retryPolicyLogger; + strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); + const modifiers = strategy.retry({ + retryCount, + response, + responseError + }); + if (modifiers.skipStrategy) { + strategyLogger.info(`Retry ${retryCount}: Skipped.`); + continue strategiesLoop; + } + const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; + if (errorToThrow) { + strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); + throw errorToThrow; + } + if (retryAfterInMs || retryAfterInMs === 0) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); + await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); + continue retryRequest; + } + if (redirectTo) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); + request.url = redirectTo; + continue retryRequest; + } + } + if (responseError) { + logger.info(`None of the retry strategies could work with the received error. Throwing it.`); + throw responseError; + } + if (response) { + logger.info(`None of the retry strategies could work with the received response. Returning it.`); + return response; + } } - return next(request); } }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js -var require_tlsPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js +var require_defaultRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tlsPolicyName = void 0; - exports2.tlsPolicy = tlsPolicy; - exports2.tlsPolicyName = "tlsPolicy"; - function tlsPolicy(tlsSettings) { + exports2.defaultRetryPolicyName = void 0; + exports2.defaultRetryPolicy = defaultRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.defaultRetryPolicyName = "defaultRetryPolicy"; + function defaultRetryPolicy(options = {}) { + var _a; return { - name: exports2.tlsPolicyName, - sendRequest: async (req, next) => { - if (!req.tlsSettings) { - req.tlsSettings = tlsSettings; - } - return next(req); - } + name: exports2.defaultRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest }; } } }); -// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js -var require_tracingContext = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js +var require_httpHeaders = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0; - exports2.knownContextKeys = { - span: Symbol.for("@azure/core-tracing span"), - namespace: Symbol.for("@azure/core-tracing namespace") - }; - function createTracingContext(options = {}) { - let context2 = new TracingContextImpl(options.parentContext); - if (options.span) { - context2 = context2.setValue(exports2.knownContextKeys.span, options.span); - } - if (options.namespace) { - context2 = context2.setValue(exports2.knownContextKeys.namespace, options.namespace); - } - return context2; + exports2.createHttpHeaders = createHttpHeaders; + function normalizeName(name) { + return name.toLowerCase(); } - exports2.createTracingContext = createTracingContext; - var TracingContextImpl = class _TracingContextImpl { - constructor(initialContext) { - this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); - } - setValue(key, value) { - const newContext = new _TracingContextImpl(this); - newContext._contextMap.set(key, value); - return newContext; - } - getValue(key) { - return this._contextMap.get(key); - } - deleteValue(key) { - const newContext = new _TracingContextImpl(this); - newContext._contextMap.delete(key); - return newContext; + function* headerIterator(map2) { + for (const entry of map2.values()) { + yield [entry.name, entry.value]; } - }; - exports2.TracingContextImpl = TracingContextImpl; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/state.js -var require_state = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.state = void 0; - exports2.state = { - instrumenterImplementation: void 0 - }; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js -var require_instrumenter = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0; - var tracingContext_js_1 = require_tracingContext(); - var state_js_1 = require_state(); - function createDefaultTracingSpan() { - return { - end: () => { - }, - isRecording: () => false, - recordException: () => { - }, - setAttribute: () => { - }, - setStatus: () => { - } - }; } - exports2.createDefaultTracingSpan = createDefaultTracingSpan; - function createDefaultInstrumenter() { - return { - createRequestHeaders: () => { - return {}; - }, - parseTraceparentHeader: () => { - return void 0; - }, - startSpan: (_name, spanOptions) => { - return { - span: createDefaultTracingSpan(), - tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }) - }; - }, - withContext(_context, callback, ...callbackArgs) { - return callback(...callbackArgs); + var HttpHeadersImpl = class { + constructor(rawHeaders) { + this._headersMap = /* @__PURE__ */ new Map(); + if (rawHeaders) { + for (const headerName of Object.keys(rawHeaders)) { + this.set(headerName, rawHeaders[headerName]); + } } - }; - } - exports2.createDefaultInstrumenter = createDefaultInstrumenter; - function useInstrumenter(instrumenter) { - state_js_1.state.instrumenterImplementation = instrumenter; - } - exports2.useInstrumenter = useInstrumenter; - function getInstrumenter() { - if (!state_js_1.state.instrumenterImplementation) { - state_js_1.state.instrumenterImplementation = createDefaultInstrumenter(); } - return state_js_1.state.instrumenterImplementation; - } - exports2.getInstrumenter = getInstrumenter; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js -var require_tracingClient = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTracingClient = void 0; - var instrumenter_js_1 = require_instrumenter(); - var tracingContext_js_1 = require_tracingContext(); - function createTracingClient(options) { - const { namespace, packageName, packageVersion } = options; - function startSpan(name, operationOptions, spanOptions) { - var _a; - const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); - let tracingContext = startSpanResult.tracingContext; - const span = startSpanResult.span; - if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { - tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace); - } - span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); - const updatedOptions = Object.assign({}, operationOptions, { - tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }) - }); - return { - span, - updatedOptions - }; + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param name - The name of the header to set. This value is case-insensitive. + * @param value - The value of the header to set. + */ + set(name, value) { + this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); } - async function withSpan(name, operationOptions, callback, spanOptions) { - const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); - try { - const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); - span.setStatus({ status: "success" }); - return result; - } catch (err) { - span.setStatus({ status: "error", error: err }); - throw err; - } finally { - span.end(); - } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param name - The name of the header. This value is case-insensitive. + */ + get(name) { + var _a; + return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; } - function withContext(context2, callback, ...callbackArgs) { - return (0, instrumenter_js_1.getInstrumenter)().withContext(context2, callback, ...callbackArgs); + /** + * Get whether or not this header collection contains a header entry for the provided header name. + * @param name - The name of the header to set. This value is case-insensitive. + */ + has(name) { + return this._headersMap.has(normalizeName(name)); } - function parseTraceparentHeader(traceparentHeader) { - return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader); + /** + * Remove the header with the provided headerName. + * @param name - The name of the header to remove. + */ + delete(name) { + this._headersMap.delete(normalizeName(name)); } - function createRequestHeaders(tracingContext) { - return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext); + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJSON(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const entry of this._headersMap.values()) { + result[entry.name] = entry.value; + } + } else { + for (const [normalizedName, entry] of this._headersMap) { + result[normalizedName] = entry.value; + } + } + return result; } - return { - startSpan, - withSpan, - withContext, - parseTraceparentHeader, - createRequestHeaders - }; - } - exports2.createTracingClient = createTracingClient; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/index.js -var require_commonjs4 = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTracingClient = exports2.useInstrumenter = void 0; - var instrumenter_js_1 = require_instrumenter(); - Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() { - return instrumenter_js_1.useInstrumenter; - } }); - var tracingClient_js_1 = require_tracingClient(); - Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() { - return tracingClient_js_1.createTracingClient; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js -var require_inspect = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.custom = void 0; - var node_util_1 = require("node:util"); - exports2.custom = node_util_1.inspect.custom; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js -var require_restError = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RestError = void 0; - exports2.isRestError = isRestError; - var core_util_1 = require_commonjs2(); - var inspect_js_1 = require_inspect(); - var sanitizer_js_1 = require_sanitizer(); - var errorSanitizer = new sanitizer_js_1.Sanitizer(); - var RestError = class _RestError extends Error { - constructor(message, options = {}) { - super(message); - this.name = "RestError"; - this.code = options.code; - this.statusCode = options.statusCode; - Object.defineProperty(this, "request", { value: options.request, enumerable: false }); - Object.defineProperty(this, "response", { value: options.response, enumerable: false }); - Object.setPrototypeOf(this, _RestError.prototype); + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJSON({ preserveCase: true })); } /** - * Logging method for util.inspect in Node + * Iterate over tuples of header [name, value] pairs. */ - [inspect_js_1.custom]() { - return `RestError: ${this.message} - ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; + [Symbol.iterator]() { + return headerIterator(this._headersMap); } }; - exports2.RestError = RestError; - RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; - RestError.PARSE_ERROR = "PARSE_ERROR"; - function isRestError(e) { - if (e instanceof RestError) { - return true; - } - return (0, core_util_1.isError)(e) && e.name === "RestError"; + function createHttpHeaders(rawHeaders) { + return new HttpHeadersImpl(rawHeaders); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js -var require_tracingPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js +var require_formDataPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tracingPolicyName = void 0; - exports2.tracingPolicy = tracingPolicy; - var core_tracing_1 = require_commonjs4(); - var constants_js_1 = require_constants8(); - var userAgent_js_1 = require_userAgent(); - var log_js_1 = require_log(); + exports2.formDataPolicyName = void 0; + exports2.formDataPolicy = formDataPolicy; var core_util_1 = require_commonjs2(); - var restError_js_1 = require_restError(); - var sanitizer_js_1 = require_sanitizer(); - exports2.tracingPolicyName = "tracingPolicy"; - function tracingPolicy(options = {}) { - const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - const tracingClient = tryCreateTracingClient(); + var httpHeaders_js_1 = require_httpHeaders(); + exports2.formDataPolicyName = "formDataPolicy"; + function formDataToFormDataMap(formData) { + var _a; + const formDataMap = {}; + for (const [key, value] of formData.entries()) { + (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = []; + formDataMap[key].push(value); + } + return formDataMap; + } + function formDataPolicy() { return { - name: exports2.tracingPolicyName, + name: exports2.formDataPolicyName, async sendRequest(request, next) { - var _a; - if (!tracingClient) { - return next(request); - } - const userAgent = await userAgentPromise; - const spanAttributes = { - "http.url": sanitizer.sanitizeUrl(request.url), - "http.method": request.method, - "http.user_agent": userAgent, - requestId: request.requestId - }; - if (userAgent) { - spanAttributes["http.user_agent"] = userAgent; - } - const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; - if (!span || !tracingContext) { - return next(request); + if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { + request.formData = formDataToFormDataMap(request.body); + request.body = void 0; } - try { - const response = await tracingClient.withContext(tracingContext, next, request); - tryProcessResponse(span, response); - return response; - } catch (err) { - tryProcessError(span, err); - throw err; + if (request.formData) { + const contentType = request.headers.get("Content-Type"); + if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { + request.body = wwwFormUrlEncode(request.formData); + } else { + await prepareFormData(request.formData, request); + } + request.formData = void 0; } + return next(request); } }; } - function tryCreateTracingClient() { - try { - return (0, core_tracing_1.createTracingClient)({ - namespace: "", - packageName: "@azure/core-rest-pipeline", - packageVersion: constants_js_1.SDK_VERSION - }); - } catch (e) { - log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); - return void 0; - } - } - function tryCreateSpan(tracingClient, request, spanAttributes) { - try { - const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { - spanKind: "client", - spanAttributes - }); - if (!span.isRecording()) { - span.end(); - return void 0; - } - const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); - for (const [key, value] of Object.entries(headers)) { - request.headers.set(key, value); + function wwwFormUrlEncode(formData) { + const urlSearchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(formData)) { + if (Array.isArray(value)) { + for (const subValue of value) { + urlSearchParams.append(key, subValue.toString()); + } + } else { + urlSearchParams.append(key, value.toString()); } - return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; - } catch (e) { - log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); - return void 0; } + return urlSearchParams.toString(); } - function tryProcessError(span, error4) { - try { - span.setStatus({ - status: "error", - error: (0, core_util_1.isError)(error4) ? error4 : void 0 - }); - if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) { - span.setAttribute("http.status_code", error4.statusCode); - } - span.end(); - } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + async function prepareFormData(formData, request) { + const contentType = request.headers.get("Content-Type"); + if (contentType && !contentType.startsWith("multipart/form-data")) { + return; } - } - function tryProcessResponse(span, response) { - try { - span.setAttribute("http.status_code", response.status); - const serviceRequestId = response.headers.get("x-ms-request-id"); - if (serviceRequestId) { - span.setAttribute("serviceRequestId", serviceRequestId); + request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); + const parts = []; + for (const [fieldName, values] of Object.entries(formData)) { + for (const value of Array.isArray(values) ? values : [values]) { + if (typeof value === "string") { + parts.push({ + headers: (0, httpHeaders_js_1.createHttpHeaders)({ + "Content-Disposition": `form-data; name="${fieldName}"` + }), + body: (0, core_util_1.stringToUint8Array)(value, "utf-8") + }); + } else if (value === void 0 || value === null || typeof value !== "object") { + throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); + } else { + const fileName = value.name || "blob"; + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); + headers.set("Content-Type", value.type || "application/octet-stream"); + parts.push({ + headers, + body: value + }); + } } - span.setStatus({ - status: "success" - }); - span.end(); - } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); } + request.multipartBody = { parts }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js -var require_createPipelineFromOptions = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineFromOptions = createPipelineFromOptions; - var logPolicy_js_1 = require_logPolicy(); - var pipeline_js_1 = require_pipeline(); - var redirectPolicy_js_1 = require_redirectPolicy(); - var userAgentPolicy_js_1 = require_userAgentPolicy(); - var multipartPolicy_js_1 = require_multipartPolicy(); - var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); - var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); - var formDataPolicy_js_1 = require_formDataPolicy(); - var core_util_1 = require_commonjs2(); - var proxyPolicy_js_1 = require_proxyPolicy(); - var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); - var tlsPolicy_js_1 = require_tlsPolicy(); - var tracingPolicy_js_1 = require_tracingPolicy(); - function createPipelineFromOptions(options) { - var _a; - const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); - if (core_util_1.isNodeLike) { - if (options.tlsOptions) { - pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); - } - pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); - pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); +// node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/ms/index.js"(exports2, module2) { + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module2.exports = function(val2, options) { + options = options || {}; + var type2 = typeof val2; + if (type2 === "string" && val2.length > 0) { + return parse(val2); + } else if (type2 === "number" && isFinite(val2)) { + return options.long ? fmtLong(val2) : fmtShort(val2); } - pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); - pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); - pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); - pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); - pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); - pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { - afterPhase: "Retry" - }); - if (core_util_1.isNodeLike) { - pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2) + ); + }; + function parse(str2) { + str2 = String(str2); + if (str2.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str2 + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type2 = (match[2] || "ms").toLowerCase(); + switch (type2) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; } - pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); - return pipeline; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js -var require_nodeHttpClient = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getBodyLength = getBodyLength; - exports2.createNodeHttpClient = createNodeHttpClient; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var http = tslib_1.__importStar(require("node:http")); - var https2 = tslib_1.__importStar(require("node:https")); - var zlib = tslib_1.__importStar(require("node:zlib")); - var node_stream_1 = require("node:stream"); - var abort_controller_1 = require_commonjs3(); - var httpHeaders_js_1 = require_httpHeaders(); - var restError_js_1 = require_restError(); - var log_js_1 = require_log(); - var DEFAULT_TLS_SETTINGS = {}; - function isReadableStream(body) { - return body && typeof body.pipe === "function"; - } - function isStreamComplete(stream) { - return new Promise((resolve5) => { - const handler = () => { - resolve5(); - stream.removeListener("close", handler); - stream.removeListener("end", handler); - stream.removeListener("error", handler); - }; - stream.on("close", handler); - stream.on("end", handler); - stream.on("error", handler); - }); } - function isArrayBuffer(body) { - return body && typeof body.byteLength === "number"; + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; } - var ReportTransform = class extends node_stream_1.Transform { - // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type - _transform(chunk, _encoding, callback) { - this.push(chunk); - this.loadedBytes += chunk.length; - try { - this.progressCallback({ loadedBytes: this.loadedBytes }); - callback(); - } catch (e) { - callback(e); - } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); } - constructor(progressCallback) { - super(); - this.loadedBytes = 0; - this.progressCallback = progressCallback; + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); } - }; - var NodeHttpClient = class { - constructor() { - this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); } - /** - * Makes a request over an underlying transport layer and returns the response. - * @param request - The request to be made. - */ - async sendRequest(request) { - var _a, _b, _c; - const abortController = new AbortController(); - let abortListener; - if (request.abortSignal) { - if (request.abortSignal.aborted) { - throw new abort_controller_1.AbortError("The operation was aborted."); - } - abortListener = (event) => { - if (event.type === "abort") { - abortController.abort(); - } - }; - request.abortSignal.addEventListener("abort", abortListener); - } - if (request.timeout > 0) { - setTimeout(() => { - abortController.abort(); - }, request.timeout); - } - const acceptEncoding = request.headers.get("Accept-Encoding"); - const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); - let body = typeof request.body === "function" ? request.body() : request.body; - if (body && !request.headers.has("Content-Length")) { - const bodyLength = getBodyLength(body); - if (bodyLength !== null) { - request.headers.set("Content-Length", bodyLength); - } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/debug/src/common.js +var require_common = __commonJS({ + "node_modules/debug/src/common.js"(exports2, module2) { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce3; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; } - let responseStream; - try { - if (body && request.onUploadProgress) { - const onUploadProgress = request.onUploadProgress; - const uploadReportStream = new ReportTransform(onUploadProgress); - uploadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in upload progress", e); - }); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } else { - uploadReportStream.end(body); - } - body = uploadReportStream; - } - const res = await this.makeRequest(request, abortController, body); - const headers = getResponseHeaders(res); - const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; - const response = { - status, - headers, - request - }; - if (request.method === "HEAD") { - res.resume(); - return response; - } - responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; - const onDownloadProgress = request.onDownloadProgress; - if (onDownloadProgress) { - const downloadReportStream = new ReportTransform(onDownloadProgress); - downloadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in download progress", e); - }); - responseStream.pipe(downloadReportStream); - responseStream = downloadReportStream; + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug4(...args) { + if (!debug4.enabled) { + return; } - if ( - // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code - ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status)) - ) { - response.readableStreamBody = responseStream; - } else { - response.bodyAsText = await streamToText(responseStream); + const self2 = debug4; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); } - return response; - } finally { - if (request.abortSignal && abortListener) { - let uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; } - let downloadStreamDone = Promise.resolve(); - if (isReadableStream(responseStream)) { - downloadStreamDone = isStreamComplete(responseStream); + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val2 = args[index]; + match = formatter.call(self2, val2); + args.splice(index, 1); + index--; } - Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { - var _a2; - if (abortListener) { - (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener); - } - }).catch((e) => { - log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); - }); + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug4.namespace = namespace; + debug4.useColors = createDebug.useColors(); + debug4.color = createDebug.selectColor(namespace); + debug4.extend = extend3; + debug4.destroy = createDebug.destroy; + Object.defineProperty(debug4, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug4); } + return debug4; } - makeRequest(request, abortController, body) { - var _a; - const url = new URL(request.url); - const isInsecure = url.protocol !== "https:"; - if (isInsecure && !request.allowInsecureConnection) { - throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + function extend3(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } } - const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); - const options = { - agent, - hostname: url.hostname, - path: `${url.pathname}${url.search}`, - port: url.port, - method: request.method, - headers: request.headers.toJSON({ preserveCase: true }) - }; - return new Promise((resolve5, reject) => { - const req = isInsecure ? http.request(options, resolve5) : https2.request(options, resolve5); - req.once("error", (err) => { - var _a2; - reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); - }); - abortController.signal.addEventListener("abort", () => { - const abortError = new abort_controller_1.AbortError("The operation was aborted."); - req.destroy(abortError); - reject(abortError); - }); - if (body && isReadableStream(body)) { - body.pipe(req); - } else if (body) { - if (typeof body === "string" || Buffer.isBuffer(body)) { - req.end(body); - } else if (isArrayBuffer(body)) { - req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; } else { - log_js_1.logger.error("Unrecognized body type", body); - reject(new restError_js_1.RestError("Unrecognized body type")); + searchIndex++; + templateIndex++; } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; } else { - req.end(); + return false; } - }); + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; } - getOrCreateAgent(request, isInsecure) { - var _a; - const disableKeepAlive = request.disableKeepAlive; - if (isInsecure) { - if (disableKeepAlive) { - return http.globalAgent; - } - if (!this.cachedHttpAgent) { - this.cachedHttpAgent = new http.Agent({ keepAlive: true }); - } - return this.cachedHttpAgent; - } else { - if (disableKeepAlive && !request.tlsSettings) { - return https2.globalAgent; - } - const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; - let agent = this.cachedHttpsAgents.get(tlsSettings); - if (agent && agent.options.keepAlive === !disableKeepAlive) { - return agent; + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; } - log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); - agent = new https2.Agent(Object.assign({ - // keepAlive is true if disableKeepAlive is false. - keepAlive: !disableKeepAlive - }, tlsSettings)); - this.cachedHttpsAgents.set(tlsSettings, agent); - return agent; } - } - }; - function getResponseHeaders(res) { - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); - for (const header of Object.keys(res.headers)) { - const value = res.headers[header]; - if (Array.isArray(value)) { - if (value.length > 0) { - headers.set(header, value[0]); + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; } - } else if (value) { - headers.set(header, value); } + return false; } - return headers; - } - function getDecodedResponseStream(stream, headers) { - const contentEncoding = headers.get("Content-Encoding"); - if (contentEncoding === "gzip") { - const unzip = zlib.createGunzip(); - stream.pipe(unzip); - return unzip; - } else if (contentEncoding === "deflate") { - const inflate = zlib.createInflate(); - stream.pipe(inflate); - return inflate; + function coerce3(val2) { + if (val2 instanceof Error) { + return val2.stack || val2.message; + } + return val2; } - return stream; - } - function streamToText(stream) { - return new Promise((resolve5, reject) => { - const buffer = []; - stream.on("data", (chunk) => { - if (Buffer.isBuffer(chunk)) { - buffer.push(chunk); - } else { - buffer.push(Buffer.from(chunk)); - } - }); - stream.on("end", () => { - resolve5(Buffer.concat(buffer).toString("utf8")); - }); - stream.on("error", (e) => { - if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { - reject(e); - } else { - reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { - code: restError_js_1.RestError.PARSE_ERROR - })); - } - }); - }); - } - function getBodyLength(body) { - if (!body) { - return 0; - } else if (Buffer.isBuffer(body)) { - return body.length; - } else if (isReadableStream(body)) { - return null; - } else if (isArrayBuffer(body)) { - return body.byteLength; - } else if (typeof body === "string") { - return Buffer.from(body).length; - } else { - return null; + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } + createDebug.enable(createDebug.load()); + return createDebug; } - function createNodeHttpClient() { - return new NodeHttpClient(); - } + module2.exports = setup; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js -var require_defaultHttpClient = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createDefaultHttpClient = createDefaultHttpClient; - var nodeHttpClient_js_1 = require_nodeHttpClient(); - function createDefaultHttpClient() { - return (0, nodeHttpClient_js_1.createNodeHttpClient)(); - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js -var require_pipelineRequest = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineRequest = createPipelineRequest; - var httpHeaders_js_1 = require_httpHeaders(); - var core_util_1 = require_commonjs2(); - var PipelineRequestImpl = class { - constructor(options) { - var _a, _b, _c, _d, _e, _f, _g; - this.url = options.url; - this.body = options.body; - this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); - this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; - this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; - this.multipartBody = options.multipartBody; - this.formData = options.formData; - this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; - this.proxySettings = options.proxySettings; - this.streamResponseStatusCodes = options.streamResponseStatusCodes; - this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; - this.abortSignal = options.abortSignal; - this.tracingOptions = options.tracingOptions; - this.onUploadProgress = options.onUploadProgress; - this.onDownloadProgress = options.onDownloadProgress; - this.requestId = options.requestId || (0, core_util_1.randomUUID)(); - this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; - this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; +// node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/debug/src/browser.js"(exports2, module2) { + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.storage = localstorage(); + exports2.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports2.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; } - }; - function createPipelineRequest(options) { - return new PipelineRequestImpl(options); + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js -var require_exponentialRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryPolicyName = void 0; - exports2.exponentialRetryPolicy = exponentialRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; - function exponentialRetryPolicy(options = {}) { - var _a; - return (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })) - ], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index++; + if (match === "%c") { + lastC = index; + } }); + args.splice(lastC, 0, c); + } + exports2.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports2.storage.setItem("debug", namespaces); + } else { + exports2.storage.removeItem("debug"); + } + } catch (error4) { + } + } + function load2() { + let r; + try { + r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); + } catch (error4) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error4) { + } } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error4) { + return "[UnexpectedJSONParseError]: " + error4.message; + } + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js -var require_systemErrorRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { +// node_modules/has-flag/index.js +var require_has_flag = __commonJS({ + "node_modules/has-flag/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.systemErrorRetryPolicyName = void 0; - exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; - function systemErrorRetryPolicy(options = {}) { - var _a; - return { - name: exports2.systemErrorRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })) - ], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest - }; - } + module2.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js -var require_throttlingRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { +// node_modules/supports-color/index.js +var require_supports_color = __commonJS({ + "node_modules/supports-color/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.throttlingRetryPolicyName = void 0; - exports2.throttlingRetryPolicy = throttlingRetryPolicy; - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; - function throttlingRetryPolicy(options = {}) { - var _a; + var os = require("os"); + var tty = require("tty"); + var hasFlag = require_has_flag(); + var { env } = process; + var forceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { + forceColor = 0; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = 1; + } + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + forceColor = 1; + } else if (env.FORCE_COLOR === "false") { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } return { - name: exports2.throttlingRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 }; } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js -var require_tokenCycler = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_CYCLER_OPTIONS = void 0; - exports2.createTokenCycler = createTokenCycler; - var helpers_js_1 = require_helpers2(); - exports2.DEFAULT_CYCLER_OPTIONS = { - forcedRefreshWindowInMs: 1e3, - // Force waiting for a refresh 1s before the token expires - retryIntervalInMs: 3e3, - // Allow refresh attempts every 3s - refreshWindowInMs: 1e3 * 60 * 2 - // Start refreshing 2m before expiry - }; - async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { - async function tryGetAccessToken() { - if (Date.now() < refreshTimeout) { - try { - return await getAccessToken(); - } catch (_a) { - return null; - } - } else { - const finalToken = await getAccessToken(); - if (finalToken === null) { - throw new Error("Failed to refresh access token."); - } - return finalToken; - } + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; } - let token = await tryGetAccessToken(); - while (token === null) { - await (0, helpers_js_1.delay)(retryIntervalInMs); - token = await tryGetAccessToken(); + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; } - return token; - } - function createTokenCycler(credential, tokenCyclerOptions) { - let refreshWorker = null; - let token = null; - let tenantId; - const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); - const cycler = { - /** - * Produces true if a refresh job is currently in progress. - */ - get isRefreshing() { - return refreshWorker !== null; - }, - /** - * Produces true if the cycler SHOULD refresh (we are within the refresh - * window and not already refreshing) - */ - get shouldRefresh() { - var _a; - if (cycler.isRefreshing) { - return false; - } - if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { - return true; - } - return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); - }, - /** - * Produces true if the cycler MUST refresh (null or nearly-expired - * token). - */ - get mustRefresh() { - return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); - } - }; - function refresh(scopes, getTokenOptions) { - var _a; - if (!cycler.isRefreshing) { - const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); - refreshWorker = beginRefresh( - tryGetAccessToken, - options.retryIntervalInMs, - // If we don't have a token, then we should timeout immediately - (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now() - ).then((_token) => { - refreshWorker = null; - token = _token; - tenantId = getTokenOptions.tenantId; - return token; - }).catch((reason) => { - refreshWorker = null; - token = null; - tenantId = void 0; - throw reason; - }); - } - return refreshWorker; + if (hasFlag("color=256")) { + return 2; } - return async (scopes, tokenOptions) => { - const hasClaimChallenge = Boolean(tokenOptions.claims); - const tenantIdChanged = tenantId !== tokenOptions.tenantId; - if (hasClaimChallenge) { - token = null; + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (process.platform === "win32") { + const osRelease = os.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; } - const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; - if (mustRefresh) { - return refresh(scopes, tokenOptions); + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { + return 1; } - if (cycler.shouldRefresh) { - refresh(scopes, tokenOptions); + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; } - return token; - }; + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; + } + function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); } + module2.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js -var require_bearerTokenAuthenticationPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bearerTokenAuthenticationPolicyName = void 0; - exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log(); - exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; - async function defaultAuthorizeRequest(options) { - const { scopes, getAccessToken, request } = options; - const getTokenOptions = { - abortSignal: request.abortSignal, - tracingOptions: request.tracingOptions - }; - const accessToken = await getAccessToken(scopes, getTokenOptions); - if (accessToken) { - options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); - } - } - function getChallenge(response) { - const challenge = response.headers.get("WWW-Authenticate"); - if (response.status === 401 && challenge) { - return challenge; - } - return; - } - function bearerTokenAuthenticationPolicy(options) { - var _a; - const { credential, scopes, challengeCallbacks } = options; - const logger = options.logger || log_js_1.logger; - const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); - const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( - credential - /* , options */ - ) : () => Promise.resolve(null); - return { - name: exports2.bearerTokenAuthenticationPolicyName, - /** - * If there's no challenge parameter: - * - It will try to retrieve the token using the cache, or the credential's getToken. - * - Then it will try the next policy with or without the retrieved token. - * - * It uses the challenge parameters to: - * - Skip a first attempt to get the token from the credential if there's no cached token, - * since it expects the token to be retrievable only after the challenge. - * - Prepare the outgoing request if the `prepareRequest` method has been provided. - * - Send an initial request to receive the challenge if it fails. - * - Process a challenge if the response contains it. - * - Retrieve a token with the challenge information, then re-send the request. - */ - async sendRequest(request, next) { - if (!request.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); - } - await callbacks.authorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - getAccessToken, - logger - }); - let response; - let error4; - try { - response = await next(request); - } catch (err) { - error4 = err; - response = err.response; - } - if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) { - const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - response, - getAccessToken, - logger - }); - if (shouldSendRequest) { - return next(request); - } - } - if (error4) { - throw error4; - } else { - return response; - } - } - }; +// node_modules/debug/src/node.js +var require_node = __commonJS({ + "node_modules/debug/src/node.js"(exports2, module2) { + var tty = require("tty"); + var util = require("util"); + exports2.init = init; + exports2.log = log; + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.destroy = util.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports2.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports2.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error4) { + } + exports2.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_2, k) => { + return k.toUpperCase(); + }); + let val2 = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val2)) { + val2 = true; + } else if (/^(no|off|false|disabled)$/i.test(val2)) { + val2 = false; + } else if (val2 === "null") { + val2 = null; + } else { + val2 = Number(val2); + } + obj[prop] = val2; + return obj; + }, {}); + function useColors() { + return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + " " + args[0]; + } + } + function getDate() { + if (exports2.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + function log(...args) { + return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load2() { + return process.env.DEBUG; + } + function init(debug4) { + debug4.inspectOpts = {}; + const keys = Object.keys(exports2.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug4.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + } } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js -var require_ndJsonPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { +// node_modules/debug/src/index.js +var require_src = __commonJS({ + "node_modules/debug/src/index.js"(exports2, module2) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module2.exports = require_browser(); + } else { + module2.exports = require_node(); + } + } +}); + +// node_modules/agent-base/dist/helpers.js +var require_helpers3 = __commonJS({ + "node_modules/agent-base/dist/helpers.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ndJsonPolicyName = void 0; - exports2.ndJsonPolicy = ndJsonPolicy; - exports2.ndJsonPolicyName = "ndJsonPolicy"; - function ndJsonPolicy() { - return { - name: exports2.ndJsonPolicyName, - async sendRequest(request, next) { - if (typeof request.body === "string" && request.body.startsWith("[")) { - const body = JSON.parse(request.body); - if (Array.isArray(body)) { - request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); - } - } - return next(request); - } - }; + exports2.req = exports2.json = exports2.toBuffer = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); + } + exports2.toBuffer = toBuffer; + async function json2(stream) { + const buf = await toBuffer(stream); + const str2 = buf.toString("utf8"); + try { + return JSON.parse(str2); + } catch (_err) { + const err = _err; + err.message += ` (input: ${str2})`; + throw err; + } + } + exports2.json = json2; + function req(url, opts = {}) { + const href = typeof url === "string" ? url : url.href; + const req2 = (href.startsWith("https:") ? https2 : http).request(url, opts); + const promise = new Promise((resolve5, reject) => { + req2.once("response", resolve5).once("error", reject).end(); + }); + req2.then = promise.then.bind(promise); + return req2; } + exports2.req = req; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js -var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { +// node_modules/agent-base/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/agent-base/dist/index.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; - exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log(); - exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; - var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; - async function sendAuthorizeRequest(options) { - var _a, _b; - const { scopes, getAccessToken, request } = options; - const getTokenOptions = { - abortSignal: request.abortSignal, - tracingOptions: request.tracingOptions - }; - return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; - } - function auxiliaryAuthenticationHeaderPolicy(options) { - const { credentials, scopes } = options; - const logger = options.logger || log_js_1.logger; - const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); - return { - name: exports2.auxiliaryAuthenticationHeaderPolicyName, - async sendRequest(request, next) { - if (!request.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); + exports2.Agent = void 0; + var net = __importStar4(require("net")); + var http = __importStar4(require("http")); + var https_1 = require("https"); + __exportStar4(require_helpers3(), exports2); + var INTERNAL = Symbol("AgentBaseInternalState"); + var Agent = class extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + if (typeof options.secureEndpoint === "boolean") { + return options.secureEndpoint; } - if (!credentials || credentials.length === 0) { - logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); - return next(request); + if (typeof options.protocol === "string") { + return options.protocol === "https:"; } - const tokenPromises = []; - for (const credential of credentials) { - let getAccessToken = tokenCyclerMap.get(credential); - if (!getAccessToken) { - getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); - tokenCyclerMap.set(credential, getAccessToken); - } - tokenPromises.push(sendAuthorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - getAccessToken, - logger - })); + } + const { stack } = new Error(); + if (typeof stack !== "string") + return false; + return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + if (!this.sockets[name]) { + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + this.totalSocketCount--; + if (sockets.length === 0) { + delete this.sockets[name]; } - const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); - if (auxiliaryTokens.length === 0) { - logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); - return next(request); + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options); + if (secureEndpoint) { + return https_1.Agent.prototype.getName.call(this, options); + } + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options) + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + try { + return socket.addRequest(req, connectOpts); + } catch (err) { + return cb(err); + } } - request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); - return next(request); + this[INTERNAL].currentSocket = socket; + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = void 0; + if (!socket) { + throw new Error("No socket was returned in the `connect()` function"); } - }; - } + return socket; + } + get defaultPort() { + return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } + }; + exports2.Agent = Agent; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js -var require_commonjs5 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { +// node_modules/https-proxy-agent/dist/parse-proxy-response.js +var require_parse_proxy_response = __commonJS({ + "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.parseProxyResponse = void 0; + var debug_1 = __importDefault4(require_src()); + var debug4 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); + function parseProxyResponse(socket) { + return new Promise((resolve5, reject) => { + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once("readable", read); + } + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("readable", read); + } + function onend() { + cleanup(); + debug4("onend"); + reject(new Error("Proxy connection ended before receiving CONNECT response")); + } + function onerror(err) { + cleanup(); + debug4("onerror %o", err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf("\r\n\r\n"); + if (endOfHeaders === -1) { + debug4("have not received end of HTTP headers yet..."); + read(); + return; + } + const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error("No header received from proxy CONNECT response")); + } + const firstLineParts = firstLine.split(" "); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(" "); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(":"); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === "string") { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } + } + debug4("got proxy server response: %o %o", firstLine, headers); + cleanup(); + resolve5({ + connect: { + statusCode, + statusText, + headers + }, + buffered + }); + } + socket.on("error", onerror); + socket.on("end", onend); + read(); + }); + } + exports2.parseProxyResponse = parseProxyResponse; + } +}); + +// node_modules/https-proxy-agent/dist/index.js +var require_dist3 = __commonJS({ + "node_modules/https-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpsProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var assert_1 = __importDefault4(require("assert")); + var debug_1 = __importDefault4(require_src()); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var parse_proxy_response_1 = require_parse_proxy_response(); + var debug4 = (0, debug_1.default)("https-proxy-agent"); + var setServernameFromNonIpHost = (options) => { + if (options.servername === void 0 && options.host && !net.isIP(options.host)) { + return { + ...options, + servername: options.host + }; + } + return options; + }; + var HttpsProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: void 0 }; + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug4("Creating new HttpsProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ["http/1.1"], + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + let socket; + if (proxy.protocol === "https:") { + debug4("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } else { + debug4("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r +`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r +`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r +`); + const { connect, buffered } = await proxyResponsePromise; + req.emit("proxyConnect", connect); + this.emit("proxyConnect", connect, req); + if (connect.statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debug4("Upgrading socket connection to TLS"); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), + socket + }); + } + return socket; + } + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debug4("Replaying proxy buffer for failed request"); + (0, assert_1.default)(s.listenerCount("data") > 0); + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } + }; + HttpsProxyAgent.protocols = ["http", "https"]; + exports2.HttpsProxyAgent = HttpsProxyAgent; + function resume(socket) { + socket.resume(); + } + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + } +}); + +// node_modules/http-proxy-agent/dist/index.js +var require_dist4 = __commonJS({ + "node_modules/http-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var debug_1 = __importDefault4(require_src()); + var events_1 = require("events"); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var debug4 = (0, debug_1.default)("http-proxy-agent"); + var HttpProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug4("Creating new HttpProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + addRequest(req, opts) { + req._header = null; + this.setRequestProps(req, opts); + super.addRequest(req, opts); + } + setRequestProps(req, opts) { + const { proxy } = this; + const protocol = opts.secureEndpoint ? "https:" : "http:"; + const hostname = req.getHeader("host") || "localhost"; + const base = `${protocol}//${hostname}`; + const url = new url_1.URL(req.path, base); + if (opts.port !== 80) { + url.port = String(opts.port); + } + req.path = String(url); + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + const value = headers[name]; + if (value) { + req.setHeader(name, value); + } + } + } + async connect(req, opts) { + req._header = null; + if (!req.path.includes("://")) { + this.setRequestProps(req, opts); + } + let first; + let endOfHeaders; + debug4("Regenerating stored HTTP header string for request"); + req._implicitHeader(); + if (req.outputData && req.outputData.length > 0) { + debug4("Patching connection write() output buffer with updated header"); + first = req.outputData[0].data; + endOfHeaders = first.indexOf("\r\n\r\n") + 4; + req.outputData[0].data = req._header + first.substring(endOfHeaders); + debug4("Output buffer: %o", req.outputData[0].data); + } + let socket; + if (this.proxy.protocol === "https:") { + debug4("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(this.connectOpts); + } else { + debug4("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + await (0, events_1.once)(socket, "connect"); + return socket; + } + }; + HttpProxyAgent.protocols = ["http", "https"]; + exports2.HttpProxyAgent = HttpProxyAgent; + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js +var require_proxyPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; + exports2.loadNoProxy = loadNoProxy; + exports2.getDefaultProxySettings = getDefaultProxySettings; + exports2.proxyPolicy = proxyPolicy; + var https_proxy_agent_1 = require_dist3(); + var http_proxy_agent_1 = require_dist4(); + var log_js_1 = require_log(); + var HTTPS_PROXY = "HTTPS_PROXY"; + var HTTP_PROXY = "HTTP_PROXY"; + var ALL_PROXY = "ALL_PROXY"; + var NO_PROXY = "NO_PROXY"; + exports2.proxyPolicyName = "proxyPolicy"; + exports2.globalNoProxyList = []; + var noProxyListLoaded = false; + var globalBypassedMap = /* @__PURE__ */ new Map(); + function getEnvironmentValue(name) { + if (process.env[name]) { + return process.env[name]; + } else if (process.env[name.toLowerCase()]) { + return process.env[name.toLowerCase()]; + } + return void 0; + } + function loadEnvironmentProxyValue() { + if (!process) { + return void 0; + } + const httpsProxy = getEnvironmentValue(HTTPS_PROXY); + const allProxy = getEnvironmentValue(ALL_PROXY); + const httpProxy = getEnvironmentValue(HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; + } + function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = new URL(uri).hostname; + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } + } else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; + } + function loadNoProxy() { + const noProxy = getEnvironmentValue(NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); + } + return []; + } + function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return void 0; + } + } + const parsedUrl = new URL(proxyUrl); + const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; + return { + host: schema2 + parsedUrl.hostname, + port: Number.parseInt(parsedUrl.port || "80"), + username: parsedUrl.username, + password: parsedUrl.password + }; + } + function getDefaultProxySettingsInternal() { + const envProxy = loadEnvironmentProxyValue(); + return envProxy ? new URL(envProxy) : void 0; + } + function getUrlFromProxySettings(settings) { + let parsedProxyUrl; + try { + parsedProxyUrl = new URL(settings.host); + } catch (_a) { + throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); + } + parsedProxyUrl.port = String(settings.port); + if (settings.username) { + parsedProxyUrl.username = settings.username; + } + if (settings.password) { + parsedProxyUrl.password = settings.password; + } + return parsedProxyUrl; + } + function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { + if (request.agent) { + return; + } + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (request.tlsSettings) { + log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); + } + const headers = request.headers.toJSON(); + if (isInsecure) { + if (!cachedAgents.httpProxyAgent) { + cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpProxyAgent; + } else { + if (!cachedAgents.httpsProxyAgent) { + cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpsProxyAgent; + } + } + function proxyPolicy(proxySettings, options) { + if (!noProxyListLoaded) { + exports2.globalNoProxyList.push(...loadNoProxy()); + } + const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); + const cachedAgents = {}; + return { + name: exports2.proxyPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) { + setProxyAgentOnRequest(request, cachedAgents, defaultProxy); + } else if (request.proxySettings) { + setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js +var require_setClientRequestIdPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.setClientRequestIdPolicyName = void 0; + exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; + exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; + function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + return { + name: exports2.setClientRequestIdPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(requestIdHeaderName)) { + request.headers.set(requestIdHeaderName, request.requestId); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js +var require_tlsPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.tlsPolicyName = void 0; + exports2.tlsPolicy = tlsPolicy; + exports2.tlsPolicyName = "tlsPolicy"; + function tlsPolicy(tlsSettings) { + return { + name: exports2.tlsPolicyName, + sendRequest: async (req, next) => { + if (!req.tlsSettings) { + req.tlsSettings = tlsSettings; + } + return next(req); + } + }; + } + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js +var require_tracingContext = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0; + exports2.knownContextKeys = { + span: Symbol.for("@azure/core-tracing span"), + namespace: Symbol.for("@azure/core-tracing namespace") + }; + function createTracingContext(options = {}) { + let context2 = new TracingContextImpl(options.parentContext); + if (options.span) { + context2 = context2.setValue(exports2.knownContextKeys.span, options.span); + } + if (options.namespace) { + context2 = context2.setValue(exports2.knownContextKeys.namespace, options.namespace); + } + return context2; + } + exports2.createTracingContext = createTracingContext; + var TracingContextImpl = class _TracingContextImpl { + constructor(initialContext) { + this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); + } + setValue(key, value) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.set(key, value); + return newContext; + } + getValue(key) { + return this._contextMap.get(key); + } + deleteValue(key) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.delete(key); + return newContext; + } + }; + exports2.TracingContextImpl = TracingContextImpl; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/state.js +var require_state = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.state = void 0; + exports2.state = { + instrumenterImplementation: void 0 + }; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js +var require_instrumenter = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0; + var tracingContext_js_1 = require_tracingContext(); + var state_js_1 = require_state(); + function createDefaultTracingSpan() { + return { + end: () => { + }, + isRecording: () => false, + recordException: () => { + }, + setAttribute: () => { + }, + setStatus: () => { + } + }; + } + exports2.createDefaultTracingSpan = createDefaultTracingSpan; + function createDefaultInstrumenter() { + return { + createRequestHeaders: () => { + return {}; + }, + parseTraceparentHeader: () => { + return void 0; + }, + startSpan: (_name, spanOptions) => { + return { + span: createDefaultTracingSpan(), + tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }) + }; + }, + withContext(_context, callback, ...callbackArgs) { + return callback(...callbackArgs); + } + }; + } + exports2.createDefaultInstrumenter = createDefaultInstrumenter; + function useInstrumenter(instrumenter) { + state_js_1.state.instrumenterImplementation = instrumenter; + } + exports2.useInstrumenter = useInstrumenter; + function getInstrumenter() { + if (!state_js_1.state.instrumenterImplementation) { + state_js_1.state.instrumenterImplementation = createDefaultInstrumenter(); + } + return state_js_1.state.instrumenterImplementation; + } + exports2.getInstrumenter = getInstrumenter; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js +var require_tracingClient = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTracingClient = void 0; + var instrumenter_js_1 = require_instrumenter(); + var tracingContext_js_1 = require_tracingContext(); + function createTracingClient(options) { + const { namespace, packageName, packageVersion } = options; + function startSpan(name, operationOptions, spanOptions) { + var _a; + const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); + let tracingContext = startSpanResult.tracingContext; + const span = startSpanResult.span; + if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { + tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace); + } + span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); + const updatedOptions = Object.assign({}, operationOptions, { + tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }) + }); + return { + span, + updatedOptions + }; + } + async function withSpan(name, operationOptions, callback, spanOptions) { + const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); + try { + const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); + span.setStatus({ status: "success" }); + return result; + } catch (err) { + span.setStatus({ status: "error", error: err }); + throw err; + } finally { + span.end(); + } + } + function withContext(context2, callback, ...callbackArgs) { + return (0, instrumenter_js_1.getInstrumenter)().withContext(context2, callback, ...callbackArgs); + } + function parseTraceparentHeader(traceparentHeader) { + return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader); + } + function createRequestHeaders(tracingContext) { + return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext); + } + return { + startSpan, + withSpan, + withContext, + parseTraceparentHeader, + createRequestHeaders + }; + } + exports2.createTracingClient = createTracingClient; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/index.js +var require_commonjs4 = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTracingClient = exports2.useInstrumenter = void 0; + var instrumenter_js_1 = require_instrumenter(); + Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() { + return instrumenter_js_1.useInstrumenter; + } }); + var tracingClient_js_1 = require_tracingClient(); + Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() { + return tracingClient_js_1.createTracingClient; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js +var require_inspect = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.custom = void 0; + var node_util_1 = require("node:util"); + exports2.custom = node_util_1.inspect.custom; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js +var require_restError = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RestError = void 0; + exports2.isRestError = isRestError; + var core_util_1 = require_commonjs2(); + var inspect_js_1 = require_inspect(); + var sanitizer_js_1 = require_sanitizer(); + var errorSanitizer = new sanitizer_js_1.Sanitizer(); + var RestError = class _RestError extends Error { + constructor(message, options = {}) { + super(message); + this.name = "RestError"; + this.code = options.code; + this.statusCode = options.statusCode; + Object.defineProperty(this, "request", { value: options.request, enumerable: false }); + Object.defineProperty(this, "response", { value: options.response, enumerable: false }); + Object.setPrototypeOf(this, _RestError.prototype); + } + /** + * Logging method for util.inspect in Node + */ + [inspect_js_1.custom]() { + return `RestError: ${this.message} + ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; + } + }; + exports2.RestError = RestError; + RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; + RestError.PARSE_ERROR = "PARSE_ERROR"; + function isRestError(e) { + if (e instanceof RestError) { + return true; + } + return (0, core_util_1.isError)(e) && e.name === "RestError"; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js +var require_tracingPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.tracingPolicyName = void 0; + exports2.tracingPolicy = tracingPolicy; + var core_tracing_1 = require_commonjs4(); + var constants_js_1 = require_constants8(); + var userAgent_js_1 = require_userAgent(); + var log_js_1 = require_log(); + var core_util_1 = require_commonjs2(); + var restError_js_1 = require_restError(); + var sanitizer_js_1 = require_sanitizer(); + exports2.tracingPolicyName = "tracingPolicy"; + function tracingPolicy(options = {}) { + const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + const tracingClient = tryCreateTracingClient(); + return { + name: exports2.tracingPolicyName, + async sendRequest(request, next) { + var _a; + if (!tracingClient) { + return next(request); + } + const userAgent = await userAgentPromise; + const spanAttributes = { + "http.url": sanitizer.sanitizeUrl(request.url), + "http.method": request.method, + "http.user_agent": userAgent, + requestId: request.requestId + }; + if (userAgent) { + spanAttributes["http.user_agent"] = userAgent; + } + const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; + if (!span || !tracingContext) { + return next(request); + } + try { + const response = await tracingClient.withContext(tracingContext, next, request); + tryProcessResponse(span, response); + return response; + } catch (err) { + tryProcessError(span, err); + throw err; + } + } + }; + } + function tryCreateTracingClient() { + try { + return (0, core_tracing_1.createTracingClient)({ + namespace: "", + packageName: "@azure/core-rest-pipeline", + packageVersion: constants_js_1.SDK_VERSION + }); + } catch (e) { + log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); + return void 0; + } + } + function tryCreateSpan(tracingClient, request, spanAttributes) { + try { + const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { + spanKind: "client", + spanAttributes + }); + if (!span.isRecording()) { + span.end(); + return void 0; + } + const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); + for (const [key, value] of Object.entries(headers)) { + request.headers.set(key, value); + } + return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; + } catch (e) { + log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + return void 0; + } + } + function tryProcessError(span, error4) { + try { + span.setStatus({ + status: "error", + error: (0, core_util_1.isError)(error4) ? error4 : void 0 + }); + if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) { + span.setAttribute("http.status_code", error4.statusCode); + } + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + } + } + function tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); + } + span.setStatus({ + status: "success" + }); + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + } + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js +var require_createPipelineFromOptions = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createPipelineFromOptions = createPipelineFromOptions; + var logPolicy_js_1 = require_logPolicy(); + var pipeline_js_1 = require_pipeline(); + var redirectPolicy_js_1 = require_redirectPolicy(); + var userAgentPolicy_js_1 = require_userAgentPolicy(); + var multipartPolicy_js_1 = require_multipartPolicy(); + var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); + var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); + var formDataPolicy_js_1 = require_formDataPolicy(); + var core_util_1 = require_commonjs2(); + var proxyPolicy_js_1 = require_proxyPolicy(); + var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); + var tlsPolicy_js_1 = require_tlsPolicy(); + var tracingPolicy_js_1 = require_tracingPolicy(); + function createPipelineFromOptions(options) { + var _a; + const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); + if (core_util_1.isNodeLike) { + if (options.tlsOptions) { + pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); + } + pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); + pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); + } + pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); + pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); + pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); + pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); + pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); + pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { + afterPhase: "Retry" + }); + if (core_util_1.isNodeLike) { + pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + } + pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); + return pipeline; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js +var require_nodeHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getBodyLength = getBodyLength; + exports2.createNodeHttpClient = createNodeHttpClient; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var http = tslib_1.__importStar(require("node:http")); + var https2 = tslib_1.__importStar(require("node:https")); + var zlib = tslib_1.__importStar(require("node:zlib")); + var node_stream_1 = require("node:stream"); + var abort_controller_1 = require_commonjs3(); + var httpHeaders_js_1 = require_httpHeaders(); + var restError_js_1 = require_restError(); + var log_js_1 = require_log(); + var DEFAULT_TLS_SETTINGS = {}; + function isReadableStream(body) { + return body && typeof body.pipe === "function"; + } + function isStreamComplete(stream) { + return new Promise((resolve5) => { + const handler = () => { + resolve5(); + stream.removeListener("close", handler); + stream.removeListener("end", handler); + stream.removeListener("error", handler); + }; + stream.on("close", handler); + stream.on("end", handler); + stream.on("error", handler); + }); + } + function isArrayBuffer(body) { + return body && typeof body.byteLength === "number"; + } + var ReportTransform = class extends node_stream_1.Transform { + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + _transform(chunk, _encoding, callback) { + this.push(chunk); + this.loadedBytes += chunk.length; + try { + this.progressCallback({ loadedBytes: this.loadedBytes }); + callback(); + } catch (e) { + callback(e); + } + } + constructor(progressCallback) { + super(); + this.loadedBytes = 0; + this.progressCallback = progressCallback; + } + }; + var NodeHttpClient = class { + constructor() { + this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); + } + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + var _a, _b, _c; + const abortController = new AbortController(); + let abortListener; + if (request.abortSignal) { + if (request.abortSignal.aborted) { + throw new abort_controller_1.AbortError("The operation was aborted."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController.abort(); + } + }; + request.abortSignal.addEventListener("abort", abortListener); + } + if (request.timeout > 0) { + setTimeout(() => { + abortController.abort(); + }, request.timeout); + } + const acceptEncoding = request.headers.get("Accept-Encoding"); + const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); + let body = typeof request.body === "function" ? request.body() : request.body; + if (body && !request.headers.has("Content-Length")) { + const bodyLength = getBodyLength(body); + if (bodyLength !== null) { + request.headers.set("Content-Length", bodyLength); + } + } + let responseStream; + try { + if (body && request.onUploadProgress) { + const onUploadProgress = request.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + uploadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in upload progress", e); + }); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); + } else { + uploadReportStream.end(body); + } + body = uploadReportStream; + } + const res = await this.makeRequest(request, abortController, body); + const headers = getResponseHeaders(res); + const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; + const response = { + status, + headers, + request + }; + if (request.method === "HEAD") { + res.resume(); + return response; + } + responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; + const onDownloadProgress = request.onDownloadProgress; + if (onDownloadProgress) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + downloadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in download progress", e); + }); + responseStream.pipe(downloadReportStream); + responseStream = downloadReportStream; + } + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status)) + ) { + response.readableStreamBody = responseStream; + } else { + response.bodyAsText = await streamToText(responseStream); + } + return response; + } finally { + if (request.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(responseStream)) { + downloadStreamDone = isStreamComplete(responseStream); + } + Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { + var _a2; + if (abortListener) { + (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener); + } + }).catch((e) => { + log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } + makeRequest(request, abortController, body) { + var _a; + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + } + const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); + const options = { + agent, + hostname: url.hostname, + path: `${url.pathname}${url.search}`, + port: url.port, + method: request.method, + headers: request.headers.toJSON({ preserveCase: true }) + }; + return new Promise((resolve5, reject) => { + const req = isInsecure ? http.request(options, resolve5) : https2.request(options, resolve5); + req.once("error", (err) => { + var _a2; + reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); + }); + abortController.signal.addEventListener("abort", () => { + const abortError = new abort_controller_1.AbortError("The operation was aborted."); + req.destroy(abortError); + reject(abortError); + }); + if (body && isReadableStream(body)) { + body.pipe(req); + } else if (body) { + if (typeof body === "string" || Buffer.isBuffer(body)) { + req.end(body); + } else if (isArrayBuffer(body)) { + req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } else { + log_js_1.logger.error("Unrecognized body type", body); + reject(new restError_js_1.RestError("Unrecognized body type")); + } + } else { + req.end(); + } + }); + } + getOrCreateAgent(request, isInsecure) { + var _a; + const disableKeepAlive = request.disableKeepAlive; + if (isInsecure) { + if (disableKeepAlive) { + return http.globalAgent; + } + if (!this.cachedHttpAgent) { + this.cachedHttpAgent = new http.Agent({ keepAlive: true }); + } + return this.cachedHttpAgent; + } else { + if (disableKeepAlive && !request.tlsSettings) { + return https2.globalAgent; + } + const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; + let agent = this.cachedHttpsAgents.get(tlsSettings); + if (agent && agent.options.keepAlive === !disableKeepAlive) { + return agent; + } + log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); + agent = new https2.Agent(Object.assign({ + // keepAlive is true if disableKeepAlive is false. + keepAlive: !disableKeepAlive + }, tlsSettings)); + this.cachedHttpsAgents.set(tlsSettings, agent); + return agent; + } + } + }; + function getResponseHeaders(res) { + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + for (const header of Object.keys(res.headers)) { + const value = res.headers[header]; + if (Array.isArray(value)) { + if (value.length > 0) { + headers.set(header, value[0]); + } + } else if (value) { + headers.set(header, value); + } + } + return headers; + } + function getDecodedResponseStream(stream, headers) { + const contentEncoding = headers.get("Content-Encoding"); + if (contentEncoding === "gzip") { + const unzip = zlib.createGunzip(); + stream.pipe(unzip); + return unzip; + } else if (contentEncoding === "deflate") { + const inflate = zlib.createInflate(); + stream.pipe(inflate); + return inflate; + } + return stream; + } + function streamToText(stream) { + return new Promise((resolve5, reject) => { + const buffer = []; + stream.on("data", (chunk) => { + if (Buffer.isBuffer(chunk)) { + buffer.push(chunk); + } else { + buffer.push(Buffer.from(chunk)); + } + }); + stream.on("end", () => { + resolve5(Buffer.concat(buffer).toString("utf8")); + }); + stream.on("error", (e) => { + if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { + reject(e); + } else { + reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { + code: restError_js_1.RestError.PARSE_ERROR + })); + } + }); + }); + } + function getBodyLength(body) { + if (!body) { + return 0; + } else if (Buffer.isBuffer(body)) { + return body.length; + } else if (isReadableStream(body)) { + return null; + } else if (isArrayBuffer(body)) { + return body.byteLength; + } else if (typeof body === "string") { + return Buffer.from(body).length; + } else { + return null; + } + } + function createNodeHttpClient() { + return new NodeHttpClient(); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js +var require_defaultHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createDefaultHttpClient = createDefaultHttpClient; + var nodeHttpClient_js_1 = require_nodeHttpClient(); + function createDefaultHttpClient() { + return (0, nodeHttpClient_js_1.createNodeHttpClient)(); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js +var require_pipelineRequest = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createPipelineRequest = createPipelineRequest; + var httpHeaders_js_1 = require_httpHeaders(); + var core_util_1 = require_commonjs2(); + var PipelineRequestImpl = class { + constructor(options) { + var _a, _b, _c, _d, _e, _f, _g; + this.url = options.url; + this.body = options.body; + this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); + this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; + this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; + this.multipartBody = options.multipartBody; + this.formData = options.formData; + this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; + this.proxySettings = options.proxySettings; + this.streamResponseStatusCodes = options.streamResponseStatusCodes; + this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; + this.abortSignal = options.abortSignal; + this.tracingOptions = options.tracingOptions; + this.onUploadProgress = options.onUploadProgress; + this.onDownloadProgress = options.onDownloadProgress; + this.requestId = options.requestId || (0, core_util_1.randomUUID)(); + this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; + this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; + } + }; + function createPipelineRequest(options) { + return new PipelineRequestImpl(options); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js +var require_exponentialRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.exponentialRetryPolicyName = void 0; + exports2.exponentialRetryPolicy = exponentialRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; + function exponentialRetryPolicy(options = {}) { + var _a; + return (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js +var require_systemErrorRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.systemErrorRetryPolicyName = void 0; + exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; + function systemErrorRetryPolicy(options = {}) { + var _a; + return { + name: exports2.systemErrorRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js +var require_throttlingRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.throttlingRetryPolicyName = void 0; + exports2.throttlingRetryPolicy = throttlingRetryPolicy; + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; + function throttlingRetryPolicy(options = {}) { + var _a; + return { + name: exports2.throttlingRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js +var require_tokenCycler = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_CYCLER_OPTIONS = void 0; + exports2.createTokenCycler = createTokenCycler; + var helpers_js_1 = require_helpers2(); + exports2.DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1e3, + // Force waiting for a refresh 1s before the token expires + retryIntervalInMs: 3e3, + // Allow refresh attempts every 3s + refreshWindowInMs: 1e3 * 60 * 2 + // Start refreshing 2m before expiry + }; + async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { + async function tryGetAccessToken() { + if (Date.now() < refreshTimeout) { + try { + return await getAccessToken(); + } catch (_a) { + return null; + } + } else { + const finalToken = await getAccessToken(); + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + let token = await tryGetAccessToken(); + while (token === null) { + await (0, helpers_js_1.delay)(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; + } + function createTokenCycler(credential, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + let tenantId; + const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + const cycler = { + /** + * Produces true if a refresh job is currently in progress. + */ + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) + */ + get shouldRefresh() { + var _a; + if (cycler.isRefreshing) { + return false; + } + if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { + return true; + } + return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); + } + }; + function refresh(scopes, getTokenOptions) { + var _a; + if (!cycler.isRefreshing) { + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); + refreshWorker = beginRefresh( + tryGetAccessToken, + options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now() + ).then((_token) => { + refreshWorker = null; + token = _token; + tenantId = getTokenOptions.tenantId; + return token; + }).catch((reason) => { + refreshWorker = null; + token = null; + tenantId = void 0; + throw reason; + }); + } + return refreshWorker; + } + return async (scopes, tokenOptions) => { + const hasClaimChallenge = Boolean(tokenOptions.claims); + const tenantIdChanged = tenantId !== tokenOptions.tenantId; + if (hasClaimChallenge) { + token = null; + } + const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; + if (mustRefresh) { + return refresh(scopes, tokenOptions); + } + if (cycler.shouldRefresh) { + refresh(scopes, tokenOptions); + } + return token; + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js +var require_bearerTokenAuthenticationPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.bearerTokenAuthenticationPolicyName = void 0; + exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log(); + exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; + async function defaultAuthorizeRequest(options) { + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions + }; + const accessToken = await getAccessToken(scopes, getTokenOptions); + if (accessToken) { + options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); + } + } + function getChallenge(response) { + const challenge = response.headers.get("WWW-Authenticate"); + if (response.status === 401 && challenge) { + return challenge; + } + return; + } + function bearerTokenAuthenticationPolicy(options) { + var _a; + const { credential, scopes, challengeCallbacks } = options; + const logger = options.logger || log_js_1.logger; + const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); + const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( + credential + /* , options */ + ) : () => Promise.resolve(null); + return { + name: exports2.bearerTokenAuthenticationPolicyName, + /** + * If there's no challenge parameter: + * - It will try to retrieve the token using the cache, or the credential's getToken. + * - Then it will try the next policy with or without the retrieved token. + * + * It uses the challenge parameters to: + * - Skip a first attempt to get the token from the credential if there's no cached token, + * since it expects the token to be retrievable only after the challenge. + * - Prepare the outgoing request if the `prepareRequest` method has been provided. + * - Send an initial request to receive the challenge if it fails. + * - Process a challenge if the response contains it. + * - Retrieve a token with the challenge information, then re-send the request. + */ + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + await callbacks.authorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + }); + let response; + let error4; + try { + response = await next(request); + } catch (err) { + error4 = err; + response = err.response; + } + if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) { + const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + response, + getAccessToken, + logger + }); + if (shouldSendRequest) { + return next(request); + } + } + if (error4) { + throw error4; + } else { + return response; + } + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js +var require_ndJsonPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ndJsonPolicyName = void 0; + exports2.ndJsonPolicy = ndJsonPolicy; + exports2.ndJsonPolicyName = "ndJsonPolicy"; + function ndJsonPolicy() { + return { + name: exports2.ndJsonPolicyName, + async sendRequest(request, next) { + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js +var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; + exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log(); + exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; + var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; + async function sendAuthorizeRequest(options) { + var _a, _b; + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions + }; + return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; + } + function auxiliaryAuthenticationHeaderPolicy(options) { + const { credentials, scopes } = options; + const logger = options.logger || log_js_1.logger; + const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); + return { + name: exports2.auxiliaryAuthenticationHeaderPolicyName, + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); + } + if (!credentials || credentials.length === 0) { + logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); + return next(request); + } + const tokenPromises = []; + for (const credential of credentials) { + let getAccessToken = tokenCyclerMap.get(credential); + if (!getAccessToken) { + getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); + tokenCyclerMap.set(credential, getAccessToken); + } + tokenPromises.push(sendAuthorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + })); + } + const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); + if (auxiliaryTokens.length === 0) { + logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); + return next(request); + } + request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js +var require_commonjs5 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; var pipeline_js_1 = require_pipeline(); Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() { return pipeline_js_1.createEmptyPipeline; @@ -64347,1936 +65853,2782 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * of the existing blob will remain unchanged. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * @param size - size of the page blob. - * @param options - + * @param size - size of the page blob. + * @param options - + */ + async createIfNotExists(size, options = {}) { + return tracingClient.withSpan("PageBlobClient-createIfNotExists", options, async (updatedOptions) => { + var _a, _b; + try { + const conditions = { ifNoneMatch: ETagAny }; + const res = assertResponse(await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions }))); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + throw e; + } + }); + } + /** + * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * + * @param body - Data to upload + * @param offset - Offset of destination page blob + * @param count - Content length of the body, also number of bytes to be uploaded + * @param options - Options to the Page Blob Upload Pages operation. + * @returns Response data for the Page Blob Upload Pages operation. + */ + async uploadPages(body2, offset, count, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("PageBlobClient-uploadPages", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.uploadPages(count, body2, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + requestOptions: { + onUploadProgress: options.onProgress + }, + range: rangeToString({ offset, count }), + sequenceNumberAccessConditions: options.conditions, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * The Upload Pages operation writes a range of pages to a page blob where the + * contents are read from a URL. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url + * + * @param sourceURL - Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication + * @param sourceOffset - The source offset to copy from. Pass 0 to copy from the beginning of source page blob + * @param destOffset - Offset of destination page blob + * @param count - Number of bytes to be uploaded from source page blob + * @param options - + */ + async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("PageBlobClient-uploadPagesFromURL", options, async (updatedOptions) => { + var _a, _b, _c, _d, _e; + return assertResponse(await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), { + abortSignal: options.abortSignal, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + sequenceNumberAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, + sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, + sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, + sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Frees the specified pages from the page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * + * @param offset - Starting byte position of the pages to clear. + * @param count - Number of bytes to clear. + * @param options - Options to the Page Blob Clear Pages operation. + * @returns Response data for the Page Blob Clear Pages operation. + */ + async clearPages(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-clearPages", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.clearPages(0, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset, count }), + sequenceNumberAccessConditions: options.conditions, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns the list of valid page ranges for a page blob or snapshot of a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param options - Options to the Page Blob Get Ranges operation. + * @returns Response data for the Page Blob Get Ranges operation. + */ + async getPageRanges(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-getPageRanges", options, async (updatedOptions) => { + var _a; + const response = assertResponse(await this.pageBlobContext.getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + })); + return rangeResponseFromModel(response); + }); + } + /** + * getPageRangesSegment returns a single segment of page ranges starting from the + * specified Marker. Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call getPageRangesSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to PageBlob Get Page Ranges Segment operation. + */ + async listPageRangesSegment(offset = 0, count, marker2, options = {}) { + return tracingClient.withSpan("PageBlobClient-getPageRangesSegment", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset, count }), + marker: marker2, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesResponseModel} + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param marker - A string value that identifies the portion of + * the get of page ranges to be returned with the next getting operation. The + * operation returns the ContinuationToken value within the response body if the + * getting operation did not return all page ranges remaining within the current page. + * The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of get + * items. The marker value is opaque to the client. + * @param options - Options to List Page Ranges operation. + */ + listPageRangeItemSegments() { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeItemSegments_1(offset = 0, count, marker2, options = {}) { + let getPageRangeItemSegmentsResponse; + if (!!marker2 || marker2 === void 0) { + do { + getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesSegment(offset, count, marker2, options)); + marker2 = getPageRangeItemSegmentsResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param options - Options to List Page Ranges operation. + */ + listPageRangeItems() { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeItems_1(offset = 0, count, options = {}) { + var _a, e_1, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeItemSegments(offset, count, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const getPageRangesSegment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_1) throw e_1.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list of page ranges for a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * .byPage() returns an async iterable iterator to list of page ranges for a page blob. + * + * Example using `for await` syntax: + * + * ```js + * // Get the pageBlobClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` + * let i = 1; + * for await (const pageRange of pageBlobClient.listPageRanges()) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = pageBlobClient.listPageRanges(); + * let pageRangeItem = await iter.next(); + * while (!pageRangeItem.done) { + * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); + * pageRangeItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of pageBlobClient.listPageRanges().byPage({ maxPageSize: 20 })) { + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = pageBlobClient.listPageRanges().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 page ranges + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = pageBlobClient.listPageRanges().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 page ranges + * for (const blob of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param options - Options to the Page Blob Get Ranges operation. + * @returns An asyncIterableIterator that supports paging. + */ + listPageRanges(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + const iter = this.listPageRangeItems(offset, count, options); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listPageRangeItemSegments(offset, count, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); + } + }; + } + /** + * Gets the collection of page ranges that differ between a specified snapshot and this page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page blob + * @param count - Number of bytes to get ranges diff. + * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @returns Response data for the Page Blob Get Page Range Diff operation. + */ + async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-getPageRangesDiff", options, async (updatedOptions) => { + var _a; + const result = assertResponse(await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevsnapshot: prevSnapshot, + range: rangeToString({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + })); + return rangeResponseFromModel(result); + }); + } + /** + * getPageRangesDiffSegment returns a single segment of page ranges starting from the + * specified Marker for difference between previous snapshot and the target page blob. + * Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call getPageRangesDiffSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. + * @param marker - A string value that identifies the portion of the get to be returned with the next get operation. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + */ + async listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options = {}) { + return tracingClient.withSpan("PageBlobClient-getPageRangesDiffSegment", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, + leaseAccessConditions: options === null || options === void 0 ? void 0 : options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.conditions), { ifTags: (_a = options === null || options === void 0 ? void 0 : options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevsnapshot: prevSnapshotOrUrl, + range: rangeToString({ + offset, + count + }), + marker: marker2, + maxPageSize: options === null || options === void 0 ? void 0 : options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesDiffResponseModel} + * + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. + * @param marker - A string value that identifies the portion of + * the get of page ranges to be returned with the next getting operation. The + * operation returns the ContinuationToken value within the response body if the + * getting operation did not return all page ranges remaining within the current page. + * The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of get + * items. The marker value is opaque to the client. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + */ + listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options) { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItemSegments_1() { + let getPageRangeItemSegmentsResponse; + if (!!marker2 || marker2 === void 0) { + do { + getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options)); + marker2 = getPageRangeItemSegmentsResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + */ + listPageRangeDiffItems(offset, count, prevSnapshotOrUrl, options) { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItems_1() { + var _a, e_2, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const getPageRangesSegment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * .byPage() returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. + * + * Example using `for await` syntax: + * + * ```js + * // Get the pageBlobClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` + * let i = 1; + * for await (const pageRange of pageBlobClient.listPageRangesDiff()) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = pageBlobClient.listPageRangesDiff(); + * let pageRangeItem = await iter.next(); + * while (!pageRangeItem.done) { + * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); + * pageRangeItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 20 })) { + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 page ranges + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = pageBlobClient.listPageRangesDiff().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 page ranges + * for (const blob of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Ranges operation. + * @returns An asyncIterableIterator that supports paging. */ - async createIfNotExists(size, options = {}) { - return tracingClient.withSpan("PageBlobClient-createIfNotExists", options, async (updatedOptions) => { - var _a, _b; - try { - const conditions = { ifNoneMatch: ETagAny }; - const res = assertResponse(await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions }))); - return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); - } catch (e) { - if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { - return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); - } - throw e; + listPageRangesDiff(offset, count, prevSnapshot, options = {}) { + options.conditions = options.conditions || {}; + const iter = this.listPageRangeDiffItems(offset, count, prevSnapshot, Object.assign({}, options)); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listPageRangeDiffItemSegments(offset, count, prevSnapshot, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); } - }); + }; } /** - * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. - * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * - * @param body - Data to upload - * @param offset - Offset of destination page blob - * @param count - Content length of the body, also number of bytes to be uploaded - * @param options - Options to the Page Blob Upload Pages operation. - * @returns Response data for the Page Blob Upload Pages operation. + * @param offset - Starting byte position of the page blob + * @param count - Number of bytes to get ranges diff. + * @param prevSnapshotUrl - URL of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @returns Response data for the Page Blob Get Page Range Diff operation. */ - async uploadPages(body2, offset, count, options = {}) { + async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl2, options = {}) { options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return tracingClient.withSpan("PageBlobClient-uploadPages", options, async (updatedOptions) => { + return tracingClient.withSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options, async (updatedOptions) => { var _a; - return assertResponse(await this.pageBlobContext.uploadPages(count, body2, { + const response = assertResponse(await this.pageBlobContext.getPageRangesDiff({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - requestOptions: { - onUploadProgress: options.onProgress - }, + prevSnapshotUrl: prevSnapshotUrl2, range: rangeToString({ offset, count }), - sequenceNumberAccessConditions: options.conditions, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions })); + return rangeResponseFromModel(response); }); } /** - * The Upload Pages operation writes a range of pages to a page blob where the - * contents are read from a URL. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url + * Resizes the page blob to the specified size (which must be a multiple of 512). + * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties * - * @param sourceURL - Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication - * @param sourceOffset - The source offset to copy from. Pass 0 to copy from the beginning of source page blob - * @param destOffset - Offset of destination page blob - * @param count - Number of bytes to be uploaded from source page blob - * @param options - + * @param size - Target size + * @param options - Options to the Page Blob Resize operation. + * @returns Response data for the Page Blob Resize operation. */ - async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { + async resize(size, options = {}) { options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return tracingClient.withSpan("PageBlobClient-uploadPagesFromURL", options, async (updatedOptions) => { - var _a, _b, _c, _d, _e; - return assertResponse(await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), { + return tracingClient.withSpan("PageBlobClient-resize", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.resize(size, { abortSignal: options.abortSignal, - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, - sequenceNumberAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, - sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, - sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, - sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince - }, - cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, - copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tracingOptions: updatedOptions.tracingOptions })); }); } /** - * Frees the specified pages from the page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * Sets a page blob's sequence number. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * - * @param offset - Starting byte position of the pages to clear. - * @param count - Number of bytes to clear. - * @param options - Options to the Page Blob Clear Pages operation. - * @returns Response data for the Page Blob Clear Pages operation. + * @param sequenceNumberAction - Indicates how the service should modify the blob's sequence number. + * @param sequenceNumber - Required if sequenceNumberAction is max or update + * @param options - Options to the Page Blob Update Sequence Number operation. + * @returns Response data for the Page Blob Update Sequence Number operation. */ - async clearPages(offset = 0, count, options = {}) { + async updateSequenceNumber(sequenceNumberAction2, sequenceNumber, options = {}) { options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-clearPages", options, async (updatedOptions) => { + return tracingClient.withSpan("PageBlobClient-updateSequenceNumber", options, async (updatedOptions) => { var _a; - return assertResponse(await this.pageBlobContext.clearPages(0, { + return assertResponse(await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction2, { abortSignal: options.abortSignal, + blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset, count }), - sequenceNumberAccessConditions: options.conditions, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions })); }); } /** - * Returns the list of valid page ranges for a page blob or snapshot of a page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. + * The snapshot is copied such that only the differential changes between the previously + * copied snapshot are transferred to the destination. + * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. + * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob + * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param options - Options to the Page Blob Get Ranges operation. - * @returns Response data for the Page Blob Get Ranges operation. + * @param copySource - Specifies the name of the source page blob snapshot. For example, + * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param options - Options to the Page Blob Copy Incremental operation. + * @returns Response data for the Page Blob Copy Incremental operation. */ - async getPageRanges(offset = 0, count, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-getPageRanges", options, async (updatedOptions) => { + async startCopyIncremental(copySource2, options = {}) { + return tracingClient.withSpan("PageBlobClient-startCopyIncremental", options, async (updatedOptions) => { var _a; - const response = assertResponse(await this.pageBlobContext.getPageRanges({ + return assertResponse(await this.pageBlobContext.copyIncremental(copySource2, { abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset, count }), tracingOptions: updatedOptions.tracingOptions })); - return rangeResponseFromModel(response); }); } - /** - * getPageRangesSegment returns a single segment of page ranges starting from the - * specified Marker. Use an empty Marker to start enumeration from the beginning. - * After getting a segment, process it, and then call getPageRangesSegment again - * (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges - * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. - * @param options - Options to PageBlob Get Page Ranges Segment operation. - */ - async listPageRangesSegment(offset = 0, count, marker2, options = {}) { - return tracingClient.withSpan("PageBlobClient-getPageRangesSegment", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.getPageRanges({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset, count }), - marker: marker2, - maxPageSize: options.maxPageSize, - tracingOptions: updatedOptions.tracingOptions - })); - }); + }; + async function getBodyAsText(batchResponse) { + let buffer2 = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); + const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer2); + buffer2 = buffer2.slice(0, responseLength); + return buffer2.toString(); + } + function utf8ByteLength(str2) { + return Buffer.byteLength(str2); + } + var HTTP_HEADER_DELIMITER = ": "; + var SPACE_DELIMITER = " "; + var NOT_FOUND = -1; + var BatchResponseParser = class { + constructor(batchResponse, subRequests) { + if (!batchResponse || !batchResponse.contentType) { + throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); + } + if (!subRequests || subRequests.size === 0) { + throw new RangeError("Invalid state: subRequests is not provided or size is 0."); + } + this.batchResponse = batchResponse; + this.subRequests = subRequests; + this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; + this.perResponsePrefix = `--${this.responseBatchBoundary}${HTTP_LINE_ENDING}`; + this.batchResponseEnding = `--${this.responseBatchBoundary}--`; + } + // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response + async parseBatchResponse() { + if (this.batchResponse._response.status !== HTTPURLConnection.HTTP_ACCEPTED) { + throw new Error(`Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.`); + } + const responseBodyAsText = await getBodyAsText(this.batchResponse); + const subResponses = responseBodyAsText.split(this.batchResponseEnding)[0].split(this.perResponsePrefix).slice(1); + const subResponseCount = subResponses.length; + if (subResponseCount !== this.subRequests.size && subResponseCount !== 1) { + throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); + } + const deserializedSubResponses = new Array(subResponseCount); + let subResponsesSucceededCount = 0; + let subResponsesFailedCount = 0; + for (let index = 0; index < subResponseCount; index++) { + const subResponse = subResponses[index]; + const deserializedSubResponse = {}; + deserializedSubResponse.headers = coreHttpCompat.toHttpHeadersLike(coreRestPipeline.createHttpHeaders()); + const responseLines = subResponse.split(`${HTTP_LINE_ENDING}`); + let subRespHeaderStartFound = false; + let subRespHeaderEndFound = false; + let subRespFailed = false; + let contentId = NOT_FOUND; + for (const responseLine of responseLines) { + if (!subRespHeaderStartFound) { + if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { + contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); + } + if (responseLine.startsWith(HTTP_VERSION_1_1)) { + subRespHeaderStartFound = true; + const tokens = responseLine.split(SPACE_DELIMITER); + deserializedSubResponse.status = parseInt(tokens[1]); + deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); + } + continue; + } + if (responseLine.trim() === "") { + if (!subRespHeaderEndFound) { + subRespHeaderEndFound = true; + } + continue; + } + if (!subRespHeaderEndFound) { + if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { + throw new Error(`Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.`); + } + const tokens = responseLine.split(HTTP_HEADER_DELIMITER); + deserializedSubResponse.headers.set(tokens[0], tokens[1]); + if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { + deserializedSubResponse.errorCode = tokens[1]; + subRespFailed = true; + } + } else { + if (!deserializedSubResponse.bodyAsText) { + deserializedSubResponse.bodyAsText = ""; + } + deserializedSubResponse.bodyAsText += responseLine; + } + } + if (contentId !== NOT_FOUND && Number.isInteger(contentId) && contentId >= 0 && contentId < this.subRequests.size && deserializedSubResponses[contentId] === void 0) { + deserializedSubResponse._request = this.subRequests.get(contentId); + deserializedSubResponses[contentId] = deserializedSubResponse; + } else { + logger.error(`subResponses[${index}] is dropped as the Content-ID is not found or invalid, Content-ID: ${contentId}`); + } + if (subRespFailed) { + subResponsesFailedCount++; + } else { + subResponsesSucceededCount++; + } + } + return { + subResponses: deserializedSubResponses, + subResponsesSucceededCount, + subResponsesFailedCount + }; + } + }; + var MutexLockStatus; + (function(MutexLockStatus2) { + MutexLockStatus2[MutexLockStatus2["LOCKED"] = 0] = "LOCKED"; + MutexLockStatus2[MutexLockStatus2["UNLOCKED"] = 1] = "UNLOCKED"; + })(MutexLockStatus || (MutexLockStatus = {})); + var Mutex = class { + /** + * Lock for a specific key. If the lock has been acquired by another customer, then + * will wait until getting the lock. + * + * @param key - lock key + */ + static async lock(key) { + return new Promise((resolve5) => { + if (this.keys[key] === void 0 || this.keys[key] === MutexLockStatus.UNLOCKED) { + this.keys[key] = MutexLockStatus.LOCKED; + resolve5(); + } else { + this.onUnlockEvent(key, () => { + this.keys[key] = MutexLockStatus.LOCKED; + resolve5(); + }); + } + }); + } + /** + * Unlock a key. + * + * @param key - + */ + static async unlock(key) { + return new Promise((resolve5) => { + if (this.keys[key] === MutexLockStatus.LOCKED) { + this.emitUnlockEvent(key); + } + delete this.keys[key]; + resolve5(); + }); + } + static onUnlockEvent(key, handler) { + if (this.listeners[key] === void 0) { + this.listeners[key] = [handler]; + } else { + this.listeners[key].push(handler); + } + } + static emitUnlockEvent(key) { + if (this.listeners[key] !== void 0 && this.listeners[key].length > 0) { + const handler = this.listeners[key].shift(); + setImmediate(() => { + handler.call(this); + }); + } + } + }; + Mutex.keys = {}; + Mutex.listeners = {}; + var BlobBatch = class { + constructor() { + this.batch = "batch"; + this.batchRequest = new InnerBatchRequest(); + } + /** + * Get the value of Content-Type for a batch request. + * The value must be multipart/mixed with a batch boundary. + * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 + */ + getMultiPartContentType() { + return this.batchRequest.getMultipartContentType(); + } + /** + * Get assembled HTTP request body for sub requests. + */ + getHttpRequestBody() { + return this.batchRequest.getHttpRequestBody(); + } + /** + * Get sub requests that are added into the batch request. + */ + getSubRequests() { + return this.batchRequest.getSubRequests(); + } + async addSubRequestInternal(subRequest, assembleSubRequestFunc) { + await Mutex.lock(this.batch); + try { + this.batchRequest.preAddSubRequest(subRequest); + await assembleSubRequestFunc(); + this.batchRequest.postAddSubRequest(subRequest); + } finally { + await Mutex.unlock(this.batch); + } + } + setBatchType(batchType) { + if (!this.batchType) { + this.batchType = batchType; + } + if (this.batchType !== batchType) { + throw new RangeError(`BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.`); + } + } + async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { + let url2; + let credential; + if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrOptions instanceof StorageSharedKeyCredential || credentialOrOptions instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrOptions))) { + url2 = urlOrBlobClient; + credential = credentialOrOptions; + } else if (urlOrBlobClient instanceof BlobClient) { + url2 = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + options = credentialOrOptions; + } else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + return tracingClient.withSpan("BatchDeleteRequest-addSubRequest", options, async (updatedOptions) => { + this.setBatchType("delete"); + await this.addSubRequestInternal({ + url: url2, + credential + }, async () => { + await new BlobClient(url2, this.batchRequest.createPipeline(credential)).delete(updatedOptions); + }); + }); + } + async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { + let url2; + let credential; + let tier2; + if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrTier instanceof StorageSharedKeyCredential || credentialOrTier instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrTier))) { + url2 = urlOrBlobClient; + credential = credentialOrTier; + tier2 = tierOrOptions; + } else if (urlOrBlobClient instanceof BlobClient) { + url2 = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + tier2 = credentialOrTier; + options = tierOrOptions; + } else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + return tracingClient.withSpan("BatchSetTierRequest-addSubRequest", options, async (updatedOptions) => { + this.setBatchType("setAccessTier"); + await this.addSubRequestInternal({ + url: url2, + credential + }, async () => { + await new BlobClient(url2, this.batchRequest.createPipeline(credential)).setAccessTier(tier2, updatedOptions); + }); + }); + } + }; + var InnerBatchRequest = class { + constructor() { + this.operationCount = 0; + this.body = ""; + const tempGuid = coreUtil.randomUUID(); + this.boundary = `batch_${tempGuid}`; + this.subRequestPrefix = `--${this.boundary}${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TYPE}: application/http${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; + this.multipartContentType = `multipart/mixed; boundary=${this.boundary}`; + this.batchRequestEnding = `--${this.boundary}--`; + this.subRequests = /* @__PURE__ */ new Map(); + } + /** + * Create pipeline to assemble sub requests. The idea here is to use existing + * credential and serialization/deserialization components, with additional policies to + * filter unnecessary headers, assemble sub requests into request's body + * and intercept request from going to wire. + * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. + */ + createPipeline(credential) { + const corePipeline = coreRestPipeline.createEmptyPipeline(); + corePipeline.addPolicy(coreClient.serializationPolicy({ + stringifyXML: coreXml.stringifyXML, + serializerOptions: { + xml: { + xmlCharKey: "#" + } + } + }), { phase: "Serialize" }); + corePipeline.addPolicy(batchHeaderFilterPolicy()); + corePipeline.addPolicy(batchRequestAssemblePolicy(this), { afterPhase: "Sign" }); + if (coreAuth.isTokenCredential(credential)) { + corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ + credential, + scopes: StorageOAuthScopes, + challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge } + }), { phase: "Sign" }); + } else if (credential instanceof StorageSharedKeyCredential) { + corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ + accountName: credential.accountName, + accountKey: credential.accountKey + }), { phase: "Sign" }); + } + const pipeline = new Pipeline([]); + pipeline._credential = credential; + pipeline._corePipeline = corePipeline; + return pipeline; + } + appendSubRequestToBody(request) { + this.body += [ + this.subRequestPrefix, + // sub request constant prefix + `${HeaderConstants.CONTENT_ID}: ${this.operationCount}`, + // sub request's content ID + "", + // empty line after sub request's content ID + `${request.method.toString()} ${getURLPathAndQuery(request.url)} ${HTTP_VERSION_1_1}${HTTP_LINE_ENDING}` + // sub request start line with method + ].join(HTTP_LINE_ENDING); + for (const [name, value] of request.headers) { + this.body += `${name}: ${value}${HTTP_LINE_ENDING}`; + } + this.body += HTTP_LINE_ENDING; + } + preAddSubRequest(subRequest) { + if (this.operationCount >= BATCH_MAX_REQUEST) { + throw new RangeError(`Cannot exceed ${BATCH_MAX_REQUEST} sub requests in a single batch`); + } + const path6 = getURLPath(subRequest.url); + if (!path6 || path6 === "") { + throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); + } + } + postAddSubRequest(subRequest) { + this.subRequests.set(this.operationCount, subRequest); + this.operationCount++; + } + // Return the http request body with assembling the ending line to the sub request body. + getHttpRequestBody() { + return `${this.body}${this.batchRequestEnding}${HTTP_LINE_ENDING}`; } - /** - * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesResponseModel} - * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param marker - A string value that identifies the portion of - * the get of page ranges to be returned with the next getting operation. The - * operation returns the ContinuationToken value within the response body if the - * getting operation did not return all page ranges remaining within the current page. - * The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of get - * items. The marker value is opaque to the client. - * @param options - Options to List Page Ranges operation. - */ - listPageRangeItemSegments() { - return tslib.__asyncGenerator(this, arguments, function* listPageRangeItemSegments_1(offset = 0, count, marker2, options = {}) { - let getPageRangeItemSegmentsResponse; - if (!!marker2 || marker2 === void 0) { - do { - getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesSegment(offset, count, marker2, options)); - marker2 = getPageRangeItemSegmentsResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); - } while (marker2); + getMultipartContentType() { + return this.multipartContentType; + } + getSubRequests() { + return this.subRequests; + } + }; + function batchRequestAssemblePolicy(batchRequest) { + return { + name: "batchRequestAssemblePolicy", + async sendRequest(request) { + batchRequest.appendSubRequestToBody(request); + return { + request, + status: 200, + headers: coreRestPipeline.createHttpHeaders() + }; + } + }; + } + function batchHeaderFilterPolicy() { + return { + name: "batchHeaderFilterPolicy", + async sendRequest(request, next) { + let xMsHeaderName = ""; + for (const [name] of request.headers) { + if (iEqual(name, HeaderConstants.X_MS_VERSION)) { + xMsHeaderName = name; + } } - }); + if (xMsHeaderName !== "") { + request.headers.delete(xMsHeaderName); + } + return next(request); + } + }; + } + var BlobBatchClient = class { + constructor(url2, credentialOrPipeline, options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { + pipeline = credentialOrPipeline; + } else if (!credentialOrPipeline) { + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + pipeline = newPipeline(credentialOrPipeline, options); + } + const storageClientContext = new StorageContextClient(url2, getCoreClientOptions(pipeline)); + const path6 = getURLPath(url2); + if (path6 && path6 !== "/") { + this.serviceOrContainerContext = storageClientContext.container; + } else { + this.serviceOrContainerContext = storageClientContext.service; + } } /** - * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects - * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param options - Options to List Page Ranges operation. + * Creates a {@link BlobBatch}. + * A BlobBatch represents an aggregated set of operations on blobs. */ - listPageRangeItems() { - return tslib.__asyncGenerator(this, arguments, function* listPageRangeItems_1(offset = 0, count, options = {}) { - var _a, e_1, _b, _c; - let marker2; - try { - for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeItemSegments(offset, count, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const getPageRangesSegment = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_1) throw e_1.error; - } + createBatch() { + return new BlobBatch(); + } + async deleteBlobs(urlsOrBlobClients, credentialOrOptions, options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); + } else { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions); } - }); + } + return this.submitBatch(batch); + } + async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); + } else { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); + } + } + return this.submitBatch(batch); } /** - * Returns an async iterable iterator to list of page ranges for a page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges - * - * .byPage() returns an async iterable iterator to list of page ranges for a page blob. - * - * Example using `for await` syntax: + * Submit batch request which consists of multiple subrequests. * - * ```js - * // Get the pageBlobClient before you run these snippets, - * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` - * let i = 1; - * for await (const pageRange of pageBlobClient.listPageRanges()) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * ``` + * Get `blobBatchClient` and other details before running the snippets. + * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` * - * Example using `iter.next()`: + * Example usage: * * ```js - * let i = 1; - * let iter = pageBlobClient.listPageRanges(); - * let pageRangeItem = await iter.next(); - * while (!pageRangeItem.done) { - * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); - * pageRangeItem = await iter.next(); - * } + * let batchRequest = new BlobBatch(); + * await batchRequest.deleteBlob(urlInString0, credential0); + * await batchRequest.deleteBlob(urlInString1, credential1, { + * deleteSnapshots: "include" + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); * ``` * - * Example using `byPage()`: + * Example using a lease: * * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of pageBlobClient.listPageRanges().byPage({ maxPageSize: 20 })) { - * for (const pageRange of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * } + * let batchRequest = new BlobBatch(); + * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); + * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { + * conditions: { leaseId: leaseId } + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); * ``` * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = pageBlobClient.listPageRanges().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 page ranges - * for (const pageRange of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * - * // Passing next marker as continuationToken - * - * iterator = pageBlobClient.listPageRanges().byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * - * // Prints 10 page ranges - * for (const blob of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * ``` - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param options - Options to the Page Blob Get Ranges operation. - * @returns An asyncIterableIterator that supports paging. + * @param batchRequest - A set of Delete or SetTier operations. + * @param options - */ - listPageRanges(offset = 0, count, options = {}) { - options.conditions = options.conditions || {}; - const iter = this.listPageRangeItems(offset, count, options); - return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listPageRangeItemSegments(offset, count, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); - } - }; + async submitBatch(batchRequest, options = {}) { + if (!batchRequest || batchRequest.getSubRequests().size === 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + return tracingClient.withSpan("BlobBatchClient-submitBatch", options, async (updatedOptions) => { + const batchRequestBody = batchRequest.getHttpRequestBody(); + const rawBatchResponse = assertResponse(await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, Object.assign({}, updatedOptions))); + const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + const responseSummary = await batchResponseParser.parseBatchResponse(); + const res = { + _response: rawBatchResponse._response, + contentType: rawBatchResponse.contentType, + errorCode: rawBatchResponse.errorCode, + requestId: rawBatchResponse.requestId, + clientRequestId: rawBatchResponse.clientRequestId, + version: rawBatchResponse.version, + subResponses: responseSummary.subResponses, + subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, + subResponsesFailedCount: responseSummary.subResponsesFailedCount + }; + return res; + }); } + }; + var ContainerClient = class extends StorageClient { /** - * Gets the collection of page ranges that differ between a specified snapshot and this page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges - * - * @param offset - Starting byte position of the page blob - * @param count - Number of bytes to get ranges diff. - * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. - * @returns Response data for the Page Blob Get Page Range Diff operation. + * The name of the container. */ - async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-getPageRangesDiff", options, async (updatedOptions) => { - var _a; - const result = assertResponse(await this.pageBlobContext.getPageRangesDiff({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevsnapshot: prevSnapshot, - range: rangeToString({ offset, count }), - tracingOptions: updatedOptions.tracingOptions - })); - return rangeResponseFromModel(result); - }); + get containerName() { + return this._containerName; + } + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { + let pipeline; + let url2; + options = options || {}; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } else if (coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipelineOrContainerName)) { + url2 = urlOrConnectionString; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { + url2 = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { + const containerName = credentialOrPipelineOrContainerName; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url2 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + pipeline = newPipeline(sharedKeyCredential, options); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + url2 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + "?" + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } else { + throw new Error("Expecting non-empty strings for containerName parameter"); + } + super(url2, pipeline); + this._containerName = this.getContainerNameFromUrl(); + this.containerContext = this.storageClientContext.container; } /** - * getPageRangesDiffSegment returns a single segment of page ranges starting from the - * specified Marker for difference between previous snapshot and the target page blob. - * Use an empty Marker to start enumeration from the beginning. - * After getting a segment, process it, and then call getPageRangesDiffSegment again - * (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * Creates a new container under the specified account. If the container with + * the same name already exists, the operation fails. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. - * @param marker - A string value that identifies the portion of the get to be returned with the next get operation. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @param options - Options to Container Create operation. + * + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * const createContainerResponse = await containerClient.create(); + * console.log("Container was created successfully", createContainerResponse.requestId); + * ``` */ - async listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options = {}) { - return tracingClient.withSpan("PageBlobClient-getPageRangesDiffSegment", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.getPageRangesDiff({ - abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, - leaseAccessConditions: options === null || options === void 0 ? void 0 : options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.conditions), { ifTags: (_a = options === null || options === void 0 ? void 0 : options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevsnapshot: prevSnapshotOrUrl, - range: rangeToString({ - offset, - count - }), - marker: marker2, - maxPageSize: options === null || options === void 0 ? void 0 : options.maxPageSize, - tracingOptions: updatedOptions.tracingOptions - })); + async create(options = {}) { + return tracingClient.withSpan("ContainerClient-create", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.create(updatedOptions)); }); } /** - * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesDiffResponseModel} - * + * Creates a new container under the specified account. If the container with + * the same name already exists, it is not changed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. - * @param marker - A string value that identifies the portion of - * the get of page ranges to be returned with the next getting operation. The - * operation returns the ContinuationToken value within the response body if the - * getting operation did not return all page ranges remaining within the current page. - * The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of get - * items. The marker value is opaque to the client. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @param options - */ - listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options) { - return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItemSegments_1() { - let getPageRangeItemSegmentsResponse; - if (!!marker2 || marker2 === void 0) { - do { - getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options)); - marker2 = getPageRangeItemSegmentsResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); - } while (marker2); + async createIfNotExists(options = {}) { + return tracingClient.withSpan("ContainerClient-createIfNotExists", options, async (updatedOptions) => { + var _a, _b; + try { + const res = await this.create(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } else { + throw e; + } } }); } /** - * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects + * Returns true if the Azure container resource represented by this client exists; false otherwise. * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * NOTE: use this function with care since an existing container might be deleted by other clients or + * applications. Vice versa new containers with the same name might be added by other clients or + * applications after this function completes. + * + * @param options - */ - listPageRangeDiffItems(offset, count, prevSnapshotOrUrl, options) { - return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItems_1() { - var _a, e_2, _b, _c; - let marker2; + async exists(options = {}) { + return tracingClient.withSpan("ContainerClient-exists", options, async (updatedOptions) => { try { - for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const getPageRangesSegment = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); - } - } catch (e_2_1) { - e_2 = { error: e_2_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_2) throw e_2.error; + await this.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }); + return true; + } catch (e) { + if (e.statusCode === 404) { + return false; } + throw e; } }); } /** - * Returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges - * - * .byPage() returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. - * - * Example using `for await` syntax: - * - * ```js - * // Get the pageBlobClient before you run these snippets, - * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` - * let i = 1; - * for await (const pageRange of pageBlobClient.listPageRangesDiff()) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * ``` + * Creates a {@link BlobClient} * - * Example using `iter.next()`: + * @param blobName - A blob name + * @returns A new BlobClient object for the given blob name. + */ + getBlobClient(blobName) { + return new BlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Creates an {@link AppendBlobClient} * - * ```js - * let i = 1; - * let iter = pageBlobClient.listPageRangesDiff(); - * let pageRangeItem = await iter.next(); - * while (!pageRangeItem.done) { - * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); - * pageRangeItem = await iter.next(); - * } - * ``` + * @param blobName - An append blob name + */ + getAppendBlobClient(blobName) { + return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Creates a {@link BlockBlobClient} * - * Example using `byPage()`: + * @param blobName - A block blob name * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 20 })) { - * for (const pageRange of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * } - * ``` * - * Example using paging with a marker: + * Example usage: * * ```js - * let i = 1; - * let iterator = pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 page ranges - * for (const pageRange of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } + * const content = "Hello world!"; * - * // Gets next marker - * let marker = response.continuationToken; + * const blockBlobClient = containerClient.getBlockBlobClient(""); + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); + * ``` + */ + getBlockBlobClient(blobName) { + return new BlockBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Creates a {@link PageBlobClient} * - * // Passing next marker as continuationToken + * @param blobName - A page blob name + */ + getPageBlobClient(blobName) { + return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Returns all user-defined metadata and system properties for the specified + * container. The data returned does not include the container's list of blobs. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties * - * iterator = pageBlobClient.listPageRangesDiff().byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which + * will retain their original casing. * - * // Prints 10 page ranges - * for (const blob of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * ``` - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. - * @param options - Options to the Page Blob Get Ranges operation. - * @returns An asyncIterableIterator that supports paging. + * @param options - Options to Container Get Properties operation. */ - listPageRangesDiff(offset, count, prevSnapshot, options = {}) { - options.conditions = options.conditions || {}; - const iter = this.listPageRangeDiffItems(offset, count, prevSnapshot, Object.assign({}, options)); - return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listPageRangeDiffItemSegments(offset, count, prevSnapshot, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); - } - }; + async getProperties(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("ContainerClient-getProperties", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), { tracingOptions: updatedOptions.tracingOptions }))); + }); } /** - * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * Marks the specified container for deletion. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * - * @param offset - Starting byte position of the page blob - * @param count - Number of bytes to get ranges diff. - * @param prevSnapshotUrl - URL of snapshot to retrieve the difference. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. - * @returns Response data for the Page Blob Get Page Range Diff operation. + * @param options - Options to Container Delete operation. */ - async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl2, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options, async (updatedOptions) => { - var _a; - const response = assertResponse(await this.pageBlobContext.getPageRangesDiff({ + async delete(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("ContainerClient-delete", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.delete({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevSnapshotUrl: prevSnapshotUrl2, - range: rangeToString({ offset, count }), + modifiedAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions })); - return rangeResponseFromModel(response); }); } /** - * Resizes the page blob to the specified size (which must be a multiple of 512). - * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties + * Marks the specified container for deletion if it exists. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * - * @param size - Target size - * @param options - Options to the Page Blob Resize operation. - * @returns Response data for the Page Blob Resize operation. + * @param options - Options to Container Delete operation. */ - async resize(size, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-resize", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.resize(size, { + async deleteIfExists(options = {}) { + return tracingClient.withSpan("ContainerClient-deleteIfExists", options, async (updatedOptions) => { + var _a, _b; + try { + const res = await this.delete(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + throw e; + } + }); + } + /** + * Sets one or more user-defined name-value pairs for the specified container. + * + * If no option provided, or no metadata defined in the parameter, the container + * metadata will be removed. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * + * @param metadata - Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param options - Options to Container Set Metadata operation. + */ + async setMetadata(metadata2, options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + if (options.conditions.ifUnmodifiedSince) { + throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + } + return tracingClient.withSpan("ContainerClient-setMetadata", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.setMetadata({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - encryptionScope: options.encryptionScope, + metadata: metadata2, + modifiedAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions })); }); } /** - * Sets a page blob's sequence number. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * Gets the permissions for the specified container. The permissions indicate + * whether container data may be accessed publicly. * - * @param sequenceNumberAction - Indicates how the service should modify the blob's sequence number. - * @param sequenceNumber - Required if sequenceNumberAction is max or update - * @param options - Options to the Page Blob Update Sequence Number operation. - * @returns Response data for the Page Blob Update Sequence Number operation. + * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. + * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl + * + * @param options - Options to Container Get Access Policy operation. */ - async updateSequenceNumber(sequenceNumberAction2, sequenceNumber, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-updateSequenceNumber", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction2, { + async getAccessPolicy(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("ContainerClient-getAccessPolicy", options, async (updatedOptions) => { + const response = assertResponse(await this.containerContext.getAccessPolicy({ abortSignal: options.abortSignal, - blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions })); + const res = { + _response: response._response, + blobPublicAccess: response.blobPublicAccess, + date: response.date, + etag: response.etag, + errorCode: response.errorCode, + lastModified: response.lastModified, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + signedIdentifiers: [], + version: response.version + }; + for (const identifier of response) { + let accessPolicy = void 0; + if (identifier.accessPolicy) { + accessPolicy = { + permissions: identifier.accessPolicy.permissions + }; + if (identifier.accessPolicy.expiresOn) { + accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); + } + if (identifier.accessPolicy.startsOn) { + accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); + } + } + res.signedIdentifiers.push({ + accessPolicy, + id: identifier.id + }); + } + return res; }); } /** - * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. - * The snapshot is copied such that only the differential changes between the previously - * copied snapshot are transferred to the destination. - * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. - * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob - * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots + * Sets the permissions for the specified container. The permissions indicate + * whether blobs in a container may be accessed publicly. * - * @param copySource - Specifies the name of the source page blob snapshot. For example, - * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= - * @param options - Options to the Page Blob Copy Incremental operation. - * @returns Response data for the Page Blob Copy Incremental operation. + * When you set permissions for a container, the existing permissions are replaced. + * If no access or containerAcl provided, the existing container ACL will be + * removed. + * + * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. + * During this interval, a shared access signature that is associated with the stored access policy will + * fail with status code 403 (Forbidden), until the access policy becomes active. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl + * + * @param access - The level of public access to data in the container. + * @param containerAcl - Array of elements each having a unique Id and details of the access policy. + * @param options - Options to Container Set Access Policy operation. */ - async startCopyIncremental(copySource2, options = {}) { - return tracingClient.withSpan("PageBlobClient-startCopyIncremental", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.copyIncremental(copySource2, { + async setAccessPolicy(access2, containerAcl2, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("ContainerClient-setAccessPolicy", options, async (updatedOptions) => { + const acl = []; + for (const identifier of containerAcl2 || []) { + acl.push({ + accessPolicy: { + expiresOn: identifier.accessPolicy.expiresOn ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) : "", + permissions: identifier.accessPolicy.permissions, + startsOn: identifier.accessPolicy.startsOn ? truncatedISO8061Date(identifier.accessPolicy.startsOn) : "" + }, + id: identifier.id + }); + } + return assertResponse(await this.containerContext.setAccessPolicy({ abortSignal: options.abortSignal, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + access: access2, + containerAcl: acl, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions })); }); } - }; - async function getBodyAsText(batchResponse) { - let buffer2 = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); - const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer2); - buffer2 = buffer2.slice(0, responseLength); - return buffer2.toString(); - } - function utf8ByteLength(str2) { - return Buffer.byteLength(str2); - } - var HTTP_HEADER_DELIMITER = ": "; - var SPACE_DELIMITER = " "; - var NOT_FOUND = -1; - var BatchResponseParser = class { - constructor(batchResponse, subRequests) { - if (!batchResponse || !batchResponse.contentType) { - throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); - } - if (!subRequests || subRequests.size === 0) { - throw new RangeError("Invalid state: subRequests is not provided or size is 0."); - } - this.batchResponse = batchResponse; - this.subRequests = subRequests; - this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; - this.perResponsePrefix = `--${this.responseBatchBoundary}${HTTP_LINE_ENDING}`; - this.batchResponseEnding = `--${this.responseBatchBoundary}--`; + /** + * Get a {@link BlobLeaseClient} that manages leases on the container. + * + * @param proposeLeaseId - Initial proposed lease Id. + * @returns A new BlobLeaseClient object for managing leases on the container. + */ + getBlobLeaseClient(proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); } - // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response - async parseBatchResponse() { - if (this.batchResponse._response.status !== HTTPURLConnection.HTTP_ACCEPTED) { - throw new Error(`Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.`); - } - const responseBodyAsText = await getBodyAsText(this.batchResponse); - const subResponses = responseBodyAsText.split(this.batchResponseEnding)[0].split(this.perResponsePrefix).slice(1); - const subResponseCount = subResponses.length; - if (subResponseCount !== this.subRequests.size && subResponseCount !== 1) { - throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); - } - const deserializedSubResponses = new Array(subResponseCount); - let subResponsesSucceededCount = 0; - let subResponsesFailedCount = 0; - for (let index = 0; index < subResponseCount; index++) { - const subResponse = subResponses[index]; - const deserializedSubResponse = {}; - deserializedSubResponse.headers = coreHttpCompat.toHttpHeadersLike(coreRestPipeline.createHttpHeaders()); - const responseLines = subResponse.split(`${HTTP_LINE_ENDING}`); - let subRespHeaderStartFound = false; - let subRespHeaderEndFound = false; - let subRespFailed = false; - let contentId = NOT_FOUND; - for (const responseLine of responseLines) { - if (!subRespHeaderStartFound) { - if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { - contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); - } - if (responseLine.startsWith(HTTP_VERSION_1_1)) { - subRespHeaderStartFound = true; - const tokens = responseLine.split(SPACE_DELIMITER); - deserializedSubResponse.status = parseInt(tokens[1]); - deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); - } - continue; - } - if (responseLine.trim() === "") { - if (!subRespHeaderEndFound) { - subRespHeaderEndFound = true; - } - continue; - } - if (!subRespHeaderEndFound) { - if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { - throw new Error(`Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.`); - } - const tokens = responseLine.split(HTTP_HEADER_DELIMITER); - deserializedSubResponse.headers.set(tokens[0], tokens[1]); - if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { - deserializedSubResponse.errorCode = tokens[1]; - subRespFailed = true; - } - } else { - if (!deserializedSubResponse.bodyAsText) { - deserializedSubResponse.bodyAsText = ""; - } - deserializedSubResponse.bodyAsText += responseLine; - } - } - if (contentId !== NOT_FOUND && Number.isInteger(contentId) && contentId >= 0 && contentId < this.subRequests.size && deserializedSubResponses[contentId] === void 0) { - deserializedSubResponse._request = this.subRequests.get(contentId); - deserializedSubResponses[contentId] = deserializedSubResponse; - } else { - logger.error(`subResponses[${index}] is dropped as the Content-ID is not found or invalid, Content-ID: ${contentId}`); - } - if (subRespFailed) { - subResponsesFailedCount++; - } else { - subResponsesSucceededCount++; + /** + * Creates a new block blob, or updates the content of an existing block blob. + * + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. + * + * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, + * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better + * performance with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param blobName - Name of the block blob to create or update. + * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param options - Options to configure the Block Blob Upload operation. + * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. + */ + async uploadBlockBlob(blobName, body2, contentLength2, options = {}) { + return tracingClient.withSpan("ContainerClient-uploadBlockBlob", options, async (updatedOptions) => { + const blockBlobClient = this.getBlockBlobClient(blobName); + const response = await blockBlobClient.upload(body2, contentLength2, updatedOptions); + return { + blockBlobClient, + response + }; + }); + } + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param blobName - + * @param options - Options to Blob Delete operation. + * @returns Block blob deletion response data. + */ + async deleteBlob(blobName, options = {}) { + return tracingClient.withSpan("ContainerClient-deleteBlob", options, async (updatedOptions) => { + let blobClient = this.getBlobClient(blobName); + if (options.versionId) { + blobClient = blobClient.withVersion(options.versionId); } - } - return { - subResponses: deserializedSubResponses, - subResponsesSucceededCount, - subResponsesFailedCount - }; + return blobClient.delete(updatedOptions); + }); } - }; - var MutexLockStatus; - (function(MutexLockStatus2) { - MutexLockStatus2[MutexLockStatus2["LOCKED"] = 0] = "LOCKED"; - MutexLockStatus2[MutexLockStatus2["UNLOCKED"] = 1] = "UNLOCKED"; - })(MutexLockStatus || (MutexLockStatus = {})); - var Mutex = class { /** - * Lock for a specific key. If the lock has been acquired by another customer, then - * will wait until getting the lock. + * listBlobFlatSegment returns a single segment of blobs starting from the + * specified Marker. Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call listBlobsFlatSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs * - * @param key - lock key + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to Container List Blob Flat Segment operation. */ - static async lock(key) { - return new Promise((resolve5) => { - if (this.keys[key] === void 0 || this.keys[key] === MutexLockStatus.UNLOCKED) { - this.keys[key] = MutexLockStatus.LOCKED; - resolve5(); - } else { - this.onUnlockEvent(key, () => { - this.keys[key] = MutexLockStatus.LOCKED; - resolve5(); - }); + async listBlobFlatSegment(marker2, options = {}) { + return tracingClient.withSpan("ContainerClient-listBlobFlatSegment", options, async (updatedOptions) => { + const response = assertResponse(await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobFlat(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { + const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return wrappedResponse; + }); + } + /** + * listBlobHierarchySegment returns a single segment of blobs starting from + * the specified Marker. Use an empty Marker to start enumeration from the + * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment + * again (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to Container List Blob Hierarchy Segment operation. + */ + async listBlobHierarchySegment(delimiter2, marker2, options = {}) { + return tracingClient.withSpan("ContainerClient-listBlobHierarchySegment", options, async (updatedOptions) => { + var _a; + const response = assertResponse(await this.containerContext.listBlobHierarchySegment(delimiter2, Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobHierarchy(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { + const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); + return blobItem; + }), blobPrefixes: (_a = response.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { + const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); + return blobPrefix; + }) }) }); + return wrappedResponse; + }); + } + /** + * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to list blobs operation. + */ + listSegments(marker_1) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { + let listBlobsFlatSegmentResponse; + if (!!marker2 || marker2 === void 0) { + do { + listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker2, options)); + marker2 = listBlobsFlatSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); + } while (marker2); } }); } /** - * Unlock a key. + * Returns an AsyncIterableIterator of {@link BlobItem} objects * - * @param key - + * @param options - Options to list blobs operation. */ - static async unlock(key) { - return new Promise((resolve5) => { - if (this.keys[key] === MutexLockStatus.LOCKED) { - this.emitUnlockEvent(key); + listItems() { + return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { + var _a, e_1, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const listBlobsFlatSegmentResponse = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_1) throw e_1.error; + } } - delete this.keys[key]; - resolve5(); }); } - static onUnlockEvent(key, handler) { - if (this.listeners[key] === void 0) { - this.listeners[key] = [handler]; - } else { - this.listeners[key].push(handler); - } - } - static emitUnlockEvent(key) { - if (this.listeners[key] !== void 0 && this.listeners[key].length > 0) { - const handler = this.listeners[key].shift(); - setImmediate(() => { - handler.call(this); - }); - } - } - }; - Mutex.keys = {}; - Mutex.listeners = {}; - var BlobBatch = class { - constructor() { - this.batch = "batch"; - this.batchRequest = new InnerBatchRequest(); - } - /** - * Get the value of Content-Type for a batch request. - * The value must be multipart/mixed with a batch boundary. - * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 - */ - getMultiPartContentType() { - return this.batchRequest.getMultipartContentType(); - } - /** - * Get assembled HTTP request body for sub requests. - */ - getHttpRequestBody() { - return this.batchRequest.getHttpRequestBody(); - } /** - * Get sub requests that are added into the batch request. + * Returns an async iterable iterator to list all the blobs + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * Example using `for await` syntax: + * + * ```js + * // Get the containerClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("");` + * let i = 1; + * for await (const blob of containerClient.listBlobsFlat()) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = containerClient.listBlobsFlat(); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * @param options - Options to list blobs. + * @returns An asyncIterableIterator that supports paging. */ - getSubRequests() { - return this.batchRequest.getSubRequests(); - } - async addSubRequestInternal(subRequest, assembleSubRequestFunc) { - await Mutex.lock(this.batch); - try { - this.batchRequest.preAddSubRequest(subRequest); - await assembleSubRequestFunc(); - this.batchRequest.postAddSubRequest(subRequest); - } finally { - await Mutex.unlock(this.batch); + listBlobsFlat(options = {}) { + const include2 = []; + if (options.includeCopy) { + include2.push("copy"); } - } - setBatchType(batchType) { - if (!this.batchType) { - this.batchType = batchType; + if (options.includeDeleted) { + include2.push("deleted"); } - if (this.batchType !== batchType) { - throw new RangeError(`BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.`); + if (options.includeMetadata) { + include2.push("metadata"); } - } - async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { - let url2; - let credential; - if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrOptions instanceof StorageSharedKeyCredential || credentialOrOptions instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrOptions))) { - url2 = urlOrBlobClient; - credential = credentialOrOptions; - } else if (urlOrBlobClient instanceof BlobClient) { - url2 = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - options = credentialOrOptions; - } else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + if (options.includeSnapshots) { + include2.push("snapshots"); } - if (!options) { - options = {}; + if (options.includeVersions) { + include2.push("versions"); } - return tracingClient.withSpan("BatchDeleteRequest-addSubRequest", options, async (updatedOptions) => { - this.setBatchType("delete"); - await this.addSubRequestInternal({ - url: url2, - credential - }, async () => { - await new BlobClient(url2, this.batchRequest.createPipeline(credential)).delete(updatedOptions); - }); - }); - } - async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { - let url2; - let credential; - let tier2; - if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrTier instanceof StorageSharedKeyCredential || credentialOrTier instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrTier))) { - url2 = urlOrBlobClient; - credential = credentialOrTier; - tier2 = tierOrOptions; - } else if (urlOrBlobClient instanceof BlobClient) { - url2 = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - tier2 = credentialOrTier; - options = tierOrOptions; - } else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + if (options.includeUncommitedBlobs) { + include2.push("uncommittedblobs"); } - if (!options) { - options = {}; + if (options.includeTags) { + include2.push("tags"); } - return tracingClient.withSpan("BatchSetTierRequest-addSubRequest", options, async (updatedOptions) => { - this.setBatchType("setAccessTier"); - await this.addSubRequestInternal({ - url: url2, - credential - }, async () => { - await new BlobClient(url2, this.batchRequest.createPipeline(credential)).setAccessTier(tier2, updatedOptions); - }); - }); + if (options.includeDeletedWithVersions) { + include2.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include2.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include2.push("legalhold"); + } + if (options.prefix === "") { + options.prefix = void 0; + } + const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); + const iter = this.listItems(updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; } - }; - var InnerBatchRequest = class { - constructor() { - this.operationCount = 0; - this.body = ""; - const tempGuid = coreUtil.randomUUID(); - this.boundary = `batch_${tempGuid}`; - this.subRequestPrefix = `--${this.boundary}${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TYPE}: application/http${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; - this.multipartContentType = `multipart/mixed; boundary=${this.boundary}`; - this.batchRequestEnding = `--${this.boundary}--`; - this.subRequests = /* @__PURE__ */ new Map(); + /** + * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to list blobs operation. + */ + listHierarchySegments(delimiter_1, marker_1) { + return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1(delimiter2, marker2, options = {}) { + let listBlobsHierarchySegmentResponse; + if (!!marker2 || marker2 === void 0) { + do { + listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter2, marker2, options)); + marker2 = listBlobsHierarchySegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); + } while (marker2); + } + }); } /** - * Create pipeline to assemble sub requests. The idea here is to use existing - * credential and serialization/deserialization components, with additional policies to - * filter unnecessary headers, assemble sub requests into request's body - * and intercept request from going to wire. - * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. + * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param options - Options to list blobs operation. */ - createPipeline(credential) { - const corePipeline = coreRestPipeline.createEmptyPipeline(); - corePipeline.addPolicy(coreClient.serializationPolicy({ - stringifyXML: coreXml.stringifyXML, - serializerOptions: { - xml: { - xmlCharKey: "#" + listItemsByHierarchy(delimiter_1) { + return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1(delimiter2, options = {}) { + var _a, e_2, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listHierarchySegments(delimiter2, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const listBlobsHierarchySegmentResponse = _c; + const segment = listBlobsHierarchySegmentResponse.segment; + if (segment.blobPrefixes) { + for (const prefix2 of segment.blobPrefixes) { + yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix2)); + } + } + for (const blob of segment.blobItems) { + yield yield tslib.__await(Object.assign({ kind: "blob" }, blob)); + } + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_2) throw e_2.error; } } - }), { phase: "Serialize" }); - corePipeline.addPolicy(batchHeaderFilterPolicy()); - corePipeline.addPolicy(batchRequestAssemblePolicy(this), { afterPhase: "Sign" }); - if (coreAuth.isTokenCredential(credential)) { - corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ - credential, - scopes: StorageOAuthScopes, - challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge } - }), { phase: "Sign" }); - } else if (credential instanceof StorageSharedKeyCredential) { - corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ - accountName: credential.accountName, - accountKey: credential.accountKey - }), { phase: "Sign" }); - } - const pipeline = new Pipeline([]); - pipeline._credential = credential; - pipeline._corePipeline = corePipeline; - return pipeline; + }); } - appendSubRequestToBody(request) { - this.body += [ - this.subRequestPrefix, - // sub request constant prefix - `${HeaderConstants.CONTENT_ID}: ${this.operationCount}`, - // sub request's content ID - "", - // empty line after sub request's content ID - `${request.method.toString()} ${getURLPathAndQuery(request.url)} ${HTTP_VERSION_1_1}${HTTP_LINE_ENDING}` - // sub request start line with method - ].join(HTTP_LINE_ENDING); - for (const [name, value] of request.headers) { - this.body += `${name}: ${value}${HTTP_LINE_ENDING}`; + /** + * Returns an async iterable iterator to list all the blobs by hierarchy. + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. + * + * Example using `for await` syntax: + * + * ```js + * for await (const item of containerClient.listBlobsByHierarchy("/")) { + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}`); + * } + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); + * let entity = await iter.next(); + * while (!entity.done) { + * let item = entity.value; + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}`); + * } + * entity = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * console.log("Listing blobs by hierarchy by page"); + * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { + * const segment = response.segment; + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}`); + * } + * } + * ``` + * + * Example using paging with a max page size: + * + * ```js + * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); + * + * let i = 1; + * for await (const response of containerClient + * .listBlobsByHierarchy("/", { prefix: "prefix2/sub1/" }) + * .byPage({ maxPageSize: 2 })) { + * console.log(`Page ${i++}`); + * const segment = response.segment; + * + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}`); + * } + * } + * ``` + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param options - Options to list blobs operation. + */ + listBlobsByHierarchy(delimiter2, options = {}) { + if (delimiter2 === "") { + throw new RangeError("delimiter should contain one or more characters"); } - this.body += HTTP_LINE_ENDING; - } - preAddSubRequest(subRequest) { - if (this.operationCount >= BATCH_MAX_REQUEST) { - throw new RangeError(`Cannot exceed ${BATCH_MAX_REQUEST} sub requests in a single batch`); + const include2 = []; + if (options.includeCopy) { + include2.push("copy"); } - const path6 = getURLPath(subRequest.url); - if (!path6 || path6 === "") { - throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); + if (options.includeDeleted) { + include2.push("deleted"); } - } - postAddSubRequest(subRequest) { - this.subRequests.set(this.operationCount, subRequest); - this.operationCount++; - } - // Return the http request body with assembling the ending line to the sub request body. - getHttpRequestBody() { - return `${this.body}${this.batchRequestEnding}${HTTP_LINE_ENDING}`; - } - getMultipartContentType() { - return this.multipartContentType; - } - getSubRequests() { - return this.subRequests; - } - }; - function batchRequestAssemblePolicy(batchRequest) { - return { - name: "batchRequestAssemblePolicy", - async sendRequest(request) { - batchRequest.appendSubRequestToBody(request); - return { - request, - status: 200, - headers: coreRestPipeline.createHttpHeaders() - }; + if (options.includeMetadata) { + include2.push("metadata"); } - }; - } - function batchHeaderFilterPolicy() { - return { - name: "batchHeaderFilterPolicy", - async sendRequest(request, next) { - let xMsHeaderName = ""; - for (const [name] of request.headers) { - if (iEqual(name, HeaderConstants.X_MS_VERSION)) { - xMsHeaderName = name; - } - } - if (xMsHeaderName !== "") { - request.headers.delete(xMsHeaderName); - } - return next(request); + if (options.includeSnapshots) { + include2.push("snapshots"); + } + if (options.includeVersions) { + include2.push("versions"); + } + if (options.includeUncommitedBlobs) { + include2.push("uncommittedblobs"); } - }; - } - var BlobBatchClient = class { - constructor(url2, credentialOrPipeline, options) { - let pipeline; - if (isPipelineLike(credentialOrPipeline)) { - pipeline = credentialOrPipeline; - } else if (!credentialOrPipeline) { - pipeline = newPipeline(new AnonymousCredential(), options); - } else { - pipeline = newPipeline(credentialOrPipeline, options); + if (options.includeTags) { + include2.push("tags"); } - const storageClientContext = new StorageContextClient(url2, getCoreClientOptions(pipeline)); - const path6 = getURLPath(url2); - if (path6 && path6 !== "/") { - this.serviceOrContainerContext = storageClientContext.container; - } else { - this.serviceOrContainerContext = storageClientContext.service; + if (options.includeDeletedWithVersions) { + include2.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include2.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include2.push("legalhold"); + } + if (options.prefix === "") { + options.prefix = void 0; } + const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); + const iter = this.listItemsByHierarchy(delimiter2, updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + async next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listHierarchySegments(delimiter2, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; } /** - * Creates a {@link BlobBatch}. - * A BlobBatch represents an aggregated set of operations on blobs. + * The Filter Blobs operation enables callers to list blobs in the container whose tags + * match a given search expression. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to find blobs by tags. */ - createBatch() { - return new BlobBatch(); + async findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options = {}) { + return tracingClient.withSpan("ContainerClient-findBlobsByTagsSegment", options, async (updatedOptions) => { + const response = assertResponse(await this.containerContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker: marker2, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { + var _a; + let tagValue = ""; + if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); + }) }); + return wrappedResponse; + }); } - async deleteBlobs(urlsOrBlobClients, credentialOrOptions, options) { - const batch = new BlobBatch(); - for (const urlOrBlobClient of urlsOrBlobClients) { - if (typeof urlOrBlobClient === "string") { - await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); - } else { - await batch.deleteBlob(urlOrBlobClient, credentialOrOptions); + /** + * Returns an AsyncIterableIterator for ContainerFindBlobsByTagsSegmentResponse. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to find blobs by tags. + */ + findBlobsByTagsSegments(tagFilterSqlExpression_1, marker_1) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1(tagFilterSqlExpression, marker2, options = {}) { + let response; + if (!!marker2 || marker2 === void 0) { + do { + response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options)); + response.blobs = response.blobs || []; + marker2 = response.continuationToken; + yield yield tslib.__await(response); + } while (marker2); } - } - return this.submitBatch(batch); + }); } - async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { - const batch = new BlobBatch(); - for (const urlOrBlobClient of urlsOrBlobClients) { - if (typeof urlOrBlobClient === "string") { - await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); - } else { - await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); + /** + * Returns an AsyncIterableIterator for blobs. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param options - Options to findBlobsByTagsItems. + */ + findBlobsByTagsItems(tagFilterSqlExpression_1) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { + var _a, e_3, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const segment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_3) throw e_3.error; + } } - } - return this.submitBatch(batch); + }); } /** - * Submit batch request which consists of multiple subrequests. + * Returns an async iterable iterator to find all blobs with specified tag + * under the specified container. * - * Get `blobBatchClient` and other details before running the snippets. - * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` + * .byPage() returns an async iterable iterator to list the blobs in pages. * - * Example usage: + * Example using `for await` syntax: * * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.deleteBlob(urlInString0, credential0); - * await batchRequest.deleteBlob(urlInString1, credential1, { - * deleteSnapshots: "include" - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); + * let i = 1; + * for await (const blob of containerClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } * ``` * - * Example using a lease: + * Example using `iter.next()`: * * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); - * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { - * conditions: { leaseId: leaseId } - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); + * let i = 1; + * const iter = containerClient.findBlobsByTags("tagkey='tagvalue'"); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } * ``` * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * Example using `byPage()`: * - * @param batchRequest - A set of Delete or SetTier operations. - * @param options - + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = containerClient + * .findBlobsByTags("tagkey='tagvalue'") + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param options - Options to find blobs by tags. */ - async submitBatch(batchRequest, options = {}) { - if (!batchRequest || batchRequest.getSubRequests().size === 0) { - throw new RangeError("Batch request should contain one or more sub requests."); - } - return tracingClient.withSpan("BlobBatchClient-submitBatch", options, async (updatedOptions) => { - const batchRequestBody = batchRequest.getHttpRequestBody(); - const rawBatchResponse = assertResponse(await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, Object.assign({}, updatedOptions))); - const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); - const responseSummary = await batchResponseParser.parseBatchResponse(); - const res = { - _response: rawBatchResponse._response, - contentType: rawBatchResponse.contentType, - errorCode: rawBatchResponse.errorCode, - requestId: rawBatchResponse.requestId, - clientRequestId: rawBatchResponse.clientRequestId, - version: rawBatchResponse.version, - subResponses: responseSummary.subResponses, - subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, - subResponsesFailedCount: responseSummary.subResponsesFailedCount - }; - return res; - }); + findBlobsByTags(tagFilterSqlExpression, options = {}) { + const listSegmentOptions = Object.assign({}, options); + const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; } - }; - var ContainerClient = class extends StorageClient { /** - * The name of the container. + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * + * @param options - Options to the Service Get Account Info operation. + * @returns Response data for the Service Get Account Info operation. */ - get containerName() { - return this._containerName; + async getAccountInfo(options = {}) { + return tracingClient.withSpan("ContainerClient-getAccountInfo", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); } - constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { - let pipeline; - let url2; - options = options || {}; - if (isPipelineLike(credentialOrPipelineOrContainerName)) { - url2 = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } else if (coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipelineOrContainerName)) { - url2 = urlOrConnectionString; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { - url2 = urlOrConnectionString; - pipeline = newPipeline(new AnonymousCredential(), options); - } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { - const containerName = credentialOrPipelineOrContainerName; - const extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - if (coreUtil.isNode) { - const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url2 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); - if (!options.proxyOptions) { - options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); - } - pipeline = newPipeline(sharedKeyCredential, options); - } else { - throw new Error("Account connection string is only supported in Node.js environment"); - } - } else if (extractedCreds.kind === "SASConnString") { - url2 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + "?" + extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); + getContainerNameFromUrl() { + let containerName; + try { + const parsedUrl = new URL(this.url); + if (parsedUrl.hostname.split(".")[1] === "blob") { + containerName = parsedUrl.pathname.split("/")[1]; + } else if (isIpEndpointStyle(parsedUrl)) { + containerName = parsedUrl.pathname.split("/")[2]; } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + containerName = parsedUrl.pathname.split("/")[1]; } - } else { - throw new Error("Expecting non-empty strings for containerName parameter"); + containerName = decodeURIComponent(containerName); + if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return containerName; + } catch (error4) { + throw new Error("Unable to extract containerName with provided information."); } - super(url2, pipeline); - this._containerName = this.getContainerNameFromUrl(); - this.containerContext = this.storageClientContext.container; } /** - * Creates a new container under the specified account. If the container with - * the same name already exists, the operation fails. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container - * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata - * - * @param options - Options to Container Create operation. + * Only available for ContainerClient constructed with a shared key credential. * + * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. * - * Example usage: + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * const createContainerResponse = await containerClient.create(); - * console.log("Container was created successfully", createContainerResponse.requestId); - * ``` + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - async create(options = {}) { - return tracingClient.withSpan("ContainerClient-create", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.create(updatedOptions)); + generateSasUrl(options) { + return new Promise((resolve5) => { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); + resolve5(appendToURLQuery(this.url, sas)); }); } /** - * Creates a new container under the specified account. If the container with - * the same name already exists, it is not changed. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container - * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata + * Only available for ContainerClient constructed with a shared key credential. * - * @param options - + * Generates string to sign for a Blob Container Service Shared Access Signature (SAS) URI + * based on the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - async createIfNotExists(options = {}) { - return tracingClient.withSpan("ContainerClient-createIfNotExists", options, async (updatedOptions) => { - var _a, _b; - try { - const res = await this.create(updatedOptions); - return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); - } catch (e) { - if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { - return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); - } else { - throw e; - } - } - }); + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + generateSasStringToSign(options) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName }, options), this.credential).stringToSign; } /** - * Returns true if the Azure container resource represented by this client exists; false otherwise. + * Creates a BlobBatchClient object to conduct batch operations. * - * NOTE: use this function with care since an existing container might be deleted by other clients or - * applications. Vice versa new containers with the same name might be added by other clients or - * applications after this function completes. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * - * @param options - + * @returns A new BlobBatchClient object for this container. */ - async exists(options = {}) { - return tracingClient.withSpan("ContainerClient-exists", options, async (updatedOptions) => { - try { - await this.getProperties({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - }); - return true; - } catch (e) { - if (e.statusCode === 404) { - return false; - } - throw e; + getBlobBatchClient() { + return new BlobBatchClient(this.url, this.pipeline); + } + }; + var AccountSASPermissions = class _AccountSASPermissions { + constructor() { + this.read = false; + this.write = false; + this.delete = false; + this.deleteVersion = false; + this.list = false; + this.add = false; + this.create = false; + this.update = false; + this.process = false; + this.tag = false; + this.filter = false; + this.setImmutabilityPolicy = false; + this.permanentDelete = false; + } + /** + * Parse initializes the AccountSASPermissions fields from a string. + * + * @param permissions - + */ + static parse(permissions) { + const accountSASPermissions = new _AccountSASPermissions(); + for (const c of permissions) { + switch (c) { + case "r": + accountSASPermissions.read = true; + break; + case "w": + accountSASPermissions.write = true; + break; + case "d": + accountSASPermissions.delete = true; + break; + case "x": + accountSASPermissions.deleteVersion = true; + break; + case "l": + accountSASPermissions.list = true; + break; + case "a": + accountSASPermissions.add = true; + break; + case "c": + accountSASPermissions.create = true; + break; + case "u": + accountSASPermissions.update = true; + break; + case "p": + accountSASPermissions.process = true; + break; + case "t": + accountSASPermissions.tag = true; + break; + case "f": + accountSASPermissions.filter = true; + break; + case "i": + accountSASPermissions.setImmutabilityPolicy = true; + break; + case "y": + accountSASPermissions.permanentDelete = true; + break; + default: + throw new RangeError(`Invalid permission character: ${c}`); } - }); - } - /** - * Creates a {@link BlobClient} - * - * @param blobName - A blob name - * @returns A new BlobClient object for the given blob name. - */ - getBlobClient(blobName) { - return new BlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + return accountSASPermissions; } /** - * Creates an {@link AppendBlobClient} + * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. * - * @param blobName - An append blob name + * @param permissionLike - */ - getAppendBlobClient(blobName) { - return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + static from(permissionLike) { + const accountSASPermissions = new _AccountSASPermissions(); + if (permissionLike.read) { + accountSASPermissions.read = true; + } + if (permissionLike.write) { + accountSASPermissions.write = true; + } + if (permissionLike.delete) { + accountSASPermissions.delete = true; + } + if (permissionLike.deleteVersion) { + accountSASPermissions.deleteVersion = true; + } + if (permissionLike.filter) { + accountSASPermissions.filter = true; + } + if (permissionLike.tag) { + accountSASPermissions.tag = true; + } + if (permissionLike.list) { + accountSASPermissions.list = true; + } + if (permissionLike.add) { + accountSASPermissions.add = true; + } + if (permissionLike.create) { + accountSASPermissions.create = true; + } + if (permissionLike.update) { + accountSASPermissions.update = true; + } + if (permissionLike.process) { + accountSASPermissions.process = true; + } + if (permissionLike.setImmutabilityPolicy) { + accountSASPermissions.setImmutabilityPolicy = true; + } + if (permissionLike.permanentDelete) { + accountSASPermissions.permanentDelete = true; + } + return accountSASPermissions; } /** - * Creates a {@link BlockBlobClient} - * - * @param blobName - A block blob name - * + * Produces the SAS permissions string for an Azure Storage account. + * Call this method to set AccountSASSignatureValues Permissions field. * - * Example usage: + * Using this method will guarantee the resource types are in + * an order accepted by the service. * - * ```js - * const content = "Hello world!"; + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * - * const blockBlobClient = containerClient.getBlockBlobClient(""); - * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); - * ``` */ - getBlockBlobClient(blobName) { - return new BlockBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + toString() { + const permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.filter) { + permissions.push("f"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.list) { + permissions.push("l"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.update) { + permissions.push("u"); + } + if (this.process) { + permissions.push("p"); + } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } + if (this.permanentDelete) { + permissions.push("y"); + } + return permissions.join(""); } - /** - * Creates a {@link PageBlobClient} - * - * @param blobName - A page blob name - */ - getPageBlobClient(blobName) { - return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + }; + var AccountSASResourceTypes = class _AccountSASResourceTypes { + constructor() { + this.service = false; + this.container = false; + this.object = false; } /** - * Returns all user-defined metadata and system properties for the specified - * container. The data returned does not include the container's list of blobs. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties - * - * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if - * they originally contained uppercase characters. This differs from the metadata keys returned by - * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which - * will retain their original casing. + * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an + * Error if it encounters a character that does not correspond to a valid resource type. * - * @param options - Options to Container Get Properties operation. + * @param resourceTypes - */ - async getProperties(options = {}) { - if (!options.conditions) { - options.conditions = {}; + static parse(resourceTypes) { + const accountSASResourceTypes = new _AccountSASResourceTypes(); + for (const c of resourceTypes) { + switch (c) { + case "s": + accountSASResourceTypes.service = true; + break; + case "c": + accountSASResourceTypes.container = true; + break; + case "o": + accountSASResourceTypes.object = true; + break; + default: + throw new RangeError(`Invalid resource type: ${c}`); + } } - return tracingClient.withSpan("ContainerClient-getProperties", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), { tracingOptions: updatedOptions.tracingOptions }))); - }); + return accountSASResourceTypes; } /** - * Marks the specified container for deletion. The container and any blobs - * contained within it are later deleted during garbage collection. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * Converts the given resource types to a string. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * - * @param options - Options to Container Delete operation. */ - async delete(options = {}) { - if (!options.conditions) { - options.conditions = {}; + toString() { + const resourceTypes = []; + if (this.service) { + resourceTypes.push("s"); } - return tracingClient.withSpan("ContainerClient-delete", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.delete({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); + if (this.container) { + resourceTypes.push("c"); + } + if (this.object) { + resourceTypes.push("o"); + } + return resourceTypes.join(""); + } + }; + var AccountSASServices = class _AccountSASServices { + constructor() { + this.blob = false; + this.file = false; + this.queue = false; + this.table = false; } /** - * Marks the specified container for deletion if it exists. The container and any blobs - * contained within it are later deleted during garbage collection. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * Creates an {@link AccountSASServices} from the specified services string. This method will throw an + * Error if it encounters a character that does not correspond to a valid service. * - * @param options - Options to Container Delete operation. + * @param services - */ - async deleteIfExists(options = {}) { - return tracingClient.withSpan("ContainerClient-deleteIfExists", options, async (updatedOptions) => { - var _a, _b; - try { - const res = await this.delete(updatedOptions); - return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); - } catch (e) { - if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { - return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); - } - throw e; + static parse(services) { + const accountSASServices = new _AccountSASServices(); + for (const c of services) { + switch (c) { + case "b": + accountSASServices.blob = true; + break; + case "f": + accountSASServices.file = true; + break; + case "q": + accountSASServices.queue = true; + break; + case "t": + accountSASServices.table = true; + break; + default: + throw new RangeError(`Invalid service character: ${c}`); } - }); + } + return accountSASServices; } /** - * Sets one or more user-defined name-value pairs for the specified container. - * - * If no option provided, or no metadata defined in the parameter, the container - * metadata will be removed. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * Converts the given services to a string. * - * @param metadata - Replace existing metadata with this value. - * If no value provided the existing metadata will be removed. - * @param options - Options to Container Set Metadata operation. */ - async setMetadata(metadata2, options = {}) { - if (!options.conditions) { - options.conditions = {}; + toString() { + const services = []; + if (this.blob) { + services.push("b"); } - if (options.conditions.ifUnmodifiedSince) { - throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + if (this.table) { + services.push("t"); } - return tracingClient.withSpan("ContainerClient-setMetadata", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.setMetadata({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: metadata2, - modifiedAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); - } - /** - * Gets the permissions for the specified container. The permissions indicate - * whether container data may be accessed publicly. - * - * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. - * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl - * - * @param options - Options to Container Get Access Policy operation. - */ - async getAccessPolicy(options = {}) { - if (!options.conditions) { - options.conditions = {}; + if (this.queue) { + services.push("q"); } - return tracingClient.withSpan("ContainerClient-getAccessPolicy", options, async (updatedOptions) => { - const response = assertResponse(await this.containerContext.getAccessPolicy({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - const res = { - _response: response._response, - blobPublicAccess: response.blobPublicAccess, - date: response.date, - etag: response.etag, - errorCode: response.errorCode, - lastModified: response.lastModified, - requestId: response.requestId, - clientRequestId: response.clientRequestId, - signedIdentifiers: [], - version: response.version - }; - for (const identifier of response) { - let accessPolicy = void 0; - if (identifier.accessPolicy) { - accessPolicy = { - permissions: identifier.accessPolicy.permissions - }; - if (identifier.accessPolicy.expiresOn) { - accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); - } - if (identifier.accessPolicy.startsOn) { - accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); - } - } - res.signedIdentifiers.push({ - accessPolicy, - id: identifier.id - }); - } - return res; - }); + if (this.file) { + services.push("f"); + } + return services.join(""); } - /** - * Sets the permissions for the specified container. The permissions indicate - * whether blobs in a container may be accessed publicly. - * - * When you set permissions for a container, the existing permissions are replaced. - * If no access or containerAcl provided, the existing container ACL will be - * removed. - * - * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. - * During this interval, a shared access signature that is associated with the stored access policy will - * fail with status code 403 (Forbidden), until the access policy becomes active. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl - * - * @param access - The level of public access to data in the container. - * @param containerAcl - Array of elements each having a unique Id and details of the access policy. - * @param options - Options to Container Set Access Policy operation. - */ - async setAccessPolicy(access2, containerAcl2, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("ContainerClient-setAccessPolicy", options, async (updatedOptions) => { - const acl = []; - for (const identifier of containerAcl2 || []) { - acl.push({ - accessPolicy: { - expiresOn: identifier.accessPolicy.expiresOn ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) : "", - permissions: identifier.accessPolicy.permissions, - startsOn: identifier.accessPolicy.startsOn ? truncatedISO8061Date(identifier.accessPolicy.startsOn) : "" - }, - id: identifier.id - }); - } - return assertResponse(await this.containerContext.setAccessPolicy({ - abortSignal: options.abortSignal, - access: access2, - containerAcl: acl, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); + }; + function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + return generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential).sasQueryParameters; + } + function generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) { + const version2 = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.setImmutabilityPolicy && version2 < "2020-08-04") { + throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); } - /** - * Get a {@link BlobLeaseClient} that manages leases on the container. - * - * @param proposeLeaseId - Initial proposed lease Id. - * @returns A new BlobLeaseClient object for managing leases on the container. - */ - getBlobLeaseClient(proposeLeaseId) { - return new BlobLeaseClient(this, proposeLeaseId); + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.deleteVersion && version2 < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.permanentDelete && version2 < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'y' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.tag && version2 < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.filter && version2 < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); + } + if (accountSASSignatureValues.encryptionScope && version2 < "2020-12-06") { + throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); + } + const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + let stringToSign; + if (version2 >= "2020-12-06") { + stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version2, + accountSASSignatureValues.encryptionScope ? accountSASSignatureValues.encryptionScope : "", + "" + // Account SAS requires an additional newline character + ].join("\n"); + } else { + stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version2, + "" + // Account SAS requires an additional newline character + ].join("\n"); } + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(version2, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, accountSASSignatureValues.encryptionScope), + stringToSign + }; + } + var BlobServiceClient = class _BlobServiceClient extends StorageClient { /** - * Creates a new block blob, or updates the content of an existing block blob. - * - * Updating an existing block blob overwrites any existing metadata on the blob. - * Partial updates are not supported; the content of the existing blob is - * overwritten with the new content. To perform a partial update of a block blob's, - * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. - * - * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, - * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better - * performance with concurrency uploading. * - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * Creates an instance of BlobServiceClient from connection string. * - * @param blobName - Name of the block blob to create or update. - * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function - * which returns a new Readable stream whose offset is from data source beginning. - * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a - * string including non non-Base64/Hex-encoded characters. - * @param options - Options to configure the Block Blob Upload operation. - * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. + * @param connectionString - Account connection string or a SAS connection string of an Azure storage account. + * [ Note - Account connection string can only be used in NODE.JS runtime. ] + * Account connection string example - + * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` + * SAS connection string example - + * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` + * @param options - Optional. Options to configure the HTTP pipeline. */ - async uploadBlockBlob(blobName, body2, contentLength2, options = {}) { - return tracingClient.withSpan("ContainerClient-uploadBlockBlob", options, async (updatedOptions) => { - const blockBlobClient = this.getBlockBlobClient(blobName); - const response = await blockBlobClient.upload(body2, contentLength2, updatedOptions); - return { - blockBlobClient, - response - }; - }); + static fromConnectionString(connectionString, options) { + options = options || {}; + const extractedCreds = extractConnectionStringParts(connectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + const pipeline = newPipeline(sharedKeyCredential, options); + return new _BlobServiceClient(extractedCreds.url, pipeline); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + const pipeline = newPipeline(new AnonymousCredential(), options); + return new _BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + constructor(url2, credentialOrPipeline, options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { + pipeline = credentialOrPipeline; + } else if (coreUtil.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential || credentialOrPipeline instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipeline)) { + pipeline = newPipeline(credentialOrPipeline, options); + } else { + pipeline = newPipeline(new AnonymousCredential(), options); + } + super(url2, pipeline); + this.serviceContext = this.storageClientContext.service; } /** - * Marks the specified blob or snapshot for deletion. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * Creates a {@link ContainerClient} object * - * @param blobName - - * @param options - Options to Blob Delete operation. - * @returns Block blob deletion response data. + * @param containerName - A container name + * @returns A new ContainerClient object for the given container name. + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * ``` */ - async deleteBlob(blobName, options = {}) { - return tracingClient.withSpan("ContainerClient-deleteBlob", options, async (updatedOptions) => { - let blobClient = this.getBlobClient(blobName); - if (options.versionId) { - blobClient = blobClient.withVersion(options.versionId); - } - return blobClient.delete(updatedOptions); - }); + getContainerClient(containerName) { + return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); } /** - * listBlobFlatSegment returns a single segment of blobs starting from the - * specified Marker. Use an empty Marker to start enumeration from the beginning. - * After getting a segment, process it, and then call listBlobsFlatSegment again - * (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * Create a Blob container. @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container * - * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. - * @param options - Options to Container List Blob Flat Segment operation. + * @param containerName - Name of the container to create. + * @param options - Options to configure Container Create operation. + * @returns Container creation response and the corresponding container client. */ - async listBlobFlatSegment(marker2, options = {}) { - return tracingClient.withSpan("ContainerClient-listBlobFlatSegment", options, async (updatedOptions) => { - const response = assertResponse(await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); - const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobFlat(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { - const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return wrappedResponse; + async createContainer(containerName, options = {}) { + return tracingClient.withSpan("BlobServiceClient-createContainer", options, async (updatedOptions) => { + const containerClient = this.getContainerClient(containerName); + const containerCreateResponse = await containerClient.create(updatedOptions); + return { + containerClient, + containerCreateResponse + }; }); } /** - * listBlobHierarchySegment returns a single segment of blobs starting from - * the specified Marker. Use an empty Marker to start enumeration from the - * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment - * again (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * Deletes a Blob container. * - * @param delimiter - The character or string used to define the virtual hierarchy - * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. - * @param options - Options to Container List Blob Hierarchy Segment operation. + * @param containerName - Name of the container to delete. + * @param options - Options to configure Container Delete operation. + * @returns Container deletion response. */ - async listBlobHierarchySegment(delimiter2, marker2, options = {}) { - return tracingClient.withSpan("ContainerClient-listBlobHierarchySegment", options, async (updatedOptions) => { - var _a; - const response = assertResponse(await this.containerContext.listBlobHierarchySegment(delimiter2, Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); - const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobHierarchy(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { - const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); - return blobItem; - }), blobPrefixes: (_a = response.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { - const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); - return blobPrefix; - }) }) }); - return wrappedResponse; + async deleteContainer(containerName, options = {}) { + return tracingClient.withSpan("BlobServiceClient-deleteContainer", options, async (updatedOptions) => { + const containerClient = this.getContainerClient(containerName); + return containerClient.delete(updatedOptions); }); } /** - * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * Restore a previously deleted Blob container. + * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. * - * @param marker - A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the ContinuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to list blobs operation. + * @param deletedContainerName - Name of the previously deleted container. + * @param deletedContainerVersion - Version of the previously deleted container, used to uniquely identify the deleted container. + * @param options - Options to configure Container Restore operation. + * @returns Container deletion response. */ - listSegments(marker_1) { - return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { - let listBlobsFlatSegmentResponse; - if (!!marker2 || marker2 === void 0) { - do { - listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker2, options)); - marker2 = listBlobsFlatSegmentResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); - } while (marker2); - } + async undeleteContainer(deletedContainerName2, deletedContainerVersion2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-undeleteContainer", options, async (updatedOptions) => { + const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName2); + const containerContext = containerClient["storageClientContext"].container; + const containerUndeleteResponse = assertResponse(await containerContext.restore({ + deletedContainerName: deletedContainerName2, + deletedContainerVersion: deletedContainerVersion2, + tracingOptions: updatedOptions.tracingOptions + })); + return { containerClient, containerUndeleteResponse }; }); } /** - * Returns an AsyncIterableIterator of {@link BlobItem} objects + * Rename an existing Blob Container. * - * @param options - Options to list blobs operation. + * @param sourceContainerName - The name of the source container. + * @param destinationContainerName - The new name of the container. + * @param options - Options to configure Container Rename operation. */ - listItems() { - return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { - var _a, e_1, _b, _c; - let marker2; - try { - for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const listBlobsFlatSegmentResponse = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_1) throw e_1.error; - } - } + /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ + // @ts-ignore Need to hide this interface for now. Make it public and turn on the live tests for it when the service is ready. + async renameContainer(sourceContainerName2, destinationContainerName, options = {}) { + return tracingClient.withSpan("BlobServiceClient-renameContainer", options, async (updatedOptions) => { + var _a; + const containerClient = this.getContainerClient(destinationContainerName); + const containerContext = containerClient["storageClientContext"].container; + const containerRenameResponse = assertResponse(await containerContext.rename(sourceContainerName2, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId }))); + return { containerClient, containerRenameResponse }; }); } /** - * Returns an async iterable iterator to list all the blobs - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * Example using `for await` syntax: - * - * ```js - * // Get the containerClient before you run these snippets, - * // Can be obtained from `blobServiceClient.getContainerClient("");` - * let i = 1; - * for await (const blob of containerClient.listBlobsFlat()) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * let iter = containerClient.listBlobsFlat(); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * - * // Passing next marker as continuationToken - * - * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints 10 blob names - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * ``` + * Gets the properties of a storage account’s Blob service, including properties + * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties * - * @param options - Options to list blobs. - * @returns An asyncIterableIterator that supports paging. + * @param options - Options to the Service Get Properties operation. + * @returns Response data for the Service Get Properties operation. */ - listBlobsFlat(options = {}) { - const include2 = []; - if (options.includeCopy) { - include2.push("copy"); - } - if (options.includeDeleted) { - include2.push("deleted"); - } - if (options.includeMetadata) { - include2.push("metadata"); - } - if (options.includeSnapshots) { - include2.push("snapshots"); - } - if (options.includeVersions) { - include2.push("versions"); - } - if (options.includeUncommitedBlobs) { - include2.push("uncommittedblobs"); - } - if (options.includeTags) { - include2.push("tags"); - } - if (options.includeDeletedWithVersions) { - include2.push("deletedwithversions"); - } - if (options.includeImmutabilityPolicy) { - include2.push("immutabilitypolicy"); - } - if (options.includeLegalHold) { - include2.push("legalhold"); - } - if (options.prefix === "") { - options.prefix = void 0; - } - const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); - const iter = this.listItems(updatedOptions); - return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - } - }; + async getProperties(options = {}) { + return tracingClient.withSpan("BlobServiceClient-getProperties", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); } /** - * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * Sets properties for a storage account’s Blob service endpoint, including properties + * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties * - * @param delimiter - The character or string used to define the virtual hierarchy - * @param marker - A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the ContinuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to list blobs operation. + * @param properties - + * @param options - Options to the Service Set Properties operation. + * @returns Response data for the Service Set Properties operation. */ - listHierarchySegments(delimiter_1, marker_1) { - return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1(delimiter2, marker2, options = {}) { - let listBlobsHierarchySegmentResponse; - if (!!marker2 || marker2 === void 0) { - do { - listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter2, marker2, options)); - marker2 = listBlobsHierarchySegmentResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); - } while (marker2); - } + async setProperties(properties, options = {}) { + return tracingClient.withSpan("BlobServiceClient-setProperties", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.setProperties(properties, { + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); }); } /** - * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * Retrieves statistics related to replication for the Blob service. It is only + * available on the secondary location endpoint when read-access geo-redundant + * replication is enabled for the storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats * - * @param delimiter - The character or string used to define the virtual hierarchy - * @param options - Options to list blobs operation. + * @param options - Options to the Service Get Statistics operation. + * @returns Response data for the Service Get Statistics operation. */ - listItemsByHierarchy(delimiter_1) { - return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1(delimiter2, options = {}) { - var _a, e_2, _b, _c; - let marker2; - try { - for (var _d = true, _e = tslib.__asyncValues(this.listHierarchySegments(delimiter2, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const listBlobsHierarchySegmentResponse = _c; - const segment = listBlobsHierarchySegmentResponse.segment; - if (segment.blobPrefixes) { - for (const prefix2 of segment.blobPrefixes) { - yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix2)); - } - } - for (const blob of segment.blobItems) { - yield yield tslib.__await(Object.assign({ kind: "blob" }, blob)); - } - } - } catch (e_2_1) { - e_2 = { error: e_2_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_2) throw e_2.error; - } - } + async getStatistics(options = {}) { + return tracingClient.withSpan("BlobServiceClient-getStatistics", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.getStatistics({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); }); } /** - * Returns an async iterable iterator to list all the blobs by hierarchy. - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. - * - * Example using `for await` syntax: - * - * ```js - * for await (const item of containerClient.listBlobsByHierarchy("/")) { - * if (item.kind === "prefix") { - * console.log(`\tBlobPrefix: ${item.name}`); - * } else { - * console.log(`\tBlobItem: name - ${item.name}`); - * } - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); - * let entity = await iter.next(); - * while (!entity.done) { - * let item = entity.value; - * if (item.kind === "prefix") { - * console.log(`\tBlobPrefix: ${item.name}`); - * } else { - * console.log(`\tBlobItem: name - ${item.name}`); - * } - * entity = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * console.log("Listing blobs by hierarchy by page"); - * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { - * const segment = response.segment; - * if (segment.blobPrefixes) { - * for (const prefix of segment.blobPrefixes) { - * console.log(`\tBlobPrefix: ${prefix.name}`); - * } - * } - * for (const blob of response.segment.blobItems) { - * console.log(`\tBlobItem: name - ${blob.name}`); - * } - * } - * ``` - * - * Example using paging with a max page size: - * - * ```js - * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); - * - * let i = 1; - * for await (const response of containerClient - * .listBlobsByHierarchy("/", { prefix: "prefix2/sub1/" }) - * .byPage({ maxPageSize: 2 })) { - * console.log(`Page ${i++}`); - * const segment = response.segment; - * - * if (segment.blobPrefixes) { - * for (const prefix of segment.blobPrefixes) { - * console.log(`\tBlobPrefix: ${prefix.name}`); - * } - * } - * - * for (const blob of response.segment.blobItems) { - * console.log(`\tBlobItem: name - ${blob.name}`); - * } - * } - * ``` + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information * - * @param delimiter - The character or string used to define the virtual hierarchy - * @param options - Options to list blobs operation. - */ - listBlobsByHierarchy(delimiter2, options = {}) { - if (delimiter2 === "") { - throw new RangeError("delimiter should contain one or more characters"); - } - const include2 = []; - if (options.includeCopy) { - include2.push("copy"); - } - if (options.includeDeleted) { - include2.push("deleted"); - } - if (options.includeMetadata) { - include2.push("metadata"); - } - if (options.includeSnapshots) { - include2.push("snapshots"); - } - if (options.includeVersions) { - include2.push("versions"); - } - if (options.includeUncommitedBlobs) { - include2.push("uncommittedblobs"); - } - if (options.includeTags) { - include2.push("tags"); - } - if (options.includeDeletedWithVersions) { - include2.push("deletedwithversions"); - } - if (options.includeImmutabilityPolicy) { - include2.push("immutabilitypolicy"); - } - if (options.includeLegalHold) { - include2.push("legalhold"); - } - if (options.prefix === "") { - options.prefix = void 0; - } - const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); - const iter = this.listItemsByHierarchy(delimiter2, updatedOptions); - return { - /** - * The next method, part of the iteration protocol - */ - async next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listHierarchySegments(delimiter2, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - } - }; + * @param options - Options to the Service Get Account Info operation. + * @returns Response data for the Service Get Account Info operation. + */ + async getAccountInfo(options = {}) { + return tracingClient.withSpan("BlobServiceClient-getAccountInfo", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); } /** - * The Filter Blobs operation enables callers to list blobs in the container whose tags - * match a given search expression. + * Returns a list of the containers under the specified account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 + * + * @param marker - A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to the Service List Container Segment operation. + * @returns Response data for the Service List Container Segment operation. + */ + async listContainersSegment(marker2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-listContainersSegment", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.listContainersSegment(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker: marker2 }, options), { include: typeof options.include === "string" ? [options.include] : options.include, tracingOptions: updatedOptions.tracingOptions }))); + }); + } + /** + * The Filter Blobs operation enables callers to list blobs across all containers whose tags + * match a given search expression. Filter blobs searches across all containers within a + * storage account but can be scoped within the expression to a single container. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. @@ -66292,8 +68644,8 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * @param options - Options to find blobs by tags. */ async findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options = {}) { - return tracingClient.withSpan("ContainerClient-findBlobsByTagsSegment", options, async (updatedOptions) => { - const response = assertResponse(await this.containerContext.filterBlobs({ + return tracingClient.withSpan("BlobServiceClient-findBlobsByTagsSegment", options, async (updatedOptions) => { + const response = assertResponse(await this.serviceContext.filterBlobs({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker: marker2, @@ -66312,7 +68664,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; }); } /** - * Returns an AsyncIterableIterator for ContainerFindBlobsByTagsSegmentResponse. + * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. @@ -66351,7 +68703,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; */ findBlobsByTagsItems(tagFilterSqlExpression_1) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { - var _a, e_3, _b, _c; + var _a, e_1, _b, _c; let marker2; try { for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { @@ -66360,29 +68712,31 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; const segment = _c; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); } - } catch (e_3_1) { - e_3 = { error: e_3_1 }; + } catch (e_1_1) { + e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); } finally { - if (e_3) throw e_3.error; + if (e_1) throw e_1.error; } } }); } /** * Returns an async iterable iterator to find all blobs with specified tag - * under the specified container. + * under the specified account. * * .byPage() returns an async iterable iterator to list the blobs in pages. * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * * Example using `for await` syntax: * * ```js * let i = 1; - * for await (const blob of containerClient.findBlobsByTags("tagkey='tagvalue'")) { - * console.log(`Blob ${i++}: ${blob.name}`); + * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${container.name}`); * } * ``` * @@ -66390,7 +68744,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * * ```js * let i = 1; - * const iter = containerClient.findBlobsByTags("tagkey='tagvalue'"); + * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); * let blobItem = await iter.next(); * while (!blobItem.done) { * console.log(`Blob ${i++}: ${blobItem.value.name}`); @@ -66403,7 +68757,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * ```js * // passing optional maxPageSize in the page settings * let i = 1; - * for await (const response of containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); @@ -66416,7 +68770,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * * ```js * let i = 1; - * let iterator = containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 blob names @@ -66429,7 +68783,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * // Gets next marker * let marker = response.continuationToken; * // Passing next marker as continuationToken - * iterator = containerClient + * iterator = blobServiceClient * .findBlobsByTags("tagkey='tagvalue'") * .byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; @@ -66473,5969 +68827,6548 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; }; } /** - * The Get Account Information operation returns the sku name and account kind - * for the specified account. - * The Get Account Information operation is available on service versions beginning - * with version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses * - * @param options - Options to the Service Get Account Info operation. - * @returns Response data for the Service Get Account Info operation. + * @param marker - A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to list containers operation. */ - async getAccountInfo(options = {}) { - return tracingClient.withSpan("ContainerClient-getAccountInfo", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.getAccountInfo({ + listSegments(marker_1) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { + let listContainersSegmentResponse; + if (!!marker2 || marker2 === void 0) { + do { + listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker2, options)); + listContainersSegmentResponse.containerItems = listContainersSegmentResponse.containerItems || []; + marker2 = listContainersSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator for Container Items + * + * @param options - Options to list containers operation. + */ + listItems() { + return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { + var _a, e_2, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const segment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list all the containers + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the containers in pages. + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const container of blobServiceClient.listContainers()) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.listContainers(); + * let containerItem = await iter.next(); + * while (!containerItem.done) { + * console.log(`Container ${i++}: ${containerItem.value.name}`); + * containerItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .listContainers() + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * ``` + * + * @param options - Options to list containers. + * @returns An asyncIterableIterator that supports paging. + */ + listContainers(options = {}) { + if (options.prefix === "") { + options.prefix = void 0; + } + const include2 = []; + if (options.includeDeleted) { + include2.push("deleted"); + } + if (options.includeMetadata) { + include2.push("metadata"); + } + if (options.includeSystem) { + include2.push("system"); + } + const listSegmentOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); + const iter = this.listItems(listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; + } + /** + * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). + * + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * + * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time + * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time + */ + async getUserDelegationKey(startsOn, expiresOn2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-getUserDelegationKey", options, async (updatedOptions) => { + const response = assertResponse(await this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn2, false) + }, { abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions })); + const userDelegationKey = { + signedObjectId: response.signedObjectId, + signedTenantId: response.signedTenantId, + signedStartsOn: new Date(response.signedStartsOn), + signedExpiresOn: new Date(response.signedExpiresOn), + signedService: response.signedService, + signedVersion: response.signedVersion, + value: response.value + }; + const res = Object.assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return res; }); } - getContainerNameFromUrl() { - let containerName; - try { - const parsedUrl = new URL(this.url); - if (parsedUrl.hostname.split(".")[1] === "blob") { - containerName = parsedUrl.pathname.split("/")[1]; - } else if (isIpEndpointStyle(parsedUrl)) { - containerName = parsedUrl.pathname.split("/")[2]; - } else { - containerName = parsedUrl.pathname.split("/")[1]; + /** + * Creates a BlobBatchClient object to conduct batch operations. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @returns A new BlobBatchClient object for this service. + */ + getBlobBatchClient() { + return new BlobBatchClient(this.url, this.pipeline); + } + /** + * Only available for BlobServiceClient constructed with a shared key credential. + * + * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * + * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. + * @param permissions - Specifies the list of permissions to be associated with the SAS. + * @param resourceTypes - Specifies the resource types associated with the shared access signature. + * @param options - Optional parameters. + * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + generateAccountSasUrl(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + } + if (expiresOn2 === void 0) { + const now = /* @__PURE__ */ new Date(); + expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + } + const sas = generateAccountSASQueryParameters(Object.assign({ + permissions, + expiresOn: expiresOn2, + resourceTypes, + services: AccountSASServices.parse("b").toString() + }, options), this.credential).toString(); + return appendToURLQuery(this.url, sas); + } + /** + * Only available for BlobServiceClient constructed with a shared key credential. + * + * Generates string to sign for a Blob account Shared Access Signature (SAS) URI based on + * the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * + * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. + * @param permissions - Specifies the list of permissions to be associated with the SAS. + * @param resourceTypes - Specifies the resource types associated with the shared access signature. + * @param options - Optional parameters. + * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + generateSasStringToSign(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + } + if (expiresOn2 === void 0) { + const now = /* @__PURE__ */ new Date(); + expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + } + return generateAccountSASQueryParametersInternal(Object.assign({ + permissions, + expiresOn: expiresOn2, + resourceTypes, + services: AccountSASServices.parse("b").toString() + }, options), this.credential).stringToSign; + } + }; + exports2.KnownEncryptionAlgorithmType = void 0; + (function(KnownEncryptionAlgorithmType) { + KnownEncryptionAlgorithmType["AES256"] = "AES256"; + })(exports2.KnownEncryptionAlgorithmType || (exports2.KnownEncryptionAlgorithmType = {})); + Object.defineProperty(exports2, "RestError", { + enumerable: true, + get: function() { + return coreRestPipeline.RestError; + } + }); + exports2.AccountSASPermissions = AccountSASPermissions; + exports2.AccountSASResourceTypes = AccountSASResourceTypes; + exports2.AccountSASServices = AccountSASServices; + exports2.AnonymousCredential = AnonymousCredential; + exports2.AnonymousCredentialPolicy = AnonymousCredentialPolicy; + exports2.AppendBlobClient = AppendBlobClient; + exports2.BaseRequestPolicy = BaseRequestPolicy; + exports2.BlobBatch = BlobBatch; + exports2.BlobBatchClient = BlobBatchClient; + exports2.BlobClient = BlobClient; + exports2.BlobLeaseClient = BlobLeaseClient; + exports2.BlobSASPermissions = BlobSASPermissions; + exports2.BlobServiceClient = BlobServiceClient; + exports2.BlockBlobClient = BlockBlobClient; + exports2.ContainerClient = ContainerClient; + exports2.ContainerSASPermissions = ContainerSASPermissions; + exports2.Credential = Credential; + exports2.CredentialPolicy = CredentialPolicy; + exports2.PageBlobClient = PageBlobClient; + exports2.Pipeline = Pipeline; + exports2.SASQueryParameters = SASQueryParameters; + exports2.StorageBrowserPolicy = StorageBrowserPolicy; + exports2.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; + exports2.StorageOAuthScopes = StorageOAuthScopes; + exports2.StorageRetryPolicy = StorageRetryPolicy; + exports2.StorageRetryPolicyFactory = StorageRetryPolicyFactory; + exports2.StorageSharedKeyCredential = StorageSharedKeyCredential; + exports2.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; + exports2.generateAccountSASQueryParameters = generateAccountSASQueryParameters; + exports2.generateBlobSASQueryParameters = generateBlobSASQueryParameters; + exports2.getBlobServiceAccountAudience = getBlobServiceAccountAudience; + exports2.isPipelineLike = isPipelineLike; + exports2.logger = logger; + exports2.newPipeline = newPipeline; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/errors.js +var require_errors2 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/errors.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UsageError = exports2.NetworkError = exports2.GHESNotSupportedError = exports2.CacheNotFoundError = exports2.InvalidResponseError = exports2.FilesNotFoundError = void 0; + var FilesNotFoundError = class extends Error { + constructor(files = []) { + let message = "No files were found to upload"; + if (files.length > 0) { + message += `: ${files.join(", ")}`; + } + super(message); + this.files = files; + this.name = "FilesNotFoundError"; + } + }; + exports2.FilesNotFoundError = FilesNotFoundError; + var InvalidResponseError = class extends Error { + constructor(message) { + super(message); + this.name = "InvalidResponseError"; + } + }; + exports2.InvalidResponseError = InvalidResponseError; + var CacheNotFoundError = class extends Error { + constructor(message = "Cache not found") { + super(message); + this.name = "CacheNotFoundError"; + } + }; + exports2.CacheNotFoundError = CacheNotFoundError; + var GHESNotSupportedError = class extends Error { + constructor(message = "@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.") { + super(message); + this.name = "GHESNotSupportedError"; + } + }; + exports2.GHESNotSupportedError = GHESNotSupportedError; + var NetworkError = class extends Error { + constructor(code) { + const message = `Unable to make request: ${code} +If you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`; + super(message); + this.code = code; + this.name = "NetworkError"; + } + }; + exports2.NetworkError = NetworkError; + NetworkError.isNetworkErrorCode = (code) => { + if (!code) + return false; + return [ + "ECONNRESET", + "ENOTFOUND", + "ETIMEDOUT", + "ECONNREFUSED", + "EHOSTUNREACH" + ].includes(code); + }; + var UsageError = class extends Error { + constructor() { + const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours. +More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; + super(message); + this.name = "UsageError"; + } + }; + exports2.UsageError = UsageError; + UsageError.isUsageErrorMessage = (msg) => { + if (!msg) + return false; + return msg.includes("insufficient usage"); + }; + } +}); + +// node_modules/@actions/cache/lib/internal/uploadUtils.js +var require_uploadUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/uploadUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - containerName = decodeURIComponent(containerName); - if (!containerName) { - throw new Error("Provided containerName is invalid."); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return containerName; - } catch (error4) { - throw new Error("Unable to extract containerName with provided information."); } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.uploadCacheArchiveSDK = exports2.UploadProgress = void 0; + var core14 = __importStar4(require_core()); + var storage_blob_1 = require_dist7(); + var errors_1 = require_errors2(); + var UploadProgress = class { + constructor(contentLength) { + this.contentLength = contentLength; + this.sentBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); } /** - * Only available for ContainerClient constructed with a shared key credential. - * - * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * Sets the number of bytes sent * - * @param options - Optional parameters. - * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * @param sentBytes the number of bytes sent */ - generateSasUrl(options) { - return new Promise((resolve5) => { - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); - } - const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); - resolve5(appendToURLQuery(this.url, sas)); - }); + setSentBytes(sentBytes) { + this.sentBytes = sentBytes; } /** - * Only available for ContainerClient constructed with a shared key credential. - * - * Generates string to sign for a Blob Container Service Shared Access Signature (SAS) URI - * based on the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas - * - * @param options - Optional parameters. - * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * Returns the total number of bytes transferred. */ - /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ - generateSasStringToSign(options) { - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); - } - return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName }, options), this.credential).stringToSign; + getTransferredBytes() { + return this.sentBytes; } /** - * Creates a BlobBatchClient object to conduct batch operations. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @returns A new BlobBatchClient object for this container. + * Returns true if the upload is complete. */ - getBlobBatchClient() { - return new BlobBatchClient(this.url, this.pipeline); - } - }; - var AccountSASPermissions = class _AccountSASPermissions { - constructor() { - this.read = false; - this.write = false; - this.delete = false; - this.deleteVersion = false; - this.list = false; - this.add = false; - this.create = false; - this.update = false; - this.process = false; - this.tag = false; - this.filter = false; - this.setImmutabilityPolicy = false; - this.permanentDelete = false; + isDone() { + return this.getTransferredBytes() === this.contentLength; } /** - * Parse initializes the AccountSASPermissions fields from a string. - * - * @param permissions - + * Prints the current upload stats. Once the upload completes, this will print one + * last line and then stop. */ - static parse(permissions) { - const accountSASPermissions = new _AccountSASPermissions(); - for (const c of permissions) { - switch (c) { - case "r": - accountSASPermissions.read = true; - break; - case "w": - accountSASPermissions.write = true; - break; - case "d": - accountSASPermissions.delete = true; - break; - case "x": - accountSASPermissions.deleteVersion = true; - break; - case "l": - accountSASPermissions.list = true; - break; - case "a": - accountSASPermissions.add = true; - break; - case "c": - accountSASPermissions.create = true; - break; - case "u": - accountSASPermissions.update = true; - break; - case "p": - accountSASPermissions.process = true; - break; - case "t": - accountSASPermissions.tag = true; - break; - case "f": - accountSASPermissions.filter = true; - break; - case "i": - accountSASPermissions.setImmutabilityPolicy = true; - break; - case "y": - accountSASPermissions.permanentDelete = true; - break; - default: - throw new RangeError(`Invalid permission character: ${c}`); - } + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.sentBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); + core14.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; } - return accountSASPermissions; } /** - * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it - * and boolean values for them. - * - * @param permissionLike - + * Returns a function used to handle TransferProgressEvents. */ - static from(permissionLike) { - const accountSASPermissions = new _AccountSASPermissions(); - if (permissionLike.read) { - accountSASPermissions.read = true; - } - if (permissionLike.write) { - accountSASPermissions.write = true; - } - if (permissionLike.delete) { - accountSASPermissions.delete = true; - } - if (permissionLike.deleteVersion) { - accountSASPermissions.deleteVersion = true; - } - if (permissionLike.filter) { - accountSASPermissions.filter = true; - } - if (permissionLike.tag) { - accountSASPermissions.tag = true; - } - if (permissionLike.list) { - accountSASPermissions.list = true; - } - if (permissionLike.add) { - accountSASPermissions.add = true; - } - if (permissionLike.create) { - accountSASPermissions.create = true; - } - if (permissionLike.update) { - accountSASPermissions.update = true; - } - if (permissionLike.process) { - accountSASPermissions.process = true; - } - if (permissionLike.setImmutabilityPolicy) { - accountSASPermissions.setImmutabilityPolicy = true; - } - if (permissionLike.permanentDelete) { - accountSASPermissions.permanentDelete = true; - } - return accountSASPermissions; + onProgress() { + return (progress) => { + this.setSentBytes(progress.loadedBytes); + }; } /** - * Produces the SAS permissions string for an Azure Storage account. - * Call this method to set AccountSASSignatureValues Permissions field. - * - * Using this method will guarantee the resource types are in - * an order accepted by the service. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * Starts the timer that displays the stats. * + * @param delayInMs the delay between each write */ - toString() { - const permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.filter) { - permissions.push("f"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.list) { - permissions.push("l"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.update) { - permissions.push("u"); - } - if (this.process) { - permissions.push("p"); - } - if (this.setImmutabilityPolicy) { - permissions.push("i"); + startDisplayTimer(delayInMs = 1e3) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + /** + * Stops the timer that displays the stats. As this typically indicates the upload + * is complete, this will display one last line, unless the last line has already + * been written. + */ + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = void 0; } - if (this.permanentDelete) { - permissions.push("y"); + this.display(); + } + }; + exports2.UploadProgress = UploadProgress; + function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) { + var _a; + return __awaiter4(this, void 0, void 0, function* () { + const blobClient = new storage_blob_1.BlobClient(signedUploadURL); + const blockBlobClient = blobClient.getBlockBlobClient(); + const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0); + const uploadOptions = { + blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize, + concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency, + maxSingleShotSize: 128 * 1024 * 1024, + onProgress: uploadProgress.onProgress() + }; + try { + uploadProgress.startDisplayTimer(); + core14.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`); + const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions); + if (response._response.status >= 400) { + throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`); + } + return response; + } catch (error4) { + core14.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error4.message}`); + throw error4; + } finally { + uploadProgress.stopDisplayTimer(); } - return permissions.join(""); + }); + } + exports2.uploadCacheArchiveSDK = uploadCacheArchiveSDK; + } +}); + +// node_modules/@actions/cache/lib/internal/requestUtils.js +var require_requestUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/requestUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - var AccountSASResourceTypes = class _AccountSASResourceTypes { - constructor() { - this.service = false; - this.container = false; - this.object = false; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - /** - * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an - * Error if it encounters a character that does not correspond to a valid resource type. - * - * @param resourceTypes - - */ - static parse(resourceTypes) { - const accountSASResourceTypes = new _AccountSASResourceTypes(); - for (const c of resourceTypes) { - switch (c) { - case "s": - accountSASResourceTypes.service = true; - break; - case "c": - accountSASResourceTypes.container = true; - break; - case "o": - accountSASResourceTypes.object = true; - break; - default: - throw new RangeError(`Invalid resource type: ${c}`); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return accountSASResourceTypes; - } - /** - * Converts the given resource types to a string. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - */ - toString() { - const resourceTypes = []; - if (this.service) { - resourceTypes.push("s"); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (this.container) { - resourceTypes.push("c"); + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } - if (this.object) { - resourceTypes.push("o"); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; + var core14 = __importStar4(require_core()); + var http_client_1 = require_lib4(); + var constants_1 = require_constants7(); + function isSuccessStatusCode(statusCode) { + if (!statusCode) { + return false; + } + return statusCode >= 200 && statusCode < 300; + } + exports2.isSuccessStatusCode = isSuccessStatusCode; + function isServerErrorStatusCode(statusCode) { + if (!statusCode) { + return true; + } + return statusCode >= 500; + } + exports2.isServerErrorStatusCode = isServerErrorStatusCode; + function isRetryableStatusCode(statusCode) { + if (!statusCode) { + return false; + } + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.GatewayTimeout + ]; + return retryableStatusCodes.includes(statusCode); + } + exports2.isRetryableStatusCode = isRetryableStatusCode; + function sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => setTimeout(resolve5, milliseconds)); + }); + } + function retry3(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = void 0) { + return __awaiter4(this, void 0, void 0, function* () { + let errorMessage = ""; + let attempt = 1; + while (attempt <= maxAttempts) { + let response = void 0; + let statusCode = void 0; + let isRetryable = false; + try { + response = yield method(); + } catch (error4) { + if (onError) { + response = onError(error4); + } + isRetryable = true; + errorMessage = error4.message; + } + if (response) { + statusCode = getStatusCode(response); + if (!isServerErrorStatusCode(statusCode)) { + return response; + } + } + if (statusCode) { + isRetryable = isRetryableStatusCode(statusCode); + errorMessage = `Cache service responded with ${statusCode}`; + } + core14.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); + if (!isRetryable) { + core14.debug(`${name} - Error is not retryable`); + break; + } + yield sleep(delay); + attempt++; } - return resourceTypes.join(""); + throw Error(`${name} failed: ${errorMessage}`); + }); + } + exports2.retry = retry3; + function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { + return __awaiter4(this, void 0, void 0, function* () { + return yield retry3( + name, + method, + (response) => response.statusCode, + maxAttempts, + delay, + // If the error object contains the statusCode property, extract it and return + // an TypedResponse so it can be processed by the retry logic. + (error4) => { + if (error4 instanceof http_client_1.HttpClientError) { + return { + statusCode: error4.statusCode, + result: null, + headers: {}, + error: error4 + }; + } else { + return void 0; + } + } + ); + }); + } + exports2.retryTypedResponse = retryTypedResponse; + function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { + return __awaiter4(this, void 0, void 0, function* () { + return yield retry3(name, method, (response) => response.message.statusCode, maxAttempts, delay); + }); + } + exports2.retryHttpClientResponse = retryHttpClientResponse; + } +}); + +// node_modules/@actions/cache/lib/internal/downloadUtils.js +var require_downloadUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/downloadUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - var AccountSASServices = class _AccountSASServices { - constructor() { - this.blob = false; - this.file = false; - this.queue = false; - this.table = false; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - /** - * Creates an {@link AccountSASServices} from the specified services string. This method will throw an - * Error if it encounters a character that does not correspond to a valid service. - * - * @param services - - */ - static parse(services) { - const accountSASServices = new _AccountSASServices(); - for (const c of services) { - switch (c) { - case "b": - accountSASServices.blob = true; - break; - case "f": - accountSASServices.file = true; - break; - case "q": - accountSASServices.queue = true; - break; - case "t": - accountSASServices.table = true; - break; - default: - throw new RangeError(`Invalid service character: ${c}`); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return accountSASServices; - } - /** - * Converts the given services to a string. - * - */ - toString() { - const services = []; - if (this.blob) { - services.push("b"); - } - if (this.table) { - services.push("t"); - } - if (this.queue) { - services.push("q"); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (this.file) { - services.push("f"); + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } - return services.join(""); - } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { - return generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential).sasQueryParameters; - } - function generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) { - const version2 = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.setImmutabilityPolicy && version2 < "2020-08-04") { - throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); - } - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.deleteVersion && version2 < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); - } - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.permanentDelete && version2 < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when provided 'y' permission."); - } - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.tag && version2 < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); - } - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.filter && version2 < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); - } - if (accountSASSignatureValues.encryptionScope && version2 < "2020-12-06") { - throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); - } - const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); - const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); - const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); - let stringToSign; - if (version2 >= "2020-12-06") { - stringToSign = [ - sharedKeyCredential.accountName, - parsedPermissions, - parsedServices, - parsedResourceTypes, - accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", - truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", - accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", - version2, - accountSASSignatureValues.encryptionScope ? accountSASSignatureValues.encryptionScope : "", - "" - // Account SAS requires an additional newline character - ].join("\n"); - } else { - stringToSign = [ - sharedKeyCredential.accountName, - parsedPermissions, - parsedServices, - parsedResourceTypes, - accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", - truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", - accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", - version2, - "" - // Account SAS requires an additional newline character - ].join("\n"); - } - const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return { - sasQueryParameters: new SASQueryParameters(version2, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, accountSASSignatureValues.encryptionScope), - stringToSign - }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; + var core14 = __importStar4(require_core()); + var http_client_1 = require_lib4(); + var storage_blob_1 = require_dist7(); + var buffer = __importStar4(require("buffer")); + var fs7 = __importStar4(require("fs")); + var stream = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var requestUtils_1 = require_requestUtils(); + var abort_controller_1 = require_dist5(); + function pipeResponseToStream(response, output) { + return __awaiter4(this, void 0, void 0, function* () { + const pipeline = util.promisify(stream.pipeline); + yield pipeline(response.message, output); + }); } - var BlobServiceClient = class _BlobServiceClient extends StorageClient { - /** - * - * Creates an instance of BlobServiceClient from connection string. - * - * @param connectionString - Account connection string or a SAS connection string of an Azure storage account. - * [ Note - Account connection string can only be used in NODE.JS runtime. ] - * Account connection string example - - * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` - * SAS connection string example - - * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` - * @param options - Optional. Options to configure the HTTP pipeline. - */ - static fromConnectionString(connectionString, options) { - options = options || {}; - const extractedCreds = extractConnectionStringParts(connectionString); - if (extractedCreds.kind === "AccountConnString") { - if (coreUtil.isNode) { - const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - if (!options.proxyOptions) { - options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); - } - const pipeline = newPipeline(sharedKeyCredential, options); - return new _BlobServiceClient(extractedCreds.url, pipeline); - } else { - throw new Error("Account connection string is only supported in Node.js environment"); - } - } else if (extractedCreds.kind === "SASConnString") { - const pipeline = newPipeline(new AnonymousCredential(), options); - return new _BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); - } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - constructor(url2, credentialOrPipeline, options) { - let pipeline; - if (isPipelineLike(credentialOrPipeline)) { - pipeline = credentialOrPipeline; - } else if (coreUtil.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential || credentialOrPipeline instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipeline)) { - pipeline = newPipeline(credentialOrPipeline, options); - } else { - pipeline = newPipeline(new AnonymousCredential(), options); - } - super(url2, pipeline); - this.serviceContext = this.storageClientContext.service; + var DownloadProgress = class { + constructor(contentLength) { + this.contentLength = contentLength; + this.segmentIndex = 0; + this.segmentSize = 0; + this.segmentOffset = 0; + this.receivedBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); } /** - * Creates a {@link ContainerClient} object - * - * @param containerName - A container name - * @returns A new ContainerClient object for the given container name. - * - * Example usage: + * Progress to the next segment. Only call this method when the previous segment + * is complete. * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * ``` + * @param segmentSize the length of the next segment */ - getContainerClient(containerName) { - return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + nextSegment(segmentSize) { + this.segmentOffset = this.segmentOffset + this.segmentSize; + this.segmentIndex = this.segmentIndex + 1; + this.segmentSize = segmentSize; + this.receivedBytes = 0; + core14.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); } /** - * Create a Blob container. @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Sets the number of bytes received for the current segment. * - * @param containerName - Name of the container to create. - * @param options - Options to configure Container Create operation. - * @returns Container creation response and the corresponding container client. + * @param receivedBytes the number of bytes received */ - async createContainer(containerName, options = {}) { - return tracingClient.withSpan("BlobServiceClient-createContainer", options, async (updatedOptions) => { - const containerClient = this.getContainerClient(containerName); - const containerCreateResponse = await containerClient.create(updatedOptions); - return { - containerClient, - containerCreateResponse - }; - }); + setReceivedBytes(receivedBytes) { + this.receivedBytes = receivedBytes; } /** - * Deletes a Blob container. - * - * @param containerName - Name of the container to delete. - * @param options - Options to configure Container Delete operation. - * @returns Container deletion response. + * Returns the total number of bytes transferred. */ - async deleteContainer(containerName, options = {}) { - return tracingClient.withSpan("BlobServiceClient-deleteContainer", options, async (updatedOptions) => { - const containerClient = this.getContainerClient(containerName); - return containerClient.delete(updatedOptions); - }); + getTransferredBytes() { + return this.segmentOffset + this.receivedBytes; } /** - * Restore a previously deleted Blob container. - * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. - * - * @param deletedContainerName - Name of the previously deleted container. - * @param deletedContainerVersion - Version of the previously deleted container, used to uniquely identify the deleted container. - * @param options - Options to configure Container Restore operation. - * @returns Container deletion response. + * Returns true if the download is complete. */ - async undeleteContainer(deletedContainerName2, deletedContainerVersion2, options = {}) { - return tracingClient.withSpan("BlobServiceClient-undeleteContainer", options, async (updatedOptions) => { - const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName2); - const containerContext = containerClient["storageClientContext"].container; - const containerUndeleteResponse = assertResponse(await containerContext.restore({ - deletedContainerName: deletedContainerName2, - deletedContainerVersion: deletedContainerVersion2, - tracingOptions: updatedOptions.tracingOptions - })); - return { containerClient, containerUndeleteResponse }; - }); + isDone() { + return this.getTransferredBytes() === this.contentLength; } /** - * Rename an existing Blob Container. - * - * @param sourceContainerName - The name of the source container. - * @param destinationContainerName - The new name of the container. - * @param options - Options to configure Container Rename operation. + * Prints the current download stats. Once the download completes, this will print one + * last line and then stop. */ - /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ - // @ts-ignore Need to hide this interface for now. Make it public and turn on the live tests for it when the service is ready. - async renameContainer(sourceContainerName2, destinationContainerName, options = {}) { - return tracingClient.withSpan("BlobServiceClient-renameContainer", options, async (updatedOptions) => { - var _a; - const containerClient = this.getContainerClient(destinationContainerName); - const containerContext = containerClient["storageClientContext"].container; - const containerRenameResponse = assertResponse(await containerContext.rename(sourceContainerName2, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId }))); - return { containerClient, containerRenameResponse }; - }); + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.segmentOffset + this.receivedBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const downloadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); + core14.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; + } } /** - * Gets the properties of a storage account’s Blob service, including properties - * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * @param options - Options to the Service Get Properties operation. - * @returns Response data for the Service Get Properties operation. + * Returns a function used to handle TransferProgressEvents. */ - async getProperties(options = {}) { - return tracingClient.withSpan("BlobServiceClient-getProperties", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.getProperties({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + onProgress() { + return (progress) => { + this.setReceivedBytes(progress.loadedBytes); + }; } /** - * Sets properties for a storage account’s Blob service endpoint, including properties - * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties + * Starts the timer that displays the stats. * - * @param properties - - * @param options - Options to the Service Set Properties operation. - * @returns Response data for the Service Set Properties operation. + * @param delayInMs the delay between each write */ - async setProperties(properties, options = {}) { - return tracingClient.withSpan("BlobServiceClient-setProperties", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.setProperties(properties, { - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + startDisplayTimer(delayInMs = 1e3) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); } /** - * Retrieves statistics related to replication for the Blob service. It is only - * available on the secondary location endpoint when read-access geo-redundant - * replication is enabled for the storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats - * - * @param options - Options to the Service Get Statistics operation. - * @returns Response data for the Service Get Statistics operation. + * Stops the timer that displays the stats. As this typically indicates the download + * is complete, this will display one last line, unless the last line has already + * been written. */ - async getStatistics(options = {}) { - return tracingClient.withSpan("BlobServiceClient-getStatistics", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.getStatistics({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = void 0; + } + this.display(); } - /** - * The Get Account Information operation returns the sku name and account kind - * for the specified account. - * The Get Account Information operation is available on service versions beginning - * with version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information - * - * @param options - Options to the Service Get Account Info operation. - * @returns Response data for the Service Get Account Info operation. - */ - async getAccountInfo(options = {}) { - return tracingClient.withSpan("BlobServiceClient-getAccountInfo", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.getAccountInfo({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); + }; + exports2.DownloadProgress = DownloadProgress; + function downloadCacheHttpClient(archiveLocation, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const writeStream = fs7.createWriteStream(archivePath); + const httpClient = new http_client_1.HttpClient("actions/cache"); + const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.get(archiveLocation); + })); + downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { + downloadResponse.message.destroy(); + core14.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); }); - } - /** - * Returns a list of the containers under the specified account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 - * - * @param marker - A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to the Service List Container Segment operation. - * @returns Response data for the Service List Container Segment operation. - */ - async listContainersSegment(marker2, options = {}) { - return tracingClient.withSpan("BlobServiceClient-listContainersSegment", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.listContainersSegment(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker: marker2 }, options), { include: typeof options.include === "string" ? [options.include] : options.include, tracingOptions: updatedOptions.tracingOptions }))); + yield pipeResponseToStream(downloadResponse, writeStream); + const contentLengthHeader = downloadResponse.message.headers["content-length"]; + if (contentLengthHeader) { + const expectedLength = parseInt(contentLengthHeader); + const actualLength = utils.getArchiveFileSizeInBytes(archivePath); + if (actualLength !== expectedLength) { + throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); + } + } else { + core14.debug("Unable to validate download, no Content-Length header"); + } + }); + } + exports2.downloadCacheHttpClient = downloadCacheHttpClient; + function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { + var _a; + return __awaiter4(this, void 0, void 0, function* () { + const archiveDescriptor = yield fs7.promises.open(archivePath, "w"); + const httpClient = new http_client_1.HttpClient("actions/cache", void 0, { + socketTimeout: options.timeoutInMs, + keepAlive: true }); - } - /** - * The Filter Blobs operation enables callers to list blobs across all containers whose tags - * match a given search expression. Filter blobs searches across all containers within a - * storage account but can be scoped within the expression to a single container. - * - * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param marker - A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to find blobs by tags. - */ - async findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options = {}) { - return tracingClient.withSpan("BlobServiceClient-findBlobsByTagsSegment", options, async (updatedOptions) => { - const response = assertResponse(await this.serviceContext.filterBlobs({ - abortSignal: options.abortSignal, - where: tagFilterSqlExpression, - marker: marker2, - maxPageSize: options.maxPageSize, - tracingOptions: updatedOptions.tracingOptions + try { + const res = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCacheMetadata", () => __awaiter4(this, void 0, void 0, function* () { + return yield httpClient.request("HEAD", archiveLocation, null, {}); })); - const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { - var _a; - let tagValue = ""; - if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { - tagValue = blob.tags.blobTagSet[0].value; + const lengthHeader = res.message.headers["content-length"]; + if (lengthHeader === void 0 || lengthHeader === null) { + throw new Error("Content-Length not found on blob response"); + } + const length = parseInt(lengthHeader); + if (Number.isNaN(length)) { + throw new Error(`Could not interpret Content-Length: ${length}`); + } + const downloads = []; + const blockSize = 4 * 1024 * 1024; + for (let offset = 0; offset < length; offset += blockSize) { + const count = Math.min(blockSize, length - offset); + downloads.push({ + offset, + promiseGetter: () => __awaiter4(this, void 0, void 0, function* () { + return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count); + }) + }); + } + downloads.reverse(); + let actives = 0; + let bytesDownloaded = 0; + const progress = new DownloadProgress(length); + progress.startDisplayTimer(); + const progressFn = progress.onProgress(); + const activeDownloads = []; + let nextDownload; + const waitAndWrite = () => __awaiter4(this, void 0, void 0, function* () { + const segment = yield Promise.race(Object.values(activeDownloads)); + yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset); + actives--; + delete activeDownloads[segment.offset]; + bytesDownloaded += segment.count; + progressFn({ loadedBytes: bytesDownloaded }); + }); + while (nextDownload = downloads.pop()) { + activeDownloads[nextDownload.offset] = nextDownload.promiseGetter(); + actives++; + if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) { + yield waitAndWrite(); } - return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); - }) }); - return wrappedResponse; - }); - } - /** - * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. - * - * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param marker - A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to find blobs by tags. - */ - findBlobsByTagsSegments(tagFilterSqlExpression_1, marker_1) { - return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1(tagFilterSqlExpression, marker2, options = {}) { - let response; - if (!!marker2 || marker2 === void 0) { - do { - response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options)); - response.blobs = response.blobs || []; - marker2 = response.continuationToken; - yield yield tslib.__await(response); - } while (marker2); } - }); - } - /** - * Returns an AsyncIterableIterator for blobs. - * - * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param options - Options to findBlobsByTagsItems. - */ - findBlobsByTagsItems(tagFilterSqlExpression_1) { - return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { - var _a, e_1, _b, _c; - let marker2; + while (actives > 0) { + yield waitAndWrite(); + } + } finally { + httpClient.dispose(); + yield archiveDescriptor.close(); + } + }); + } + exports2.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent; + function downloadSegmentRetry(httpClient, archiveLocation, offset, count) { + return __awaiter4(this, void 0, void 0, function* () { + const retries = 5; + let failures = 0; + while (true) { try { - for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const segment = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); + const timeout = 3e4; + const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count)); + if (typeof result === "string") { + throw new Error("downloadSegmentRetry failed due to timeout"); } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_1) throw e_1.error; + return result; + } catch (err) { + if (failures >= retries) { + throw err; } + failures++; } - }); - } - /** - * Returns an async iterable iterator to find all blobs with specified tag - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { - * console.log(`Blob ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .findBlobsByTags("tagkey='tagvalue'") - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * ``` - * - * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param options - Options to find blobs by tags. - */ - findBlobsByTags(tagFilterSqlExpression, options = {}) { - const listSegmentOptions = Object.assign({}, options); - const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + } + }); + } + function downloadSegment(httpClient, archiveLocation, offset, count) { + return __awaiter4(this, void 0, void 0, function* () { + const partRes = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCachePart", () => __awaiter4(this, void 0, void 0, function* () { + return yield httpClient.get(archiveLocation, { + Range: `bytes=${offset}-${offset + count - 1}` + }); + })); + if (!partRes.readBodyBuffer) { + throw new Error("Expected HttpClientResponse to implement readBodyBuffer"); + } return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - } + offset, + count, + buffer: yield partRes.readBodyBuffer() }; + }); + } + function downloadCacheStorageSDK(archiveLocation, archivePath, options) { + var _a; + return __awaiter4(this, void 0, void 0, function* () { + const client = new storage_blob_1.BlockBlobClient(archiveLocation, void 0, { + retryOptions: { + // Override the timeout used when downloading each 4 MB chunk + // The default is 2 min / MB, which is way too slow + tryTimeoutInMs: options.timeoutInMs + } + }); + const properties = yield client.getProperties(); + const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; + if (contentLength < 0) { + core14.debug("Unable to determine content length, downloading file with http-client..."); + yield downloadCacheHttpClient(archiveLocation, archivePath); + } else { + const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); + const downloadProgress = new DownloadProgress(contentLength); + const fd = fs7.openSync(archivePath, "w"); + try { + downloadProgress.startDisplayTimer(); + const controller = new abort_controller_1.AbortController(); + const abortSignal = controller.signal; + while (!downloadProgress.isDone()) { + const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; + const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); + downloadProgress.nextSegment(segmentSize); + const result = yield promiseWithTimeout(options.segmentTimeoutInMs || 36e5, client.downloadToBuffer(segmentStart, segmentSize, { + abortSignal, + concurrency: options.downloadConcurrency, + onProgress: downloadProgress.onProgress() + })); + if (result === "timeout") { + controller.abort(); + throw new Error("Aborting cache download as the download time exceeded the timeout."); + } else if (Buffer.isBuffer(result)) { + fs7.writeFileSync(fd, result); + } + } + } finally { + downloadProgress.stopDisplayTimer(); + fs7.closeSync(fd); + } + } + }); + } + exports2.downloadCacheStorageSDK = downloadCacheStorageSDK; + var promiseWithTimeout = (timeoutMs, promise) => __awaiter4(void 0, void 0, void 0, function* () { + let timeoutHandle; + const timeoutPromise = new Promise((resolve5) => { + timeoutHandle = setTimeout(() => resolve5("timeout"), timeoutMs); + }); + return Promise.race([promise, timeoutPromise]).then((result) => { + clearTimeout(timeoutHandle); + return result; + }); + }); + } +}); + +// node_modules/@actions/cache/lib/options.js +var require_options = __commonJS({ + "node_modules/@actions/cache/lib/options.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getDownloadOptions = exports2.getUploadOptions = void 0; + var core14 = __importStar4(require_core()); + function getUploadOptions(copy) { + const result = { + useAzureSdk: false, + uploadConcurrency: 4, + uploadChunkSize: 32 * 1024 * 1024 + }; + if (copy) { + if (typeof copy.useAzureSdk === "boolean") { + result.useAzureSdk = copy.useAzureSdk; + } + if (typeof copy.uploadConcurrency === "number") { + result.uploadConcurrency = copy.uploadConcurrency; + } + if (typeof copy.uploadChunkSize === "number") { + result.uploadChunkSize = copy.uploadChunkSize; + } + } + result.uploadConcurrency = !isNaN(Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) ? Math.min(32, Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) : result.uploadConcurrency; + result.uploadChunkSize = !isNaN(Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"])) ? Math.min(128 * 1024 * 1024, Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"]) * 1024 * 1024) : result.uploadChunkSize; + core14.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core14.debug(`Upload concurrency: ${result.uploadConcurrency}`); + core14.debug(`Upload chunk size: ${result.uploadChunkSize}`); + return result; + } + exports2.getUploadOptions = getUploadOptions; + function getDownloadOptions(copy) { + const result = { + useAzureSdk: false, + concurrentBlobDownloads: true, + downloadConcurrency: 8, + timeoutInMs: 3e4, + segmentTimeoutInMs: 6e5, + lookupOnly: false + }; + if (copy) { + if (typeof copy.useAzureSdk === "boolean") { + result.useAzureSdk = copy.useAzureSdk; + } + if (typeof copy.concurrentBlobDownloads === "boolean") { + result.concurrentBlobDownloads = copy.concurrentBlobDownloads; + } + if (typeof copy.downloadConcurrency === "number") { + result.downloadConcurrency = copy.downloadConcurrency; + } + if (typeof copy.timeoutInMs === "number") { + result.timeoutInMs = copy.timeoutInMs; + } + if (typeof copy.segmentTimeoutInMs === "number") { + result.segmentTimeoutInMs = copy.segmentTimeoutInMs; + } + if (typeof copy.lookupOnly === "boolean") { + result.lookupOnly = copy.lookupOnly; + } + } + const segmentDownloadTimeoutMins = process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]; + if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) { + result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1e3; + } + core14.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core14.debug(`Download concurrency: ${result.downloadConcurrency}`); + core14.debug(`Request timeout (ms): ${result.timeoutInMs}`); + core14.debug(`Cache segment download timeout mins env var: ${process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]}`); + core14.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`); + core14.debug(`Lookup only: ${result.lookupOnly}`); + return result; + } + exports2.getDownloadOptions = getDownloadOptions; + } +}); + +// node_modules/@actions/cache/lib/internal/config.js +var require_config = __commonJS({ + "node_modules/@actions/cache/lib/internal/config.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getCacheServiceURL = exports2.getCacheServiceVersion = exports2.isGhes = void 0; + function isGhes() { + const ghUrl = new URL(process.env["GITHUB_SERVER_URL"] || "https://github.com"); + const hostname = ghUrl.hostname.trimEnd().toUpperCase(); + const isGitHubHost = hostname === "GITHUB.COM"; + const isGheHost = hostname.endsWith(".GHE.COM"); + const isLocalHost = hostname.endsWith(".LOCALHOST"); + return !isGitHubHost && !isGheHost && !isLocalHost; + } + exports2.isGhes = isGhes; + function getCacheServiceVersion() { + if (isGhes()) + return "v1"; + return process.env["ACTIONS_CACHE_SERVICE_V2"] ? "v2" : "v1"; + } + exports2.getCacheServiceVersion = getCacheServiceVersion; + function getCacheServiceURL() { + const version = getCacheServiceVersion(); + switch (version) { + case "v1": + return process.env["ACTIONS_CACHE_URL"] || process.env["ACTIONS_RESULTS_URL"] || ""; + case "v2": + return process.env["ACTIONS_RESULTS_URL"] || ""; + default: + throw new Error(`Unsupported cache service version: ${version}`); + } + } + exports2.getCacheServiceURL = getCacheServiceURL; + } +}); + +// node_modules/@actions/cache/package.json +var require_package2 = __commonJS({ + "node_modules/@actions/cache/package.json"(exports2, module2) { + module2.exports = { + name: "@actions/cache", + version: "4.1.0", + preview: true, + description: "Actions cache lib", + keywords: [ + "github", + "actions", + "cache" + ], + homepage: "https://github.com/actions/toolkit/tree/main/packages/cache", + license: "MIT", + main: "lib/cache.js", + types: "lib/cache.d.ts", + directories: { + lib: "lib", + test: "__tests__" + }, + files: [ + "lib", + "!.DS_Store" + ], + publishConfig: { + access: "public" + }, + repository: { + type: "git", + url: "git+https://github.com/actions/toolkit.git", + directory: "packages/cache" + }, + scripts: { + "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", + test: 'echo "Error: run tests from root" && exit 1', + tsc: "tsc" + }, + bugs: { + url: "https://github.com/actions/toolkit/issues" + }, + dependencies: { + "@actions/core": "^1.11.1", + "@actions/exec": "^1.0.1", + "@actions/glob": "^0.1.0", + "@protobuf-ts/runtime-rpc": "^2.11.1", + "@actions/http-client": "^2.1.1", + "@actions/io": "^1.0.1", + "@azure/abort-controller": "^1.1.0", + "@azure/ms-rest-js": "^2.6.0", + "@azure/storage-blob": "^12.13.0", + semver: "^6.3.1" + }, + devDependencies: { + "@types/node": "^22.13.9", + "@types/semver": "^6.0.0", + "@protobuf-ts/plugin": "^2.9.4", + typescript: "^5.2.2" + } + }; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/user-agent.js +var require_user_agent = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/user-agent.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getUserAgentString = void 0; + var packageJson = require_package2(); + function getUserAgentString() { + return `@actions/cache-${packageJson.version}`; + } + exports2.getUserAgentString = getUserAgentString; + } +}); + +// node_modules/@actions/cache/lib/internal/cacheHttpClient.js +var require_cacheHttpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/cacheHttpClient.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - /** - * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses - * - * @param marker - A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to list containers operation. - */ - listSegments(marker_1) { - return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { - let listContainersSegmentResponse; - if (!!marker2 || marker2 === void 0) { - do { - listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker2, options)); - listContainersSegmentResponse.containerItems = listContainersSegmentResponse.containerItems || []; - marker2 = listContainersSegmentResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); - } while (marker2); - } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); }); } - /** - * Returns an AsyncIterableIterator for Container Items - * - * @param options - Options to list containers operation. - */ - listItems() { - return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { - var _a, e_2, _b, _c; - let marker2; + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { try { - for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const segment = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); - } - } catch (e_2_1) { - e_2 = { error: e_2_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_2) throw e_2.error; - } + step(generator.next(value)); + } catch (e) { + reject(e); } - }); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; + var core14 = __importStar4(require_core()); + var http_client_1 = require_lib4(); + var auth_1 = require_auth2(); + var fs7 = __importStar4(require("fs")); + var url_1 = require("url"); + var utils = __importStar4(require_cacheUtils()); + var uploadUtils_1 = require_uploadUtils(); + var downloadUtils_1 = require_downloadUtils(); + var options_1 = require_options(); + var requestUtils_1 = require_requestUtils(); + var config_1 = require_config(); + var user_agent_1 = require_user_agent(); + function getCacheApiUrl(resource) { + const baseUrl = (0, config_1.getCacheServiceURL)(); + if (!baseUrl) { + throw new Error("Cache Service Url not found, unable to restore cache."); } - /** - * Returns an async iterable iterator to list all the containers - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the containers in pages. - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const container of blobServiceClient.listContainers()) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.listContainers(); - * let containerItem = await iter.next(); - * while (!containerItem.done) { - * console.log(`Container ${i++}: ${containerItem.value.name}`); - * containerItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .listContainers() - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints 10 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * ``` - * - * @param options - Options to list containers. - * @returns An asyncIterableIterator that supports paging. - */ - listContainers(options = {}) { - if (options.prefix === "") { - options.prefix = void 0; + const url = `${baseUrl}_apis/artifactcache/${resource}`; + core14.debug(`Resource Url: ${url}`); + return url; + } + function createAcceptHeader(type2, apiVersion) { + return `${type2};api-version=${apiVersion}`; + } + function getRequestOptions() { + const requestOptions = { + headers: { + Accept: createAcceptHeader("application/json", "6.0-preview.1") } - const include2 = []; - if (options.includeDeleted) { - include2.push("deleted"); + }; + return requestOptions; + } + function createHttpClient() { + const token = process.env["ACTIONS_RUNTIME_TOKEN"] || ""; + const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); + return new http_client_1.HttpClient((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions()); + } + function getCacheEntry(keys, paths, options) { + return __awaiter4(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); + const resource = `cache?keys=${encodeURIComponent(keys.join(","))}&version=${version}`; + const response = yield (0, requestUtils_1.retryTypedResponse)("getCacheEntry", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.getJson(getCacheApiUrl(resource)); + })); + if (response.statusCode === 204) { + if (core14.isDebug()) { + yield printCachesListForDiagnostics(keys[0], httpClient, version); + } + return null; } - if (options.includeMetadata) { - include2.push("metadata"); + if (!(0, requestUtils_1.isSuccessStatusCode)(response.statusCode)) { + throw new Error(`Cache service responded with ${response.statusCode}`); } - if (options.includeSystem) { - include2.push("system"); + const cacheResult = response.result; + const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; + if (!cacheDownloadUrl) { + throw new Error("Cache not found."); } - const listSegmentOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); - const iter = this.listItems(listSegmentOptions); - return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + core14.setSecret(cacheDownloadUrl); + core14.debug(`Cache Result:`); + core14.debug(JSON.stringify(cacheResult)); + return cacheResult; + }); + } + exports2.getCacheEntry = getCacheEntry; + function printCachesListForDiagnostics(key, httpClient, version) { + return __awaiter4(this, void 0, void 0, function* () { + const resource = `caches?key=${encodeURIComponent(key)}`; + const response = yield (0, requestUtils_1.retryTypedResponse)("listCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.getJson(getCacheApiUrl(resource)); + })); + if (response.statusCode === 200) { + const cacheListResult = response.result; + const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount; + if (totalCount && totalCount > 0) { + core14.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env["GITHUB_REF"]}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key +Other caches with similar key:`); + for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) { + core14.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`); + } + } + } + }); + } + function downloadCache(archiveLocation, archivePath, options) { + return __awaiter4(this, void 0, void 0, function* () { + const archiveUrl = new url_1.URL(archiveLocation); + const downloadOptions = (0, options_1.getDownloadOptions)(options); + if (archiveUrl.hostname.endsWith(".blob.core.windows.net")) { + if (downloadOptions.useAzureSdk) { + yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions); + } else if (downloadOptions.concurrentBlobDownloads) { + yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions); + } else { + yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); } + } else { + yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); + } + }); + } + exports2.downloadCache = downloadCache; + function reserveCache(key, paths, options) { + return __awaiter4(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); + const reserveCacheRequest = { + key, + version, + cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize }; + const response = yield (0, requestUtils_1.retryTypedResponse)("reserveCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl("caches"), reserveCacheRequest); + })); + return response; + }); + } + exports2.reserveCache = reserveCache; + function getContentRange(start, end) { + return `bytes ${start}-${end}/*`; + } + function uploadChunk(httpClient, resourceUrl, openStream, start, end) { + return __awaiter4(this, void 0, void 0, function* () { + core14.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); + const additionalHeaders = { + "Content-Type": "application/octet-stream", + "Content-Range": getContentRange(start, end) + }; + const uploadChunkResponse = yield (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.sendStream("PATCH", resourceUrl, openStream(), additionalHeaders); + })); + if (!(0, requestUtils_1.isSuccessStatusCode)(uploadChunkResponse.message.statusCode)) { + throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); + } + }); + } + function uploadFile(httpClient, cacheId, archivePath, options) { + return __awaiter4(this, void 0, void 0, function* () { + const fileSize = utils.getArchiveFileSizeInBytes(archivePath); + const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); + const fd = fs7.openSync(archivePath, "r"); + const uploadOptions = (0, options_1.getUploadOptions)(options); + const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency); + const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize); + const parallelUploads = [...new Array(concurrency).keys()]; + core14.debug("Awaiting all uploads"); + let offset = 0; + try { + yield Promise.all(parallelUploads.map(() => __awaiter4(this, void 0, void 0, function* () { + while (offset < fileSize) { + const chunkSize = Math.min(fileSize - offset, maxChunkSize); + const start = offset; + const end = offset + chunkSize - 1; + offset += maxChunkSize; + yield uploadChunk(httpClient, resourceUrl, () => fs7.createReadStream(archivePath, { + fd, + start, + end, + autoClose: false + }).on("error", (error4) => { + throw new Error(`Cache upload failed because file read failed with ${error4.message}`); + }), start, end); + } + }))); + } finally { + fs7.closeSync(fd); + } + return; + }); + } + function commitCache(httpClient, cacheId, filesize) { + return __awaiter4(this, void 0, void 0, function* () { + const commitCacheRequest = { size: filesize }; + return yield (0, requestUtils_1.retryTypedResponse)("commitCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); + })); + }); + } + function saveCache4(cacheId, archivePath, signedUploadURL, options) { + return __awaiter4(this, void 0, void 0, function* () { + const uploadOptions = (0, options_1.getUploadOptions)(options); + if (uploadOptions.useAzureSdk) { + if (!signedUploadURL) { + throw new Error("Azure Storage SDK can only be used when a signed URL is provided."); + } + yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options); + } else { + const httpClient = createHttpClient(); + core14.debug("Upload cache"); + yield uploadFile(httpClient, cacheId, archivePath, options); + core14.debug("Commiting cache"); + const cacheSize = utils.getArchiveFileSizeInBytes(archivePath); + core14.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); + const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); + if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) { + throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); + } + core14.info("Cache saved successfully"); + } + }); + } + exports2.saveCache = saveCache4; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js +var require_json_typings = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isJsonObject = exports2.typeofJsonValue = void 0; + function typeofJsonValue(value) { + let t = typeof value; + if (t == "object") { + if (Array.isArray(value)) + return "array"; + if (value === null) + return "null"; } - /** - * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). - * - * Retrieves a user delegation key for the Blob service. This is only a valid operation when using - * bearer token authentication. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key - * - * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time - * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time - */ - async getUserDelegationKey(startsOn, expiresOn2, options = {}) { - return tracingClient.withSpan("BlobServiceClient-getUserDelegationKey", options, async (updatedOptions) => { - const response = assertResponse(await this.serviceContext.getUserDelegationKey({ - startsOn: truncatedISO8061Date(startsOn, false), - expiresOn: truncatedISO8061Date(expiresOn2, false) - }, { - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - const userDelegationKey = { - signedObjectId: response.signedObjectId, - signedTenantId: response.signedTenantId, - signedStartsOn: new Date(response.signedStartsOn), - signedExpiresOn: new Date(response.signedExpiresOn), - signedService: response.signedService, - signedVersion: response.signedVersion, - value: response.value - }; - const res = Object.assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); - return res; - }); - } - /** - * Creates a BlobBatchClient object to conduct batch operations. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @returns A new BlobBatchClient object for this service. - */ - getBlobBatchClient() { - return new BlobBatchClient(this.url, this.pipeline); - } - /** - * Only available for BlobServiceClient constructed with a shared key credential. - * - * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas - * - * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. - * @param permissions - Specifies the list of permissions to be associated with the SAS. - * @param resourceTypes - Specifies the resource types associated with the shared access signature. - * @param options - Optional parameters. - * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - */ - generateAccountSasUrl(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + return t; + } + exports2.typeofJsonValue = typeofJsonValue; + function isJsonObject(value) { + return value !== null && typeof value == "object" && !Array.isArray(value); + } + exports2.isJsonObject = isJsonObject; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/base64.js +var require_base642 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/base64.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.base64encode = exports2.base64decode = void 0; + var encTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); + var decTable = []; + for (let i = 0; i < encTable.length; i++) + decTable[encTable[i].charCodeAt(0)] = i; + decTable["-".charCodeAt(0)] = encTable.indexOf("+"); + decTable["_".charCodeAt(0)] = encTable.indexOf("/"); + function base64decode(base64Str) { + let es = base64Str.length * 3 / 4; + if (base64Str[base64Str.length - 2] == "=") + es -= 2; + else if (base64Str[base64Str.length - 1] == "=") + es -= 1; + let bytes = new Uint8Array(es), bytePos = 0, groupPos = 0, b, p = 0; + for (let i = 0; i < base64Str.length; i++) { + b = decTable[base64Str.charCodeAt(i)]; + if (b === void 0) { + switch (base64Str[i]) { + case "=": + groupPos = 0; + // reset state when padding found + case "\n": + case "\r": + case " ": + case " ": + continue; + // skip white-space, and padding + default: + throw Error(`invalid base64 string.`); + } } - if (expiresOn2 === void 0) { - const now = /* @__PURE__ */ new Date(); - expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + switch (groupPos) { + case 0: + p = b; + groupPos = 1; + break; + case 1: + bytes[bytePos++] = p << 2 | (b & 48) >> 4; + p = b; + groupPos = 2; + break; + case 2: + bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; + p = b; + groupPos = 3; + break; + case 3: + bytes[bytePos++] = (p & 3) << 6 | b; + groupPos = 0; + break; } - const sas = generateAccountSASQueryParameters(Object.assign({ - permissions, - expiresOn: expiresOn2, - resourceTypes, - services: AccountSASServices.parse("b").toString() - }, options), this.credential).toString(); - return appendToURLQuery(this.url, sas); } - /** - * Only available for BlobServiceClient constructed with a shared key credential. - * - * Generates string to sign for a Blob account Shared Access Signature (SAS) URI based on - * the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas - * - * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. - * @param permissions - Specifies the list of permissions to be associated with the SAS. - * @param resourceTypes - Specifies the resource types associated with the shared access signature. - * @param options - Optional parameters. - * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - */ - generateSasStringToSign(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + if (groupPos == 1) + throw Error(`invalid base64 string.`); + return bytes.subarray(0, bytePos); + } + exports2.base64decode = base64decode; + function base64encode(bytes) { + let base64 = "", groupPos = 0, b, p = 0; + for (let i = 0; i < bytes.length; i++) { + b = bytes[i]; + switch (groupPos) { + case 0: + base64 += encTable[b >> 2]; + p = (b & 3) << 4; + groupPos = 1; + break; + case 1: + base64 += encTable[p | b >> 4]; + p = (b & 15) << 2; + groupPos = 2; + break; + case 2: + base64 += encTable[p | b >> 6]; + base64 += encTable[b & 63]; + groupPos = 0; + break; } - if (expiresOn2 === void 0) { - const now = /* @__PURE__ */ new Date(); - expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + } + if (groupPos) { + base64 += encTable[p]; + base64 += "="; + if (groupPos == 1) + base64 += "="; + } + return base64; + } + exports2.base64encode = base64encode; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js +var require_protobufjs_utf8 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.utf8read = void 0; + var fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); + function utf8read(bytes) { + if (bytes.length < 1) + return ""; + let pos = 0, parts = [], chunk = [], i = 0, t; + let len = bytes.length; + while (pos < len) { + t = bytes[pos++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 65536; + chunk[i++] = 55296 + (t >> 10); + chunk[i++] = 56320 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; + if (i > 8191) { + parts.push(fromCharCodes(chunk)); + i = 0; } - return generateAccountSASQueryParametersInternal(Object.assign({ - permissions, - expiresOn: expiresOn2, - resourceTypes, - services: AccountSASServices.parse("b").toString() - }, options), this.credential).stringToSign; } - }; - exports2.KnownEncryptionAlgorithmType = void 0; - (function(KnownEncryptionAlgorithmType) { - KnownEncryptionAlgorithmType["AES256"] = "AES256"; - })(exports2.KnownEncryptionAlgorithmType || (exports2.KnownEncryptionAlgorithmType = {})); - Object.defineProperty(exports2, "RestError", { - enumerable: true, - get: function() { - return coreRestPipeline.RestError; + if (parts.length) { + if (i) + parts.push(fromCharCodes(chunk.slice(0, i))); + return parts.join(""); } - }); - exports2.AccountSASPermissions = AccountSASPermissions; - exports2.AccountSASResourceTypes = AccountSASResourceTypes; - exports2.AccountSASServices = AccountSASServices; - exports2.AnonymousCredential = AnonymousCredential; - exports2.AnonymousCredentialPolicy = AnonymousCredentialPolicy; - exports2.AppendBlobClient = AppendBlobClient; - exports2.BaseRequestPolicy = BaseRequestPolicy; - exports2.BlobBatch = BlobBatch; - exports2.BlobBatchClient = BlobBatchClient; - exports2.BlobClient = BlobClient; - exports2.BlobLeaseClient = BlobLeaseClient; - exports2.BlobSASPermissions = BlobSASPermissions; - exports2.BlobServiceClient = BlobServiceClient; - exports2.BlockBlobClient = BlockBlobClient; - exports2.ContainerClient = ContainerClient; - exports2.ContainerSASPermissions = ContainerSASPermissions; - exports2.Credential = Credential; - exports2.CredentialPolicy = CredentialPolicy; - exports2.PageBlobClient = PageBlobClient; - exports2.Pipeline = Pipeline; - exports2.SASQueryParameters = SASQueryParameters; - exports2.StorageBrowserPolicy = StorageBrowserPolicy; - exports2.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; - exports2.StorageOAuthScopes = StorageOAuthScopes; - exports2.StorageRetryPolicy = StorageRetryPolicy; - exports2.StorageRetryPolicyFactory = StorageRetryPolicyFactory; - exports2.StorageSharedKeyCredential = StorageSharedKeyCredential; - exports2.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; - exports2.generateAccountSASQueryParameters = generateAccountSASQueryParameters; - exports2.generateBlobSASQueryParameters = generateBlobSASQueryParameters; - exports2.getBlobServiceAccountAudience = getBlobServiceAccountAudience; - exports2.isPipelineLike = isPipelineLike; - exports2.logger = logger; - exports2.newPipeline = newPipeline; + return fromCharCodes(chunk.slice(0, i)); + } + exports2.utf8read = utf8read; } }); -// node_modules/@actions/cache/lib/internal/shared/errors.js -var require_errors2 = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/errors.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js +var require_binary_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UsageError = exports2.NetworkError = exports2.GHESNotSupportedError = exports2.CacheNotFoundError = exports2.InvalidResponseError = exports2.FilesNotFoundError = void 0; - var FilesNotFoundError = class extends Error { - constructor(files = []) { - let message = "No files were found to upload"; - if (files.length > 0) { - message += `: ${files.join(", ")}`; + exports2.WireType = exports2.mergeBinaryOptions = exports2.UnknownFieldHandler = void 0; + var UnknownFieldHandler; + (function(UnknownFieldHandler2) { + UnknownFieldHandler2.symbol = Symbol.for("protobuf-ts/unknown"); + UnknownFieldHandler2.onRead = (typeName, message, fieldNo, wireType, data) => { + let container = is(message) ? message[UnknownFieldHandler2.symbol] : message[UnknownFieldHandler2.symbol] = []; + container.push({ no: fieldNo, wireType, data }); + }; + UnknownFieldHandler2.onWrite = (typeName, message, writer) => { + for (let { no, wireType, data } of UnknownFieldHandler2.list(message)) + writer.tag(no, wireType).raw(data); + }; + UnknownFieldHandler2.list = (message, fieldNo) => { + if (is(message)) { + let all = message[UnknownFieldHandler2.symbol]; + return fieldNo ? all.filter((uf) => uf.no == fieldNo) : all; + } + return []; + }; + UnknownFieldHandler2.last = (message, fieldNo) => UnknownFieldHandler2.list(message, fieldNo).slice(-1)[0]; + const is = (message) => message && Array.isArray(message[UnknownFieldHandler2.symbol]); + })(UnknownFieldHandler = exports2.UnknownFieldHandler || (exports2.UnknownFieldHandler = {})); + function mergeBinaryOptions(a, b) { + return Object.assign(Object.assign({}, a), b); + } + exports2.mergeBinaryOptions = mergeBinaryOptions; + var WireType; + (function(WireType2) { + WireType2[WireType2["Varint"] = 0] = "Varint"; + WireType2[WireType2["Bit64"] = 1] = "Bit64"; + WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited"; + WireType2[WireType2["StartGroup"] = 3] = "StartGroup"; + WireType2[WireType2["EndGroup"] = 4] = "EndGroup"; + WireType2[WireType2["Bit32"] = 5] = "Bit32"; + })(WireType = exports2.WireType || (exports2.WireType = {})); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js +var require_goog_varint = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.varint32read = exports2.varint32write = exports2.int64toString = exports2.int64fromString = exports2.varint64write = exports2.varint64read = void 0; + function varint64read() { + let lowBits = 0; + let highBits = 0; + for (let shift = 0; shift < 28; shift += 7) { + let b = this.buf[this.pos++]; + lowBits |= (b & 127) << shift; + if ((b & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; } - super(message); - this.files = files; - this.name = "FilesNotFoundError"; } - }; - exports2.FilesNotFoundError = FilesNotFoundError; - var InvalidResponseError = class extends Error { - constructor(message) { - super(message); - this.name = "InvalidResponseError"; + let middleByte = this.buf[this.pos++]; + lowBits |= (middleByte & 15) << 28; + highBits = (middleByte & 112) >> 4; + if ((middleByte & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; } - }; - exports2.InvalidResponseError = InvalidResponseError; - var CacheNotFoundError = class extends Error { - constructor(message = "Cache not found") { - super(message); - this.name = "CacheNotFoundError"; + for (let shift = 3; shift <= 31; shift += 7) { + let b = this.buf[this.pos++]; + highBits |= (b & 127) << shift; + if ((b & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } } - }; - exports2.CacheNotFoundError = CacheNotFoundError; - var GHESNotSupportedError = class extends Error { - constructor(message = "@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.") { - super(message); - this.name = "GHESNotSupportedError"; + throw new Error("invalid varint"); + } + exports2.varint64read = varint64read; + function varint64write(lo, hi, bytes) { + for (let i = 0; i < 28; i = i + 7) { + const shift = lo >>> i; + const hasNext = !(shift >>> 7 == 0 && hi == 0); + const byte = (hasNext ? shift | 128 : shift) & 255; + bytes.push(byte); + if (!hasNext) { + return; + } } - }; - exports2.GHESNotSupportedError = GHESNotSupportedError; - var NetworkError = class extends Error { - constructor(code) { - const message = `Unable to make request: ${code} -If you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`; - super(message); - this.code = code; - this.name = "NetworkError"; + const splitBits = lo >>> 28 & 15 | (hi & 7) << 4; + const hasMoreBits = !(hi >> 3 == 0); + bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255); + if (!hasMoreBits) { + return; } - }; - exports2.NetworkError = NetworkError; - NetworkError.isNetworkErrorCode = (code) => { - if (!code) - return false; - return [ - "ECONNRESET", - "ENOTFOUND", - "ETIMEDOUT", - "ECONNREFUSED", - "EHOSTUNREACH" - ].includes(code); - }; - var UsageError = class extends Error { - constructor() { - const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours. -More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; - super(message); - this.name = "UsageError"; + for (let i = 3; i < 31; i = i + 7) { + const shift = hi >>> i; + const hasNext = !(shift >>> 7 == 0); + const byte = (hasNext ? shift | 128 : shift) & 255; + bytes.push(byte); + if (!hasNext) { + return; + } } - }; - exports2.UsageError = UsageError; - UsageError.isUsageErrorMessage = (msg) => { - if (!msg) - return false; - return msg.includes("insufficient usage"); - }; + bytes.push(hi >>> 31 & 1); + } + exports2.varint64write = varint64write; + var TWO_PWR_32_DBL = (1 << 16) * (1 << 16); + function int64fromString(dec) { + let minus = dec[0] == "-"; + if (minus) + dec = dec.slice(1); + const base = 1e6; + let lowBits = 0; + let highBits = 0; + function add1e6digit(begin, end) { + const digit1e6 = Number(dec.slice(begin, end)); + highBits *= base; + lowBits = lowBits * base + digit1e6; + if (lowBits >= TWO_PWR_32_DBL) { + highBits = highBits + (lowBits / TWO_PWR_32_DBL | 0); + lowBits = lowBits % TWO_PWR_32_DBL; + } + } + add1e6digit(-24, -18); + add1e6digit(-18, -12); + add1e6digit(-12, -6); + add1e6digit(-6); + return [minus, lowBits, highBits]; + } + exports2.int64fromString = int64fromString; + function int64toString(bitsLow, bitsHigh) { + if (bitsHigh >>> 0 <= 2097151) { + return "" + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); + } + let low = bitsLow & 16777215; + let mid = (bitsLow >>> 24 | bitsHigh << 8) >>> 0 & 16777215; + let high = bitsHigh >> 16 & 65535; + let digitA = low + mid * 6777216 + high * 6710656; + let digitB = mid + high * 8147497; + let digitC = high * 2; + let base = 1e7; + if (digitA >= base) { + digitB += Math.floor(digitA / base); + digitA %= base; + } + if (digitB >= base) { + digitC += Math.floor(digitB / base); + digitB %= base; + } + function decimalFrom1e7(digit1e7, needLeadingZeros) { + let partial = digit1e7 ? String(digit1e7) : ""; + if (needLeadingZeros) { + return "0000000".slice(partial.length) + partial; + } + return partial; + } + return decimalFrom1e7( + digitC, + /*needLeadingZeros=*/ + 0 + ) + decimalFrom1e7( + digitB, + /*needLeadingZeros=*/ + digitC + ) + // If the final 1e7 digit didn't need leading zeros, we would have + // returned via the trivial code path at the top. + decimalFrom1e7( + digitA, + /*needLeadingZeros=*/ + 1 + ); + } + exports2.int64toString = int64toString; + function varint32write(value, bytes) { + if (value >= 0) { + while (value > 127) { + bytes.push(value & 127 | 128); + value = value >>> 7; + } + bytes.push(value); + } else { + for (let i = 0; i < 9; i++) { + bytes.push(value & 127 | 128); + value = value >> 7; + } + bytes.push(1); + } + } + exports2.varint32write = varint32write; + function varint32read() { + let b = this.buf[this.pos++]; + let result = b & 127; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 7; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 14; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 21; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 15) << 28; + for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++) + b = this.buf[this.pos++]; + if ((b & 128) != 0) + throw new Error("invalid varint"); + this.assertBounds(); + return result >>> 0; + } + exports2.varint32read = varint32read; } }); -// node_modules/@actions/cache/lib/internal/uploadUtils.js -var require_uploadUtils = __commonJS({ - "node_modules/@actions/cache/lib/internal/uploadUtils.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js +var require_pb_long = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PbLong = exports2.PbULong = exports2.detectBi = void 0; + var goog_varint_1 = require_goog_varint(); + var BI; + function detectBi() { + const dv = new DataView(new ArrayBuffer(8)); + const ok = globalThis.BigInt !== void 0 && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function"; + BI = ok ? { + MIN: BigInt("-9223372036854775808"), + MAX: BigInt("9223372036854775807"), + UMIN: BigInt("0"), + UMAX: BigInt("18446744073709551615"), + C: BigInt, + V: dv + } : void 0; + } + exports2.detectBi = detectBi; + detectBi(); + function assertBi(bi) { + if (!bi) + throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); + } + var RE_DECIMAL_STR = /^-?[0-9]+$/; + var TWO_PWR_32_DBL = 4294967296; + var HALF_2_PWR_32 = 2147483648; + var SharedPbLong = class { + /** + * Create a new instance with the given bits. + */ + constructor(lo, hi) { + this.lo = lo | 0; + this.hi = hi | 0; } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); + /** + * Is this instance equal to 0? + */ + isZero() { + return this.lo == 0 && this.hi == 0; } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + /** + * Convert to a native number. + */ + toNumber() { + let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); + if (!Number.isSafeInteger(result)) + throw new Error("cannot convert to safe number"); + return result; + } + }; + var PbULong = class _PbULong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error("string is no integer"); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.UMIN) + throw new Error("signed value for ulong"); + if (value > BI.UMAX) + throw new Error("ulong too large"); + BI.V.setBigUint64(0, value, true); + return new _PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error("string is no integer"); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) + throw new Error("signed value for ulong"); + return new _PbULong(lo, hi); + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error("number is no integer"); + if (value < 0) + throw new Error("signed value for ulong"); + return new _PbULong(value, value / TWO_PWR_32_DBL); } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uploadCacheArchiveSDK = exports2.UploadProgress = void 0; - var core14 = __importStar4(require_core()); - var storage_blob_1 = require_dist7(); - var errors_1 = require_errors2(); - var UploadProgress = class { - constructor(contentLength) { - this.contentLength = contentLength; - this.sentBytes = 0; - this.displayedComplete = false; - this.startTime = Date.now(); + throw new Error("unknown value " + typeof value); } /** - * Sets the number of bytes sent - * - * @param sentBytes the number of bytes sent + * Convert to decimal string. */ - setSentBytes(sentBytes) { - this.sentBytes = sentBytes; + toString() { + return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); } /** - * Returns the total number of bytes transferred. + * Convert to native bigint. */ - getTransferredBytes() { - return this.sentBytes; + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigUint64(0, true); } + }; + exports2.PbULong = PbULong; + PbULong.ZERO = new PbULong(0, 0); + var PbLong = class _PbLong extends SharedPbLong { /** - * Returns true if the upload is complete. + * Create instance from a `string`, `number` or `bigint`. */ - isDone() { - return this.getTransferredBytes() === this.contentLength; + static from(value) { + if (BI) + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error("string is no integer"); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.MIN) + throw new Error("signed long too small"); + if (value > BI.MAX) + throw new Error("signed long too large"); + BI.V.setBigInt64(0, value, true); + return new _PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + } + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error("string is no integer"); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) { + if (hi > HALF_2_PWR_32 || hi == HALF_2_PWR_32 && lo != 0) + throw new Error("signed long too small"); + } else if (hi >= HALF_2_PWR_32) + throw new Error("signed long too large"); + let pbl = new _PbLong(lo, hi); + return minus ? pbl.negate() : pbl; + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error("number is no integer"); + return value > 0 ? new _PbLong(value, value / TWO_PWR_32_DBL) : new _PbLong(-value, -value / TWO_PWR_32_DBL).negate(); + } + throw new Error("unknown value " + typeof value); } /** - * Prints the current upload stats. Once the upload completes, this will print one - * last line and then stop. + * Do we have a minus sign? */ - display() { - if (this.displayedComplete) { - return; - } - const transferredBytes = this.sentBytes; - const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); - const elapsedTime = Date.now() - this.startTime; - const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); - core14.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`); - if (this.isDone()) { - this.displayedComplete = true; - } + isNegative() { + return (this.hi & HALF_2_PWR_32) !== 0; } /** - * Returns a function used to handle TransferProgressEvents. + * Negate two's complement. + * Invert all the bits and add one to the result. */ - onProgress() { - return (progress) => { - this.setSentBytes(progress.loadedBytes); - }; + negate() { + let hi = ~this.hi, lo = this.lo; + if (lo) + lo = ~lo + 1; + else + hi += 1; + return new _PbLong(lo, hi); } /** - * Starts the timer that displays the stats. - * - * @param delayInMs the delay between each write + * Convert to decimal string. */ - startDisplayTimer(delayInMs = 1e3) { - const displayCallback = () => { - this.display(); - if (!this.isDone()) { - this.timeoutHandle = setTimeout(displayCallback, delayInMs); - } - }; - this.timeoutHandle = setTimeout(displayCallback, delayInMs); + toString() { + if (BI) + return this.toBigInt().toString(); + if (this.isNegative()) { + let n = this.negate(); + return "-" + goog_varint_1.int64toString(n.lo, n.hi); + } + return goog_varint_1.int64toString(this.lo, this.hi); } /** - * Stops the timer that displays the stats. As this typically indicates the upload - * is complete, this will display one last line, unless the last line has already - * been written. + * Convert to native bigint. */ - stopDisplayTimer() { - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - this.timeoutHandle = void 0; - } - this.display(); + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigInt64(0, true); } }; - exports2.UploadProgress = UploadProgress; - function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) { - var _a; - return __awaiter4(this, void 0, void 0, function* () { - const blobClient = new storage_blob_1.BlobClient(signedUploadURL); - const blockBlobClient = blobClient.getBlockBlobClient(); - const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0); - const uploadOptions = { - blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize, - concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency, - maxSingleShotSize: 128 * 1024 * 1024, - onProgress: uploadProgress.onProgress() - }; - try { - uploadProgress.startDisplayTimer(); - core14.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`); - const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions); - if (response._response.status >= 400) { - throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`); - } - return response; - } catch (error4) { - core14.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error4.message}`); - throw error4; - } finally { - uploadProgress.stopDisplayTimer(); - } - }); - } - exports2.uploadCacheArchiveSDK = uploadCacheArchiveSDK; + exports2.PbLong = PbLong; + PbLong.ZERO = new PbLong(0, 0); } }); -// node_modules/@actions/cache/lib/internal/requestUtils.js -var require_requestUtils = __commonJS({ - "node_modules/@actions/cache/lib/internal/requestUtils.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js +var require_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; - var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var constants_1 = require_constants7(); - function isSuccessStatusCode(statusCode) { - if (!statusCode) { - return false; - } - return statusCode >= 200 && statusCode < 300; + exports2.BinaryReader = exports2.binaryReadOptions = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var defaultsRead = { + readUnknownField: true, + readerFactory: (bytes) => new BinaryReader(bytes) + }; + function binaryReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } - exports2.isSuccessStatusCode = isSuccessStatusCode; - function isServerErrorStatusCode(statusCode) { - if (!statusCode) { - return true; + exports2.binaryReadOptions = binaryReadOptions; + var BinaryReader = class { + constructor(buf, textDecoder) { + this.varint64 = goog_varint_1.varint64read; + this.uint32 = goog_varint_1.varint32read; + this.buf = buf; + this.len = buf.length; + this.pos = 0; + this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true + }); } - return statusCode >= 500; - } - exports2.isServerErrorStatusCode = isServerErrorStatusCode; - function isRetryableStatusCode(statusCode) { - if (!statusCode) { - return false; + /** + * Reads a tag - field number and wire type. + */ + tag() { + let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; + if (fieldNo <= 0 || wireType < 0 || wireType > 5) + throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); + return [fieldNo, wireType]; } - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.GatewayTimeout - ]; - return retryableStatusCodes.includes(statusCode); - } - exports2.isRetryableStatusCode = isRetryableStatusCode; - function sleep(milliseconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve5) => setTimeout(resolve5, milliseconds)); - }); - } - function retry3(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = void 0) { - return __awaiter4(this, void 0, void 0, function* () { - let errorMessage = ""; - let attempt = 1; - while (attempt <= maxAttempts) { - let response = void 0; - let statusCode = void 0; - let isRetryable = false; - try { - response = yield method(); - } catch (error4) { - if (onError) { - response = onError(error4); + /** + * Skip one element on the wire and return the skipped data. + * Supports WireType.StartGroup since v2.0.0-alpha.23. + */ + skip(wireType) { + let start = this.pos; + switch (wireType) { + case binary_format_contract_1.WireType.Varint: + while (this.buf[this.pos++] & 128) { } - isRetryable = true; - errorMessage = error4.message; - } - if (response) { - statusCode = getStatusCode(response); - if (!isServerErrorStatusCode(statusCode)) { - return response; + break; + case binary_format_contract_1.WireType.Bit64: + this.pos += 4; + case binary_format_contract_1.WireType.Bit32: + this.pos += 4; + break; + case binary_format_contract_1.WireType.LengthDelimited: + let len = this.uint32(); + this.pos += len; + break; + case binary_format_contract_1.WireType.StartGroup: + let t; + while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { + this.skip(t); } - } - if (statusCode) { - isRetryable = isRetryableStatusCode(statusCode); - errorMessage = `Cache service responded with ${statusCode}`; - } - core14.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); - if (!isRetryable) { - core14.debug(`${name} - Error is not retryable`); break; - } - yield sleep(delay); - attempt++; + default: + throw new Error("cant skip wire type " + wireType); } - throw Error(`${name} failed: ${errorMessage}`); - }); - } - exports2.retry = retry3; - function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { - return __awaiter4(this, void 0, void 0, function* () { - return yield retry3( - name, - method, - (response) => response.statusCode, - maxAttempts, - delay, - // If the error object contains the statusCode property, extract it and return - // an TypedResponse so it can be processed by the retry logic. - (error4) => { - if (error4 instanceof http_client_1.HttpClientError) { - return { - statusCode: error4.statusCode, - result: null, - headers: {}, - error: error4 - }; - } else { - return void 0; - } - } - ); - }); - } - exports2.retryTypedResponse = retryTypedResponse; - function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { - return __awaiter4(this, void 0, void 0, function* () { - return yield retry3(name, method, (response) => response.message.statusCode, maxAttempts, delay); - }); - } - exports2.retryHttpClientResponse = retryHttpClientResponse; - } -}); - -// node_modules/@actions/cache/lib/internal/downloadUtils.js -var require_downloadUtils = __commonJS({ - "node_modules/@actions/cache/lib/internal/downloadUtils.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + this.assertBounds(); + return this.buf.subarray(start, this.pos); + } + /** + * Throws error if position in byte array is out of range. + */ + assertBounds() { + if (this.pos > this.len) + throw new RangeError("premature EOF"); + } + /** + * Read a `int32` field, a signed 32 bit varint. + */ + int32() { + return this.uint32() | 0; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + /** + * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. + */ + sint32() { + let zze = this.uint32(); + return zze >>> 1 ^ -(zze & 1); } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); + /** + * Read a `int64` field, a signed 64-bit varint. + */ + int64() { + return new pb_long_1.PbLong(...this.varint64()); } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; - var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var storage_blob_1 = require_dist7(); - var buffer = __importStar4(require("buffer")); - var fs7 = __importStar4(require("fs")); - var stream = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var utils = __importStar4(require_cacheUtils()); - var constants_1 = require_constants7(); - var requestUtils_1 = require_requestUtils(); - var abort_controller_1 = require_dist5(); - function pipeResponseToStream(response, output) { - return __awaiter4(this, void 0, void 0, function* () { - const pipeline = util.promisify(stream.pipeline); - yield pipeline(response.message, output); - }); - } - var DownloadProgress = class { - constructor(contentLength) { - this.contentLength = contentLength; - this.segmentIndex = 0; - this.segmentSize = 0; - this.segmentOffset = 0; - this.receivedBytes = 0; - this.displayedComplete = false; - this.startTime = Date.now(); + /** + * Read a `uint64` field, an unsigned 64-bit varint. + */ + uint64() { + return new pb_long_1.PbULong(...this.varint64()); } /** - * Progress to the next segment. Only call this method when the previous segment - * is complete. - * - * @param segmentSize the length of the next segment + * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. */ - nextSegment(segmentSize) { - this.segmentOffset = this.segmentOffset + this.segmentSize; - this.segmentIndex = this.segmentIndex + 1; - this.segmentSize = segmentSize; - this.receivedBytes = 0; - core14.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); + sint64() { + let [lo, hi] = this.varint64(); + let s = -(lo & 1); + lo = (lo >>> 1 | (hi & 1) << 31) ^ s; + hi = hi >>> 1 ^ s; + return new pb_long_1.PbLong(lo, hi); } /** - * Sets the number of bytes received for the current segment. - * - * @param receivedBytes the number of bytes received + * Read a `bool` field, a variant. */ - setReceivedBytes(receivedBytes) { - this.receivedBytes = receivedBytes; + bool() { + let [lo, hi] = this.varint64(); + return lo !== 0 || hi !== 0; } /** - * Returns the total number of bytes transferred. + * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. */ - getTransferredBytes() { - return this.segmentOffset + this.receivedBytes; + fixed32() { + return this.view.getUint32((this.pos += 4) - 4, true); } /** - * Returns true if the download is complete. + * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. */ - isDone() { - return this.getTransferredBytes() === this.contentLength; + sfixed32() { + return this.view.getInt32((this.pos += 4) - 4, true); } /** - * Prints the current download stats. Once the download completes, this will print one - * last line and then stop. + * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. */ - display() { - if (this.displayedComplete) { - return; - } - const transferredBytes = this.segmentOffset + this.receivedBytes; - const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); - const elapsedTime = Date.now() - this.startTime; - const downloadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); - core14.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); - if (this.isDone()) { - this.displayedComplete = true; - } + fixed64() { + return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); } /** - * Returns a function used to handle TransferProgressEvents. + * Read a `fixed64` field, a signed, fixed-length 64-bit integer. */ - onProgress() { - return (progress) => { - this.setReceivedBytes(progress.loadedBytes); - }; + sfixed64() { + return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); } /** - * Starts the timer that displays the stats. - * - * @param delayInMs the delay between each write + * Read a `float` field, 32-bit floating point number. */ - startDisplayTimer(delayInMs = 1e3) { - const displayCallback = () => { - this.display(); - if (!this.isDone()) { - this.timeoutHandle = setTimeout(displayCallback, delayInMs); - } - }; - this.timeoutHandle = setTimeout(displayCallback, delayInMs); + float() { + return this.view.getFloat32((this.pos += 4) - 4, true); } /** - * Stops the timer that displays the stats. As this typically indicates the download - * is complete, this will display one last line, unless the last line has already - * been written. + * Read a `double` field, a 64-bit floating point number. */ - stopDisplayTimer() { - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - this.timeoutHandle = void 0; - } - this.display(); + double() { + return this.view.getFloat64((this.pos += 8) - 8, true); + } + /** + * Read a `bytes` field, length-delimited arbitrary data. + */ + bytes() { + let len = this.uint32(); + let start = this.pos; + this.pos += len; + this.assertBounds(); + return this.buf.subarray(start, start + len); + } + /** + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); } }; - exports2.DownloadProgress = DownloadProgress; - function downloadCacheHttpClient(archiveLocation, archivePath) { - return __awaiter4(this, void 0, void 0, function* () { - const writeStream = fs7.createWriteStream(archivePath); - const httpClient = new http_client_1.HttpClient("actions/cache"); - const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.get(archiveLocation); - })); - downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { - downloadResponse.message.destroy(); - core14.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); - }); - yield pipeResponseToStream(downloadResponse, writeStream); - const contentLengthHeader = downloadResponse.message.headers["content-length"]; - if (contentLengthHeader) { - const expectedLength = parseInt(contentLengthHeader); - const actualLength = utils.getArchiveFileSizeInBytes(archivePath); - if (actualLength !== expectedLength) { - throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); - } - } else { - core14.debug("Unable to validate download, no Content-Length header"); - } - }); + exports2.BinaryReader = BinaryReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js +var require_assert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; + function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } } - exports2.downloadCacheHttpClient = downloadCacheHttpClient; - function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { - var _a; - return __awaiter4(this, void 0, void 0, function* () { - const archiveDescriptor = yield fs7.promises.open(archivePath, "w"); - const httpClient = new http_client_1.HttpClient("actions/cache", void 0, { - socketTimeout: options.timeoutInMs, - keepAlive: true - }); - try { - const res = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCacheMetadata", () => __awaiter4(this, void 0, void 0, function* () { - return yield httpClient.request("HEAD", archiveLocation, null, {}); - })); - const lengthHeader = res.message.headers["content-length"]; - if (lengthHeader === void 0 || lengthHeader === null) { - throw new Error("Content-Length not found on blob response"); - } - const length = parseInt(lengthHeader); - if (Number.isNaN(length)) { - throw new Error(`Could not interpret Content-Length: ${length}`); - } - const downloads = []; - const blockSize = 4 * 1024 * 1024; - for (let offset = 0; offset < length; offset += blockSize) { - const count = Math.min(blockSize, length - offset); - downloads.push({ - offset, - promiseGetter: () => __awaiter4(this, void 0, void 0, function* () { - return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count); - }) - }); - } - downloads.reverse(); - let actives = 0; - let bytesDownloaded = 0; - const progress = new DownloadProgress(length); - progress.startDisplayTimer(); - const progressFn = progress.onProgress(); - const activeDownloads = []; - let nextDownload; - const waitAndWrite = () => __awaiter4(this, void 0, void 0, function* () { - const segment = yield Promise.race(Object.values(activeDownloads)); - yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset); - actives--; - delete activeDownloads[segment.offset]; - bytesDownloaded += segment.count; - progressFn({ loadedBytes: bytesDownloaded }); - }); - while (nextDownload = downloads.pop()) { - activeDownloads[nextDownload.offset] = nextDownload.promiseGetter(); - actives++; - if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) { - yield waitAndWrite(); - } - } - while (actives > 0) { - yield waitAndWrite(); - } - } finally { - httpClient.dispose(); - yield archiveDescriptor.close(); - } - }); + exports2.assert = assert; + function assertNever2(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); } - exports2.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent; - function downloadSegmentRetry(httpClient, archiveLocation, offset, count) { - return __awaiter4(this, void 0, void 0, function* () { - const retries = 5; - let failures = 0; - while (true) { - try { - const timeout = 3e4; - const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count)); - if (typeof result === "string") { - throw new Error("downloadSegmentRetry failed due to timeout"); - } - return result; - } catch (err) { - if (failures >= retries) { - throw err; - } - failures++; - } - } - }); + exports2.assertNever = assertNever2; + var FLOAT32_MAX = 34028234663852886e22; + var FLOAT32_MIN = -34028234663852886e22; + var UINT32_MAX = 4294967295; + var INT32_MAX = 2147483647; + var INT32_MIN = -2147483648; + function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid int 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error("invalid int 32: " + arg); } - function downloadSegment(httpClient, archiveLocation, offset, count) { - return __awaiter4(this, void 0, void 0, function* () { - const partRes = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCachePart", () => __awaiter4(this, void 0, void 0, function* () { - return yield httpClient.get(archiveLocation, { - Range: `bytes=${offset}-${offset + count - 1}` - }); - })); - if (!partRes.readBodyBuffer) { - throw new Error("Expected HttpClientResponse to implement readBodyBuffer"); - } - return { - offset, - count, - buffer: yield partRes.readBodyBuffer() - }; - }); + exports2.assertInt32 = assertInt32; + function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid uint 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error("invalid uint 32: " + arg); } - function downloadCacheStorageSDK(archiveLocation, archivePath, options) { - var _a; - return __awaiter4(this, void 0, void 0, function* () { - const client = new storage_blob_1.BlockBlobClient(archiveLocation, void 0, { - retryOptions: { - // Override the timeout used when downloading each 4 MB chunk - // The default is 2 min / MB, which is way too slow - tryTimeoutInMs: options.timeoutInMs - } - }); - const properties = yield client.getProperties(); - const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; - if (contentLength < 0) { - core14.debug("Unable to determine content length, downloading file with http-client..."); - yield downloadCacheHttpClient(archiveLocation, archivePath); - } else { - const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); - const downloadProgress = new DownloadProgress(contentLength); - const fd = fs7.openSync(archivePath, "w"); - try { - downloadProgress.startDisplayTimer(); - const controller = new abort_controller_1.AbortController(); - const abortSignal = controller.signal; - while (!downloadProgress.isDone()) { - const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; - const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); - downloadProgress.nextSegment(segmentSize); - const result = yield promiseWithTimeout(options.segmentTimeoutInMs || 36e5, client.downloadToBuffer(segmentStart, segmentSize, { - abortSignal, - concurrency: options.downloadConcurrency, - onProgress: downloadProgress.onProgress() - })); - if (result === "timeout") { - controller.abort(); - throw new Error("Aborting cache download as the download time exceeded the timeout."); - } else if (Buffer.isBuffer(result)) { - fs7.writeFileSync(fd, result); - } - } - } finally { - downloadProgress.stopDisplayTimer(); - fs7.closeSync(fd); - } - } - }); + exports2.assertUInt32 = assertUInt32; + function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error("invalid float 32: " + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error("invalid float 32: " + arg); } - exports2.downloadCacheStorageSDK = downloadCacheStorageSDK; - var promiseWithTimeout = (timeoutMs, promise) => __awaiter4(void 0, void 0, void 0, function* () { - let timeoutHandle; - const timeoutPromise = new Promise((resolve5) => { - timeoutHandle = setTimeout(() => resolve5("timeout"), timeoutMs); - }); - return Promise.race([promise, timeoutPromise]).then((result) => { - clearTimeout(timeoutHandle); - return result; - }); - }); + exports2.assertFloat32 = assertFloat32; } }); -// node_modules/@actions/cache/lib/options.js -var require_options = __commonJS({ - "node_modules/@actions/cache/lib/options.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js +var require_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var assert_1 = require_assert(); + var defaultsWrite = { + writeUnknownFields: true, + writerFactory: () => new BinaryWriter() + }; + function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.binaryWriteOptions = binaryWriteOptions; + var BinaryWriter = class { + constructor(textEncoder) { + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; + } + this.chunks = []; + return bytes; + } + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; + } + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + let chunk = this.finish(); + let prev = this.stack.pop(); + if (!prev) + throw new Error("invalid state, fork stack empty"); + this.chunks = prev.chunks; + this.buf = prev.buf; + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type2) { + return this.uint32((fieldNo << 3 | type2) >>> 0); } - __setModuleDefault4(result, mod); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getDownloadOptions = exports2.getUploadOptions = void 0; - var core14 = __importStar4(require_core()); - function getUploadOptions(copy) { - const result = { - useAzureSdk: false, - uploadConcurrency: 4, - uploadChunkSize: 32 * 1024 * 1024 - }; - if (copy) { - if (typeof copy.useAzureSdk === "boolean") { - result.useAzureSdk = copy.useAzureSdk; - } - if (typeof copy.uploadConcurrency === "number") { - result.uploadConcurrency = copy.uploadConcurrency; - } - if (typeof copy.uploadChunkSize === "number") { - result.uploadChunkSize = copy.uploadChunkSize; + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; } + this.chunks.push(chunk); + return this; } - result.uploadConcurrency = !isNaN(Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) ? Math.min(32, Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) : result.uploadConcurrency; - result.uploadChunkSize = !isNaN(Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"])) ? Math.min(128 * 1024 * 1024, Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"]) * 1024 * 1024) : result.uploadChunkSize; - core14.debug(`Use Azure SDK: ${result.useAzureSdk}`); - core14.debug(`Upload concurrency: ${result.uploadConcurrency}`); - core14.debug(`Upload chunk size: ${result.uploadChunkSize}`); - return result; - } - exports2.getUploadOptions = getUploadOptions; - function getDownloadOptions(copy) { - const result = { - useAzureSdk: false, - concurrentBlobDownloads: true, - downloadConcurrency: 8, - timeoutInMs: 3e4, - segmentTimeoutInMs: 6e5, - lookupOnly: false - }; - if (copy) { - if (typeof copy.useAzureSdk === "boolean") { - result.useAzureSdk = copy.useAzureSdk; - } - if (typeof copy.concurrentBlobDownloads === "boolean") { - result.concurrentBlobDownloads = copy.concurrentBlobDownloads; - } - if (typeof copy.downloadConcurrency === "number") { - result.downloadConcurrency = copy.downloadConcurrency; - } - if (typeof copy.timeoutInMs === "number") { - result.timeoutInMs = copy.timeoutInMs; - } - if (typeof copy.segmentTimeoutInMs === "number") { - result.segmentTimeoutInMs = copy.segmentTimeoutInMs; - } - if (typeof copy.lookupOnly === "boolean") { - result.lookupOnly = copy.lookupOnly; + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); + while (value > 127) { + this.buf.push(value & 127 | 128); + value = value >>> 7; } + this.buf.push(value); + return this; } - const segmentDownloadTimeoutMins = process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]; - if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) { - result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1e3; + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; } - core14.debug(`Use Azure SDK: ${result.useAzureSdk}`); - core14.debug(`Download concurrency: ${result.downloadConcurrency}`); - core14.debug(`Request timeout (ms): ${result.timeoutInMs}`); - core14.debug(`Cache segment download timeout mins env var: ${process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]}`); - core14.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`); - core14.debug(`Lookup only: ${result.lookupOnly}`); - return result; - } - exports2.getDownloadOptions = getDownloadOptions; + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; + } + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); + return this.raw(value); + } + /** + * Write a `string` value, length-delimited data converted to UTF-8 text. + */ + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Write a `float` value, 32-bit floating point number. + */ + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `double` value, a 64-bit floating point number. + */ + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); + } + /** + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + */ + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + */ + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + */ + sint32(value) { + assert_1.assertInt32(value); + value = (value << 1 ^ value >> 31) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + */ + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + */ + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `int64` value, a signed 64-bit varint. + */ + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + /** + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + */ + sint64(value) { + let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; + } + /** + * Write a `uint64` value, an unsigned 64-bit varint. + */ + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + }; + exports2.BinaryWriter = BinaryWriter; } }); -// node_modules/@actions/cache/lib/internal/config.js -var require_config = __commonJS({ - "node_modules/@actions/cache/lib/internal/config.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js +var require_json_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getCacheServiceURL = exports2.getCacheServiceVersion = exports2.isGhes = void 0; - function isGhes() { - const ghUrl = new URL(process.env["GITHUB_SERVER_URL"] || "https://github.com"); - const hostname = ghUrl.hostname.trimEnd().toUpperCase(); - const isGitHubHost = hostname === "GITHUB.COM"; - const isGheHost = hostname.endsWith(".GHE.COM"); - const isLocalHost = hostname.endsWith(".LOCALHOST"); - return !isGitHubHost && !isGheHost && !isLocalHost; + exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; + var defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0 + }; + var defaultsRead = { + ignoreUnknownFields: false + }; + function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } - exports2.isGhes = isGhes; - function getCacheServiceVersion() { - if (isGhes()) - return "v1"; - return process.env["ACTIONS_CACHE_SERVICE_V2"] ? "v2" : "v1"; + exports2.jsonReadOptions = jsonReadOptions; + function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; } - exports2.getCacheServiceVersion = getCacheServiceVersion; - function getCacheServiceURL() { - const version = getCacheServiceVersion(); - switch (version) { - case "v1": - return process.env["ACTIONS_CACHE_URL"] || process.env["ACTIONS_RESULTS_URL"] || ""; - case "v2": - return process.env["ACTIONS_RESULTS_URL"] || ""; - default: - throw new Error(`Unsupported cache service version: ${version}`); - } + exports2.jsonWriteOptions = jsonWriteOptions; + function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; + return c; } - exports2.getCacheServiceURL = getCacheServiceURL; - } -}); - -// node_modules/@actions/cache/package.json -var require_package2 = __commonJS({ - "node_modules/@actions/cache/package.json"(exports2, module2) { - module2.exports = { - name: "@actions/cache", - version: "4.1.0", - preview: true, - description: "Actions cache lib", - keywords: [ - "github", - "actions", - "cache" - ], - homepage: "https://github.com/actions/toolkit/tree/main/packages/cache", - license: "MIT", - main: "lib/cache.js", - types: "lib/cache.d.ts", - directories: { - lib: "lib", - test: "__tests__" - }, - files: [ - "lib", - "!.DS_Store" - ], - publishConfig: { - access: "public" - }, - repository: { - type: "git", - url: "git+https://github.com/actions/toolkit.git", - directory: "packages/cache" - }, - scripts: { - "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", - test: 'echo "Error: run tests from root" && exit 1', - tsc: "tsc" - }, - bugs: { - url: "https://github.com/actions/toolkit/issues" - }, - dependencies: { - "@actions/core": "^1.11.1", - "@actions/exec": "^1.0.1", - "@actions/glob": "^0.1.0", - "@protobuf-ts/runtime-rpc": "^2.11.1", - "@actions/http-client": "^2.1.1", - "@actions/io": "^1.0.1", - "@azure/abort-controller": "^1.1.0", - "@azure/ms-rest-js": "^2.6.0", - "@azure/storage-blob": "^12.13.0", - semver: "^6.3.1" - }, - devDependencies: { - "@types/node": "^22.13.9", - "@types/semver": "^6.0.0", - "@protobuf-ts/plugin": "^2.9.4", - typescript: "^5.2.2" - } - }; + exports2.mergeJsonOptions = mergeJsonOptions; } }); -// node_modules/@actions/cache/lib/internal/shared/user-agent.js -var require_user_agent = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/user-agent.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js +var require_message_type_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUserAgentString = void 0; - var packageJson = require_package2(); - function getUserAgentString() { - return `@actions/cache-${packageJson.version}`; - } - exports2.getUserAgentString = getUserAgentString; + exports2.MESSAGE_TYPE = void 0; + exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); } }); -// node_modules/@actions/cache/lib/internal/cacheHttpClient.js -var require_cacheHttpClient = __commonJS({ - "node_modules/@actions/cache/lib/internal/cacheHttpClient.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js +var require_lower_camel_case = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; - var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); - var fs7 = __importStar4(require("fs")); - var url_1 = require("url"); - var utils = __importStar4(require_cacheUtils()); - var uploadUtils_1 = require_uploadUtils(); - var downloadUtils_1 = require_downloadUtils(); - var options_1 = require_options(); - var requestUtils_1 = require_requestUtils(); - var config_1 = require_config(); - var user_agent_1 = require_user_agent(); - function getCacheApiUrl(resource) { - const baseUrl = (0, config_1.getCacheServiceURL)(); - if (!baseUrl) { - throw new Error("Cache Service Url not found, unable to restore cache."); - } - const url = `${baseUrl}_apis/artifactcache/${resource}`; - core14.debug(`Resource Url: ${url}`); - return url; - } - function createAcceptHeader(type2, apiVersion) { - return `${type2};api-version=${apiVersion}`; - } - function getRequestOptions() { - const requestOptions = { - headers: { - Accept: createAcceptHeader("application/json", "6.0-preview.1") - } - }; - return requestOptions; - } - function createHttpClient() { - const token = process.env["ACTIONS_RUNTIME_TOKEN"] || ""; - const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); - return new http_client_1.HttpClient((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions()); - } - function getCacheEntry(keys, paths, options) { - return __awaiter4(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); - const resource = `cache?keys=${encodeURIComponent(keys.join(","))}&version=${version}`; - const response = yield (0, requestUtils_1.retryTypedResponse)("getCacheEntry", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.getJson(getCacheApiUrl(resource)); - })); - if (response.statusCode === 204) { - if (core14.isDebug()) { - yield printCachesListForDiagnostics(keys[0], httpClient, version); - } - return null; - } - if (!(0, requestUtils_1.isSuccessStatusCode)(response.statusCode)) { - throw new Error(`Cache service responded with ${response.statusCode}`); - } - const cacheResult = response.result; - const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; - if (!cacheDownloadUrl) { - throw new Error("Cache not found."); - } - core14.setSecret(cacheDownloadUrl); - core14.debug(`Cache Result:`); - core14.debug(JSON.stringify(cacheResult)); - return cacheResult; - }); - } - exports2.getCacheEntry = getCacheEntry; - function printCachesListForDiagnostics(key, httpClient, version) { - return __awaiter4(this, void 0, void 0, function* () { - const resource = `caches?key=${encodeURIComponent(key)}`; - const response = yield (0, requestUtils_1.retryTypedResponse)("listCache", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.getJson(getCacheApiUrl(resource)); - })); - if (response.statusCode === 200) { - const cacheListResult = response.result; - const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount; - if (totalCount && totalCount > 0) { - core14.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env["GITHUB_REF"]}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key -Other caches with similar key:`); - for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) { - core14.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`); - } - } - } - }); - } - function downloadCache(archiveLocation, archivePath, options) { - return __awaiter4(this, void 0, void 0, function* () { - const archiveUrl = new url_1.URL(archiveLocation); - const downloadOptions = (0, options_1.getDownloadOptions)(options); - if (archiveUrl.hostname.endsWith(".blob.core.windows.net")) { - if (downloadOptions.useAzureSdk) { - yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions); - } else if (downloadOptions.concurrentBlobDownloads) { - yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions); - } else { - yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); - } + exports2.lowerCamelCase = void 0; + function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == "_") { + capNext = true; + } else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } else if (i == 0) { + sb.push(next.toLowerCase()); } else { - yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); + sb.push(next); } - }); - } - exports2.downloadCache = downloadCache; - function reserveCache(key, paths, options) { - return __awaiter4(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); - const reserveCacheRequest = { - key, - version, - cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize - }; - const response = yield (0, requestUtils_1.retryTypedResponse)("reserveCache", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl("caches"), reserveCacheRequest); - })); - return response; - }); - } - exports2.reserveCache = reserveCache; - function getContentRange(start, end) { - return `bytes ${start}-${end}/*`; + } + return sb.join(""); } - function uploadChunk(httpClient, resourceUrl, openStream, start, end) { - return __awaiter4(this, void 0, void 0, function* () { - core14.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); - const additionalHeaders = { - "Content-Type": "application/octet-stream", - "Content-Range": getContentRange(start, end) - }; - const uploadChunkResponse = yield (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.sendStream("PATCH", resourceUrl, openStream(), additionalHeaders); - })); - if (!(0, requestUtils_1.isSuccessStatusCode)(uploadChunkResponse.message.statusCode)) { - throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); - } - }); + exports2.lowerCamelCase = lowerCamelCase; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js +var require_reflection_info = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; + var lower_camel_case_1 = require_lower_camel_case(); + var ScalarType; + (function(ScalarType2) { + ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; + ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; + ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; + ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; + ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; + ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; + ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; + ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; + ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; + ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; + ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; + ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; + ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; + ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; + ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; + })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); + var LongType; + (function(LongType2) { + LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; + LongType2[LongType2["STRING"] = 1] = "STRING"; + LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; + })(LongType = exports2.LongType || (exports2.LongType = {})); + var RepeatType; + (function(RepeatType2) { + RepeatType2[RepeatType2["NO"] = 0] = "NO"; + RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; + RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; + })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); + function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; + return field; } - function uploadFile(httpClient, cacheId, archivePath, options) { - return __awaiter4(this, void 0, void 0, function* () { - const fileSize = utils.getArchiveFileSizeInBytes(archivePath); - const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); - const fd = fs7.openSync(archivePath, "r"); - const uploadOptions = (0, options_1.getUploadOptions)(options); - const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency); - const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize); - const parallelUploads = [...new Array(concurrency).keys()]; - core14.debug("Awaiting all uploads"); - let offset = 0; - try { - yield Promise.all(parallelUploads.map(() => __awaiter4(this, void 0, void 0, function* () { - while (offset < fileSize) { - const chunkSize = Math.min(fileSize - offset, maxChunkSize); - const start = offset; - const end = offset + chunkSize - 1; - offset += maxChunkSize; - yield uploadChunk(httpClient, resourceUrl, () => fs7.createReadStream(archivePath, { - fd, - start, - end, - autoClose: false - }).on("error", (error4) => { - throw new Error(`Cache upload failed because file read failed with ${error4.message}`); - }), start, end); - } - }))); - } finally { - fs7.closeSync(fd); - } - return; - }); + exports2.normalizeFieldInfo = normalizeFieldInfo; + function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; } - function commitCache(httpClient, cacheId, filesize) { - return __awaiter4(this, void 0, void 0, function* () { - const commitCacheRequest = { size: filesize }; - return yield (0, requestUtils_1.retryTypedResponse)("commitCache", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); - })); - }); + exports2.readFieldOptions = readFieldOptions; + function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - function saveCache4(cacheId, archivePath, signedUploadURL, options) { - return __awaiter4(this, void 0, void 0, function* () { - const uploadOptions = (0, options_1.getUploadOptions)(options); - if (uploadOptions.useAzureSdk) { - if (!signedUploadURL) { - throw new Error("Azure Storage SDK can only be used when a signed URL is provided."); - } - yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options); - } else { - const httpClient = createHttpClient(); - core14.debug("Upload cache"); - yield uploadFile(httpClient, cacheId, archivePath, options); - core14.debug("Commiting cache"); - const cacheSize = utils.getArchiveFileSizeInBytes(archivePath); - core14.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); - const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); - if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) { - throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); - } - core14.info("Cache saved successfully"); - } - }); + exports2.readFieldOption = readFieldOption; + function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.saveCache = saveCache4; + exports2.readMessageOption = readMessageOption; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js -var require_json_typings = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js +var require_oneof = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isJsonObject = exports2.typeofJsonValue = void 0; - function typeofJsonValue(value) { - let t = typeof value; - if (t == "object") { - if (Array.isArray(value)) - return "array"; - if (value === null) - return "null"; + exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; + function isOneofGroup(any) { + if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === void 0) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; } - return t; } - exports2.typeofJsonValue = typeofJsonValue; - function isJsonObject(value) { - return value !== null && typeof value == "object" && !Array.isArray(value); + exports2.isOneofGroup = isOneofGroup; + function getOneofValue(oneof, kind) { + return oneof[kind]; } - exports2.isJsonObject = isJsonObject; + exports2.getOneofValue = getOneofValue; + function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== void 0) { + oneof[kind] = value; + } + } + exports2.setOneofValue = setOneofValue; + function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== void 0 && kind !== void 0) { + oneof[kind] = value; + } + } + exports2.setUnknownOneofValue = setUnknownOneofValue; + function clearOneofValue(oneof) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = void 0; + } + exports2.clearOneofValue = clearOneofValue; + function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === void 0) { + return void 0; + } + return oneof[oneof.oneofKind]; + } + exports2.getSelectedOneofValue = getSelectedOneofValue; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/base64.js -var require_base642 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/base64.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js +var require_reflection_type_check = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.base64encode = exports2.base64decode = void 0; - var encTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); - var decTable = []; - for (let i = 0; i < encTable.length; i++) - decTable[encTable[i].charCodeAt(0)] = i; - decTable["-".charCodeAt(0)] = encTable.indexOf("+"); - decTable["_".charCodeAt(0)] = encTable.indexOf("/"); - function base64decode(base64Str) { - let es = base64Str.length * 3 / 4; - if (base64Str[base64Str.length - 2] == "=") - es -= 2; - else if (base64Str[base64Str.length - 1] == "=") - es -= 1; - let bytes = new Uint8Array(es), bytePos = 0, groupPos = 0, b, p = 0; - for (let i = 0; i < base64Str.length; i++) { - b = decTable[base64Str.charCodeAt(i)]; - if (b === void 0) { - switch (base64Str[i]) { - case "=": - groupPos = 0; - // reset state when padding found - case "\n": - case "\r": - case " ": - case " ": - continue; - // skip white-space, and padding - default: - throw Error(`invalid base64 string.`); + exports2.ReflectionTypeCheck = void 0; + var reflection_info_1 = require_reflection_info(); + var oneof_1 = require_oneof(); + var ReflectionTypeCheck = class { + constructor(info7) { + var _a; + this.fields = (_a = info7.fields) !== null && _a !== void 0 ? _a : []; + } + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); + } + } else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; + } } } - switch (groupPos) { - case 0: - p = b; - groupPos = 1; - break; - case 1: - bytes[bytePos++] = p << 2 | (b & 48) >> 4; - p = b; - groupPos = 2; - break; - case 2: - bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; - p = b; - groupPos = 3; - break; - case 3: - bytes[bytePos++] = (p & 3) << 6 | b; - groupPos = 0; - break; + this.data = { req, known, oneofs: Object.values(oneofs) }; + } + /** + * Is the argument a valid message as specified by the + * reflection information? + * + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. + * + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. + */ + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === void 0 || typeof message != "object") + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + if (keys.some((k) => !data.known.includes(k))) + return false; + } + if (depth < 1) { + return true; + } + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === void 0) + continue; + const field = this.fields.find((f) => f.localName === group.oneofKind); + if (!field) + return false; + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + for (const field of this.fields) { + if (field.oneof !== void 0) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; } + return true; } - if (groupPos == 1) - throw Error(`invalid base64 string.`); - return bytes.subarray(0, bytePos); - } - exports2.base64decode = base64decode; - function base64encode(bytes) { - let base64 = "", groupPos = 0, b, p = 0; - for (let i = 0; i < bytes.length; i++) { - b = bytes[i]; - switch (groupPos) { - case 0: - base64 += encTable[b >> 2]; - p = (b & 3) << 4; - groupPos = 1; - break; - case 1: - base64 += encTable[p | b >> 4]; - p = (b & 15) << 2; - groupPos = 2; - break; - case 2: - base64 += encTable[p | b >> 6]; - base64 += encTable[b & 63]; - groupPos = 0; + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === void 0) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != "object" || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } break; } + return true; } - if (groupPos) { - base64 += encTable[p]; - base64 += "="; - if (groupPos == 1) - base64 += "="; + message(arg, type2, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type2.isAssignable(arg, depth); + } + return type2.is(arg, depth); + } + messages(arg, type2, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.isAssignable(arg[i], depth - 1)) + return false; + } else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.is(arg[i], depth - 1)) + return false; + } + return true; + } + scalar(arg, type2, longType) { + let argType = typeof arg; + switch (type2) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == "boolean"; + case reflection_info_1.ScalarType.STRING: + return argType == "string"; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == "number" && !isNaN(arg); + default: + return argType == "number" && Number.isInteger(arg); + } } - return base64; - } - exports2.base64encode = base64encode; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js -var require_protobufjs_utf8 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.utf8read = void 0; - var fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); - function utf8read(bytes) { - if (bytes.length < 1) - return ""; - let pos = 0, parts = [], chunk = [], i = 0, t; - let len = bytes.length; - while (pos < len) { - t = bytes[pos++]; - if (t < 128) - chunk[i++] = t; - else if (t > 191 && t < 224) - chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 65536; - chunk[i++] = 55296 + (t >> 10); - chunk[i++] = 56320 + (t & 1023); - } else - chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; - if (i > 8191) { - parts.push(fromCharCodes(chunk)); - i = 0; + scalars(arg, type2, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type2, longType)) + return false; } + return true; } - if (parts.length) { - if (i) - parts.push(fromCharCodes(chunk.slice(0, i))); - return parts.join(""); + mapKeys(map2, type2, depth) { + let keys = Object.keys(map2); + switch (type2) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); + default: + return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + } } - return fromCharCodes(chunk.slice(0, i)); - } - exports2.utf8read = utf8read; + }; + exports2.ReflectionTypeCheck = ReflectionTypeCheck; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js -var require_binary_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js +var require_reflection_long_convert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WireType = exports2.mergeBinaryOptions = exports2.UnknownFieldHandler = void 0; - var UnknownFieldHandler; - (function(UnknownFieldHandler2) { - UnknownFieldHandler2.symbol = Symbol.for("protobuf-ts/unknown"); - UnknownFieldHandler2.onRead = (typeName, message, fieldNo, wireType, data) => { - let container = is(message) ? message[UnknownFieldHandler2.symbol] : message[UnknownFieldHandler2.symbol] = []; - container.push({ no: fieldNo, wireType, data }); - }; - UnknownFieldHandler2.onWrite = (typeName, message, writer) => { - for (let { no, wireType, data } of UnknownFieldHandler2.list(message)) - writer.tag(no, wireType).raw(data); - }; - UnknownFieldHandler2.list = (message, fieldNo) => { - if (is(message)) { - let all = message[UnknownFieldHandler2.symbol]; - return fieldNo ? all.filter((uf) => uf.no == fieldNo) : all; - } - return []; - }; - UnknownFieldHandler2.last = (message, fieldNo) => UnknownFieldHandler2.list(message, fieldNo).slice(-1)[0]; - const is = (message) => message && Array.isArray(message[UnknownFieldHandler2.symbol]); - })(UnknownFieldHandler = exports2.UnknownFieldHandler || (exports2.UnknownFieldHandler = {})); - function mergeBinaryOptions(a, b) { - return Object.assign(Object.assign({}, a), b); + exports2.reflectionLongConvert = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionLongConvert(long, type2) { + switch (type2) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + return long.toString(); + } } - exports2.mergeBinaryOptions = mergeBinaryOptions; - var WireType; - (function(WireType2) { - WireType2[WireType2["Varint"] = 0] = "Varint"; - WireType2[WireType2["Bit64"] = 1] = "Bit64"; - WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited"; - WireType2[WireType2["StartGroup"] = 3] = "StartGroup"; - WireType2[WireType2["EndGroup"] = 4] = "EndGroup"; - WireType2[WireType2["Bit32"] = 5] = "Bit32"; - })(WireType = exports2.WireType || (exports2.WireType = {})); + exports2.reflectionLongConvert = reflectionLongConvert; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js -var require_goog_varint = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js +var require_reflection_json_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.varint32read = exports2.varint32write = exports2.int64toString = exports2.int64fromString = exports2.varint64write = exports2.varint64read = void 0; - function varint64read() { - let lowBits = 0; - let highBits = 0; - for (let shift = 0; shift < 28; shift += 7) { - let b = this.buf[this.pos++]; - lowBits |= (b & 127) << shift; - if ((b & 128) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } - } - let middleByte = this.buf[this.pos++]; - lowBits |= (middleByte & 15) << 28; - highBits = (middleByte & 112) >> 4; - if ((middleByte & 128) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } - for (let shift = 3; shift <= 31; shift += 7) { - let b = this.buf[this.pos++]; - highBits |= (b & 127) << shift; - if ((b & 128) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } + exports2.ReflectionJsonReader = void 0; + var json_typings_1 = require_json_typings(); + var base64_1 = require_base642(); + var reflection_info_1 = require_reflection_info(); + var pb_long_1 = require_pb_long(); + var assert_1 = require_assert(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var ReflectionJsonReader = class { + constructor(info7) { + this.info = info7; } - throw new Error("invalid varint"); - } - exports2.varint64read = varint64read; - function varint64write(lo, hi, bytes) { - for (let i = 0; i < 28; i = i + 7) { - const shift = lo >>> i; - const hasNext = !(shift >>> 7 == 0 && hi == 0); - const byte = (hasNext ? shift | 128 : shift) & 255; - bytes.push(byte); - if (!hasNext) { - return; + prepare() { + var _a; + if (this.fMap === void 0) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } } } - const splitBits = lo >>> 28 & 15 | (hi & 7) << 4; - const hasMoreBits = !(hi >> 3 == 0); - bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255); - if (!hasMoreBits) { - return; - } - for (let i = 3; i < 31; i = i + 7) { - const shift = hi >>> i; - const hasNext = !(shift >>> 7 == 0); - const byte = (hasNext ? shift | 128 : shift) & 255; - bytes.push(byte); - if (!hasNext) { - return; + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); } } - bytes.push(hi >>> 31 & 1); - } - exports2.varint64write = varint64write; - var TWO_PWR_32_DBL = (1 << 16) * (1 << 16); - function int64fromString(dec) { - let minus = dec[0] == "-"; - if (minus) - dec = dec.slice(1); - const base = 1e6; - let lowBits = 0; - let highBits = 0; - function add1e6digit(begin, end) { - const digit1e6 = Number(dec.slice(begin, end)); - highBits *= base; - lowBits = lowBits * base + digit1e6; - if (lowBits >= TWO_PWR_32_DBL) { - highBits = highBits + (lowBits / TWO_PWR_32_DBL | 0); - lowBits = lowBits % TWO_PWR_32_DBL; + /** + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + let target; + if (field.oneof) { + if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { + continue; + } + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } else { + target = message; + } + if (field.kind == "map") { + if (jsonValue === null) { + continue; + } + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + const fieldObj = target[localName]; + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + let val2; + switch (field.V.kind) { + case "message": + val2 = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val2; + } + } else if (field.repeat) { + if (jsonValue === null) + continue; + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + const fieldArr = target[localName]; + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val2; + switch (field.kind) { + case "message": + val2 = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name, jsonValue); + fieldArr.push(val2); + } + } else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { + this.assert(field.oneof === void 0, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + if (jsonValue === null) + continue; + let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + target[localName] = val2; + break; + case "scalar": + if (jsonValue === null) + continue; + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } } } - add1e6digit(-24, -18); - add1e6digit(-18, -12); - add1e6digit(-12, -6); - add1e6digit(-6); - return [minus, lowBits, highBits]; - } - exports2.int64fromString = int64fromString; - function int64toString(bitsLow, bitsHigh) { - if (bitsHigh >>> 0 <= 2097151) { - return "" + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); - } - let low = bitsLow & 16777215; - let mid = (bitsLow >>> 24 | bitsHigh << 8) >>> 0 & 16777215; - let high = bitsHigh >> 16 & 65535; - let digitA = low + mid * 6777216 + high * 6710656; - let digitB = mid + high * 8147497; - let digitC = high * 2; - let base = 1e7; - if (digitA >= base) { - digitB += Math.floor(digitA / base); - digitA %= base; - } - if (digitB >= base) { - digitC += Math.floor(digitB / base); - digitB %= base; - } - function decimalFrom1e7(digit1e7, needLeadingZeros) { - let partial = digit1e7 ? String(digit1e7) : ""; - if (needLeadingZeros) { - return "0000000".slice(partial.length) + partial; + /** + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + */ + enum(type2, json2, fieldName, ignoreUnknownFields) { + if (type2[0] == "google.protobuf.NullValue") + assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); + if (json2 === null) + return 0; + switch (typeof json2) { + case "number": + assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); + return json2; + case "string": + let localEnumName = json2; + if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) + localEnumName = json2.substring(type2[2].length); + let enumNumber = type2[1][localEnumName]; + if (typeof enumNumber === "undefined" && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); + return enumNumber; } - return partial; + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); } - return decimalFrom1e7( - digitC, - /*needLeadingZeros=*/ - 0 - ) + decimalFrom1e7( - digitB, - /*needLeadingZeros=*/ - digitC - ) + // If the final 1e7 digit didn't need leading zeros, we would have - // returned via the trivial code path at the top. - decimalFrom1e7( - digitA, - /*needLeadingZeros=*/ - 1 - ); - } - exports2.int64toString = int64toString; - function varint32write(value, bytes) { - if (value >= 0) { - while (value > 127) { - bytes.push(value & 127 | 128); - value = value >>> 7; - } - bytes.push(value); - } else { - for (let i = 0; i < 9; i++) { - bytes.push(value & 127 | 128); - value = value >> 7; + scalar(json2, type2, longType, fieldName) { + let e; + try { + switch (type2) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json2 === null) + return 0; + if (json2 === "NaN") + return Number.NaN; + if (json2 === "Infinity") + return Number.POSITIVE_INFINITY; + if (json2 === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json2 === "") { + e = "empty string"; + break; + } + if (typeof json2 == "string" && json2.trim().length !== json2.length) { + e = "extra whitespace"; + break; + } + if (typeof json2 != "string" && typeof json2 != "number") { + break; + } + let float2 = Number(json2); + if (Number.isNaN(float2)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float2)) { + e = "too large or small"; + break; + } + if (type2 == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float2); + return float2; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json2 === null) + return 0; + let int32; + if (typeof json2 == "number") + int32 = json2; + else if (json2 === "") + e = "empty string"; + else if (typeof json2 == "string") { + if (json2.trim().length !== json2.length) + e = "extra whitespace"; + else + int32 = Number(json2); + } + if (int32 === void 0) + break; + if (type2 == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json2 === null) + return false; + if (typeof json2 !== "boolean") + break; + return json2; + // string: + case reflection_info_1.ScalarType.STRING: + if (json2 === null) + return ""; + if (typeof json2 !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json2); + } catch (e2) { + e2 = "invalid UTF8"; + break; + } + return json2; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json2 === null || json2 === "") + return new Uint8Array(0); + if (typeof json2 !== "string") + break; + return base64_1.base64decode(json2); + } + } catch (error4) { + e = error4.message; } - bytes.push(1); - } - } - exports2.varint32write = varint32write; - function varint32read() { - let b = this.buf[this.pos++]; - let result = b & 127; - if ((b & 128) == 0) { - this.assertBounds(); - return result; - } - b = this.buf[this.pos++]; - result |= (b & 127) << 7; - if ((b & 128) == 0) { - this.assertBounds(); - return result; - } - b = this.buf[this.pos++]; - result |= (b & 127) << 14; - if ((b & 128) == 0) { - this.assertBounds(); - return result; - } - b = this.buf[this.pos++]; - result |= (b & 127) << 21; - if ((b & 128) == 0) { - this.assertBounds(); - return result; + this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - b = this.buf[this.pos++]; - result |= (b & 15) << 28; - for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++) - b = this.buf[this.pos++]; - if ((b & 128) != 0) - throw new Error("invalid varint"); - this.assertBounds(); - return result >>> 0; - } - exports2.varint32read = varint32read; + }; + exports2.ReflectionJsonReader = ReflectionJsonReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js -var require_pb_long = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js +var require_reflection_json_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PbLong = exports2.PbULong = exports2.detectBi = void 0; - var goog_varint_1 = require_goog_varint(); - var BI; - function detectBi() { - const dv = new DataView(new ArrayBuffer(8)); - const ok = globalThis.BigInt !== void 0 && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function"; - BI = ok ? { - MIN: BigInt("-9223372036854775808"), - MAX: BigInt("9223372036854775807"), - UMIN: BigInt("0"), - UMAX: BigInt("18446744073709551615"), - C: BigInt, - V: dv - } : void 0; - } - exports2.detectBi = detectBi; - detectBi(); - function assertBi(bi) { - if (!bi) - throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); - } - var RE_DECIMAL_STR = /^-?[0-9]+$/; - var TWO_PWR_32_DBL = 4294967296; - var HALF_2_PWR_32 = 2147483648; - var SharedPbLong = class { - /** - * Create a new instance with the given bits. - */ - constructor(lo, hi) { - this.lo = lo | 0; - this.hi = hi | 0; - } - /** - * Is this instance equal to 0? - */ - isZero() { - return this.lo == 0 && this.hi == 0; + exports2.ReflectionJsonWriter = void 0; + var base64_1 = require_base642(); + var pb_long_1 = require_pb_long(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); + var ReflectionJsonWriter = class { + constructor(info7) { + var _a; + this.fields = (_a = info7.fields) !== null && _a !== void 0 ? _a : []; } /** - * Convert to a native number. + * Converts the message to a JSON object, based on the field descriptors. */ - toNumber() { - let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); - if (!Number.isSafeInteger(result)) - throw new Error("cannot convert to safe number"); - return result; + write(message, options) { + const json2 = {}, source = message; + for (const field of this.fields) { + if (!field.oneof) { + let jsonValue2 = this.field(field, source[field.localName], options); + if (jsonValue2 !== void 0) + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; + continue; + } + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; + const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== void 0); + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + } + return json2; } - }; - var PbULong = class _PbULong extends SharedPbLong { - /** - * Create instance from a `string`, `number` or `bigint`. - */ - static from(value) { - if (BI) - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - if (value == "") - throw new Error("string is no integer"); - value = BI.C(value); - case "number": - if (value === 0) - return this.ZERO; - value = BI.C(value); - case "bigint": - if (!value) - return this.ZERO; - if (value < BI.UMIN) - throw new Error("signed value for ulong"); - if (value > BI.UMAX) - throw new Error("ulong too large"); - BI.V.setBigUint64(0, value, true); - return new _PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + field(field, value, options) { + let jsonValue = void 0; + if (field.kind == "map") { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); + const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; } - else - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - value = value.trim(); - if (!RE_DECIMAL_STR.test(value)) - throw new Error("string is no integer"); - let [minus, lo, hi] = goog_varint_1.int64fromString(value); - if (minus) - throw new Error("signed value for ulong"); - return new _PbULong(lo, hi); - case "number": - if (value == 0) - return this.ZERO; - if (!Number.isSafeInteger(value)) - throw new Error("number is no integer"); - if (value < 0) - throw new Error("signed value for ulong"); - return new _PbULong(value, value / TWO_PWR_32_DBL); + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); + const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val2 = this.message(messageType, value[i], field.name, options); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; } - throw new Error("unknown value " + typeof value); + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } + } + return jsonValue; } /** - * Convert to decimal string. + * Returns `null` as the default for google.protobuf.NullValue. */ - toString() { - return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); + enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type2[0] == "google.protobuf.NullValue") + return !emitDefaultValues && !optional ? void 0 : null; + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + if (value === 0 && !emitDefaultValues && !optional) + return void 0; + assert_1.assert(typeof value == "number"); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type2[1].hasOwnProperty(value)) + return value; + if (type2[2]) + return type2[2] + type2[1][value]; + return type2[1][value]; } - /** - * Convert to native bigint. - */ - toBigInt() { - assertBi(BI); - BI.V.setInt32(0, this.lo, true); - BI.V.setInt32(4, this.hi, true); - return BI.V.getBigUint64(0, true); + message(type2, value, fieldName, options) { + if (value === void 0) + return options.emitDefaultValues ? null : void 0; + return type2.internalJsonWrite(value, options); + } + scalar(type2, value, fieldName, optional, emitDefaultValues) { + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + const ed = emitDefaultValues || optional; + switch (type2) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assert(typeof value == "number"); + if (Number.isNaN(value)) + return "NaN"; + if (value === Number.POSITIVE_INFINITY) + return "Infinity"; + if (value === Number.NEGATIVE_INFINITY) + return "-Infinity"; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? "" : void 0; + assert_1.assert(typeof value == "string"); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : void 0; + assert_1.assert(typeof value == "boolean"); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return void 0; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return void 0; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : void 0; + return base64_1.base64encode(value); + } } }; - exports2.PbULong = PbULong; - PbULong.ZERO = new PbULong(0, 0); - var PbLong = class _PbLong extends SharedPbLong { + exports2.ReflectionJsonWriter = ReflectionJsonWriter; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js +var require_reflection_scalar_default = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionScalarDefault = void 0; + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var pb_long_1 = require_pb_long(); + function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { + switch (type2) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + return 0; + } + } + exports2.reflectionScalarDefault = reflectionScalarDefault; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js +var require_reflection_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionBinaryReader = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var ReflectionBinaryReader = class { + constructor(info7) { + this.info = info7; + } + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + } + } /** - * Create instance from a `string`, `number` or `bigint`. + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. */ - static from(value) { - if (BI) - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - if (value == "") - throw new Error("string is no integer"); - value = BI.C(value); - case "number": - if (value === 0) - return this.ZERO; - value = BI.C(value); - case "bigint": - if (!value) - return this.ZERO; - if (value < BI.MIN) - throw new Error("signed long too small"); - if (value > BI.MAX) - throw new Error("signed long too large"); - BI.V.setBigInt64(0, value, true); - return new _PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + read(reader, message, options, length) { + this.prepare(); + const end = length === void 0 ? reader.len : reader.pos + length; + while (reader.pos < end) { + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; } - else - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - value = value.trim(); - if (!RE_DECIMAL_STR.test(value)) - throw new Error("string is no integer"); - let [minus, lo, hi] = goog_varint_1.int64fromString(value); - if (minus) { - if (hi > HALF_2_PWR_32 || hi == HALF_2_PWR_32 && lo != 0) - throw new Error("signed long too small"); - } else if (hi >= HALF_2_PWR_32) - throw new Error("signed long too large"); - let pbl = new _PbLong(lo, hi); - return minus ? pbl.negate() : pbl; - case "number": - if (value == 0) - return this.ZERO; - if (!Number.isSafeInteger(value)) - throw new Error("number is no integer"); - return value > 0 ? new _PbLong(value, value / TWO_PWR_32_DBL) : new _PbLong(-value, -value / TWO_PWR_32_DBL).negate(); + let target = message, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + target = target[field.oneof]; + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : void 0; + if (repeated) { + let arr = target[localName]; + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } else + arr.push(this.scalar(reader, T, L)); + } else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + target[localName][mapKey] = mapVal; + break; } - throw new Error("unknown value " + typeof value); - } - /** - * Do we have a minus sign? - */ - isNegative() { - return (this.hi & HALF_2_PWR_32) !== 0; - } - /** - * Negate two's complement. - * Invert all the bits and add one to the result. - */ - negate() { - let hi = ~this.hi, lo = this.lo; - if (lo) - lo = ~lo + 1; - else - hi += 1; - return new _PbLong(lo, hi); + } } /** - * Convert to decimal string. + * Read a map field, expecting key field = 1, value field = 2 */ - toString() { - if (BI) - return this.toBigInt().toString(); - if (this.isNegative()) { - let n = this.negate(); - return "-" + goog_varint_1.int64toString(n.lo, n.hi); + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = void 0; + let val2 = void 0; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val2 = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val2 = reader.int32(); + break; + case "message": + val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } } - return goog_varint_1.int64toString(this.lo, this.hi); + if (key === void 0) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val2 === void 0) + switch (field.V.kind) { + case "scalar": + val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val2 = 0; + break; + case "message": + val2 = field.V.T().create(); + break; + } + return [key, val2]; } - /** - * Convert to native bigint. - */ - toBigInt() { - assertBi(BI); - BI.V.setInt32(0, this.lo, true); - BI.V.setInt32(4, this.hi, true); - return BI.V.getBigInt64(0, true); + scalar(reader, type2, longType) { + switch (type2) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } } }; - exports2.PbLong = PbLong; - PbLong.ZERO = new PbLong(0, 0); + exports2.ReflectionBinaryReader = ReflectionBinaryReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js -var require_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js +var require_reflection_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryReader = exports2.binaryReadOptions = void 0; + exports2.ReflectionBinaryWriter = void 0; var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); - var defaultsRead = { - readUnknownField: true, - readerFactory: (bytes) => new BinaryReader(bytes) - }; - function binaryReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.binaryReadOptions = binaryReadOptions; - var BinaryReader = class { - constructor(buf, textDecoder) { - this.varint64 = goog_varint_1.varint64read; - this.uint32 = goog_varint_1.varint32read; - this.buf = buf; - this.len = buf.length; - this.pos = 0; - this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); - this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { - fatal: true, - ignoreBOM: true - }); + var ReflectionBinaryWriter = class { + constructor(info7) { + this.info = info7; } - /** - * Reads a tag - field number and wire type. - */ - tag() { - let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; - if (fieldNo <= 0 || wireType < 0 || wireType > 5) - throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); - return [fieldNo, wireType]; + prepare() { + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); + } } /** - * Skip one element on the wire and return the skipped data. - * Supports WireType.StartGroup since v2.0.0-alpha.23. + * Writes the message to binary format. */ - skip(wireType) { - let start = this.pos; - switch (wireType) { - case binary_format_contract_1.WireType.Varint: - while (this.buf[this.pos++] & 128) { - } + write(message, writer, options) { + this.prepare(); + for (const field of this.fields) { + let value, emitDefault, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; + value = group[localName]; + emitDefault = true; + } else { + value = message[localName]; + emitDefault = false; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } else if (value === void 0) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == "object" && value !== null); + for (const [key, val2] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val2); + break; + } + } + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); + } + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); break; - case binary_format_contract_1.WireType.Bit64: - this.pos += 4; - case binary_format_contract_1.WireType.Bit32: - this.pos += 4; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == "true" || key == "false"); + keyValue = key == "true"; break; - case binary_format_contract_1.WireType.LengthDelimited: - let len = this.uint32(); - this.pos += len; + } + this.scalar(writer, field.K, 1, keyValue, true); + switch (field.V.kind) { + case "scalar": + this.scalar(writer, field.V.T, 2, value, true); break; - case binary_format_contract_1.WireType.StartGroup: - let t; - while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { - this.skip(t); - } + case "enum": + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; + case "message": + this.message(writer, options, field.V.T(), 2, value); break; - default: - throw new Error("cant skip wire type " + wireType); } - this.assertBounds(); - return this.buf.subarray(start, this.pos); - } - /** - * Throws error if position in byte array is out of range. - */ - assertBounds() { - if (this.pos > this.len) - throw new RangeError("premature EOF"); - } - /** - * Read a `int32` field, a signed 32 bit varint. - */ - int32() { - return this.uint32() | 0; - } - /** - * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. - */ - sint32() { - let zze = this.uint32(); - return zze >>> 1 ^ -(zze & 1); - } - /** - * Read a `int64` field, a signed 64-bit varint. - */ - int64() { - return new pb_long_1.PbLong(...this.varint64()); - } - /** - * Read a `uint64` field, an unsigned 64-bit varint. - */ - uint64() { - return new pb_long_1.PbULong(...this.varint64()); - } - /** - * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. - */ - sint64() { - let [lo, hi] = this.varint64(); - let s = -(lo & 1); - lo = (lo >>> 1 | (hi & 1) << 31) ^ s; - hi = hi >>> 1 ^ s; - return new pb_long_1.PbLong(lo, hi); - } - /** - * Read a `bool` field, a variant. - */ - bool() { - let [lo, hi] = this.varint64(); - return lo !== 0 || hi !== 0; - } - /** - * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. - */ - fixed32() { - return this.view.getUint32((this.pos += 4) - 4, true); - } - /** - * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. - */ - sfixed32() { - return this.view.getInt32((this.pos += 4) - 4, true); - } - /** - * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. - */ - fixed64() { - return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); - } - /** - * Read a `fixed64` field, a signed, fixed-length 64-bit integer. - */ - sfixed64() { - return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); + writer.join(); } - /** - * Read a `float` field, 32-bit floating point number. - */ - float() { - return this.view.getFloat32((this.pos += 4) - 4, true); + message(writer, options, handler, fieldNo, value) { + if (value === void 0) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); } /** - * Read a `double` field, a 64-bit floating point number. + * Write a single scalar value. */ - double() { - return this.view.getFloat64((this.pos += 8) - 8, true); + scalar(writer, type2, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type2, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); + } } /** - * Read a `bytes` field, length-delimited arbitrary data. + * Write an array of scalar values in packed format. */ - bytes() { - let len = this.uint32(); - let start = this.pos; - this.pos += len; - this.assertBounds(); - return this.buf.subarray(start, start + len); + packed(writer, type2, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let [, method] = this.scalarInfo(type2); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + writer.join(); } /** - * Read a `string` field, length-delimited data converted to UTF-8 text. + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. */ - string() { - return this.textDecoder.decode(this.bytes()); + scalarInfo(type2, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === void 0; + let d = value === 0; + switch (type2) { + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; + case reflection_info_1.ScalarType.STRING: + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; + case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; + case reflection_info_1.ScalarType.FLOAT: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; + case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; + case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; + case reflection_info_1.ScalarType.SINT32: + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; + } + return [t, m, i || d]; } }; - exports2.BinaryReader = BinaryReader; + exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js +var require_reflection_create = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionCreate = void 0; + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var message_type_contract_1 = require_message_type_contract(); + function reflectionCreate(type2) { + const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); + for (let field of type2.fields) { + let name = field.localName; + if (field.opt) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: void 0 }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } + } + return msg; + } + exports2.reflectionCreate = reflectionCreate; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js -var require_assert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js +var require_reflection_merge_partial = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; - function assert(condition, msg) { - if (!condition) { - throw new Error(msg); + exports2.reflectionMergePartial = void 0; + function reflectionMergePartial(info7, target, source) { + let fieldValue, input = source, output; + for (let field of info7.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { + continue; + } + fieldValue = group[name]; + output = target[field.oneof]; + output.oneofKind = group.oneofKind; + if (fieldValue == void 0) { + delete output[name]; + continue; + } + } else { + fieldValue = input[name]; + output = target; + if (fieldValue == void 0) { + continue; + } + } + if (field.repeat) + output[name].length = fieldValue.length; + switch (field.kind) { + case "scalar": + case "enum": + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; + else + output[name] = fieldValue; + break; + case "message": + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === void 0) + output[name] = T.create(fieldValue); + else + T.mergePartial(output[name], fieldValue); + break; + case "map": + switch (field.V.kind) { + case "scalar": + case "enum": + Object.assign(output[name], fieldValue); + break; + case "message": + let T2 = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T2.create(fieldValue[k]); + break; + } + break; + } } } - exports2.assert = assert; - function assertNever2(value, msg) { - throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + exports2.reflectionMergePartial = reflectionMergePartial; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js +var require_reflection_equals = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionEquals = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionEquals(info7, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info7.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) + return false; + break; + } + } + return true; } - exports2.assertNever = assertNever2; - var FLOAT32_MAX = 34028234663852886e22; - var FLOAT32_MIN = -34028234663852886e22; - var UINT32_MAX = 4294967295; - var INT32_MAX = 2147483647; - var INT32_MIN = -2147483648; - function assertInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid int 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) - throw new Error("invalid int 32: " + arg); + exports2.reflectionEquals = reflectionEquals; + var objectValues = Object.values; + function primitiveEq(type2, a, b) { + if (a === b) + return true; + if (type2 !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; } - exports2.assertInt32 = assertInt32; - function assertUInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid uint 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) - throw new Error("invalid uint 32: " + arg); + function repeatedPrimitiveEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type2, a[i], b[i])) + return false; + return true; } - exports2.assertUInt32 = assertUInt32; - function assertFloat32(arg) { - if (typeof arg !== "number") - throw new Error("invalid float 32: " + typeof arg); - if (!Number.isFinite(arg)) - return; - if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) - throw new Error("invalid float 32: " + arg); + function repeatedMsgEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type2.equals(a[i], b[i])) + return false; + return true; } - exports2.assertFloat32 = assertFloat32; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js -var require_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js +var require_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; - var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); - var assert_1 = require_assert(); - var defaultsWrite = { - writeUnknownFields: true, - writerFactory: () => new BinaryWriter() - }; - function binaryWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.binaryWriteOptions = binaryWriteOptions; - var BinaryWriter = class { - constructor(textEncoder) { - this.stack = []; - this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); - this.chunks = []; - this.buf = []; + exports2.MessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_type_check_1 = require_reflection_type_check(); + var reflection_json_reader_1 = require_reflection_json_reader(); + var reflection_json_writer_1 = require_reflection_json_writer(); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + var reflection_create_1 = require_reflection_create(); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + var json_typings_1 = require_json_typings(); + var json_format_contract_1 = require_json_format_contract(); + var reflection_equals_1 = require_reflection_equals(); + var binary_writer_1 = require_binary_writer(); + var binary_reader_1 = require_binary_reader(); + var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); + var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; + var MessageType = class { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + messageTypeDescriptor.value = this; + this.messagePrototype = Object.create(null, baseDescriptors); + this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); + this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); + this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } - /** - * Return all bytes written and reset this writer. - */ - finish() { - this.chunks.push(new Uint8Array(this.buf)); - let len = 0; - for (let i = 0; i < this.chunks.length; i++) - len += this.chunks[i].length; - let bytes = new Uint8Array(len); - let offset = 0; - for (let i = 0; i < this.chunks.length; i++) { - bytes.set(this.chunks[i], offset); - offset += this.chunks[i].length; + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== void 0) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); } - this.chunks = []; - return bytes; - } - /** - * Start a new fork for length-delimited data like a message - * or a packed repeated field. - * - * Must be joined later with `join()`. - */ - fork() { - this.stack.push({ chunks: this.chunks, buf: this.buf }); - this.chunks = []; - this.buf = []; - return this; - } - /** - * Join the last fork. Write its length and bytes, then - * return to the previous state. - */ - join() { - let chunk = this.finish(); - let prev = this.stack.pop(); - if (!prev) - throw new Error("invalid state, fork stack empty"); - this.chunks = prev.chunks; - this.buf = prev.buf; - this.uint32(chunk.byteLength); - return this.raw(chunk); + return message; } /** - * Writes a tag (field number and wire type). - * - * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * Clone the message. * - * Generated code should compute the tag ahead of time and call `uint32()`. - */ - tag(fieldNo, type2) { - return this.uint32((fieldNo << 3 | type2) >>> 0); - } - /** - * Write a chunk of raw bytes. - */ - raw(chunk) { - if (this.buf.length) { - this.chunks.push(new Uint8Array(this.buf)); - this.buf = []; - } - this.chunks.push(chunk); - return this; - } - /** - * Write a `uint32` value, an unsigned 32 bit varint. - */ - uint32(value) { - assert_1.assertUInt32(value); - while (value > 127) { - this.buf.push(value & 127 | 128); - value = value >>> 7; - } - this.buf.push(value); - return this; - } - /** - * Write a `int32` value, a signed 32 bit varint. - */ - int32(value) { - assert_1.assertInt32(value); - goog_varint_1.varint32write(value, this.buf); - return this; - } - /** - * Write a `bool` value, a variant. - */ - bool(value) { - this.buf.push(value ? 1 : 0); - return this; - } - /** - * Write a `bytes` value, length-delimited arbitrary data. + * Unknown fields are discarded. */ - bytes(value) { - this.uint32(value.byteLength); - return this.raw(value); + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; } /** - * Write a `string` value, length-delimited data converted to UTF-8 text. + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. */ - string(value) { - let chunk = this.textEncoder.encode(value); - this.uint32(chunk.byteLength); - return this.raw(chunk); + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); } /** - * Write a `float` value, 32-bit floating point number. + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? */ - float(value) { - assert_1.assertFloat32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setFloat32(0, value, true); - return this.raw(chunk); + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); } /** - * Write a `double` value, a 64-bit floating point number. + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? */ - double(value) { - let chunk = new Uint8Array(8); - new DataView(chunk.buffer).setFloat64(0, value, true); - return this.raw(chunk); + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); } /** - * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + * Copy partial data into the target message. */ - fixed32(value) { - assert_1.assertUInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setUint32(0, value, true); - return this.raw(chunk); + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); } /** - * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + * Create a new message from binary format. */ - sfixed32(value) { - assert_1.assertInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setInt32(0, value, true); - return this.raw(chunk); + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); } /** - * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + * Read a new message from a JSON value. */ - sint32(value) { - assert_1.assertInt32(value); - value = (value << 1 ^ value >> 31) >>> 0; - goog_varint_1.varint32write(value, this.buf); - return this; + fromJson(json2, options) { + return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); } /** - * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. */ - sfixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbLong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + fromJsonString(json2, options) { + let value = JSON.parse(json2); + return this.fromJson(value, options); } /** - * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + * Write the message to canonical JSON value. */ - fixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbULong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); } /** - * Write a `int64` value, a signed 64-bit varint. + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` */ - int64(value) { - let long = pb_long_1.PbLong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); } /** - * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + * Write the message to binary format. */ - sint64(value) { - let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; - goog_varint_1.varint64write(lo, hi, this.buf); - return this; + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); } /** - * Write a `uint64` value, an unsigned 64-bit varint. + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. */ - uint64(value) { - let long = pb_long_1.PbULong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; - } - }; - exports2.BinaryWriter = BinaryWriter; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js -var require_json_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; - var defaultsWrite = { - emitDefaultValues: false, - enumAsInteger: false, - useProtoFieldName: false, - prettySpaces: 0 - }; - var defaultsRead = { - ignoreUnknownFields: false - }; - function jsonReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.jsonReadOptions = jsonReadOptions; - function jsonWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.jsonWriteOptions = jsonWriteOptions; - function mergeJsonOptions(a, b) { - var _a, _b; - let c = Object.assign(Object.assign({}, a), b); - c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; - return c; - } - exports2.mergeJsonOptions = mergeJsonOptions; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js -var require_message_type_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MESSAGE_TYPE = void 0; - exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js -var require_lower_camel_case = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.lowerCamelCase = void 0; - function lowerCamelCase(snakeCase) { - let capNext = false; - const sb = []; - for (let i = 0; i < snakeCase.length; i++) { - let next = snakeCase.charAt(i); - if (next == "_") { - capNext = true; - } else if (/\d/.test(next)) { - sb.push(next); - capNext = true; - } else if (capNext) { - sb.push(next.toUpperCase()); - capNext = false; - } else if (i == 0) { - sb.push(next.toLowerCase()); - } else { - sb.push(next); + internalJsonRead(json2, options, target) { + if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json2, message, options); + return message; } + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); } - return sb.join(""); - } - exports2.lowerCamelCase = lowerCamelCase; + /** + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). + * + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); + } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. + * + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. + */ + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; + } + /** + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. + * + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. + */ + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; + } + }; + exports2.MessageType = MessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js -var require_reflection_info = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js +var require_reflection_contains_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; - var lower_camel_case_1 = require_lower_camel_case(); - var ScalarType; - (function(ScalarType2) { - ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; - ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; - ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; - ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; - ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; - ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; - ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; - ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; - ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; - ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; - ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; - ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; - ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; - ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; - ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; - })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); - var LongType; - (function(LongType2) { - LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; - LongType2[LongType2["STRING"] = 1] = "STRING"; - LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; - })(LongType = exports2.LongType || (exports2.LongType = {})); - var RepeatType; - (function(RepeatType2) { - RepeatType2[RepeatType2["NO"] = 0] = "NO"; - RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; - RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; - })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); - function normalizeFieldInfo(field) { - var _a, _b, _c, _d; - field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); - field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); - field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; - field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; - return field; - } - exports2.normalizeFieldInfo = normalizeFieldInfo; - function readFieldOptions(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readFieldOptions = readFieldOptions; - function readFieldOption(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readFieldOption = readFieldOption; - function readMessageOption(messageType, extensionName, extensionType) { - const options = messageType.options; - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; + exports2.containsMessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; } - exports2.readMessageOption = readMessageOption; + exports2.containsMessageType = containsMessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js -var require_oneof = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js +var require_enum_object = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; - function isOneofGroup(any) { - if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; + function isEnumObject(arg) { + if (typeof arg != "object" || arg === null) { return false; } - switch (typeof any.oneofKind) { - case "string": - if (any[any.oneofKind] === void 0) - return false; - return Object.keys(any).length == 2; - case "undefined": - return Object.keys(any).length == 1; - default: - return false; - } - } - exports2.isOneofGroup = isOneofGroup; - function getOneofValue(oneof, kind) { - return oneof[kind]; - } - exports2.getOneofValue = getOneofValue; - function setOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + if (!arg.hasOwnProperty(0)) { + return false; } - oneof.oneofKind = kind; - if (value !== void 0) { - oneof[kind] = value; + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + let nam = arg[num]; + if (nam === void 0) + return false; + if (arg[nam] !== num) + return false; + } else { + let num2 = arg[k]; + if (num2 === void 0) + return false; + if (typeof num2 !== "number") + return false; + if (arg[num2] === void 0) + return false; + } } + return true; } - exports2.setOneofValue = setOneofValue; - function setUnknownOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== void 0 && kind !== void 0) { - oneof[kind] = value; - } + exports2.isEnumObject = isEnumObject; + function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; } - exports2.setUnknownOneofValue = setUnknownOneofValue; - function clearOneofValue(oneof) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = void 0; + exports2.listEnumValues = listEnumValues; + function listEnumNames(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.name); } - exports2.clearOneofValue = clearOneofValue; - function getSelectedOneofValue(oneof) { - if (oneof.oneofKind === void 0) { - return void 0; - } - return oneof[oneof.oneofKind]; + exports2.listEnumNames = listEnumNames; + function listEnumNumbers(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); } - exports2.getSelectedOneofValue = getSelectedOneofValue; + exports2.listEnumNumbers = listEnumNumbers; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js -var require_reflection_type_check = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionTypeCheck = void 0; + var json_typings_1 = require_json_typings(); + Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { + return json_typings_1.typeofJsonValue; + } }); + Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { + return json_typings_1.isJsonObject; + } }); + var base64_1 = require_base642(); + Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { + return base64_1.base64decode; + } }); + Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { + return base64_1.base64encode; + } }); + var protobufjs_utf8_1 = require_protobufjs_utf8(); + Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { + return protobufjs_utf8_1.utf8read; + } }); + var binary_format_contract_1 = require_binary_format_contract(); + Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { + return binary_format_contract_1.WireType; + } }); + Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { + return binary_format_contract_1.mergeBinaryOptions; + } }); + Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { + return binary_format_contract_1.UnknownFieldHandler; + } }); + var binary_reader_1 = require_binary_reader(); + Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { + return binary_reader_1.BinaryReader; + } }); + Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { + return binary_reader_1.binaryReadOptions; + } }); + var binary_writer_1 = require_binary_writer(); + Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { + return binary_writer_1.BinaryWriter; + } }); + Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { + return binary_writer_1.binaryWriteOptions; + } }); + var pb_long_1 = require_pb_long(); + Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { + return pb_long_1.PbLong; + } }); + Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { + return pb_long_1.PbULong; + } }); + var json_format_contract_1 = require_json_format_contract(); + Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonReadOptions; + } }); + Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonWriteOptions; + } }); + Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { + return json_format_contract_1.mergeJsonOptions; + } }); + var message_type_contract_1 = require_message_type_contract(); + Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { + return message_type_contract_1.MESSAGE_TYPE; + } }); + var message_type_1 = require_message_type(); + Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { + return message_type_1.MessageType; + } }); var reflection_info_1 = require_reflection_info(); + Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { + return reflection_info_1.ScalarType; + } }); + Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { + return reflection_info_1.LongType; + } }); + Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { + return reflection_info_1.RepeatType; + } }); + Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { + return reflection_info_1.normalizeFieldInfo; + } }); + Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { + return reflection_info_1.readFieldOptions; + } }); + Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { + return reflection_info_1.readFieldOption; + } }); + Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { + return reflection_info_1.readMessageOption; + } }); + var reflection_type_check_1 = require_reflection_type_check(); + Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { + return reflection_type_check_1.ReflectionTypeCheck; + } }); + var reflection_create_1 = require_reflection_create(); + Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { + return reflection_create_1.reflectionCreate; + } }); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { + return reflection_scalar_default_1.reflectionScalarDefault; + } }); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { + return reflection_merge_partial_1.reflectionMergePartial; + } }); + var reflection_equals_1 = require_reflection_equals(); + Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { + return reflection_equals_1.reflectionEquals; + } }); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { + return reflection_binary_reader_1.ReflectionBinaryReader; + } }); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { + return reflection_binary_writer_1.ReflectionBinaryWriter; + } }); + var reflection_json_reader_1 = require_reflection_json_reader(); + Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { + return reflection_json_reader_1.ReflectionJsonReader; + } }); + var reflection_json_writer_1 = require_reflection_json_writer(); + Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { + return reflection_json_writer_1.ReflectionJsonWriter; + } }); + var reflection_contains_message_type_1 = require_reflection_contains_message_type(); + Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { + return reflection_contains_message_type_1.containsMessageType; + } }); var oneof_1 = require_oneof(); - var ReflectionTypeCheck = class { - constructor(info7) { - var _a; - this.fields = (_a = info7.fields) !== null && _a !== void 0 ? _a : []; - } - prepare() { - if (this.data) - return; - const req = [], known = [], oneofs = []; - for (let field of this.fields) { - if (field.oneof) { - if (!oneofs.includes(field.oneof)) { - oneofs.push(field.oneof); - req.push(field.oneof); - known.push(field.oneof); - } - } else { - known.push(field.localName); - switch (field.kind) { - case "scalar": - case "enum": - if (!field.opt || field.repeat) - req.push(field.localName); - break; - case "message": - if (field.repeat) - req.push(field.localName); - break; - case "map": - req.push(field.localName); - break; - } - } - } - this.data = { req, known, oneofs: Object.values(oneofs) }; - } - /** - * Is the argument a valid message as specified by the - * reflection information? - * - * Checks all field types recursively. The `depth` - * specifies how deep into the structure the check will be. - * - * With a depth of 0, only the presence of fields - * is checked. - * - * With a depth of 1 or more, the field types are checked. - * - * With a depth of 2 or more, the members of map, repeated - * and message fields are checked. - * - * Message fields will be checked recursively with depth - 1. - * - * The number of map entries / repeated values being checked - * is < depth. - */ - is(message, depth, allowExcessProperties = false) { - if (depth < 0) - return true; - if (message === null || message === void 0 || typeof message != "object") - return false; - this.prepare(); - let keys = Object.keys(message), data = this.data; - if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) - return false; - if (!allowExcessProperties) { - if (keys.some((k) => !data.known.includes(k))) - return false; - } - if (depth < 1) { - return true; - } - for (const name of data.oneofs) { - const group = message[name]; - if (!oneof_1.isOneofGroup(group)) - return false; - if (group.oneofKind === void 0) - continue; - const field = this.fields.find((f) => f.localName === group.oneofKind); - if (!field) - return false; - if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) - return false; - } - for (const field of this.fields) { - if (field.oneof !== void 0) - continue; - if (!this.field(message[field.localName], field, allowExcessProperties, depth)) - return false; - } - return true; - } - field(arg, field, allowExcessProperties, depth) { - let repeated = field.repeat; - switch (field.kind) { - case "scalar": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, field.T, depth, field.L); - return this.scalar(arg, field.T, field.L); - case "enum": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); - return this.scalar(arg, reflection_info_1.ScalarType.INT32); - case "message": - if (arg === void 0) - return true; - if (repeated) - return this.messages(arg, field.T(), allowExcessProperties, depth); - return this.message(arg, field.T(), allowExcessProperties, depth); - case "map": - if (typeof arg != "object" || arg === null) - return false; - if (depth < 2) - return true; - if (!this.mapKeys(arg, field.K, depth)) - return false; - switch (field.V.kind) { - case "scalar": - return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); - case "enum": - return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); - case "message": - return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); - } - break; - } - return true; - } - message(arg, type2, allowExcessProperties, depth) { - if (allowExcessProperties) { - return type2.isAssignable(arg, depth); - } - return type2.is(arg, depth); - } - messages(arg, type2, allowExcessProperties, depth) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (allowExcessProperties) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.isAssignable(arg[i], depth - 1)) - return false; - } else { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.is(arg[i], depth - 1)) - return false; - } - return true; + Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { + return oneof_1.isOneofGroup; + } }); + Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { + return oneof_1.setOneofValue; + } }); + Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { + return oneof_1.getOneofValue; + } }); + Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { + return oneof_1.clearOneofValue; + } }); + Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { + return oneof_1.getSelectedOneofValue; + } }); + var enum_object_1 = require_enum_object(); + Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { + return enum_object_1.listEnumValues; + } }); + Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { + return enum_object_1.listEnumNames; + } }); + Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { + return enum_object_1.listEnumNumbers; + } }); + Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { + return enum_object_1.isEnumObject; + } }); + var lower_camel_case_1 = require_lower_camel_case(); + Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { + return lower_camel_case_1.lowerCamelCase; + } }); + var assert_1 = require_assert(); + Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { + return assert_1.assert; + } }); + Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { + return assert_1.assertNever; + } }); + Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { + return assert_1.assertInt32; + } }); + Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { + return assert_1.assertUInt32; + } }); + Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { + return assert_1.assertFloat32; + } }); + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js +var require_reflection_info2 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + var runtime_1 = require_commonjs11(); + function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + m.serverStreaming = !!m.serverStreaming; + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; + return m; + } + exports2.normalizeMethodInfo = normalizeMethodInfo; + function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readMethodOptions = readMethodOptions; + function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; } - scalar(arg, type2, longType) { - let argType = typeof arg; - switch (type2) { - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - switch (longType) { - case reflection_info_1.LongType.BIGINT: - return argType == "bigint"; - case reflection_info_1.LongType.NUMBER: - return argType == "number" && !isNaN(arg); - default: - return argType == "string"; - } - case reflection_info_1.ScalarType.BOOL: - return argType == "boolean"; - case reflection_info_1.ScalarType.STRING: - return argType == "string"; - case reflection_info_1.ScalarType.BYTES: - return arg instanceof Uint8Array; - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return argType == "number" && !isNaN(arg); - default: - return argType == "number" && Number.isInteger(arg); - } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - scalars(arg, type2, depth, longType) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (Array.isArray(arg)) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!this.scalar(arg[i], type2, longType)) - return false; - } - return true; + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMethodOption = readMethodOption; + function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return void 0; } - mapKeys(map2, type2, depth) { - let keys = Object.keys(map2); - switch (type2) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); - case reflection_info_1.ScalarType.BOOL: - return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); - default: - return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); - } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - }; - exports2.ReflectionTypeCheck = ReflectionTypeCheck; + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readServiceOption = readServiceOption; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js -var require_reflection_long_convert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js +var require_service_type = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionLongConvert = void 0; - var reflection_info_1 = require_reflection_info(); - function reflectionLongConvert(long, type2) { - switch (type2) { - case reflection_info_1.LongType.BIGINT: - return long.toBigInt(); - case reflection_info_1.LongType.NUMBER: - return long.toNumber(); - default: - return long.toString(); + exports2.ServiceType = void 0; + var reflection_info_1 = require_reflection_info2(); + var ServiceType = class { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; } - } - exports2.reflectionLongConvert = reflectionLongConvert; + }; + exports2.ServiceType = ServiceType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js -var require_reflection_json_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js +var require_rpc_error = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonReader = void 0; - var json_typings_1 = require_json_typings(); - var base64_1 = require_base642(); - var reflection_info_1 = require_reflection_info(); - var pb_long_1 = require_pb_long(); - var assert_1 = require_assert(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var ReflectionJsonReader = class { - constructor(info7) { - this.info = info7; + exports2.RpcError = void 0; + var RpcError = class extends Error { + constructor(message, code = "UNKNOWN", meta) { + super(message); + this.name = "RpcError"; + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; } - prepare() { - var _a; - if (this.fMap === void 0) { - this.fMap = {}; - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - for (const field of fieldsInput) { - this.fMap[field.name] = field; - this.fMap[field.jsonName] = field; - this.fMap[field.localName] = field; - } + toString() { + const l = [this.name + ": " + this.message]; + if (this.code) { + l.push(""); + l.push("Code: " + this.code); } - } - // Cannot parse JSON for #. - assert(condition, fieldName, jsonValue) { - if (!condition) { - let what = json_typings_1.typeofJsonValue(jsonValue); - if (what == "number" || what == "boolean") - what = jsonValue.toString(); - throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + if (this.serviceName && this.methodName) { + l.push("Method: " + this.serviceName + "/" + this.methodName); } - } - /** - * Reads a message from canonical JSON format into the target message. - * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. - * - * If a message field is already present, it will be merged with the - * new data. - */ - read(input, message, options) { - this.prepare(); - const oneofsHandled = []; - for (const [jsonKey, jsonValue] of Object.entries(input)) { - const field = this.fMap[jsonKey]; - if (!field) { - if (!options.ignoreUnknownFields) - throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); - continue; - } - const localName = field.localName; - let target; - if (field.oneof) { - if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { - continue; - } - if (oneofsHandled.includes(field.oneof)) - throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); - oneofsHandled.push(field.oneof); - target = message[field.oneof] = { - oneofKind: localName - }; - } else { - target = message; - } - if (field.kind == "map") { - if (jsonValue === null) { - continue; - } - this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); - const fieldObj = target[localName]; - for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { - this.assert(jsonObjValue !== null, field.name + " map value", null); - let val2; - switch (field.V.kind) { - case "message": - val2 = field.V.T().internalJsonRead(jsonObjValue, options); - break; - case "enum": - val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); - let key = jsonObjKey; - if (field.K == reflection_info_1.ScalarType.BOOL) - key = key == "true" ? true : key == "false" ? false : key; - key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); - fieldObj[key] = val2; - } - } else if (field.repeat) { - if (jsonValue === null) - continue; - this.assert(Array.isArray(jsonValue), field.name, jsonValue); - const fieldArr = target[localName]; - for (const jsonItem of jsonValue) { - this.assert(jsonItem !== null, field.name, null); - let val2; - switch (field.kind) { - case "message": - val2 = field.T().internalJsonRead(jsonItem, options); - break; - case "enum": - val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonItem, field.T, field.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name, jsonValue); - fieldArr.push(val2); - } - } else { - switch (field.kind) { - case "message": - if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { - this.assert(field.oneof === void 0, field.name + " (oneof member)", null); - continue; - } - target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); - break; - case "enum": - if (jsonValue === null) - continue; - let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - target[localName] = val2; - break; - case "scalar": - if (jsonValue === null) - continue; - target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); - break; - } + let m = Object.entries(this.meta); + if (m.length) { + l.push(""); + l.push("Meta:"); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); } } + return l.join("\n"); } - /** - * Returns `false` for unrecognized string representations. - * - * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). - */ - enum(type2, json2, fieldName, ignoreUnknownFields) { - if (type2[0] == "google.protobuf.NullValue") - assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); - if (json2 === null) - return 0; - switch (typeof json2) { - case "number": - assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); - return json2; - case "string": - let localEnumName = json2; - if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) - localEnumName = json2.substring(type2[2].length); - let enumNumber = type2[1][localEnumName]; - if (typeof enumNumber === "undefined" && ignoreUnknownFields) { - return false; - } - assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); - return enumNumber; + }; + exports2.RpcError = RpcError; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js +var require_rpc_options = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.mergeRpcOptions = void 0; + var runtime_1 = require_commonjs11(); + function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val2 = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); + break; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); + break; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); + break; } - assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); } - scalar(json2, type2, longType, fieldName) { - let e; - try { - switch (type2) { - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - if (json2 === null) - return 0; - if (json2 === "NaN") - return Number.NaN; - if (json2 === "Infinity") - return Number.POSITIVE_INFINITY; - if (json2 === "-Infinity") - return Number.NEGATIVE_INFINITY; - if (json2 === "") { - e = "empty string"; - break; - } - if (typeof json2 == "string" && json2.trim().length !== json2.length) { - e = "extra whitespace"; - break; - } - if (typeof json2 != "string" && typeof json2 != "number") { - break; - } - let float2 = Number(json2); - if (Number.isNaN(float2)) { - e = "not a number"; - break; - } - if (!Number.isFinite(float2)) { - e = "too large or small"; - break; - } - if (type2 == reflection_info_1.ScalarType.FLOAT) - assert_1.assertFloat32(float2); - return float2; - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - if (json2 === null) - return 0; - let int32; - if (typeof json2 == "number") - int32 = json2; - else if (json2 === "") - e = "empty string"; - else if (typeof json2 == "string") { - if (json2.trim().length !== json2.length) - e = "extra whitespace"; - else - int32 = Number(json2); - } - if (int32 === void 0) - break; - if (type2 == reflection_info_1.ScalarType.UINT32) - assert_1.assertUInt32(int32); - else - assert_1.assertInt32(int32); - return int32; - // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.UINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); - // bool: - case reflection_info_1.ScalarType.BOOL: - if (json2 === null) - return false; - if (typeof json2 !== "boolean") - break; - return json2; - // string: - case reflection_info_1.ScalarType.STRING: - if (json2 === null) - return ""; - if (typeof json2 !== "string") { - e = "extra whitespace"; - break; - } - try { - encodeURIComponent(json2); - } catch (e2) { - e2 = "invalid UTF8"; - break; - } - return json2; - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - if (json2 === null || json2 === "") - return new Uint8Array(0); - if (typeof json2 !== "string") - break; - return base64_1.base64decode(json2); - } - } catch (error4) { - e = error4.message; - } - this.assert(false, fieldName + (e ? " - " + e : ""), json2); + return o; + } + exports2.mergeRpcOptions = mergeRpcOptions; + function copy(a, into) { + if (!a) + return; + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; } - }; - exports2.ReflectionJsonReader = ReflectionJsonReader; + } } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js -var require_reflection_json_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js +var require_deferred = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonWriter = void 0; - var base64_1 = require_base642(); - var pb_long_1 = require_pb_long(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var ReflectionJsonWriter = class { - constructor(info7) { - var _a; - this.fields = (_a = info7.fields) !== null && _a !== void 0 ? _a : []; - } + exports2.Deferred = exports2.DeferredState = void 0; + var DeferredState; + (function(DeferredState2) { + DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; + DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; + DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; + })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); + var Deferred = class { /** - * Converts the message to a JSON object, based on the field descriptors. + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. */ - write(message, options) { - const json2 = {}, source = message; - for (const field of this.fields) { - if (!field.oneof) { - let jsonValue2 = this.field(field, source[field.localName], options); - if (jsonValue2 !== void 0) - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; - continue; - } - const group = source[field.oneof]; - if (group.oneofKind !== field.localName) - continue; - const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; - let jsonValue = this.field(field, group[field.localName], opt); - assert_1.assert(jsonValue !== void 0); - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve5, reject) => { + this._resolve = resolve5; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch((_2) => { + }); } - return json2; } - field(field, value, options) { - let jsonValue = void 0; - if (field.kind == "map") { - assert_1.assert(typeof value == "object" && value !== null); - const jsonObj = {}; - switch (field.V.kind) { - case "scalar": - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "message": - const messageType = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.message(messageType, entryValue, field.name, options); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "enum": - const enumInfo = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); - const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - } - if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) - jsonValue = jsonObj; - } else if (field.repeat) { - assert_1.assert(Array.isArray(value)); - const jsonArr = []; - switch (field.kind) { - case "scalar": - for (let i = 0; i < value.length; i++) { - const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "enum": - const enumInfo = field.T(); - for (let i = 0; i < value.length; i++) { - assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); - const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "message": - const messageType = field.T(); - for (let i = 0; i < value.length; i++) { - const val2 = this.message(messageType, value[i], field.name, options); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - } - if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) - jsonValue = jsonArr; - } else { - switch (field.kind) { - case "scalar": - jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); - break; - case "enum": - jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); - break; - case "message": - jsonValue = this.message(field.T(), value, field.name, options); - break; - } - } - return jsonValue; + /** + * Get the current state of the promise. + */ + get state() { + return this._state; } /** - * Returns `null` as the default for google.protobuf.NullValue. + * Get the deferred promise. */ - enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { - if (type2[0] == "google.protobuf.NullValue") - return !emitDefaultValues && !optional ? void 0 : null; - if (value === void 0) { - assert_1.assert(optional); - return void 0; - } - if (value === 0 && !emitDefaultValues && !optional) - return void 0; - assert_1.assert(typeof value == "number"); - assert_1.assert(Number.isInteger(value)); - if (enumAsInteger || !type2[1].hasOwnProperty(value)) - return value; - if (type2[2]) - return type2[2] + type2[1][value]; - return type2[1][value]; + get promise() { + return this._promise; } - message(type2, value, fieldName, options) { - if (value === void 0) - return options.emitDefaultValues ? null : void 0; - return type2.internalJsonWrite(value, options); + /** + * Resolve the promise. Throws if the promise is already resolved or rejected. + */ + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; } - scalar(type2, value, fieldName, optional, emitDefaultValues) { - if (value === void 0) { - assert_1.assert(optional); - return void 0; - } - const ed = emitDefaultValues || optional; - switch (type2) { - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertInt32(value); - return value; - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertUInt32(value); - return value; - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.FLOAT: - assert_1.assertFloat32(value); - case reflection_info_1.ScalarType.DOUBLE: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assert(typeof value == "number"); - if (Number.isNaN(value)) - return "NaN"; - if (value === Number.POSITIVE_INFINITY) - return "Infinity"; - if (value === Number.NEGATIVE_INFINITY) - return "-Infinity"; - return value; - // string: - case reflection_info_1.ScalarType.STRING: - if (value === "") - return ed ? "" : void 0; - assert_1.assert(typeof value == "string"); - return value; - // bool: - case reflection_info_1.ScalarType.BOOL: - if (value === false) - return ed ? false : void 0; - assert_1.assert(typeof value == "boolean"); - return value; - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let ulong = pb_long_1.PbULong.from(value); - if (ulong.isZero() && !ed) - return void 0; - return ulong.toString(); - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let long = pb_long_1.PbLong.from(value); - if (long.isZero() && !ed) - return void 0; - return long.toString(); - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - assert_1.assert(value instanceof Uint8Array); - if (!value.byteLength) - return ed ? "" : void 0; - return base64_1.base64encode(value); - } + /** + * Reject the promise. Throws if the promise is already resolved or rejected. + */ + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; + } + /** + * Resolve the promise. Ignore if not pending. + */ + resolvePending(val2) { + if (this._state === DeferredState.PENDING) + this.resolve(val2); + } + /** + * Reject the promise. Ignore if not pending. + */ + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); } }; - exports2.ReflectionJsonWriter = ReflectionJsonWriter; + exports2.Deferred = Deferred; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js -var require_reflection_scalar_default = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js +var require_rpc_output_stream = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionScalarDefault = void 0; - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var pb_long_1 = require_pb_long(); - function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { - switch (type2) { - case reflection_info_1.ScalarType.BOOL: - return false; - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return 0; - case reflection_info_1.ScalarType.BYTES: - return new Uint8Array(0); - case reflection_info_1.ScalarType.STRING: - return ""; - default: - return 0; + exports2.RpcOutputStreamController = void 0; + var deferred_1 = require_deferred(); + var runtime_1 = require_commonjs11(); + var RpcOutputStreamController = class { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [] + }; + this._closed = false; + this._itState = { q: [] }; } - } - exports2.reflectionScalarDefault = reflectionScalarDefault; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js -var require_reflection_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryReader = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var ReflectionBinaryReader = class { - constructor(info7) { - this.info = info7; + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); } - prepare() { - var _a; - if (!this.fieldNoToField) { - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); - } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); } + // --- Controller API /** - * Reads a message from binary format into the target message. - * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. - * - * If a message field is already present, it will be merged with the - * new data. + * Is this stream already closed by a completion or error? */ - read(reader, message, options, length) { - this.prepare(); - const end = length === void 0 ? reader.len : reader.pos + length; - while (reader.pos < end) { - const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); - if (!field) { - let u = options.readUnknownField; - if (u == "throw") - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); - continue; - } - let target = message, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - target = target[field.oneof]; - if (target.oneofKind !== localName) - target = message[field.oneof] = { - oneofKind: localName - }; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - let L = field.kind == "scalar" ? field.L : void 0; - if (repeated) { - let arr = target[localName]; - if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { - let e = reader.uint32() + reader.pos; - while (reader.pos < e) - arr.push(this.scalar(reader, T, L)); - } else - arr.push(this.scalar(reader, T, L)); - } else - target[localName] = this.scalar(reader, T, L); - break; - case "message": - if (repeated) { - let arr = target[localName]; - let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); - arr.push(msg); - } else - target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); - break; - case "map": - let [mapKey, mapVal] = this.mapEntry(field, reader, options); - target[localName][mapKey] = mapVal; - break; - } - } + get closed() { + return this._closed !== false; } /** - * Read a map field, expecting key field = 1, value field = 2 + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. */ - mapEntry(field, reader, options) { - let length = reader.uint32(); - let end = reader.pos + length; - let key = void 0; - let val2 = void 0; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case 1: - if (field.K == reflection_info_1.ScalarType.BOOL) - key = reader.bool().toString(); - else - key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); - break; - case 2: - switch (field.V.kind) { - case "scalar": - val2 = this.scalar(reader, field.V.T, field.V.L); - break; - case "enum": - val2 = reader.int32(); - break; - case "message": - val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); - break; - } - break; - default: - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); - } - } - if (key === void 0) { - let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); - key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; - } - if (val2 === void 0) - switch (field.V.kind) { - case "scalar": - val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); - break; - case "enum": - val2 = 0; - break; - case "message": - val2 = field.V.T().create(); - break; + notifyNext(message, error4, complete) { + runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); + if (message) + this.notifyMessage(message); + if (error4) + this.notifyError(error4); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. + * + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, "stream is closed"); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach((l) => l(message)); + this._lis.nxt.forEach((l) => l(message, void 0, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. + * + * Triggers onNext and onError callbacks. + */ + notifyError(error4) { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = error4; + this.pushIt(error4); + this._lis.err.forEach((l) => l(error4)); + this._lis.nxt.forEach((l) => l(void 0, error4, false)); + this.clearLis(); + } + /** + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. + */ + notifyComplete() { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach((l) => l()); + this._lis.nxt.forEach((l) => l(void 0, void 0, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); + runtime_1.assert(!state.p, "iterator contract broken"); + let first = state.q.shift(); + if (first) + return "value" in first ? Promise.resolve(first) : Promise.reject(first); + state.p = new deferred_1.Deferred(); + return state.p.promise; } - return [key, val2]; + }; } - scalar(reader, type2, longType) { - switch (type2) { - case reflection_info_1.ScalarType.INT32: - return reader.int32(); - case reflection_info_1.ScalarType.STRING: - return reader.string(); - case reflection_info_1.ScalarType.BOOL: - return reader.bool(); - case reflection_info_1.ScalarType.DOUBLE: - return reader.double(); - case reflection_info_1.ScalarType.FLOAT: - return reader.float(); - case reflection_info_1.ScalarType.INT64: - return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); - case reflection_info_1.ScalarType.UINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); - case reflection_info_1.ScalarType.FIXED32: - return reader.fixed32(); - case reflection_info_1.ScalarType.BYTES: - return reader.bytes(); - case reflection_info_1.ScalarType.UINT32: - return reader.uint32(); - case reflection_info_1.ScalarType.SFIXED32: - return reader.sfixed32(); - case reflection_info_1.ScalarType.SFIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); - case reflection_info_1.ScalarType.SINT32: - return reader.sint32(); - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (state.p) { + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + "value" in result ? p.resolve(result) : p.reject(result); + delete state.p; + } else { + state.q.push(result); } } }; - exports2.ReflectionBinaryReader = ReflectionBinaryReader; + exports2.RpcOutputStreamController = RpcOutputStreamController; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js -var require_reflection_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js +var require_unary_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryWriter = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var pb_long_1 = require_pb_long(); - var ReflectionBinaryWriter = class { - constructor(info7) { - this.info = info7; - } - prepare() { - if (!this.fields) { - const fieldsInput = this.info.fields ? this.info.fields.concat() : []; - this.fields = fieldsInput.sort((a, b) => a.no - b.no); - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - /** - * Writes the message to binary format. - */ - write(message, writer, options) { - this.prepare(); - for (const field of this.fields) { - let value, emitDefault, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - const group = message[field.oneof]; - if (group.oneofKind !== localName) - continue; - value = group[localName]; - emitDefault = true; - } else { - value = message[localName]; - emitDefault = false; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (repeated) { - assert_1.assert(Array.isArray(value)); - if (repeated == reflection_info_1.RepeatType.PACKED) - this.packed(writer, T, field.no, value); - else - for (const item of value) - this.scalar(writer, T, field.no, item, true); - } else if (value === void 0) - assert_1.assert(field.opt); - else - this.scalar(writer, T, field.no, value, emitDefault || field.opt); - break; - case "message": - if (repeated) { - assert_1.assert(Array.isArray(value)); - for (const item of value) - this.message(writer, options, field.T(), field.no, item); - } else { - this.message(writer, options, field.T(), field.no, value); - } - break; - case "map": - assert_1.assert(typeof value == "object" && value !== null); - for (const [key, val2] of Object.entries(value)) - this.mapEntry(writer, options, field, key, val2); - break; + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - let u = options.writeUnknownFields; - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); - } - mapEntry(writer, options, field, key, value) { - writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let keyValue = key; - switch (field.K) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - keyValue = Number.parseInt(key); - break; - case reflection_info_1.ScalarType.BOOL: - assert_1.assert(key == "true" || key == "false"); - keyValue = key == "true"; - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - this.scalar(writer, field.K, 1, keyValue, true); - switch (field.V.kind) { - case "scalar": - this.scalar(writer, field.V.T, 2, value, true); - break; - case "enum": - this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); - break; - case "message": - this.message(writer, options, field.V.T(), 2, value); - break; + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } - writer.join(); - } - message(writer, options, handler, fieldNo, value) { - if (value === void 0) - return; - handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); - writer.join(); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UnaryCall = void 0; + var UnaryCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; } /** - * Write a single scalar value. + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. */ - scalar(writer, type2, fieldNo, value, emitDefault) { - let [wireType, method, isDefault] = this.scalarInfo(type2, value); - if (!isDefault || emitDefault) { - writer.tag(fieldNo, wireType); - writer[method](value); + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.UnaryCall = UnaryCall; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js +var require_server_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerStreamingCall = void 0; + var ServerStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } /** - * Write an array of scalar values in packed format. + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. */ - packed(writer, type2, fieldNo, value) { - if (!value.length) - return; - assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); - writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let [, method] = this.scalarInfo(type2); - for (let i = 0; i < value.length; i++) - writer[method](value[i]); - writer.join(); + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } - /** - * Get information for writing a scalar value. - * - * Returns tuple: - * [0]: appropriate WireType - * [1]: name of the appropriate method of IBinaryWriter - * [2]: whether the given value is a default value - * - * If argument `value` is omitted, [2] is always false. - */ - scalarInfo(type2, value) { - let t = binary_format_contract_1.WireType.Varint; - let m; - let i = value === void 0; - let d = value === 0; - switch (type2) { - case reflection_info_1.ScalarType.INT32: - m = "int32"; - break; - case reflection_info_1.ScalarType.STRING: - d = i || !value.length; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "string"; - break; - case reflection_info_1.ScalarType.BOOL: - d = value === false; - m = "bool"; - break; - case reflection_info_1.ScalarType.UINT32: - m = "uint32"; - break; - case reflection_info_1.ScalarType.DOUBLE: - t = binary_format_contract_1.WireType.Bit64; - m = "double"; - break; - case reflection_info_1.ScalarType.FLOAT: - t = binary_format_contract_1.WireType.Bit32; - m = "float"; - break; - case reflection_info_1.ScalarType.INT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "int64"; - break; - case reflection_info_1.ScalarType.UINT64: - d = i || pb_long_1.PbULong.from(value).isZero(); - m = "uint64"; - break; - case reflection_info_1.ScalarType.FIXED64: - d = i || pb_long_1.PbULong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "fixed64"; - break; - case reflection_info_1.ScalarType.BYTES: - d = i || !value.byteLength; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "bytes"; - break; - case reflection_info_1.ScalarType.FIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "fixed32"; - break; - case reflection_info_1.ScalarType.SFIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "sfixed32"; - break; - case reflection_info_1.ScalarType.SFIXED64: - d = i || pb_long_1.PbLong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "sfixed64"; - break; - case reflection_info_1.ScalarType.SINT32: - m = "sint32"; - break; - case reflection_info_1.ScalarType.SINT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "sint64"; - break; - } - return [t, m, i || d]; + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + exports2.ServerStreamingCall = ServerStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js -var require_reflection_create = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js +var require_client_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionCreate = void 0; - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var message_type_contract_1 = require_message_type_contract(); - function reflectionCreate(type2) { - const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); - for (let field of type2.fields) { - let name = field.localName; - if (field.opt) - continue; - if (field.oneof) - msg[field.oneof] = { oneofKind: void 0 }; - else if (field.repeat) - msg[name] = []; - else - switch (field.kind) { - case "scalar": - msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); - break; - case "enum": - msg[name] = 0; - break; - case "map": - msg[name] = {}; - break; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ClientStreamingCall = void 0; + var ClientStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; } - return msg; - } - exports2.reflectionCreate = reflectionCreate; + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.ClientStreamingCall = ClientStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js -var require_reflection_merge_partial = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js +var require_duplex_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionMergePartial = void 0; - function reflectionMergePartial(info7, target, source) { - let fieldValue, input = source, output; - for (let field of info7.fields) { - let name = field.localName; - if (field.oneof) { - const group = input[field.oneof]; - if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { - continue; - } - fieldValue = group[name]; - output = target[field.oneof]; - output.oneofKind = group.oneofKind; - if (fieldValue == void 0) { - delete output[name]; - continue; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - } else { - fieldValue = input[name]; - output = target; - if (fieldValue == void 0) { - continue; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - if (field.repeat) - output[name].length = fieldValue.length; - switch (field.kind) { - case "scalar": - case "enum": - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = fieldValue[i]; - else - output[name] = fieldValue; - break; - case "message": - let T = field.T(); - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = T.create(fieldValue[i]); - else if (output[name] === void 0) - output[name] = T.create(fieldValue); - else - T.mergePartial(output[name], fieldValue); - break; - case "map": - switch (field.V.kind) { - case "scalar": - case "enum": - Object.assign(output[name], fieldValue); - break; - case "message": - let T2 = field.V.T(); - for (let k of Object.keys(fieldValue)) - output[name][k] = T2.create(fieldValue[k]); - break; - } - break; + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } - } - } - exports2.reflectionMergePartial = reflectionMergePartial; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js -var require_reflection_equals = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { - "use strict"; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionEquals = void 0; - var reflection_info_1 = require_reflection_info(); - function reflectionEquals(info7, a, b) { - if (a === b) - return true; - if (!a || !b) - return false; - for (let field of info7.fields) { - let localName = field.localName; - let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; - let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; - switch (field.kind) { - case "enum": - case "scalar": - let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) - return false; - break; - case "map": - if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) - return false; - break; - case "message": - let T = field.T(); - if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) - return false; - break; - } + exports2.DuplexStreamingCall = void 0; + var DuplexStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } - return true; - } - exports2.reflectionEquals = reflectionEquals; - var objectValues = Object.values; - function primitiveEq(type2, a, b) { - if (a === b) - return true; - if (type2 !== reflection_info_1.ScalarType.BYTES) - return false; - let ba = a; - let bb = b; - if (ba.length !== bb.length) - return false; - for (let i = 0; i < ba.length; i++) - if (ba[i] != bb[i]) - return false; - return true; - } - function repeatedPrimitiveEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!primitiveEq(type2, a[i], b[i])) - return false; - return true; - } - function repeatedMsgEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!type2.equals(a[i], b[i])) - return false; - return true; - } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers + }; + }); + } + }; + exports2.DuplexStreamingCall = DuplexStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js -var require_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js +var require_test_transport = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_type_check_1 = require_reflection_type_check(); - var reflection_json_reader_1 = require_reflection_json_reader(); - var reflection_json_writer_1 = require_reflection_json_writer(); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - var reflection_create_1 = require_reflection_create(); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - var json_typings_1 = require_json_typings(); - var json_format_contract_1 = require_json_format_contract(); - var reflection_equals_1 = require_reflection_equals(); - var binary_writer_1 = require_binary_writer(); - var binary_reader_1 = require_binary_reader(); - var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); - var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; - var MessageType = class { - constructor(name, fields, options) { - this.defaultCheckDepth = 16; - this.typeName = name; - this.fields = fields.map(reflection_info_1.normalizeFieldInfo); - this.options = options !== null && options !== void 0 ? options : {}; - messageTypeDescriptor.value = this; - this.messagePrototype = Object.create(null, baseDescriptors); - this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); - this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); - this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); - this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); - this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - create(value) { - let message = reflection_create_1.reflectionCreate(this); - if (value !== void 0) { - reflection_merge_partial_1.reflectionMergePartial(this, message, value); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - return message; - } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TestTransport = void 0; + var rpc_error_1 = require_rpc_error(); + var runtime_1 = require_commonjs11(); + var rpc_output_stream_1 = require_rpc_output_stream(); + var rpc_options_1 = require_rpc_options(); + var unary_call_1 = require_unary_call(); + var server_streaming_call_1 = require_server_streaming_call(); + var client_streaming_call_1 = require_client_streaming_call(); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + var TestTransport = class _TestTransport { /** - * Clone the message. - * - * Unknown fields are discarded. + * Initialize with mock data. Omitted fields have default value. */ - clone(message) { - let copy = this.create(); - reflection_merge_partial_1.reflectionMergePartial(this, copy, message); - return copy; + constructor(data) { + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; } /** - * Determines whether two message of the same type have the same field values. - * Checks for deep equality, traversing repeated fields, oneof groups, maps - * and messages recursively. - * Will also return true if both messages are `undefined`. + * Sent message(s) during the last operation. */ - equals(a, b) { - return reflection_equals_1.reflectionEquals(this, a, b); + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; + } else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; } /** - * Is the given value assignable to our message type - * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + * Sending message(s) completed? */ - is(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, false); + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } else if (typeof this.lastInput == "object") { + return true; + } + return false; } - /** - * Is the given value assignable to our message type, - * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? - */ - isAssignable(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, true); + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); } - /** - * Copy partial data into the target message. - */ - mergePartial(target, source) { - reflection_merge_partial_1.reflectionMergePartial(this, target, source); + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } else if (this.data.response !== void 0) { + r = this.data.response; + } else { + r = method.O.create(); + } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); } /** - * Create a new message from binary format. + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. */ - fromBinary(data, options) { - let opt = binary_reader_1.binaryReadOptions(options); - return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + streamResponses(method, stream, abort) { + return __awaiter4(this, void 0, void 0, function* () { + const messages = []; + if (this.data.response === void 0) { + messages.push(method.O.create()); + } else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + try { + yield delay(this.responseDelay, abort)(void 0); + } catch (error4) { + stream.notifyError(error4); + return; + } + if (this.data.response instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.response); + return; + } + for (let msg of messages) { + stream.notifyMessage(msg); + try { + yield delay(this.betweenResponseDelay, abort)(void 0); + } catch (error4) { + stream.notifyError(error4); + return; + } + } + if (this.data.status instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.status); + return; + } + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.trailers); + return; + } + stream.notifyComplete(); + }); + } + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); + } + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); + } + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } + } + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); + } + unary(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { + }).then(delay(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { + }).then(delay(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { + }).then(delay(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); + } + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); + } + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { + }).then(delay(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { + }).then(delay(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { + }).then(delay(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + } + }; + exports2.TestTransport = TestTransport; + TestTransport.defaultHeaders = { + responseHeader: "test" + }; + TestTransport.defaultStatus = { + code: "OK", + detail: "all good" + }; + TestTransport.defaultTrailers = { + responseTrailer: "test" + }; + function delay(ms, abort) { + return (v) => new Promise((resolve5, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } else { + const id = setTimeout(() => resolve5(v), ms); + if (abort) { + abort.addEventListener("abort", (ev) => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } + } + }); + } + var TestInputStream = class { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; + } + get sent() { + return this._sent; + } + get completed() { + return this._completed; + } + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); + } + const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; + return Promise.resolve(void 0).then(() => { + this._sent.push(message); + }).then(delay(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); + } + const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; + return Promise.resolve(void 0).then(() => { + this._completed = true; + }).then(delay(delayMs, this.abort)); } - /** - * Read a new message from a JSON value. - */ - fromJson(json2, options) { - return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + }; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js +var require_rpc_interceptor = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; + var runtime_1 = require_commonjs11(); + function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + } + return tail(method, input, options); } - /** - * Read a new message from a JSON string. - * This is equivalent to `T.fromJson(JSON.parse(json))`. - */ - fromJsonString(json2, options) { - let value = JSON.parse(json2); - return this.fromJson(value, options); + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); } - /** - * Write the message to canonical JSON value. - */ - toJson(message, options) { - return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + } + return tail(method, options); } - /** - * Convert the message to canonical JSON string. - * This is equivalent to `JSON.stringify(T.toJson(t))` - */ - toJsonString(message, options) { - var _a; - let value = this.toJson(message, options); - return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); } - /** - * Write the message to binary format. - */ - toBinary(message, options) { - let opt = binary_writer_1.binaryWriteOptions(options); - return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + runtime_1.assertNever(kind); + } + exports2.stackIntercept = stackIntercept; + function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); + } + exports2.stackUnaryInterceptors = stackUnaryInterceptors; + function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); + } + exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; + function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); + } + exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; + function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); + } + exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js +var require_server_call_context = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerCallContextController = void 0; + var ServerCallContextController = class { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; } /** - * This is an internal method. If you just want to read a message from - * JSON, use `fromJson()` or `fromJsonString()`. + * Set the call cancelled. * - * Reads JSON value and merges the fields into the target - * according to protobuf rules. If the target is omitted, - * a new instance is created first. + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. */ - internalJsonRead(json2, options, target) { - if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refJsonReader.read(json2, message, options); - return message; + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } } - throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); } /** - * This is an internal method. If you just want to write a message - * to JSON, use `toJson()` or `toJsonString(). - * - * Writes JSON value and returns it. + * Send response headers. */ - internalJsonWrite(message, options) { - return this.refJsonWriter.write(message, options); + sendResponseHeaders(data) { + this._sendRH(data); } /** - * This is an internal method. If you just want to write a message - * in binary format, use `toBinary()`. + * Is the call cancelled? * - * Serializes the message in binary format and appends it to the given - * writer. Returns passed writer. + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. */ - internalBinaryWrite(message, writer, options) { - this.refBinWriter.write(message, writer, options); - return writer; + get cancelled() { + return this._cancelled; } /** - * This is an internal method. If you just want to read a message from - * binary data, use `fromBinary()`. - * - * Reads data from binary format and merges the fields into - * the target according to protobuf rules. If the target is - * omitted, a new instance is created first. + * Add a callback for cancellation. */ - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refBinReader.read(reader, message, options, length); - return message; + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; } }; - exports2.MessageType = MessageType; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js -var require_reflection_contains_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.containsMessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - function containsMessageType(msg) { - return msg[message_type_contract_1.MESSAGE_TYPE] != null; - } - exports2.containsMessageType = containsMessageType; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js -var require_enum_object = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; - function isEnumObject(arg) { - if (typeof arg != "object" || arg === null) { - return false; - } - if (!arg.hasOwnProperty(0)) { - return false; - } - for (let k of Object.keys(arg)) { - let num = parseInt(k); - if (!Number.isNaN(num)) { - let nam = arg[num]; - if (nam === void 0) - return false; - if (arg[nam] !== num) - return false; - } else { - let num2 = arg[k]; - if (num2 === void 0) - return false; - if (typeof num2 !== "number") - return false; - if (arg[num2] === void 0) - return false; - } - } - return true; - } - exports2.isEnumObject = isEnumObject; - function listEnumValues(enumObject) { - if (!isEnumObject(enumObject)) - throw new Error("not a typescript enum object"); - let values = []; - for (let [name, number] of Object.entries(enumObject)) - if (typeof number == "number") - values.push({ name, number }); - return values; - } - exports2.listEnumValues = listEnumValues; - function listEnumNames(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.name); - } - exports2.listEnumNames = listEnumNames; - function listEnumNumbers(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); - } - exports2.listEnumNumbers = listEnumNumbers; + exports2.ServerCallContextController = ServerCallContextController; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/index.js -var require_commonjs11 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var json_typings_1 = require_json_typings(); - Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { - return json_typings_1.typeofJsonValue; - } }); - Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { - return json_typings_1.isJsonObject; - } }); - var base64_1 = require_base642(); - Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { - return base64_1.base64decode; - } }); - Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { - return base64_1.base64encode; - } }); - var protobufjs_utf8_1 = require_protobufjs_utf8(); - Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { - return protobufjs_utf8_1.utf8read; - } }); - var binary_format_contract_1 = require_binary_format_contract(); - Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { - return binary_format_contract_1.WireType; - } }); - Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { - return binary_format_contract_1.mergeBinaryOptions; - } }); - Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { - return binary_format_contract_1.UnknownFieldHandler; - } }); - var binary_reader_1 = require_binary_reader(); - Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { - return binary_reader_1.BinaryReader; - } }); - Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { - return binary_reader_1.binaryReadOptions; - } }); - var binary_writer_1 = require_binary_writer(); - Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { - return binary_writer_1.BinaryWriter; - } }); - Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { - return binary_writer_1.binaryWriteOptions; - } }); - var pb_long_1 = require_pb_long(); - Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { - return pb_long_1.PbLong; - } }); - Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { - return pb_long_1.PbULong; - } }); - var json_format_contract_1 = require_json_format_contract(); - Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonReadOptions; - } }); - Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonWriteOptions; - } }); - Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { - return json_format_contract_1.mergeJsonOptions; - } }); - var message_type_contract_1 = require_message_type_contract(); - Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { - return message_type_contract_1.MESSAGE_TYPE; - } }); - var message_type_1 = require_message_type(); - Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { - return message_type_1.MessageType; - } }); - var reflection_info_1 = require_reflection_info(); - Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { - return reflection_info_1.ScalarType; - } }); - Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { - return reflection_info_1.LongType; - } }); - Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { - return reflection_info_1.RepeatType; - } }); - Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { - return reflection_info_1.normalizeFieldInfo; - } }); - Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { - return reflection_info_1.readFieldOptions; - } }); - Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { - return reflection_info_1.readFieldOption; - } }); - Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { - return reflection_info_1.readMessageOption; - } }); - var reflection_type_check_1 = require_reflection_type_check(); - Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { - return reflection_type_check_1.ReflectionTypeCheck; - } }); - var reflection_create_1 = require_reflection_create(); - Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { - return reflection_create_1.reflectionCreate; - } }); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { - return reflection_scalar_default_1.reflectionScalarDefault; - } }); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { - return reflection_merge_partial_1.reflectionMergePartial; - } }); - var reflection_equals_1 = require_reflection_equals(); - Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { - return reflection_equals_1.reflectionEquals; - } }); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { - return reflection_binary_reader_1.ReflectionBinaryReader; - } }); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { - return reflection_binary_writer_1.ReflectionBinaryWriter; - } }); - var reflection_json_reader_1 = require_reflection_json_reader(); - Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { - return reflection_json_reader_1.ReflectionJsonReader; - } }); - var reflection_json_writer_1 = require_reflection_json_writer(); - Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { - return reflection_json_writer_1.ReflectionJsonWriter; - } }); - var reflection_contains_message_type_1 = require_reflection_contains_message_type(); - Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { - return reflection_contains_message_type_1.containsMessageType; - } }); - var oneof_1 = require_oneof(); - Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { - return oneof_1.isOneofGroup; + var service_type_1 = require_service_type(); + Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { + return service_type_1.ServiceType; } }); - Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { - return oneof_1.setOneofValue; + var reflection_info_1 = require_reflection_info2(); + Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { + return reflection_info_1.readMethodOptions; } }); - Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { - return oneof_1.getOneofValue; + Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { + return reflection_info_1.readMethodOption; } }); - Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { - return oneof_1.clearOneofValue; + Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { + return reflection_info_1.readServiceOption; } }); - Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { - return oneof_1.getSelectedOneofValue; + var rpc_error_1 = require_rpc_error(); + Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { + return rpc_error_1.RpcError; } }); - var enum_object_1 = require_enum_object(); - Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { - return enum_object_1.listEnumValues; + var rpc_options_1 = require_rpc_options(); + Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { + return rpc_options_1.mergeRpcOptions; } }); - Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { - return enum_object_1.listEnumNames; + var rpc_output_stream_1 = require_rpc_output_stream(); + Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { + return rpc_output_stream_1.RpcOutputStreamController; } }); - Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { - return enum_object_1.listEnumNumbers; + var test_transport_1 = require_test_transport(); + Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { + return test_transport_1.TestTransport; } }); - Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { - return enum_object_1.isEnumObject; + var deferred_1 = require_deferred(); + Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { + return deferred_1.Deferred; } }); - var lower_camel_case_1 = require_lower_camel_case(); - Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { - return lower_camel_case_1.lowerCamelCase; + Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { + return deferred_1.DeferredState; } }); - var assert_1 = require_assert(); - Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { - return assert_1.assert; + var duplex_streaming_call_1 = require_duplex_streaming_call(); + Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { + return duplex_streaming_call_1.DuplexStreamingCall; } }); - Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { - return assert_1.assertNever; + var client_streaming_call_1 = require_client_streaming_call(); + Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { + return client_streaming_call_1.ClientStreamingCall; } }); - Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { - return assert_1.assertInt32; + var server_streaming_call_1 = require_server_streaming_call(); + Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { + return server_streaming_call_1.ServerStreamingCall; } }); - Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { - return assert_1.assertUInt32; + var unary_call_1 = require_unary_call(); + Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { + return unary_call_1.UnaryCall; } }); - Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { - return assert_1.assertFloat32; + var rpc_interceptor_1 = require_rpc_interceptor(); + Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { + return rpc_interceptor_1.stackIntercept; + } }); + Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackDuplexStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackClientStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackServerStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackUnaryInterceptors; + } }); + var server_call_context_1 = require_server_call_context(); + Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { + return server_call_context_1.ServerCallContextController; } }); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js -var require_reflection_info2 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; - var runtime_1 = require_commonjs11(); - function normalizeMethodInfo(method, service) { - var _a, _b, _c; - let m = method; - m.service = service; - m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); - m.serverStreaming = !!m.serverStreaming; - m.clientStreaming = !!m.clientStreaming; - m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; - m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; - return m; - } - exports2.normalizeMethodInfo = normalizeMethodInfo; - function readMethodOptions(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readMethodOptions = readMethodOptions; - function readMethodOption(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readMethodOption = readMethodOption; - function readServiceOption(service, extensionName, extensionType) { - const options = service.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readServiceOption = readServiceOption; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js -var require_service_type = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js +var require_cachescope = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceType = void 0; - var reflection_info_1 = require_reflection_info2(); - var ServiceType = class { - constructor(typeName, methods, options) { - this.typeName = typeName; - this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); - this.options = options !== null && options !== void 0 ? options : {}; + exports2.CacheScope = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var CacheScope$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheScope", [ + { + no: 1, + name: "scope", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "permission", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + create(value) { + const message = { scope: "", permission: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string scope */ + 1: + message.scope = reader.string(); + break; + case /* int64 permission */ + 2: + message.permission = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.scope !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); + if (message.permission !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.ServiceType = ServiceType; + exports2.CacheScope = new CacheScope$Type(); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js -var require_rpc_error = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js +var require_cachemetadata = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcError = void 0; - var RpcError = class extends Error { - constructor(message, code = "UNKNOWN", meta) { - super(message); - this.name = "RpcError"; - Object.setPrototypeOf(this, new.target.prototype); - this.code = code; - this.meta = meta !== null && meta !== void 0 ? meta : {}; + exports2.CacheMetadata = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachescope_1 = require_cachescope(); + var CacheMetadata$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheMetadata", [ + { + no: 1, + name: "repository_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } + ]); } - toString() { - const l = [this.name + ": " + this.message]; - if (this.code) { - l.push(""); - l.push("Code: " + this.code); - } - if (this.serviceName && this.methodName) { - l.push("Method: " + this.serviceName + "/" + this.methodName); - } - let m = Object.entries(this.meta); - if (m.length) { - l.push(""); - l.push("Meta:"); - for (let [k, v] of m) { - l.push(` ${k}: ${v}`); + create(value) { + const message = { repositoryId: "0", scope: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 repository_id */ + 1: + message.repositoryId = reader.int64().toString(); + break; + case /* repeated github.actions.results.entities.v1.CacheScope scope */ + 2: + message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - return l.join("\n"); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.repositoryId !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); + for (let i = 0; i < message.scope.length; i++) + cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.RpcError = RpcError; + exports2.CacheMetadata = new CacheMetadata$Type(); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js -var require_rpc_options = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js +var require_cache2 = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeRpcOptions = void 0; + exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); var runtime_1 = require_commonjs11(); - function mergeRpcOptions(defaults, options) { - if (!options) - return defaults; - let o = {}; - copy(defaults, o); - copy(options, o); - for (let key of Object.keys(options)) { - let val2 = options[key]; - switch (key) { - case "jsonOptions": - o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); - break; - case "binaryOptions": - o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); - break; - case "meta": - o.meta = {}; - copy(defaults.meta, o.meta); - copy(options.meta, o.meta); - break; - case "interceptors": - o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); - break; + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachemetadata_1 = require_cachemetadata(); + var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* string version */ + 3: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.version !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); + var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedUploadUrl: "", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); + var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size_bytes", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", sizeBytes: "0", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* int64 size_bytes */ + 3: + message.sizeBytes = reader.int64().toString(); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.sizeBytes !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); + var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "entry_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, entryId: "0", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* int64 entry_id */ + 2: + message.entryId = reader.int64().toString(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.entryId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - return o; - } - exports2.mergeRpcOptions = mergeRpcOptions; - function copy(a, into) { - if (!a) - return; - let c = into; - for (let [k, v] of Object.entries(a)) { - if (v instanceof Date) - c[k] = new Date(v.getTime()); - else if (Array.isArray(v)) - c[k] = v.concat(); - else - c[k] = v; + }; + exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); + var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "restore_keys", + kind: "scalar", + repeat: 2, + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - } - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js -var require_deferred = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Deferred = exports2.DeferredState = void 0; - var DeferredState; - (function(DeferredState2) { - DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; - DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; - DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; - })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); - var Deferred = class { - /** - * @param preventUnhandledRejectionWarning - prevents the warning - * "Unhandled Promise rejection" by adding a noop rejection handler. - * Working with calls returned from the runtime-rpc package in an - * async function usually means awaiting one call property after - * the other. This means that the "status" is not being awaited when - * an earlier await for the "headers" is rejected. This causes the - * "unhandled promise reject" warning. A more correct behaviour for - * calls might be to become aware whether at least one of the - * promises is handled and swallow the rejection warning for the - * others. - */ - constructor(preventUnhandledRejectionWarning = true) { - this._state = DeferredState.PENDING; - this._promise = new Promise((resolve5, reject) => { - this._resolve = resolve5; - this._reject = reject; - }); - if (preventUnhandledRejectionWarning) { - this._promise.catch((_2) => { - }); - } + create(value) { + const message = { key: "", restoreKeys: [], version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - /** - * Get the current state of the promise. - */ - get state() { - return this._state; + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* repeated string restore_keys */ + 3: + message.restoreKeys.push(reader.string()); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - /** - * Get the deferred promise. - */ - get promise() { - return this._promise; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + for (let i = 0; i < message.restoreKeys.length; i++) + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - /** - * Resolve the promise. Throws if the promise is already resolved or rejected. - */ - resolve(value) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); - this._resolve(value); - this._state = DeferredState.RESOLVED; + }; + exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); + var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_download_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "matched_key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - /** - * Reject the promise. Throws if the promise is already resolved or rejected. - */ - reject(reason) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); - this._reject(reason); - this._state = DeferredState.REJECTED; + create(value) { + const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - /** - * Resolve the promise. Ignore if not pending. - */ - resolvePending(val2) { - if (this._state === DeferredState.PENDING) - this.resolve(val2); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_download_url */ + 2: + message.signedDownloadUrl = reader.string(); + break; + case /* string matched_key */ + 3: + message.matchedKey = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - /** - * Reject the promise. Ignore if not pending. - */ - rejectPending(reason) { - if (this._state === DeferredState.PENDING) - this.reject(reason); + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedDownloadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); + if (message.matchedKey !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.Deferred = Deferred; + exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); + exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ + { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, + { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, + { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } + ]); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js -var require_rpc_output_stream = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js +var require_cache_twirp_client = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcOutputStreamController = void 0; - var deferred_1 = require_deferred(); - var runtime_1 = require_commonjs11(); - var RpcOutputStreamController = class { - constructor() { - this._lis = { - nxt: [], - msg: [], - err: [], - cmp: [] - }; - this._closed = false; - this._itState = { q: [] }; - } - // --- RpcOutputStream callback API - onNext(callback) { - return this.addLis(callback, this._lis.nxt); - } - onMessage(callback) { - return this.addLis(callback, this._lis.msg); - } - onError(callback) { - return this.addLis(callback, this._lis.err); - } - onComplete(callback) { - return this.addLis(callback, this._lis.cmp); - } - addLis(callback, list) { - list.push(callback); - return () => { - let i = list.indexOf(callback); - if (i >= 0) - list.splice(i, 1); - }; - } - // remove all listeners - clearLis() { - for (let l of Object.values(this._lis)) - l.splice(0, l.length); + exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; + var cache_1 = require_cache2(); + var CacheServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - // --- Controller API - /** - * Is this stream already closed by a completion or error? - */ - get closed() { - return this._closed !== false; + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Emit message, close with error, or close successfully, but only one - * at a time. - * Can be used to wrap a stream by using the other stream's `onNext`. - */ - notifyNext(message, error4, complete) { - runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); - if (message) - this.notifyMessage(message); - if (error4) - this.notifyError(error4); - if (complete) - this.notifyComplete(); + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Emits a new message. Throws if stream is closed. - * - * Triggers onNext and onMessage callbacks. - */ - notifyMessage(message) { - runtime_1.assert(!this.closed, "stream is closed"); - this.pushIt({ value: message, done: false }); - this._lis.msg.forEach((l) => l(message)); - this._lis.nxt.forEach((l) => l(message, void 0, false)); + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Closes the stream with an error. Throws if stream is closed. - * - * Triggers onNext and onError callbacks. - */ - notifyError(error4) { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = error4; - this.pushIt(error4); - this._lis.err.forEach((l) => l(error4)); - this._lis.nxt.forEach((l) => l(void 0, error4, false)); - this.clearLis(); + }; + exports2.CacheServiceClientJSON = CacheServiceClientJSON; + var CacheServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - /** - * Closes the stream successfully. Throws if stream is closed. - * - * Triggers onNext and onComplete callbacks. - */ - notifyComplete() { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = true; - this.pushIt({ value: null, done: true }); - this._lis.cmp.forEach((l) => l()); - this._lis.nxt.forEach((l) => l(void 0, void 0, true)); - this.clearLis(); + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); } - /** - * Creates an async iterator (that can be used with `for await {...}`) - * to consume the stream. - * - * Some things to note: - * - If an error occurs, the `for await` will throw it. - * - If an error occurred before the `for await` was started, `for await` - * will re-throw it. - * - If the stream is already complete, the `for await` will be empty. - * - If your `for await` consumes slower than the stream produces, - * for example because you are relaying messages in a slow operation, - * messages are queued. - */ - [Symbol.asyncIterator]() { - if (this._closed === true) - this.pushIt({ value: null, done: true }); - else if (this._closed !== false) - this.pushIt(this._closed); - return { - next: () => { - let state = this._itState; - runtime_1.assert(state, "bad state"); - runtime_1.assert(!state.p, "iterator contract broken"); - let first = state.q.shift(); - if (first) - return "value" in first ? Promise.resolve(first) : Promise.reject(first); - state.p = new deferred_1.Deferred(); - return state.p.promise; - } - }; + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); } - // "push" a new iterator result. - // this either resolves a pending promise, or enqueues the result. - pushIt(result) { - let state = this._itState; - if (state.p) { - const p = state.p; - runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); - "value" in result ? p.resolve(result) : p.reject(result); - delete state.p; - } else { - state.q.push(result); - } + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.RpcOutputStreamController = RpcOutputStreamController; + exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js -var require_unary_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/util.js +var require_util10 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UnaryCall = void 0; - var UnaryCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; + exports2.maskSecretUrls = exports2.maskSigUrl = void 0; + var core_1 = require_core(); + function maskSigUrl(url) { + if (!url) + return; + try { + const parsedUrl = new URL(url); + const signature = parsedUrl.searchParams.get("sig"); + if (signature) { + (0, core_1.setSecret)(signature); + (0, core_1.setSecret)(encodeURIComponent(signature)); + } + } catch (error4) { + (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); + } + } + exports2.maskSigUrl = maskSigUrl; + function maskSecretUrls(body) { + if (typeof body !== "object" || body === null) { + (0, core_1.debug)("body is not an object or is null"); + return; } - /** - * If you are only interested in the final outcome of this call, - * you can await it to receive a `FinishedUnaryCall`. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { + maskSigUrl(body.signed_upload_url); } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - response, - status, - trailers - }; - }); + if ("signed_download_url" in body && typeof body.signed_download_url === "string") { + maskSigUrl(body.signed_download_url); } - }; - exports2.UnaryCall = UnaryCall; + } + exports2.maskSecretUrls = maskSecretUrls; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js -var require_server_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js +var require_cacheTwirpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -72465,117 +75398,182 @@ var require_server_streaming_call = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerStreamingCall = void 0; - var ServerStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * You should first setup some listeners to the `request` to - * see the actual messages the server replied with. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + exports2.internalCacheTwirpClient = void 0; + var core_1 = require_core(); + var user_agent_1 = require_user_agent(); + var errors_1 = require_errors2(); + var config_1 = require_config(); + var cacheUtils_1 = require_cacheUtils(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib4(); + var cache_twirp_client_1 = require_cache_twirp_client(); + var util_1 = require_util10(); + var CacheServiceClient = class { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3e3; + this.retryMultiplier = 1.5; + const token = (0, cacheUtils_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getCacheServiceURL)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; + } + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) + ]); } - promiseFinished() { + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - status, - trailers + const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url}`); + const headers = { + "Content-Type": contentType }; + try { + const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { + return this.httpClient.post(url, JSON.stringify(data), headers); + })); + return body; + } catch (error4) { + throw new Error(`Failed to ${method}: ${error4.message}`); + } }); } - }; - exports2.ServerStreamingCall = ServerStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js -var require_client_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); + retryableRequest(operation) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ""; + let rawBody = ""; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, util_1.maskSecretUrls)(body); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } catch (error4) { + if (error4 instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + } + if (error4 instanceof errors_1.UsageError) { + throw error4; + } + if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { + throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + } + isRetryable = true; + errorMessage = error4.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; + } + throw new Error(`Request failed`); }); } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ClientStreamingCall = void 0; - var ClientStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); } - promiseFinished() { + sleep(milliseconds) { return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - response, - status, - trailers - }; + return new Promise((resolve5) => setTimeout(resolve5, milliseconds)); }); } + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error("attempt should be a positive integer"); + } + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); + } }; - exports2.ClientStreamingCall = ClientStreamingCall; + function internalCacheTwirpClient(options) { + const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new cache_twirp_client_1.CacheServiceClientJSON(client); + } + exports2.internalCacheTwirpClient = internalCacheTwirpClient; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js -var require_duplex_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { +// node_modules/@actions/cache/lib/internal/tar.js +var require_tar = __commonJS({ + "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve5) { @@ -72604,46 +75602,221 @@ var require_duplex_streaming_call = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DuplexStreamingCall = void 0; - var DuplexStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - status, - trailers - }; - }); + exports2.createTar = exports2.extractTar = exports2.listTar = void 0; + var exec_1 = require_exec(); + var io6 = __importStar4(require_io()); + var fs_1 = require("fs"); + var path6 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var IS_WINDOWS = process.platform === "win32"; + function getTarPath() { + return __awaiter4(this, void 0, void 0, function* () { + switch (process.platform) { + case "win32": { + const gnuTar = yield utils.getGnuTarPathOnWindows(); + const systemTar = constants_1.SystemTarPathOnWindows; + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else if ((0, fs_1.existsSync)(systemTar)) { + return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; + } + break; + } + case "darwin": { + const gnuTar = yield io6.which("gtar", false); + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else { + return { + path: yield io6.which("tar", true), + type: constants_1.ArchiveToolType.BSD + }; + } + } + default: + break; + } + return { + path: yield io6.which("tar", true), + type: constants_1.ArchiveToolType.GNU + }; + }); + } + function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + const args = [`"${tarPath.path}"`]; + const cacheFileName = utils.getCacheFileName(compressionMethod); + const tarFile = "cache.tar"; + const workingDirectory = getWorkingDirectory(); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (type2) { + case "create": + args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); + break; + case "extract": + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path6.sep}`, "g"), "/")); + break; + case "list": + args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "-P"); + break; + } + if (tarPath.type === constants_1.ArchiveToolType.GNU) { + switch (process.platform) { + case "win32": + args.push("--force-local"); + break; + case "darwin": + args.push("--delay-directory-restore"); + break; + } + } + return args; + }); + } + function getCommands(compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + let args; + const tarPath = yield getTarPath(); + const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); + const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + if (BSD_TAR_ZSTD && type2 !== "create") { + args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; + } else { + args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; + } + if (BSD_TAR_ZSTD) { + return args; + } + return [args.join(" ")]; + }); + } + function getWorkingDirectory() { + var _a; + return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); + } + function getDecompressionProgram(tarPath, compressionMethod, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -d --long=30 --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path6.sep}`, "g"), "/") + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -d --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path6.sep}`, "g"), "/") + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; + default: + return ["-z"]; + } + }); + } + function getCompressionProgram(tarPath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheFileName = utils.getCacheFileName(compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --long=30 --force -o", + cacheFileName.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), + constants_1.TarFilename + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --force -o", + cacheFileName.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), + constants_1.TarFilename + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; + default: + return ["-z"]; + } + }); + } + function execCommands(commands, cwd) { + return __awaiter4(this, void 0, void 0, function* () { + for (const command of commands) { + try { + yield (0, exec_1.exec)(command, void 0, { + cwd, + env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) + }); + } catch (error4) { + throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + } + } + }); + } + function listTar(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const commands = yield getCommands(compressionMethod, "list", archivePath); + yield execCommands(commands); + }); + } + exports2.listTar = listTar; + function extractTar2(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const workingDirectory = getWorkingDirectory(); + yield io6.mkdirP(workingDirectory); + const commands = yield getCommands(compressionMethod, "extract", archivePath); + yield execCommands(commands); + }); + } + exports2.extractTar = extractTar2; + function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + (0, fs_1.writeFileSync)(path6.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); + const commands = yield getCommands(compressionMethod, "create"); + yield execCommands(commands, archiveFolder); + }); + } + exports2.createTar = createTar; + } +}); + +// node_modules/@actions/cache/lib/cache.js +var require_cache3 = __commonJS({ + "node_modules/@actions/cache/lib/cache.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.DuplexStreamingCall = DuplexStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js -var require_test_transport = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve5) { @@ -72672,1374 +75845,1218 @@ var require_test_transport = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TestTransport = void 0; - var rpc_error_1 = require_rpc_error(); - var runtime_1 = require_commonjs11(); - var rpc_output_stream_1 = require_rpc_output_stream(); - var rpc_options_1 = require_rpc_options(); - var unary_call_1 = require_unary_call(); - var server_streaming_call_1 = require_server_streaming_call(); - var client_streaming_call_1 = require_client_streaming_call(); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - var TestTransport = class _TestTransport { - /** - * Initialize with mock data. Omitted fields have default value. - */ - constructor(data) { - this.suppressUncaughtRejections = true; - this.headerDelay = 10; - this.responseDelay = 50; - this.betweenResponseDelay = 10; - this.afterResponseDelay = 10; - this.data = data !== null && data !== void 0 ? data : {}; + exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + var core14 = __importStar4(require_core()); + var path6 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var cacheHttpClient = __importStar4(require_cacheHttpClient()); + var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); + var config_1 = require_config(); + var tar_1 = require_tar(); + var http_client_1 = require_lib4(); + var ValidationError = class _ValidationError extends Error { + constructor(message) { + super(message); + this.name = "ValidationError"; + Object.setPrototypeOf(this, _ValidationError.prototype); } - /** - * Sent message(s) during the last operation. - */ - get sentMessages() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.sent; - } else if (typeof this.lastInput == "object") { - return [this.lastInput.single]; - } - return []; + }; + exports2.ValidationError = ValidationError; + var ReserveCacheError2 = class _ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = "ReserveCacheError"; + Object.setPrototypeOf(this, _ReserveCacheError.prototype); } - /** - * Sending message(s) completed? - */ - get sendComplete() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.completed; - } else if (typeof this.lastInput == "object") { - return true; - } - return false; + }; + exports2.ReserveCacheError = ReserveCacheError2; + var FinalizeCacheError = class _FinalizeCacheError extends Error { + constructor(message) { + super(message); + this.name = "FinalizeCacheError"; + Object.setPrototypeOf(this, _FinalizeCacheError.prototype); } - // Creates a promise for response headers from the mock data. - promiseHeaders() { - var _a; - const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; - return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); + }; + exports2.FinalizeCacheError = FinalizeCacheError; + function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); } - // Creates a promise for a single, valid, message from the mock data. - promiseSingleResponse(method) { - if (this.data.response instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.response); + } + function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } + } + function isFeatureAvailable() { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + switch (cacheServiceVersion) { + case "v2": + return !!process.env["ACTIONS_RESULTS_URL"]; + case "v1": + default: + return !!process.env["ACTIONS_CACHE_URL"]; + } + } + exports2.isFeatureAvailable = isFeatureAvailable; + function restoreCache4(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core14.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + switch (cacheServiceVersion) { + case "v2": + return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + case "v1": + default: + return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); } - let r; - if (Array.isArray(this.data.response)) { - runtime_1.assert(this.data.response.length > 0); - r = this.data.response[0]; - } else if (this.data.response !== void 0) { - r = this.data.response; - } else { - r = method.O.create(); + }); + } + exports2.restoreCache = restoreCache4; + function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core14.debug("Resolved Keys:"); + core14.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); } - runtime_1.assert(method.O.is(r)); - return Promise.resolve(r); - } - /** - * Pushes response messages from the mock data to the output stream. - * If an error response, status or trailers are mocked, the stream is - * closed with the respective error. - * Otherwise, stream is completed successfully. - * - * The returned promise resolves when the stream is closed. It should - * not reject. If it does, code is broken. - */ - streamResponses(method, stream, abort) { - return __awaiter4(this, void 0, void 0, function* () { - const messages = []; - if (this.data.response === void 0) { - messages.push(method.O.create()); - } else if (Array.isArray(this.data.response)) { - for (let msg of this.data.response) { - runtime_1.assert(method.O.is(msg)); - messages.push(msg); + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + let archivePath = ""; + try { + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod, + enableCrossOsArchive + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + return void 0; + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core14.info("Lookup only - skipping download"); + return cacheEntry.cacheKey; + } + archivePath = path6.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core14.debug(`Archive Path: ${archivePath}`); + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core14.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core14.info("Cache restored successfully"); + return cacheEntry.cacheKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core14.error(`Failed to restore: ${error4.message}`); + } else { + core14.warning(`Failed to restore: ${error4.message}`); } - } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { - runtime_1.assert(method.O.is(this.data.response)); - messages.push(this.data.response); } + } finally { try { - yield delay(this.responseDelay, abort)(void 0); + yield utils.unlinkFile(archivePath); } catch (error4) { - stream.notifyError(error4); - return; + core14.debug(`Failed to delete archive: ${error4}`); } - if (this.data.response instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.response); - return; + } + return void 0; + }); + } + function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core14.debug("Resolved Keys:"); + core14.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + let archivePath = ""; + try { + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + const compressionMethod = yield utils.getCompressionMethod(); + const request = { + key: primaryKey, + restoreKeys, + version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) + }; + const response = yield twirpClient.GetCacheEntryDownloadURL(request); + if (!response.ok) { + core14.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); + return void 0; } - for (let msg of messages) { - stream.notifyMessage(msg); - try { - yield delay(this.betweenResponseDelay, abort)(void 0); - } catch (error4) { - stream.notifyError(error4); - return; + const isRestoreKeyMatch = request.key !== response.matchedKey; + if (isRestoreKeyMatch) { + core14.info(`Cache hit for restore-key: ${response.matchedKey}`); + } else { + core14.info(`Cache hit for: ${response.matchedKey}`); + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core14.info("Lookup only - skipping download"); + return response.matchedKey; + } + archivePath = path6.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core14.debug(`Archive path: ${archivePath}`); + core14.debug(`Starting download of archive to: ${archivePath}`); + yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + if (core14.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core14.info("Cache restored successfully"); + return response.matchedKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core14.error(`Failed to restore: ${error4.message}`); + } else { + core14.warning(`Failed to restore: ${error4.message}`); } } - if (this.data.status instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.status); - return; + } finally { + try { + if (archivePath) { + yield utils.unlinkFile(archivePath); + } + } catch (error4) { + core14.debug(`Failed to delete archive: ${error4}`); } - if (this.data.trailers instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.trailers); - return; + } + return void 0; + }); + } + function saveCache4(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core14.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + checkKey(key); + switch (cacheServiceVersion) { + case "v2": + return yield saveCacheV2(paths, key, options, enableCrossOsArchive); + case "v1": + default: + return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + } + }); + } + exports2.saveCache = saveCache4; + function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { + var _a, _b, _c, _d, _e; + return __awaiter4(this, void 0, void 0, function* () { + const compressionMethod = yield utils.getCompressionMethod(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core14.debug("Cache Paths:"); + core14.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path6.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core14.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core14.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); } - stream.notifyComplete(); - }); - } - // Creates a promise for response status from the mock data. - promiseStatus() { - var _a; - const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; - return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); - } - // Creates a promise for response trailers from the mock data. - promiseTrailers() { - var _a; - const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; - return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); - } - maybeSuppressUncaught(...promise) { - if (this.suppressUncaughtRejections) { - for (let p of promise) { - p.catch(() => { - }); + const fileSizeLimit = 10 * 1024 * 1024 * 1024; + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core14.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core14.debug("Reserving Cache"); + const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod, + enableCrossOsArchive, + cacheSize: archiveFileSize + }); + if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { + cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { + throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); + } else { + throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); + } + core14.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError2.name) { + core14.info(`Failed to save: ${typedError.message}`); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core14.error(`Failed to save: ${typedError.message}`); + } else { + core14.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core14.debug(`Failed to delete archive: ${error4}`); } } - } - mergeOptions(options) { - return rpc_options_1.mergeRpcOptions({}, options); - } - unary(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { - }).then(delay(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { - }).then(delay(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { - }).then(delay(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); - } - serverStreaming(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); - } - clientStreaming(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { - }).then(delay(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { - }).then(delay(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { - }).then(delay(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); - } - duplex(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); - } - }; - exports2.TestTransport = TestTransport; - TestTransport.defaultHeaders = { - responseHeader: "test" - }; - TestTransport.defaultStatus = { - code: "OK", - detail: "all good" - }; - TestTransport.defaultTrailers = { - responseTrailer: "test" - }; - function delay(ms, abort) { - return (v) => new Promise((resolve5, reject) => { - if (abort === null || abort === void 0 ? void 0 : abort.aborted) { - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - } else { - const id = setTimeout(() => resolve5(v), ms); - if (abort) { - abort.addEventListener("abort", (ev) => { - clearTimeout(id); - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - }); + return cacheId; + }); + } + function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); + const compressionMethod = yield utils.getCompressionMethod(); + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core14.debug("Cache Paths:"); + core14.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path6.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core14.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core14.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core14.debug(`File Size: ${archiveFileSize}`); + options.archiveSizeBytes = archiveFileSize; + core14.debug("Reserving Cache"); + const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); + const request = { + key, + version + }; + let signedUploadUrl; + try { + const response = yield twirpClient.CreateCacheEntry(request); + if (!response.ok) { + if (response.message) { + core14.warning(`Cache reservation failed: ${response.message}`); + } + throw new Error(response.message || "Response was not ok"); + } + signedUploadUrl = response.signedUploadUrl; + } catch (error4) { + core14.debug(`Failed to reserve cache: ${error4}`); + throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); + } + core14.debug(`Attempting to upload cache located at: ${archivePath}`); + yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); + const finalizeRequest = { + key, + version, + sizeBytes: `${archiveFileSize}` + }; + const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); + core14.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); + if (!finalizeResponse.ok) { + if (finalizeResponse.message) { + throw new FinalizeCacheError(finalizeResponse.message); + } + throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); + } + cacheId = parseInt(finalizeResponse.entryId); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError2.name) { + core14.info(`Failed to save: ${typedError.message}`); + } else if (typedError.name === FinalizeCacheError.name) { + core14.warning(typedError.message); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core14.error(`Failed to save: ${typedError.message}`); + } else { + core14.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core14.debug(`Failed to delete archive: ${error4}`); } } + return cacheId; }); } - var TestInputStream = class { - constructor(data, abort) { - this._completed = false; - this._sent = []; - this.data = data; - this.abort = abort; - } - get sent() { - return this._sent; - } - get completed() { - return this._completed; - } - send(message) { - if (this.data.inputMessage instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputMessage); - } - const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; - return Promise.resolve(void 0).then(() => { - this._sent.push(message); - }).then(delay(delayMs, this.abort)); - } - complete() { - if (this.data.inputComplete instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputComplete); - } - const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; - return Promise.resolve(void 0).then(() => { - this._completed = true; - }).then(delay(delayMs, this.abort)); - } - }; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js -var require_rpc_interceptor = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { +// node_modules/@actions/tool-cache/lib/manifest.js +var require_manifest = __commonJS({ + "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; - var runtime_1 = require_commonjs11(); - function stackIntercept(kind, transport, method, options, input) { - var _a, _b, _c, _d; - if (kind == "unary") { - let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); - for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); - } - return tail(method, input, options); - } - if (kind == "serverStreaming") { - let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); - for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); - } - return tail(method, input, options); - } - if (kind == "clientStreaming") { - let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); - for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); - } - return tail(method, options); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - if (kind == "duplex") { - let tail = (mtd, opt) => transport.duplex(mtd, opt); - for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); - } - return tail(method, options); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - runtime_1.assertNever(kind); - } - exports2.stackIntercept = stackIntercept; - function stackUnaryInterceptors(transport, method, input, options) { - return stackIntercept("unary", transport, method, options, input); - } - exports2.stackUnaryInterceptors = stackUnaryInterceptors; - function stackServerStreamingInterceptors(transport, method, input, options) { - return stackIntercept("serverStreaming", transport, method, options, input); - } - exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; - function stackClientStreamingInterceptors(transport, method, options) { - return stackIntercept("clientStreaming", transport, method, options); - } - exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; - function stackDuplexStreamingInterceptors(transport, method, options) { - return stackIntercept("duplex", transport, method, options); - } - exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js -var require_server_call_context = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerCallContextController = void 0; - var ServerCallContextController = class { - constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { - this._cancelled = false; - this._listeners = []; - this.method = method; - this.headers = headers; - this.deadline = deadline; - this.trailers = {}; - this._sendRH = sendResponseHeadersFn; - this.status = defaultStatus; + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - /** - * Set the call cancelled. - * - * Invokes all callbacks registered with onCancel() and - * sets `cancelled = true`. - */ - notifyCancelled() { - if (!this._cancelled) { - this._cancelled = true; - for (let l of this._listeners) { - l(); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - } - /** - * Send response headers. - */ - sendResponseHeaders(data) { - this._sendRH(data); - } - /** - * Is the call cancelled? - * - * When the client closes the connection before the server - * is done, the call is cancelled. - * - * If you want to cancel a request on the server, throw a - * RpcError with the CANCELLED status code. - */ - get cancelled() { - return this._cancelled; - } - /** - * Add a callback for cancellation. - */ - onCancel(callback) { - const l = this._listeners; - l.push(callback); - return () => { - let i = l.indexOf(callback); - if (i >= 0) - l.splice(i, 1); - }; - } - }; - exports2.ServerCallContextController = ServerCallContextController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js -var require_commonjs12 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var service_type_1 = require_service_type(); - Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { - return service_type_1.ServiceType; - } }); - var reflection_info_1 = require_reflection_info2(); - Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { - return reflection_info_1.readMethodOptions; - } }); - Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { - return reflection_info_1.readMethodOption; - } }); - Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { - return reflection_info_1.readServiceOption; - } }); - var rpc_error_1 = require_rpc_error(); - Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { - return rpc_error_1.RpcError; - } }); - var rpc_options_1 = require_rpc_options(); - Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { - return rpc_options_1.mergeRpcOptions; - } }); - var rpc_output_stream_1 = require_rpc_output_stream(); - Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { - return rpc_output_stream_1.RpcOutputStreamController; - } }); - var test_transport_1 = require_test_transport(); - Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { - return test_transport_1.TestTransport; - } }); - var deferred_1 = require_deferred(); - Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { - return deferred_1.Deferred; - } }); - Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { - return deferred_1.DeferredState; - } }); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { - return duplex_streaming_call_1.DuplexStreamingCall; - } }); - var client_streaming_call_1 = require_client_streaming_call(); - Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { - return client_streaming_call_1.ClientStreamingCall; - } }); - var server_streaming_call_1 = require_server_streaming_call(); - Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { - return server_streaming_call_1.ServerStreamingCall; - } }); - var unary_call_1 = require_unary_call(); - Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { - return unary_call_1.UnaryCall; - } }); - var rpc_interceptor_1 = require_rpc_interceptor(); - Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { - return rpc_interceptor_1.stackIntercept; - } }); - Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackDuplexStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackClientStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackServerStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackUnaryInterceptors; - } }); - var server_call_context_1 = require_server_call_context(); - Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { - return server_call_context_1.ServerCallContextController; - } }); - } -}); - -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js -var require_cachescope = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheScope = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var CacheScope$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheScope", [ - { - no: 1, - name: "scope", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "permission", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - } - ]); - } - create(value) { - const message = { scope: "", permission: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string scope */ - 1: - message.scope = reader.string(); - break; - case /* int64 permission */ - 2: - message.permission = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.scope !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); - if (message.permission !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - exports2.CacheScope = new CacheScope$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js -var require_cachemetadata = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { - "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheMetadata = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachescope_1 = require_cachescope(); - var CacheMetadata$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheMetadata", [ - { - no: 1, - name: "repository_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } - ]); - } - create(value) { - const message = { repositoryId: "0", scope: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int64 repository_id */ - 1: - message.repositoryId = reader.int64().toString(); - break; - case /* repeated github.actions.results.entities.v1.CacheScope scope */ - 2: - message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; + var semver8 = __importStar4(require_semver2()); + var core_1 = require_core(); + var os = require("os"); + var cp = require("child_process"); + var fs7 = require("fs"); + function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); + if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + file = candidate.files.find((item) => { + (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module2.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } else { + chk = semver8.satisfies(osVersion, item.platform_version); + } + } + return chk; + }); + if (file) { + (0, core_1.debug)(`matched ${candidate.version}`); + match = candidate; break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + } + if (match && file) { + result = Object.assign({}, match); + result.files = [file]; + } + return result; + }); + } + exports2._findMatch = _findMatch; + function _getOsVersion() { + const plat = os.platform(); + let version = ""; + if (plat === "darwin") { + version = cp.execSync("sw_vers -productVersion").toString(); + } else if (plat === "linux") { + const lsbContents = module2.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split("\n"); + for (const line of lines) { + const parts = line.split("="); + if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { + version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); + break; + } } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.repositoryId !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); - for (let i = 0; i < message.scope.length; i++) - cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; } - }; - exports2.CacheMetadata = new CacheMetadata$Type(); + return version; + } + exports2._getOsVersion = _getOsVersion; + function _readLinuxVersionFile() { + const lsbReleaseFile = "/etc/lsb-release"; + const osReleaseFile = "/etc/os-release"; + let contents = ""; + if (fs7.existsSync(lsbReleaseFile)) { + contents = fs7.readFileSync(lsbReleaseFile).toString(); + } else if (fs7.existsSync(osReleaseFile)) { + contents = fs7.readFileSync(osReleaseFile).toString(); + } + return contents; + } + exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js -var require_cache2 = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachemetadata_1 = require_cachemetadata(); - var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); - } - create(value) { - const message = { key: "", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* string version */ - 3: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - return message; + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.version !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - }; - exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); - var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_upload_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - create(value) { - const message = { ok: false, signedUploadUrl: "", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_upload_url */ - 2: - message.signedUploadUrl = reader.string(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; } }; - exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); - var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "size_bytes", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + } +}); + +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - create(value) { - const message = { key: "", sizeBytes: "0", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* int64 size_bytes */ - 3: - message.sizeBytes = reader.int64().toString(); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return message; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.sizeBytes !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); + }); } }; - exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); - var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "entry_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - ]); - } - create(value) { - const message = { ok: false, entryId: "0", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 entry_id */ - 2: - message.entryId = reader.int64().toString(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.entryId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); - var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "restore_keys", - kind: "scalar", - repeat: 2, - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - create(value) { - const message = { key: "", restoreKeys: [], version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* repeated string restore_keys */ - 3: - message.restoreKeys.push(reader.string()); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - for (let i = 0; i < message.restoreKeys.length; i++) - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - }; - exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); - var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_download_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "matched_key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - create(value) { - const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_download_url */ - 2: - message.signedDownloadUrl = reader.string(); - break; - case /* string matched_key */ - 3: - message.matchedKey = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedDownloadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); - if (message.matchedKey !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - }; - exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); - exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ - { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, - { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, - { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } - ]); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js -var require_cache_twirp_client = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; - var cache_1 = require_cache2(); - var CacheServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - }; - exports2.CacheServiceClientJSON = CacheServiceClientJSON; - var CacheServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - }; - exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; - } -}); - -// node_modules/@actions/cache/lib/internal/shared/util.js -var require_util10 = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.maskSecretUrls = exports2.maskSigUrl = void 0; - var core_1 = require_core(); - function maskSigUrl(url) { - if (!url) - return; - try { - const parsedUrl = new URL(url); - const signature = parsedUrl.searchParams.get("sig"); - if (signature) { - (0, core_1.setSecret)(signature); - (0, core_1.setSecret)(encodeURIComponent(signature)); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - } catch (error4) { - (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); - } - } - exports2.maskSigUrl = maskSigUrl; - function maskSecretUrls(body) { - if (typeof body !== "object" || body === null) { - (0, core_1.debug)("body is not an object or is null"); - return; + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { - maskSigUrl(body.signed_upload_url); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; } - if ("signed_download_url" in body && typeof body.signed_download_url === "string") { - maskSigUrl(body.signed_download_url); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - } - exports2.maskSecretUrls = maskSecretUrls; - } -}); - -// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js -var require_cacheTwirpClient = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.internalCacheTwirpClient = void 0; - var core_1 = require_core(); - var user_agent_1 = require_user_agent(); - var errors_1 = require_errors2(); - var config_1 = require_config(); - var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); - var cache_twirp_client_1 = require_cache_twirp_client(); - var util_1 = require_util10(); - var CacheServiceClient = class { - constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { - this.maxAttempts = 5; - this.baseRetryIntervalMilliseconds = 3e3; - this.retryMultiplier = 1.5; - const token = (0, cacheUtils_1.getRuntimeToken)(); - this.baseUrl = (0, config_1.getCacheServiceURL)(); - if (maxAttempts) { - this.maxAttempts = maxAttempts; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } - if (baseRetryIntervalMilliseconds) { - this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (retryMultiplier) { - this.retryMultiplier = retryMultiplier; + if (proxyAgent) { + return proxyAgent; } - this.httpClient = new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(token) - ]); + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - // This function satisfies the Rpc interface. It is compatible with the JSON - // JSON generated client. - request(service, method, contentType, data) { + _performExponentialBackoff(retryNumber) { return __awaiter4(this, void 0, void 0, function* () { - const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; - (0, core_1.debug)(`[Request] ${method} ${url}`); - const headers = { - "Content-Type": contentType - }; - try { - const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { - return this.httpClient.post(url, JSON.stringify(data), headers); - })); - return body; - } catch (error4) { - throw new Error(`Failed to ${method}: ${error4.message}`); - } + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); }); } - retryableRequest(operation) { + _processResponse(res, options) { return __awaiter4(this, void 0, void 0, function* () { - let attempt = 0; - let errorMessage = ""; - let rawBody = ""; - while (attempt < this.maxAttempts) { - let isRetryable = false; - try { - const response = yield operation(); - const statusCode = response.message.statusCode; - rawBody = yield response.readBody(); - (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); - (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); - const body = JSON.parse(rawBody); - (0, util_1.maskSecretUrls)(body); - (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); - if (this.isSuccessStatusCode(statusCode)) { - return { response, body }; - } - isRetryable = this.isRetryableHttpStatusCode(statusCode); - errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; - if (body.msg) { - if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { - throw new errors_1.UsageError(); + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; } - errorMessage = `${errorMessage}: ${body.msg}`; - } - } catch (error4) { - if (error4 instanceof SyntaxError) { - (0, core_1.debug)(`Raw Body: ${rawBody}`); - } - if (error4 instanceof errors_1.UsageError) { - throw error4; - } - if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { - throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); } - isRetryable = true; - errorMessage = error4.message; + return value; } - if (!isRetryable) { - throw new Error(`Received non-retryable error: ${errorMessage}`); + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { } - if (attempt + 1 === this.maxAttempts) { - throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); } - const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); - (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); - yield this.sleep(retryTimeMilliseconds); - attempt++; - } - throw new Error(`Request failed`); - }); - } - isSuccessStatusCode(statusCode) { - if (!statusCode) - return false; - return statusCode >= 200 && statusCode < 300; - } - isRetryableHttpStatusCode(statusCode) { - if (!statusCode) - return false; - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.GatewayTimeout, - http_client_1.HttpCodes.InternalServerError, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.TooManyRequests - ]; - return retryableStatusCodes.includes(statusCode); - } - sleep(milliseconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve5) => setTimeout(resolve5, milliseconds)); + })); }); } - getExponentialRetryTimeMilliseconds(attempt) { - if (attempt < 0) { - throw new Error("attempt should be a positive integer"); - } - if (attempt === 0) { - return this.baseRetryIntervalMilliseconds; - } - const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); - const maxTime = minTime * this.retryMultiplier; - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); - } }; - function internalCacheTwirpClient(options) { - const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); - return new cache_twirp_client_1.CacheServiceClientJSON(client); - } - exports2.internalCacheTwirpClient = internalCacheTwirpClient; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/cache/lib/internal/tar.js -var require_tar = __commonJS({ - "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74096,193 +77113,56 @@ var require_tar = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTar = exports2.extractTar = exports2.listTar = void 0; - var exec_1 = require_exec(); - var io6 = __importStar4(require_io()); - var fs_1 = require("fs"); - var path6 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var constants_1 = require_constants7(); - var IS_WINDOWS = process.platform === "win32"; - function getTarPath() { - return __awaiter4(this, void 0, void 0, function* () { - switch (process.platform) { - case "win32": { - const gnuTar = yield utils.getGnuTarPathOnWindows(); - const systemTar = constants_1.SystemTarPathOnWindows; - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else if ((0, fs_1.existsSync)(systemTar)) { - return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; - } - break; - } - case "darwin": { - const gnuTar = yield io6.which("gtar", false); - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else { - return { - path: yield io6.which("tar", true), - type: constants_1.ArchiveToolType.BSD - }; - } - } - default: - break; - } - return { - path: yield io6.which("tar", true), - type: constants_1.ArchiveToolType.GNU - }; - }); - } - function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - const args = [`"${tarPath.path}"`]; - const cacheFileName = utils.getCacheFileName(compressionMethod); - const tarFile = "cache.tar"; - const workingDirectory = getWorkingDirectory(); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (type2) { - case "create": - args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); - break; - case "extract": - args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path6.sep}`, "g"), "/")); - break; - case "list": - args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), "-P"); - break; - } - if (tarPath.type === constants_1.ArchiveToolType.GNU) { - switch (process.platform) { - case "win32": - args.push("--force-local"); - break; - case "darwin": - args.push("--delay-directory-restore"); - break; - } - } - return args; - }); - } - function getCommands(compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - let args; - const tarPath = yield getTarPath(); - const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); - const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - if (BSD_TAR_ZSTD && type2 !== "create") { - args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; - } else { - args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; - } - if (BSD_TAR_ZSTD) { - return args; - } - return [args.join(" ")]; - }); - } - function getWorkingDirectory() { - var _a; - return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); - } - function getDecompressionProgram(tarPath, compressionMethod, archivePath) { - return __awaiter4(this, void 0, void 0, function* () { - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -d --long=30 --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path6.sep}`, "g"), "/") - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -d --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path6.sep}`, "g"), "/") - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; - default: - return ["-z"]; - } - }); - } - function getCompressionProgram(tarPath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const cacheFileName = utils.getCacheFileName(compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --long=30 --force -o", - cacheFileName.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), - constants_1.TarFilename - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --force -o", - cacheFileName.replace(new RegExp(`\\${path6.sep}`, "g"), "/"), - constants_1.TarFilename - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; - default: - return ["-z"]; - } - }); - } - function execCommands(commands, cwd) { - return __awaiter4(this, void 0, void 0, function* () { - for (const command of commands) { - try { - yield (0, exec_1.exec)(command, void 0, { - cwd, - env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) - }); - } catch (error4) { - throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); - } - } - }); - } - function listTar(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const commands = yield getCommands(compressionMethod, "list", archivePath); - yield execCommands(commands); - }); - } - exports2.listTar = listTar; - function extractTar2(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const workingDirectory = getWorkingDirectory(); - yield io6.mkdirP(workingDirectory); - const commands = yield getCommands(compressionMethod, "extract", archivePath); - yield execCommands(commands); - }); - } - exports2.extractTar = extractTar2; - function createTar(archiveFolder, sourceDirectories, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - (0, fs_1.writeFileSync)(path6.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); - const commands = yield getCommands(compressionMethod, "create"); - yield execCommands(commands, archiveFolder); - }); - } - exports2.createTar = createTar; + exports2.RetryHelper = void 0; + var core14 = __importStar4(require_core()); + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); + } + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); + } + } + execute(action, isRetryable) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 1; + while (attempt < this.maxAttempts) { + try { + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; + } + core14.info(err.message); + } + const seconds = this.getSleepAmount(); + core14.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); + attempt++; + } + return yield action(); + }); + } + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + } + sleep(seconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => setTimeout(resolve5, seconds * 1e3)); + }); + } + }; + exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/cache/lib/cache.js -var require_cache3 = __commonJS({ - "node_modules/@actions/cache/lib/cache.js"(exports2) { +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74339,517 +77219,610 @@ var require_cache3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; var core14 = __importStar4(require_core()); + var io6 = __importStar4(require_io()); + var crypto = __importStar4(require("crypto")); + var fs7 = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os = __importStar4(require("os")); var path6 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var cacheHttpClient = __importStar4(require_cacheHttpClient()); - var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); - var config_1 = require_config(); - var tar_1 = require_tar(); - var http_client_1 = require_lib(); - var ValidationError = class _ValidationError extends Error { - constructor(message) { - super(message); - this.name = "ValidationError"; - Object.setPrototypeOf(this, _ValidationError.prototype); - } - }; - exports2.ValidationError = ValidationError; - var ReserveCacheError2 = class _ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = "ReserveCacheError"; - Object.setPrototypeOf(this, _ReserveCacheError.prototype); - } - }; - exports2.ReserveCacheError = ReserveCacheError2; - var FinalizeCacheError = class _FinalizeCacheError extends Error { - constructor(message) { - super(message); - this.name = "FinalizeCacheError"; - Object.setPrototypeOf(this, _FinalizeCacheError.prototype); + var httpm = __importStar4(require_lib5()); + var semver8 = __importStar4(require_semver2()); + var stream = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); } }; - exports2.FinalizeCacheError = FinalizeCacheError; - function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } - } - function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); - } - } - function isFeatureAvailable() { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - switch (cacheServiceVersion) { - case "v2": - return !!process.env["ACTIONS_RESULTS_URL"]; - case "v1": - default: - return !!process.env["ACTIONS_CACHE_URL"]; - } - } - exports2.isFeatureAvailable = isFeatureAvailable; - function restoreCache4(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.HTTPError = HTTPError; + var IS_WINDOWS = process.platform === "win32"; + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core14.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - switch (cacheServiceVersion) { - case "v2": - return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - case "v1": - default: - return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - } + dest = dest || path6.join(_getTempDirectory(), crypto.randomUUID()); + yield io6.mkdirP(path6.dirname(dest)); + core14.debug(`Downloading ${url}`); + core14.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; + } + } + return true; + }); }); } - exports2.restoreCache = restoreCache4; - function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core14.debug("Resolved Keys:"); - core14.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + if (fs7.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); } - for (const key of keys) { - checkKey(key); + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core14.debug("set auth"); + if (headers === void 0) { + headers = {}; + } + headers.authorization = auth; } - const compressionMethod = yield utils.getCompressionMethod(); - let archivePath = ""; + const response = yield http.get(url, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError(response.message.statusCode); + core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; + } + const pipeline = util.promisify(stream.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; try { - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod, - enableCrossOsArchive - }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - return void 0; - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core14.info("Lookup only - skipping download"); - return cacheEntry.cacheKey; - } - archivePath = path6.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core14.debug(`Archive Path: ${archivePath}`); - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core14.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core14.info("Cache restored successfully"); - return cacheEntry.cacheKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core14.error(`Failed to restore: ${error4.message}`); - } else { - core14.warning(`Failed to restore: ${error4.message}`); + yield pipeline(readStream, fs7.createWriteStream(dest)); + core14.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core14.debug("download failed"); + try { + yield io6.rmRF(dest); + } catch (err) { + core14.debug(`Failed to delete '${dest}'. ${err.message}`); } } - } finally { + } + }); + } + function extract7z(file, dest, _7zPath) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core14.debug(`Failed to delete archive: ${error4}`); + const logLevel = core14.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file + ]; + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } else { + const escapedScript = path6.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true + }; + try { + const powershellPath = yield io6.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); } } - return void 0; + return dest; }); } - function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core14.debug("Resolved Keys:"); - core14.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + core14.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + core14.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + if (core14.isDebug() && !flags.includes("v")) { + args.push("-v"); + } + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); + } + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); + } + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; + }); + } + exports2.extractTar = extractTar2; + function extractXar(file, dest, flags = []) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + args.push("-x", "-C", dest, "-f", file); + if (core14.isDebug()) { + args.push("-v"); + } + const xarPath = yield io6.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; + }); + } + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } else { + yield extractZipNix(file, dest); + } + return dest; + }); + } + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io6.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core14.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io6.which("powershell", true); + core14.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); + } + }); + } + function extractZipNix(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const unzipPath = yield io6.which("unzip", true); + const args = [file]; + if (!core14.isDebug()) { + args.unshift("-q"); + } + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); + }); + } + function cacheDir(sourceDir, tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver8.clean(version) || version; + arch = arch || os.arch(); + core14.debug(`Caching tool ${tool} ${version} ${arch}`); + core14.debug(`source dir: ${sourceDir}`); + if (!fs7.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); + } + const destPath = yield _createToolPath(tool, version, arch); + for (const itemName of fs7.readdirSync(sourceDir)) { + const s = path6.join(sourceDir, itemName); + yield io6.cp(s, destPath, { recursive: true }); + } + _completeToolPath(tool, version, arch); + return destPath; + }); + } + exports2.cacheDir = cacheDir; + function cacheFile(sourceFile, targetFile, tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver8.clean(version) || version; + arch = arch || os.arch(); + core14.debug(`Caching tool ${tool} ${version} ${arch}`); + core14.debug(`source file: ${sourceFile}`); + if (!fs7.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); + } + const destFolder = yield _createToolPath(tool, version, arch); + const destPath = path6.join(destFolder, targetFile); + core14.debug(`destination file ${destPath}`); + yield io6.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch); + return destFolder; + }); + } + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch) { + if (!toolName) { + throw new Error("toolName parameter is required"); + } + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); + } + arch = arch || os.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions2(toolName, arch); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; + } + let toolPath = ""; + if (versionSpec) { + versionSpec = semver8.clean(versionSpec) || ""; + const cachePath = path6.join(_getCacheDirectory(), toolName, versionSpec, arch); + core14.debug(`checking cache: ${cachePath}`); + if (fs7.existsSync(cachePath) && fs7.existsSync(`${cachePath}.complete`)) { + core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); + toolPath = cachePath; + } else { + core14.debug("not found"); + } + } + return toolPath; + } + exports2.find = find2; + function findAllVersions2(toolName, arch) { + const versions = []; + arch = arch || os.arch(); + const toolPath = path6.join(_getCacheDirectory(), toolName); + if (fs7.existsSync(toolPath)) { + const children = fs7.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path6.join(toolPath, child, arch || ""); + if (fs7.existsSync(fullPath) && fs7.existsSync(`${fullPath}.complete`)) { + versions.push(child); + } + } + } + } + return versions; + } + exports2.findAllVersions = findAllVersions2; + function getManifestFromRepo(owner, repo, auth, branch = "master") { + return __awaiter4(this, void 0, void 0, function* () { + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core14.debug("set auth"); + headers.authorization = auth; } - for (const key of keys) { - checkKey(key); + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; } - let archivePath = ""; - try { - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - const compressionMethod = yield utils.getCompressionMethod(); - const request = { - key: primaryKey, - restoreKeys, - version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) - }; - const response = yield twirpClient.GetCacheEntryDownloadURL(request); - if (!response.ok) { - core14.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); - return void 0; - } - const isRestoreKeyMatch = request.key !== response.matchedKey; - if (isRestoreKeyMatch) { - core14.info(`Cache hit for restore-key: ${response.matchedKey}`); - } else { - core14.info(`Cache hit for: ${response.matchedKey}`); - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core14.info("Lookup only - skipping download"); - return response.matchedKey; - } - archivePath = path6.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core14.debug(`Archive path: ${archivePath}`); - core14.debug(`Starting download of archive to: ${archivePath}`); - yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - if (core14.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core14.info("Cache restored successfully"); - return response.matchedKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core14.error(`Failed to restore: ${error4.message}`); - } else { - core14.warning(`Failed to restore: ${error4.message}`); - } + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; } - } finally { + } + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); try { - if (archivePath) { - yield utils.unlinkFile(archivePath); - } - } catch (error4) { - core14.debug(`Failed to delete archive: ${error4}`); + releases = JSON.parse(versionsRaw); + } catch (_a) { + core14.debug("Invalid json"); } } - return void 0; + return releases; }); } - function saveCache4(paths, key, options, enableCrossOsArchive = false) { + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core14.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - checkKey(key); - switch (cacheServiceVersion) { - case "v2": - return yield saveCacheV2(paths, key, options, enableCrossOsArchive); - case "v1": - default: - return yield saveCacheV1(paths, key, options, enableCrossOsArchive); - } + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; }); } - exports2.saveCache = saveCache4; - function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { - var _a, _b, _c, _d, _e; + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { return __awaiter4(this, void 0, void 0, function* () { - const compressionMethod = yield utils.getCompressionMethod(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core14.debug("Cache Paths:"); - core14.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); - } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path6.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core14.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core14.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const fileSizeLimit = 10 * 1024 * 1024 * 1024; - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core14.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); - } - core14.debug("Reserving Cache"); - const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod, - enableCrossOsArchive, - cacheSize: archiveFileSize - }); - if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { - cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; - } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { - throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); - } else { - throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); - } - core14.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError2.name) { - core14.info(`Failed to save: ${typedError.message}`); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core14.error(`Failed to save: ${typedError.message}`); - } else { - core14.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core14.debug(`Failed to delete archive: ${error4}`); - } + if (!dest) { + dest = path6.join(_getTempDirectory(), crypto.randomUUID()); } - return cacheId; + yield io6.mkdirP(dest); + return dest; }); } - function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + function _createToolPath(tool, version, arch) { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); - const compressionMethod = yield utils.getCompressionMethod(); - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core14.debug("Cache Paths:"); - core14.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); - } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path6.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core14.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core14.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core14.debug(`File Size: ${archiveFileSize}`); - options.archiveSizeBytes = archiveFileSize; - core14.debug("Reserving Cache"); - const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); - const request = { - key, - version - }; - let signedUploadUrl; - try { - const response = yield twirpClient.CreateCacheEntry(request); - if (!response.ok) { - if (response.message) { - core14.warning(`Cache reservation failed: ${response.message}`); - } - throw new Error(response.message || "Response was not ok"); - } - signedUploadUrl = response.signedUploadUrl; - } catch (error4) { - core14.debug(`Failed to reserve cache: ${error4}`); - throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); - } - core14.debug(`Attempting to upload cache located at: ${archivePath}`); - yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); - const finalizeRequest = { - key, - version, - sizeBytes: `${archiveFileSize}` - }; - const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); - core14.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); - if (!finalizeResponse.ok) { - if (finalizeResponse.message) { - throw new FinalizeCacheError(finalizeResponse.message); - } - throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); - } - cacheId = parseInt(finalizeResponse.entryId); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError2.name) { - core14.info(`Failed to save: ${typedError.message}`); - } else if (typedError.name === FinalizeCacheError.name) { - core14.warning(typedError.message); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core14.error(`Failed to save: ${typedError.message}`); - } else { - core14.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core14.debug(`Failed to delete archive: ${error4}`); - } + const folderPath = path6.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); + core14.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io6.rmRF(folderPath); + yield io6.rmRF(markerPath); + yield io6.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch) { + const folderPath = path6.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); + const markerPath = `${folderPath}.complete`; + fs7.writeFileSync(markerPath, ""); + core14.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver8.clean(versionSpec) || ""; + core14.debug(`isExplicit: ${c}`); + const valid3 = semver8.valid(c) != null; + core14.debug(`explicit? ${valid3}`); + return valid3; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { + let version = ""; + core14.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver8.gt(a, b)) { + return 1; } - return cacheId; + return -1; }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver8.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; + } + } + if (version) { + core14.debug(`matched: ${version}`); + } else { + core14.debug("match not found"); + } + return version; + } + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); } } }); -// node_modules/@actions/tool-cache/lib/manifest.js -var require_manifest = __commonJS({ - "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + module2.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return true; + } + return a !== a && b !== b; }; + } +}); + +// node_modules/@actions/http-client/lib/proxy.js +var require_proxy5 = __commonJS({ + "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver8 = __importStar4(require_semver2()); - var core_1 = require_core(); - var os = require("os"); - var cp = require("child_process"); - var fs7 = require("fs"); - function _findMatch(versionSpec, stable, candidates, archFilter) { - return __awaiter4(this, void 0, void 0, function* () { - const platFilter = os.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { - file = candidate.files.find((item) => { - (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module2.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } else { - chk = semver8.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - (0, core_1.debug)(`matched ${candidate.version}`); - match = candidate; - break; - } - } + exports2.getProxyUrl = getProxyUrl; + exports2.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (match && file) { - result = Object.assign({}, match); - result.files = [file]; + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - return result; - }); + } else { + return void 0; + } } - exports2._findMatch = _findMatch; - function _getOsVersion() { - const plat = os.platform(); - let version = ""; - if (plat === "darwin") { - version = cp.execSync("sw_vers -productVersion").toString(); - } else if (plat === "linux") { - const lsbContents = module2.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split("\n"); - for (const line of lines) { - const parts = line.split("="); - if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { - version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); - break; - } - } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - return version; - } - exports2._getOsVersion = _getOsVersion; - function _readLinuxVersionFile() { - const lsbReleaseFile = "/etc/lsb-release"; - const osReleaseFile = "/etc/os-release"; - let contents = ""; - if (fs7.existsSync(lsbReleaseFile)) { - contents = fs7.readFileSync(lsbReleaseFile).toString(); - } else if (fs7.existsSync(osReleaseFile)) { - contents = fs7.readFileSync(osReleaseFile).toString(); + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; } - return contents; - } - exports2._readLinuxVersionFile = _readLinuxVersionFile; + }; } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib6 = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74869,15 +77842,25 @@ var require_retry_helper = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve5) { @@ -74906,629 +77889,616 @@ var require_retry_helper = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core14 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); - } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); - } + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy5()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - execute(action, isRetryable) { + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core14.info(err.message); - } - const seconds = this.getSleepAmount(); - core14.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); + }); + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - return yield action(); + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); }); } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - sleep(seconds) { + del(requestUrl, additionalHeaders) { return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve5) => setTimeout(resolve5, seconds * 1e3)); + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); }); } - }; - exports2.RetryHelper = RetryHelper; - } -}); - -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); }); } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core14 = __importStar4(require_core()); - var io6 = __importStar4(require_io()); - var crypto = __importStar4(require("crypto")); - var fs7 = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os = __importStar4(require("os")); - var path6 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver8 = __importStar4(require_semver2()); - var stream = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.HTTPError = HTTPError; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path6.join(_getTempDirectory(), crypto.randomUUID()); - yield io6.mkdirP(path6.dirname(dest)); - core14.debug(`Downloading ${url}`); - core14.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs7.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - if (auth) { - core14.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + postJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - headers.authorization = auth; - } - const response = yield http.get(url, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError(response.message.statusCode); - core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - const pipeline = util.promisify(stream.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs7.createWriteStream(dest)); - core14.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core14.debug("download failed"); - try { - yield io6.rmRF(dest); - } catch (err) { - core14.debug(`Failed to delete '${dest}'. ${err.message}`); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); + } } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core14.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); - } - } else { - const escapedScript = path6.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io6.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core14.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); }); - core14.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core14.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - args.push("-x", "-C", dest, "-f", file); - if (core14.isDebug()) { - args.push("-v"); - } - const xarPath = yield io6.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io6.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core14.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io6.which("powershell", true); - core14.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); - } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io6.which("unzip", true); - const args = [file]; - if (!core14.isDebug()) { - args.unshift("-q"); + req.end(); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir(sourceDir, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch = arch || os.arch(); - core14.debug(`Caching tool ${tool} ${version} ${arch}`); - core14.debug(`source dir: ${sourceDir}`); - if (!fs7.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const destPath = yield _createToolPath(tool, version, arch); - for (const itemName of fs7.readdirSync(sourceDir)) { - const s = path6.join(sourceDir, itemName); - yield io6.cp(s, destPath, { recursive: true }); + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; } - _completeToolPath(tool, version, arch); - return destPath; - }); - } - exports2.cacheDir = cacheDir; - function cacheFile(sourceFile, targetFile, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch = arch || os.arch(); - core14.debug(`Caching tool ${tool} ${version} ${arch}`); - core14.debug(`source file: ${sourceFile}`); - if (!fs7.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } } - const destFolder = yield _createToolPath(tool, version, arch); - const destPath = path6.join(destFolder, targetFile); - core14.debug(`destination file ${destPath}`); - yield io6.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); - } - arch = arch || os.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions2(toolName, arch); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + return info7; } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver8.clean(versionSpec) || ""; - const cachePath = path6.join(_getCacheDirectory(), toolName, versionSpec, arch); - core14.debug(`checking cache: ${cachePath}`); - if (fs7.existsSync(cachePath) && fs7.existsSync(`${cachePath}.complete`)) { - core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); - toolPath = cachePath; - } else { - core14.debug("not found"); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - return toolPath; - } - exports2.find = find2; - function findAllVersions2(toolName, arch) { - const versions = []; - arch = arch || os.arch(); - const toolPath = path6.join(_getCacheDirectory(), toolName); - if (fs7.existsSync(toolPath)) { - const children = fs7.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path6.join(toolPath, child, arch || ""); - if (fs7.existsSync(fullPath) && fs7.existsSync(`${fullPath}.complete`)) { - versions.push(child); - } + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; } } - } - return versions; - } - exports2.findAllVersions = findAllVersions2; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core14.debug("set auth"); - headers.authorization = auth; + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + if (clientHeader !== void 0) { + return clientHeader; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; + return _default2; + } + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; + } } } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core14.debug("Invalid json"); + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; } } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path6.join(_getTempDirectory(), crypto.randomUUID()); + if (clientHeader !== void 0) { + return clientHeader; } - yield io6.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path6.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); - core14.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io6.rmRF(folderPath); - yield io6.rmRF(markerPath); - yield io6.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch) { - const folderPath = path6.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); - const markerPath = `${folderPath}.complete`; - fs7.writeFileSync(markerPath, ""); - core14.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver8.clean(versionSpec) || ""; - core14.debug(`isExplicit: ${c}`); - const valid3 = semver8.valid(c) != null; - core14.debug(`explicit? ${valid3}`); - return valid3; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core14.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver8.gt(a, b)) { - return 1; + return _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver8.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (!useProxy) { + agent = this._agent; } - } - if (version) { - core14.debug(`matched: ${version}`); - } else { - core14.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - return true; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); + } + })); + }); } - return a !== a && b !== b; }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -76096,78 +79066,476 @@ var require_config2 = __commonJS({ if (!ghWorkspaceDir) { throw new Error("Unable to get the GITHUB_WORKSPACE env variable"); } - return ghWorkspaceDir; - } - function getConcurrency() { - const numCPUs = os_1.default.cpus().length; - let concurrencyCap = 32; - if (numCPUs > 4) { - const concurrency = 16 * numCPUs; - concurrencyCap = concurrency > 300 ? 300 : concurrency; + return ghWorkspaceDir; + } + function getConcurrency() { + const numCPUs = os_1.default.cpus().length; + let concurrencyCap = 32; + if (numCPUs > 4) { + const concurrency = 16 * numCPUs; + concurrencyCap = concurrency > 300 ? 300 : concurrency; + } + const concurrencyOverride = process.env["ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY"]; + if (concurrencyOverride) { + const concurrency = parseInt(concurrencyOverride); + if (isNaN(concurrency) || concurrency < 1) { + throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY env variable"); + } + if (concurrency < concurrencyCap) { + (0, core_1.info)(`Set concurrency based on the value set in ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY.`); + return concurrency; + } + (0, core_1.info)(`ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY is higher than the cap of ${concurrencyCap} based on the number of cpus. Set it to the maximum value allowed.`); + return concurrencyCap; + } + return 5; + } + function getUploadChunkTimeout() { + const timeoutVar = process.env["ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS"]; + if (!timeoutVar) { + return 3e5; + } + const timeout = parseInt(timeoutVar); + if (isNaN(timeout)) { + throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS env variable"); + } + return timeout; + } + function getMaxArtifactListCount() { + const maxCountVar = process.env["ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT"] || "1000"; + const maxCount = parseInt(maxCountVar); + if (isNaN(maxCount) || maxCount < 1) { + throw new Error("Invalid value set for ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT env variable"); + } + return maxCount; + } + } +}); + +// node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js +var require_timestamp = __commonJS({ + "node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Timestamp = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var runtime_6 = require_commonjs11(); + var runtime_7 = require_commonjs11(); + var Timestamp$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.Timestamp", [ + { + no: 1, + name: "seconds", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 2, + name: "nanos", + kind: "scalar", + T: 5 + /*ScalarType.INT32*/ + } + ]); + } + /** + * Creates a new `Timestamp` for the current time. + */ + now() { + const msg = this.create(); + const ms = Date.now(); + msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); + msg.nanos = ms % 1e3 * 1e6; + return msg; + } + /** + * Converts a `Timestamp` to a JavaScript Date. + */ + toDate(message) { + return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1e3 + Math.ceil(message.nanos / 1e6)); + } + /** + * Converts a JavaScript Date to a `Timestamp`. + */ + fromDate(date) { + const msg = this.create(); + const ms = date.getTime(); + msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); + msg.nanos = ms % 1e3 * 1e6; + return msg; + } + /** + * In JSON format, the `Timestamp` type is encoded as a string + * in the RFC 3339 format. + */ + internalJsonWrite(message, options) { + let ms = runtime_6.PbLong.from(message.seconds).toNumber() * 1e3; + if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) + throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); + if (message.nanos < 0) + throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative."); + let z = "Z"; + if (message.nanos > 0) { + let nanosStr = (message.nanos + 1e9).toString().substring(1); + if (nanosStr.substring(3) === "000000") + z = "." + nanosStr.substring(0, 3) + "Z"; + else if (nanosStr.substring(6) === "000") + z = "." + nanosStr.substring(0, 6) + "Z"; + else + z = "." + nanosStr + "Z"; + } + return new Date(ms).toISOString().replace(".000Z", z); + } + /** + * In JSON format, the `Timestamp` type is encoded as a string + * in the RFC 3339 format. + */ + internalJsonRead(json2, options, target) { + if (typeof json2 !== "string") + throw new Error("Unable to parse Timestamp from JSON " + (0, runtime_5.typeofJsonValue)(json2) + "."); + let matches = json2.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/); + if (!matches) + throw new Error("Unable to parse Timestamp from JSON. Invalid format."); + let ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z")); + if (Number.isNaN(ms)) + throw new Error("Unable to parse Timestamp from JSON. Invalid value."); + if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) + throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); + if (!target) + target = this.create(); + target.seconds = runtime_6.PbLong.from(ms / 1e3).toString(); + target.nanos = 0; + if (matches[7]) + target.nanos = parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1e9; + return target; + } + create(value) { + const message = { seconds: "0", nanos: 0 }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 seconds */ + 1: + message.seconds = reader.int64().toString(); + break; + case /* int32 nanos */ + 2: + message.nanos = reader.int32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.seconds !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.seconds); + if (message.nanos !== 0) + writer.tag(2, runtime_1.WireType.Varint).int32(message.nanos); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.Timestamp = new Timestamp$Type(); + } +}); + +// node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js +var require_wrappers = __commonJS({ + "node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BytesValue = exports2.StringValue = exports2.BoolValue = exports2.UInt32Value = exports2.Int32Value = exports2.UInt64Value = exports2.Int64Value = exports2.FloatValue = exports2.DoubleValue = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var runtime_6 = require_commonjs11(); + var runtime_7 = require_commonjs11(); + var DoubleValue$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.DoubleValue", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 1 + /*ScalarType.DOUBLE*/ + } + ]); + } + /** + * Encode `DoubleValue` to JSON number. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(2, message.value, "value", false, true); + } + /** + * Decode `DoubleValue` from JSON number. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + return target; + } + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* double value */ + 1: + message.value = reader.double(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Bit64).double(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.DoubleValue = new DoubleValue$Type(); + var FloatValue$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.FloatValue", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 2 + /*ScalarType.FLOAT*/ + } + ]); + } + /** + * Encode `FloatValue` to JSON number. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(1, message.value, "value", false, true); + } + /** + * Decode `FloatValue` from JSON number. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + return target; + } + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* float value */ + 1: + message.value = reader.float(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Bit32).float(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FloatValue = new FloatValue$Type(); + var Int64Value$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.Int64Value", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + /** + * Encode `Int64Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true); + } + /** + * Decode `Int64Value` from JSON string. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.INT64, runtime_2.LongType.STRING, "value"); + return target; + } + create(value) { + const message = { value: "0" }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 value */ + 1: + message.value = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== "0") + writer.tag(1, runtime_3.WireType.Varint).int64(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.Int64Value = new Int64Value$Type(); + var UInt64Value$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.UInt64Value", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 4 + /*ScalarType.UINT64*/ + } + ]); + } + /** + * Encode `UInt64Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true); } - const concurrencyOverride = process.env["ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY"]; - if (concurrencyOverride) { - const concurrency = parseInt(concurrencyOverride); - if (isNaN(concurrency) || concurrency < 1) { - throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY env variable"); - } - if (concurrency < concurrencyCap) { - (0, core_1.info)(`Set concurrency based on the value set in ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY.`); - return concurrency; - } - (0, core_1.info)(`ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY is higher than the cap of ${concurrencyCap} based on the number of cpus. Set it to the maximum value allowed.`); - return concurrencyCap; + /** + * Decode `UInt64Value` from JSON string. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.UINT64, runtime_2.LongType.STRING, "value"); + return target; } - return 5; - } - function getUploadChunkTimeout() { - const timeoutVar = process.env["ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS"]; - if (!timeoutVar) { - return 3e5; + create(value) { + const message = { value: "0" }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; } - const timeout = parseInt(timeoutVar); - if (isNaN(timeout)) { - throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS env variable"); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* uint64 value */ + 1: + message.value = reader.uint64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - return timeout; - } - function getMaxArtifactListCount() { - const maxCountVar = process.env["ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT"] || "1000"; - const maxCount = parseInt(maxCountVar); - if (isNaN(maxCount) || maxCount < 1) { - throw new Error("Invalid value set for ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT env variable"); + internalBinaryWrite(message, writer, options) { + if (message.value !== "0") + writer.tag(1, runtime_3.WireType.Varint).uint64(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - return maxCount; - } - } -}); - -// node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js -var require_timestamp = __commonJS({ - "node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Timestamp = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var runtime_6 = require_commonjs11(); - var runtime_7 = require_commonjs11(); - var Timestamp$Type = class extends runtime_7.MessageType { + }; + exports2.UInt64Value = new UInt64Value$Type(); + var Int32Value$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.Timestamp", [ + super("google.protobuf.Int32Value", [ { no: 1, - name: "seconds", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 2, - name: "nanos", + name: "value", kind: "scalar", T: 5 /*ScalarType.INT32*/ @@ -76175,81 +79543,89 @@ var require_timestamp = __commonJS({ ]); } /** - * Creates a new `Timestamp` for the current time. + * Encode `Int32Value` to JSON string. */ - now() { - const msg = this.create(); - const ms = Date.now(); - msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); - msg.nanos = ms % 1e3 * 1e6; - return msg; + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(5, message.value, "value", false, true); } /** - * Converts a `Timestamp` to a JavaScript Date. + * Decode `Int32Value` from JSON string. */ - toDate(message) { - return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1e3 + Math.ceil(message.nanos / 1e6)); + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, 5, void 0, "value"); + return target; } - /** - * Converts a JavaScript Date to a `Timestamp`. - */ - fromDate(date) { - const msg = this.create(); - const ms = date.getTime(); - msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); - msg.nanos = ms % 1e3 * 1e6; - return msg; + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int32 value */ + 1: + message.value = reader.int32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Varint).int32(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.Int32Value = new Int32Value$Type(); + var UInt32Value$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.UInt32Value", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 13 + /*ScalarType.UINT32*/ + } + ]); } /** - * In JSON format, the `Timestamp` type is encoded as a string - * in the RFC 3339 format. + * Encode `UInt32Value` to JSON string. */ internalJsonWrite(message, options) { - let ms = runtime_6.PbLong.from(message.seconds).toNumber() * 1e3; - if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) - throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); - if (message.nanos < 0) - throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative."); - let z = "Z"; - if (message.nanos > 0) { - let nanosStr = (message.nanos + 1e9).toString().substring(1); - if (nanosStr.substring(3) === "000000") - z = "." + nanosStr.substring(0, 3) + "Z"; - else if (nanosStr.substring(6) === "000") - z = "." + nanosStr.substring(0, 6) + "Z"; - else - z = "." + nanosStr + "Z"; - } - return new Date(ms).toISOString().replace(".000Z", z); + return this.refJsonWriter.scalar(13, message.value, "value", false, true); } /** - * In JSON format, the `Timestamp` type is encoded as a string - * in the RFC 3339 format. + * Decode `UInt32Value` from JSON string. */ internalJsonRead(json2, options, target) { - if (typeof json2 !== "string") - throw new Error("Unable to parse Timestamp from JSON " + (0, runtime_5.typeofJsonValue)(json2) + "."); - let matches = json2.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/); - if (!matches) - throw new Error("Unable to parse Timestamp from JSON. Invalid format."); - let ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z")); - if (Number.isNaN(ms)) - throw new Error("Unable to parse Timestamp from JSON. Invalid value."); - if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) - throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); if (!target) target = this.create(); - target.seconds = runtime_6.PbLong.from(ms / 1e3).toString(); - target.nanos = 0; - if (matches[7]) - target.nanos = parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1e9; + target.value = this.refJsonReader.scalar(json2, 13, void 0, "value"); return target; } create(value) { - const message = { seconds: "0", nanos: 0 }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); + (0, runtime_5.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76257,13 +79633,9 @@ var require_timestamp = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* int64 seconds */ + case /* uint32 value */ 1: - message.seconds = reader.int64().toString(); - break; - case /* int32 nanos */ - 2: - message.nanos = reader.int32(); + message.value = reader.uint32(); break; default: let u = options.readUnknownField; @@ -76271,68 +79643,50 @@ var require_timestamp = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.seconds !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.seconds); - if (message.nanos !== 0) - writer.tag(2, runtime_1.WireType.Varint).int32(message.nanos); + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Varint).uint32(message.value); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.Timestamp = new Timestamp$Type(); - } -}); - -// node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js -var require_wrappers = __commonJS({ - "node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BytesValue = exports2.StringValue = exports2.BoolValue = exports2.UInt32Value = exports2.Int32Value = exports2.UInt64Value = exports2.Int64Value = exports2.FloatValue = exports2.DoubleValue = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var runtime_6 = require_commonjs11(); - var runtime_7 = require_commonjs11(); - var DoubleValue$Type = class extends runtime_7.MessageType { + exports2.UInt32Value = new UInt32Value$Type(); + var BoolValue$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.DoubleValue", [ + super("google.protobuf.BoolValue", [ { no: 1, name: "value", kind: "scalar", - T: 1 - /*ScalarType.DOUBLE*/ + T: 8 + /*ScalarType.BOOL*/ } ]); } /** - * Encode `DoubleValue` to JSON number. + * Encode `BoolValue` to JSON bool. */ internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(2, message.value, "value", false, true); + return message.value; } /** - * Decode `DoubleValue` from JSON number. + * Decode `BoolValue` from JSON bool. */ internalJsonRead(json2, options, target) { if (!target) target = this.create(); - target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + target.value = this.refJsonReader.scalar(json2, 8, void 0, "value"); return target; } create(value) { - const message = { value: 0 }; + const message = { value: false }; globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_5.reflectionMergePartial)(this, message, value); @@ -76343,9 +79697,9 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* double value */ + case /* bool value */ 1: - message.value = reader.double(); + message.value = reader.bool(); break; default: let u = options.readUnknownField; @@ -76359,44 +79713,44 @@ var require_wrappers = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Bit64).double(message.value); + if (message.value !== false) + writer.tag(1, runtime_3.WireType.Varint).bool(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.DoubleValue = new DoubleValue$Type(); - var FloatValue$Type = class extends runtime_7.MessageType { + exports2.BoolValue = new BoolValue$Type(); + var StringValue$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.FloatValue", [ + super("google.protobuf.StringValue", [ { no: 1, name: "value", kind: "scalar", - T: 2 - /*ScalarType.FLOAT*/ + T: 9 + /*ScalarType.STRING*/ } ]); } /** - * Encode `FloatValue` to JSON number. + * Encode `StringValue` to JSON string. */ internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(1, message.value, "value", false, true); + return message.value; } /** - * Decode `FloatValue` from JSON number. + * Decode `StringValue` from JSON string. */ internalJsonRead(json2, options, target) { if (!target) target = this.create(); - target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + target.value = this.refJsonReader.scalar(json2, 9, void 0, "value"); return target; } create(value) { - const message = { value: 0 }; + const message = { value: "" }; globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_5.reflectionMergePartial)(this, message, value); @@ -76407,9 +79761,9 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* float value */ + case /* string value */ 1: - message.value = reader.float(); + message.value = reader.string(); break; default: let u = options.readUnknownField; @@ -76423,44 +79777,44 @@ var require_wrappers = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Bit32).float(message.value); + if (message.value !== "") + writer.tag(1, runtime_3.WireType.LengthDelimited).string(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.FloatValue = new FloatValue$Type(); - var Int64Value$Type = class extends runtime_7.MessageType { + exports2.StringValue = new StringValue$Type(); + var BytesValue$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.Int64Value", [ + super("google.protobuf.BytesValue", [ { no: 1, name: "value", kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + T: 12 + /*ScalarType.BYTES*/ } ]); } /** - * Encode `Int64Value` to JSON string. + * Encode `BytesValue` to JSON string. */ internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true); + return this.refJsonWriter.scalar(12, message.value, "value", false, true); } /** - * Decode `Int64Value` from JSON string. + * Decode `BytesValue` from JSON string. */ internalJsonRead(json2, options, target) { if (!target) target = this.create(); - target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.INT64, runtime_2.LongType.STRING, "value"); + target.value = this.refJsonReader.scalar(json2, 12, void 0, "value"); return target; } create(value) { - const message = { value: "0" }; + const message = { value: new Uint8Array(0) }; globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_5.reflectionMergePartial)(this, message, value); @@ -76471,9 +79825,9 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* int64 value */ + case /* bytes value */ 1: - message.value = reader.int64().toString(); + message.value = reader.bytes(); break; default: let u = options.readUnknownField; @@ -76487,47 +79841,195 @@ var require_wrappers = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== "0") - writer.tag(1, runtime_3.WireType.Varint).int64(message.value); + if (message.value.length) + writer.tag(1, runtime_3.WireType.LengthDelimited).bytes(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.Int64Value = new Int64Value$Type(); - var UInt64Value$Type = class extends runtime_7.MessageType { + exports2.BytesValue = new BytesValue$Type(); + } +}); + +// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js +var require_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArtifactService = exports2.DeleteArtifactResponse = exports2.DeleteArtifactRequest = exports2.GetSignedArtifactURLResponse = exports2.GetSignedArtifactURLRequest = exports2.ListArtifactsResponse_MonolithArtifact = exports2.ListArtifactsResponse = exports2.ListArtifactsRequest = exports2.FinalizeArtifactResponse = exports2.FinalizeArtifactRequest = exports2.CreateArtifactResponse = exports2.CreateArtifactRequest = exports2.FinalizeMigratedArtifactResponse = exports2.FinalizeMigratedArtifactRequest = exports2.MigrateArtifactResponse = exports2.MigrateArtifactRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var wrappers_1 = require_wrappers(); + var wrappers_2 = require_wrappers(); + var timestamp_1 = require_timestamp(); + var MigrateArtifactRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.MigrateArtifactRequest", [ + { + no: 1, + name: "workflow_run_backend_id", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { no: 3, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp } + ]); + } + create(value) { + const message = { workflowRunBackendId: "", name: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string workflow_run_backend_id */ + 1: + message.workflowRunBackendId = reader.string(); + break; + case /* string name */ + 2: + message.name = reader.string(); + break; + case /* google.protobuf.Timestamp expires_at */ + 3: + message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.name !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.expiresAt) + timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.MigrateArtifactRequest = new MigrateArtifactRequest$Type(); + var MigrateArtifactResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.MigrateArtifactResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedUploadUrl: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.MigrateArtifactResponse = new MigrateArtifactResponse$Type(); + var FinalizeMigratedArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.UInt64Value", [ + super("github.actions.results.api.v1.FinalizeMigratedArtifactRequest", [ { no: 1, - name: "value", + name: "workflow_run_backend_id", kind: "scalar", - T: 4 - /*ScalarType.UINT64*/ + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ } ]); } - /** - * Encode `UInt64Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true); - } - /** - * Decode `UInt64Value` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.UINT64, runtime_2.LongType.STRING, "value"); - return target; - } create(value) { - const message = { value: "0" }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { workflowRunBackendId: "", name: "", size: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76535,9 +80037,17 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* uint64 value */ + case /* string workflow_run_backend_id */ 1: - message.value = reader.uint64().toString(); + message.workflowRunBackendId = reader.string(); + break; + case /* string name */ + 2: + message.name = reader.string(); + break; + case /* int64 size */ + 3: + message.size = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -76545,53 +80055,49 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== "0") - writer.tag(1, runtime_3.WireType.Varint).uint64(message.value); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.name !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.size !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.size); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.UInt64Value = new UInt64Value$Type(); - var Int32Value$Type = class extends runtime_7.MessageType { + exports2.FinalizeMigratedArtifactRequest = new FinalizeMigratedArtifactRequest$Type(); + var FinalizeMigratedArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.Int32Value", [ + super("github.actions.results.api.v1.FinalizeMigratedArtifactResponse", [ { no: 1, - name: "value", + name: "ok", kind: "scalar", - T: 5 - /*ScalarType.INT32*/ + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "artifact_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ } ]); } - /** - * Encode `Int32Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(5, message.value, "value", false, true); - } - /** - * Decode `Int32Value` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 5, void 0, "value"); - return target; - } create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { ok: false, artifactId: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76599,9 +80105,13 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* int32 value */ + case /* bool ok */ 1: - message.value = reader.int32(); + message.ok = reader.bool(); + break; + case /* int64 artifact_id */ + 2: + message.artifactId = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -76609,53 +80119,62 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Varint).int32(message.value); + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.Int32Value = new Int32Value$Type(); - var UInt32Value$Type = class extends runtime_7.MessageType { + exports2.FinalizeMigratedArtifactResponse = new FinalizeMigratedArtifactResponse$Type(); + var CreateArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.UInt32Value", [ + super("github.actions.results.api.v1.CreateArtifactRequest", [ { no: 1, - name: "value", + name: "workflow_run_backend_id", kind: "scalar", - T: 13 - /*ScalarType.UINT32*/ + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "workflow_job_run_backend_id", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { no: 4, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp }, + { + no: 5, + name: "version", + kind: "scalar", + T: 5 + /*ScalarType.INT32*/ } ]); } - /** - * Encode `UInt32Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(13, message.value, "value", false, true); - } - /** - * Decode `UInt32Value` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 13, void 0, "value"); - return target; - } create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", version: 0 }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76663,9 +80182,25 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* uint32 value */ + case /* string workflow_run_backend_id */ 1: - message.value = reader.uint32(); + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ + 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* string name */ + 3: + message.name = reader.string(); + break; + case /* google.protobuf.Timestamp expires_at */ + 4: + message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + break; + case /* int32 version */ + 5: + message.version = reader.int32(); break; default: let u = options.readUnknownField; @@ -76673,53 +80208,53 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Varint).uint32(message.value); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.name !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.expiresAt) + timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.version !== 0) + writer.tag(5, runtime_1.WireType.Varint).int32(message.version); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.UInt32Value = new UInt32Value$Type(); - var BoolValue$Type = class extends runtime_7.MessageType { + exports2.CreateArtifactRequest = new CreateArtifactRequest$Type(); + var CreateArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.BoolValue", [ + super("github.actions.results.api.v1.CreateArtifactResponse", [ { no: 1, - name: "value", + name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ } ]); } - /** - * Encode `BoolValue` to JSON bool. - */ - internalJsonWrite(message, options) { - return message.value; - } - /** - * Decode `BoolValue` from JSON bool. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 8, void 0, "value"); - return target; - } create(value) { - const message = { value: false }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { ok: false, signedUploadUrl: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76727,9 +80262,13 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bool value */ + case /* bool ok */ 1: - message.value = reader.bool(); + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); break; default: let u = options.readUnknownField; @@ -76737,53 +80276,62 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== false) - writer.tag(1, runtime_3.WireType.Varint).bool(message.value); + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.BoolValue = new BoolValue$Type(); - var StringValue$Type = class extends runtime_7.MessageType { + exports2.CreateArtifactResponse = new CreateArtifactResponse$Type(); + var FinalizeArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.StringValue", [ + super("github.actions.results.api.v1.FinalizeArtifactRequest", [ { no: 1, - name: "value", + name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ - } + }, + { + no: 2, + name: "workflow_job_run_backend_id", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "size", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 5, name: "hash", kind: "message", T: () => wrappers_2.StringValue } ]); } - /** - * Encode `StringValue` to JSON string. - */ - internalJsonWrite(message, options) { - return message.value; - } - /** - * Decode `StringValue` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 9, void 0, "value"); - return target; - } create(value) { - const message = { value: "" }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", size: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76791,9 +80339,25 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* string value */ + case /* string workflow_run_backend_id */ 1: - message.value = reader.string(); + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ + 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* string name */ + 3: + message.name = reader.string(); + break; + case /* int64 size */ + 4: + message.size = reader.int64().toString(); + break; + case /* google.protobuf.StringValue hash */ + 5: + message.hash = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.hash); break; default: let u = options.readUnknownField; @@ -76801,53 +80365,53 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== "") - writer.tag(1, runtime_3.WireType.LengthDelimited).string(message.value); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.name !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.size !== "0") + writer.tag(4, runtime_1.WireType.Varint).int64(message.size); + if (message.hash) + wrappers_2.StringValue.internalBinaryWrite(message.hash, writer.tag(5, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.StringValue = new StringValue$Type(); - var BytesValue$Type = class extends runtime_7.MessageType { + exports2.FinalizeArtifactRequest = new FinalizeArtifactRequest$Type(); + var FinalizeArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.BytesValue", [ + super("github.actions.results.api.v1.FinalizeArtifactResponse", [ { no: 1, - name: "value", + name: "ok", kind: "scalar", - T: 12 - /*ScalarType.BYTES*/ + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "artifact_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ } ]); } - /** - * Encode `BytesValue` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(12, message.value, "value", false, true); - } - /** - * Decode `BytesValue` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 12, void 0, "value"); - return target; - } create(value) { - const message = { value: new Uint8Array(0) }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { ok: false, artifactId: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76855,9 +80419,13 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bytes value */ + case /* bool ok */ 1: - message.value = reader.bytes(); + message.ok = reader.bool(); + break; + case /* int64 artifact_id */ + 2: + message.artifactId = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -76865,42 +80433,26 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value.length) - writer.tag(1, runtime_3.WireType.LengthDelimited).bytes(message.value); + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.BytesValue = new BytesValue$Type(); - } -}); - -// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js -var require_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArtifactService = exports2.DeleteArtifactResponse = exports2.DeleteArtifactRequest = exports2.GetSignedArtifactURLResponse = exports2.GetSignedArtifactURLRequest = exports2.ListArtifactsResponse_MonolithArtifact = exports2.ListArtifactsResponse = exports2.ListArtifactsRequest = exports2.FinalizeArtifactResponse = exports2.FinalizeArtifactRequest = exports2.CreateArtifactResponse = exports2.CreateArtifactRequest = exports2.FinalizeMigratedArtifactResponse = exports2.FinalizeMigratedArtifactRequest = exports2.MigrateArtifactResponse = exports2.MigrateArtifactRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var wrappers_1 = require_wrappers(); - var wrappers_2 = require_wrappers(); - var timestamp_1 = require_timestamp(); - var MigrateArtifactRequest$Type = class extends runtime_5.MessageType { + exports2.FinalizeArtifactResponse = new FinalizeArtifactResponse$Type(); + var ListArtifactsRequest$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.MigrateArtifactRequest", [ + super("github.actions.results.api.v1.ListArtifactsRequest", [ { no: 1, name: "workflow_run_backend_id", @@ -76910,16 +80462,17 @@ var require_artifact = __commonJS({ }, { no: 2, - name: "name", + name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 3, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp } + { no: 3, name: "name_filter", kind: "message", T: () => wrappers_2.StringValue }, + { no: 4, name: "id_filter", kind: "message", T: () => wrappers_1.Int64Value } ]); } create(value) { - const message = { workflowRunBackendId: "", name: "" }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -76934,13 +80487,17 @@ var require_artifact = __commonJS({ 1: message.workflowRunBackendId = reader.string(); break; - case /* string name */ + case /* string workflow_job_run_backend_id */ 2: - message.name = reader.string(); + message.workflowJobRunBackendId = reader.string(); break; - case /* google.protobuf.Timestamp expires_at */ + case /* google.protobuf.StringValue name_filter */ 3: - message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + message.nameFilter = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.nameFilter); + break; + case /* google.protobuf.Int64Value id_filter */ + 4: + message.idFilter = wrappers_1.Int64Value.internalBinaryRead(reader, reader.uint32(), options, message.idFilter); break; default: let u = options.readUnknownField; @@ -76956,38 +80513,106 @@ var require_artifact = __commonJS({ internalBinaryWrite(message, writer, options) { if (message.workflowRunBackendId !== "") writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.name !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.expiresAt) - timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.nameFilter) + wrappers_2.StringValue.internalBinaryWrite(message.nameFilter, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.idFilter) + wrappers_1.Int64Value.internalBinaryWrite(message.idFilter, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.ListArtifactsRequest = new ListArtifactsRequest$Type(); + var ListArtifactsResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.ListArtifactsResponse", [ + { no: 1, name: "artifacts", kind: "message", repeat: 1, T: () => exports2.ListArtifactsResponse_MonolithArtifact } + ]); + } + create(value) { + const message = { artifacts: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts */ + 1: + message.artifacts.push(exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + for (let i = 0; i < message.artifacts.length; i++) + exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryWrite(message.artifacts[i], writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.MigrateArtifactRequest = new MigrateArtifactRequest$Type(); - var MigrateArtifactResponse$Type = class extends runtime_5.MessageType { + exports2.ListArtifactsResponse = new ListArtifactsResponse$Type(); + var ListArtifactsResponse_MonolithArtifact$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.MigrateArtifactResponse", [ + super("github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact", [ { no: 1, - name: "ok", + name: "workflow_run_backend_id", kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ + T: 9 + /*ScalarType.STRING*/ }, { no: 2, - name: "signed_upload_url", + name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ - } + }, + { + no: 3, + name: "database_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 5, + name: "size", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 6, name: "created_at", kind: "message", T: () => timestamp_1.Timestamp }, + { no: 7, name: "digest", kind: "message", T: () => wrappers_2.StringValue } ]); } create(value) { - const message = { ok: false, signedUploadUrl: "" }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", databaseId: "0", name: "", size: "0" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -76998,13 +80623,33 @@ var require_artifact = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bool ok */ + case /* string workflow_run_backend_id */ 1: - message.ok = reader.bool(); + message.workflowRunBackendId = reader.string(); break; - case /* string signed_upload_url */ + case /* string workflow_job_run_backend_id */ 2: - message.signedUploadUrl = reader.string(); + message.workflowJobRunBackendId = reader.string(); + break; + case /* int64 database_id */ + 3: + message.databaseId = reader.int64().toString(); + break; + case /* string name */ + 4: + message.name = reader.string(); + break; + case /* int64 size */ + 5: + message.size = reader.int64().toString(); + break; + case /* google.protobuf.Timestamp created_at */ + 6: + message.createdAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.createdAt); + break; + case /* google.protobuf.StringValue digest */ + 7: + message.digest = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.digest); break; default: let u = options.readUnknownField; @@ -77018,20 +80663,30 @@ var require_artifact = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.databaseId !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.databaseId); + if (message.name !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.size !== "0") + writer.tag(5, runtime_1.WireType.Varint).int64(message.size); + if (message.createdAt) + timestamp_1.Timestamp.internalBinaryWrite(message.createdAt, writer.tag(6, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.digest) + wrappers_2.StringValue.internalBinaryWrite(message.digest, writer.tag(7, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.MigrateArtifactResponse = new MigrateArtifactResponse$Type(); - var FinalizeMigratedArtifactRequest$Type = class extends runtime_5.MessageType { + exports2.ListArtifactsResponse_MonolithArtifact = new ListArtifactsResponse_MonolithArtifact$Type(); + var GetSignedArtifactURLRequest$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.FinalizeMigratedArtifactRequest", [ + super("github.actions.results.api.v1.GetSignedArtifactURLRequest", [ { no: 1, name: "workflow_run_backend_id", @@ -77041,22 +80696,22 @@ var require_artifact = __commonJS({ }, { no: 2, - name: "name", + name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, - name: "size", + name: "name", kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + T: 9 + /*ScalarType.STRING*/ } ]); } create(value) { - const message = { workflowRunBackendId: "", name: "", size: "0" }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -77071,13 +80726,13 @@ var require_artifact = __commonJS({ 1: message.workflowRunBackendId = reader.string(); break; - case /* string name */ + case /* string workflow_job_run_backend_id */ 2: - message.name = reader.string(); + message.workflowJobRunBackendId = reader.string(); break; - case /* int64 size */ + case /* string name */ 3: - message.size = reader.int64().toString(); + message.name = reader.string(); break; default: let u = options.readUnknownField; @@ -77093,38 +80748,31 @@ var require_artifact = __commonJS({ internalBinaryWrite(message, writer, options) { if (message.workflowRunBackendId !== "") writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); if (message.name !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.size !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.size); + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.FinalizeMigratedArtifactRequest = new FinalizeMigratedArtifactRequest$Type(); - var FinalizeMigratedArtifactResponse$Type = class extends runtime_5.MessageType { + exports2.GetSignedArtifactURLRequest = new GetSignedArtifactURLRequest$Type(); + var GetSignedArtifactURLResponse$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.FinalizeMigratedArtifactResponse", [ + super("github.actions.results.api.v1.GetSignedArtifactURLResponse", [ { no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "artifact_id", + name: "signed_url", kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + T: 9 + /*ScalarType.STRING*/ } ]); } create(value) { - const message = { ok: false, artifactId: "0" }; + const message = { signedUrl: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -77135,13 +80783,9 @@ var require_artifact = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bool ok */ + case /* string signed_url */ 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ - 2: - message.artifactId = reader.int64().toString(); + message.signedUrl = reader.string(); break; default: let u = options.readUnknownField; @@ -77155,20 +80799,18 @@ var require_artifact = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); + if (message.signedUrl !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.signedUrl); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.FinalizeMigratedArtifactResponse = new FinalizeMigratedArtifactResponse$Type(); - var CreateArtifactRequest$Type = class extends runtime_5.MessageType { + exports2.GetSignedArtifactURLResponse = new GetSignedArtifactURLResponse$Type(); + var DeleteArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.CreateArtifactRequest", [ + super("github.actions.results.api.v1.DeleteArtifactRequest", [ { no: 1, name: "workflow_run_backend_id", @@ -77189,19 +80831,11 @@ var require_artifact = __commonJS({ kind: "scalar", T: 9 /*ScalarType.STRING*/ - }, - { no: 4, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp }, - { - no: 5, - name: "version", - kind: "scalar", - T: 5 - /*ScalarType.INT32*/ } ]); } create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", version: 0 }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -77224,14 +80858,6 @@ var require_artifact = __commonJS({ 3: message.name = reader.string(); break; - case /* google.protobuf.Timestamp expires_at */ - 4: - message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); - break; - case /* int32 version */ - 5: - message.version = reader.int32(); - break; default: let u = options.readUnknownField; if (u === "throw") @@ -77250,20 +80876,16 @@ var require_artifact = __commonJS({ writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); if (message.name !== "") writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.expiresAt) - timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.version !== 0) - writer.tag(5, runtime_1.WireType.Varint).int32(message.version); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.CreateArtifactRequest = new CreateArtifactRequest$Type(); - var CreateArtifactResponse$Type = class extends runtime_5.MessageType { + exports2.DeleteArtifactRequest = new DeleteArtifactRequest$Type(); + var DeleteArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.CreateArtifactResponse", [ + super("github.actions.results.api.v1.DeleteArtifactResponse", [ { no: 1, name: "ok", @@ -77273,15 +80895,15 @@ var require_artifact = __commonJS({ }, { no: 2, - name: "signed_upload_url", + name: "artifact_id", kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + T: 3 + /*ScalarType.INT64*/ } ]); } create(value) { - const message = { ok: false, signedUploadUrl: "" }; + const message = { ok: false, artifactId: "0" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -77296,9 +80918,9 @@ var require_artifact = __commonJS({ 1: message.ok = reader.bool(); break; - case /* string signed_upload_url */ + case /* int64 artifact_id */ 2: - message.signedUploadUrl = reader.string(); + message.artifactId = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -77314,938 +80936,1091 @@ var require_artifact = __commonJS({ internalBinaryWrite(message, writer, options) { if (message.ok !== false) writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.CreateArtifactResponse = new CreateArtifactResponse$Type(); - var FinalizeArtifactRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeArtifactRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "size", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 5, name: "hash", kind: "message", T: () => wrappers_2.StringValue } - ]); + exports2.DeleteArtifactResponse = new DeleteArtifactResponse$Type(); + exports2.ArtifactService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.ArtifactService", [ + { name: "CreateArtifact", options: {}, I: exports2.CreateArtifactRequest, O: exports2.CreateArtifactResponse }, + { name: "FinalizeArtifact", options: {}, I: exports2.FinalizeArtifactRequest, O: exports2.FinalizeArtifactResponse }, + { name: "ListArtifacts", options: {}, I: exports2.ListArtifactsRequest, O: exports2.ListArtifactsResponse }, + { name: "GetSignedArtifactURL", options: {}, I: exports2.GetSignedArtifactURLRequest, O: exports2.GetSignedArtifactURLResponse }, + { name: "DeleteArtifact", options: {}, I: exports2.DeleteArtifactRequest, O: exports2.DeleteArtifactResponse }, + { name: "MigrateArtifact", options: {}, I: exports2.MigrateArtifactRequest, O: exports2.MigrateArtifactResponse }, + { name: "FinalizeMigratedArtifact", options: {}, I: exports2.FinalizeMigratedArtifactRequest, O: exports2.FinalizeMigratedArtifactResponse } + ]); + } +}); + +// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js +var require_artifact_twirp_client = __commonJS({ + "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArtifactServiceClientProtobuf = exports2.ArtifactServiceClientJSON = void 0; + var artifact_1 = require_artifact(); + var ArtifactServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateArtifact.bind(this); + this.FinalizeArtifact.bind(this); + this.ListArtifacts.bind(this); + this.GetSignedArtifactURL.bind(this); + this.DeleteArtifact.bind(this); } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", size: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + CreateArtifact(request) { + const data = artifact_1.CreateArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/json", data); + return promise.then((data2) => artifact_1.CreateArtifactResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ - 3: - message.name = reader.string(); - break; - case /* int64 size */ - 4: - message.size = reader.int64().toString(); - break; - case /* google.protobuf.StringValue hash */ - 5: - message.hash = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.hash); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + FinalizeArtifact(request) { + const data = artifact_1.FinalizeArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/json", data); + return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + ListArtifacts(request) { + const data = artifact_1.ListArtifactsRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/json", data); + return promise.then((data2) => artifact_1.ListArtifactsResponse.fromJson(data2, { ignoreUnknownFields: true })); + } + GetSignedArtifactURL(request) { + const data = artifact_1.GetSignedArtifactURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/json", data); + return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + DeleteArtifact(request) { + const data = artifact_1.DeleteArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/json", data); + return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + }; + exports2.ArtifactServiceClientJSON = ArtifactServiceClientJSON; + var ArtifactServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateArtifact.bind(this); + this.FinalizeArtifact.bind(this); + this.ListArtifacts.bind(this); + this.GetSignedArtifactURL.bind(this); + this.DeleteArtifact.bind(this); + } + CreateArtifact(request) { + const data = artifact_1.CreateArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/protobuf", data); + return promise.then((data2) => artifact_1.CreateArtifactResponse.fromBinary(data2)); + } + FinalizeArtifact(request) { + const data = artifact_1.FinalizeArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/protobuf", data); + return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromBinary(data2)); + } + ListArtifacts(request) { + const data = artifact_1.ListArtifactsRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/protobuf", data); + return promise.then((data2) => artifact_1.ListArtifactsResponse.fromBinary(data2)); + } + GetSignedArtifactURL(request) { + const data = artifact_1.GetSignedArtifactURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/protobuf", data); + return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromBinary(data2)); + } + DeleteArtifact(request) { + const data = artifact_1.DeleteArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/protobuf", data); + return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromBinary(data2)); + } + }; + exports2.ArtifactServiceClientProtobuf = ArtifactServiceClientProtobuf; + } +}); + +// node_modules/@actions/artifact/lib/generated/index.js +var require_generated = __commonJS({ + "node_modules/@actions/artifact/lib/generated/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar4(require_timestamp(), exports2); + __exportStar4(require_wrappers(), exports2); + __exportStar4(require_artifact(), exports2); + __exportStar4(require_artifact_twirp_client(), exports2); + } +}); + +// node_modules/@actions/artifact/lib/internal/upload/retention.js +var require_retention = __commonJS({ + "node_modules/@actions/artifact/lib/internal/upload/retention.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getExpiration = getExpiration; + var generated_1 = require_generated(); + var core14 = __importStar4(require_core()); + function getExpiration(retentionDays) { + if (!retentionDays) { + return void 0; + } + const maxRetentionDays = getRetentionDays(); + if (maxRetentionDays && maxRetentionDays < retentionDays) { + core14.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); + retentionDays = maxRetentionDays; + } + const expirationDate = /* @__PURE__ */ new Date(); + expirationDate.setDate(expirationDate.getDate() + retentionDays); + return generated_1.Timestamp.fromDate(expirationDate); + } + function getRetentionDays() { + const retentionDays = process.env["GITHUB_RETENTION_DAYS"]; + if (!retentionDays) { + return void 0; + } + const days = parseInt(retentionDays); + if (isNaN(days)) { + return void 0; + } + return days; + } + } +}); + +// node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js +var require_path_and_artifact_name_validation = __commonJS({ + "node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.validateArtifactName = validateArtifactName; + exports2.validateFilePath = validateFilePath; + var core_1 = require_core(); + var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ + ['"', ' Double quote "'], + [":", " Colon :"], + ["<", " Less than <"], + [">", " Greater than >"], + ["|", " Vertical bar |"], + ["*", " Asterisk *"], + ["?", " Question mark ?"], + ["\r", " Carriage return \\r"], + ["\n", " Line feed \\n"] + ]); + var invalidArtifactNameCharacters = new Map([ + ...invalidArtifactFilePathCharacters, + ["\\", " Backslash \\"], + ["/", " Forward slash /"] + ]); + function validateArtifactName(name) { + if (!name) { + throw new Error(`Provided artifact name input during validation is empty`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { + if (name.includes(invalidCharacterKey)) { + throw new Error(`The artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} + +These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.size !== "0") - writer.tag(4, runtime_1.WireType.Varint).int64(message.size); - if (message.hash) - wrappers_2.StringValue.internalBinaryWrite(message.hash, writer.tag(5, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + (0, core_1.info)(`Artifact name is valid!`); + } + function validateFilePath(path6) { + if (!path6) { + throw new Error(`Provided file path input during validation is empty`); } - }; - exports2.FinalizeArtifactRequest = new FinalizeArtifactRequest$Type(); - var FinalizeArtifactResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeArtifactResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "artifact_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - } - ]); + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { + if (path6.includes(invalidCharacterKey)) { + throw new Error(`The path for one of the files in artifact is not valid: ${path6}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} + +The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. + `); + } } - create(value) { - const message = { ok: false, artifactId: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + } + } +}); + +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/proxy.js +var require_proxy6 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ - 2: - message.artifactId = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - return message; + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - }; - exports2.FinalizeArtifactResponse = new FinalizeArtifactResponse$Type(); - var ListArtifactsRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { no: 3, name: "name_filter", kind: "message", T: () => wrappers_2.StringValue }, - { no: 4, name: "id_filter", kind: "message", T: () => wrappers_1.Int64Value } - ]); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* google.protobuf.StringValue name_filter */ - 3: - message.nameFilter = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.nameFilter); - break; - case /* google.protobuf.Int64Value id_filter */ - 4: - message.idFilter = wrappers_1.Int64Value.internalBinaryRead(reader, reader.uint32(), options, message.idFilter); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.nameFilter) - wrappers_2.StringValue.internalBinaryWrite(message.nameFilter, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.idFilter) - wrappers_1.Int64Value.internalBinaryWrite(message.idFilter, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - }; - exports2.ListArtifactsRequest = new ListArtifactsRequest$Type(); - var ListArtifactsResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsResponse", [ - { no: 1, name: "artifacts", kind: "message", repeat: 1, T: () => exports2.ListArtifactsResponse_MonolithArtifact } - ]); + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } } - create(value) { - const message = { artifacts: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts */ - 1: - message.artifacts.push(exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryRead(reader, reader.uint32(), options)); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + get username() { + return this._decodedUsername; } - internalBinaryWrite(message, writer, options) { - for (let i = 0; i < message.artifacts.length; i++) - exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryWrite(message.artifacts[i], writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + get password() { + return this._decodedPassword; } }; - exports2.ListArtifactsResponse = new ListArtifactsResponse$Type(); - var ListArtifactsResponse_MonolithArtifact$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "database_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 5, - name: "size", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 6, name: "created_at", kind: "message", T: () => timestamp_1.Timestamp }, - { no: 7, name: "digest", kind: "message", T: () => wrappers_2.StringValue } - ]); + } +}); + +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/index.js +var require_lib7 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", databaseId: "0", name: "", size: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* int64 database_id */ - 3: - message.databaseId = reader.int64().toString(); - break; - case /* string name */ - 4: - message.name = reader.string(); - break; - case /* int64 size */ - 5: - message.size = reader.int64().toString(); - break; - case /* google.protobuf.Timestamp created_at */ - 6: - message.createdAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.createdAt); - break; - case /* google.protobuf.StringValue digest */ - 7: - message.digest = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.digest); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.databaseId !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.databaseId); - if (message.name !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.size !== "0") - writer.tag(5, runtime_1.WireType.Varint).int64(message.size); - if (message.createdAt) - timestamp_1.Timestamp.internalBinaryWrite(message.createdAt, writer.tag(6, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.digest) - wrappers_2.StringValue.internalBinaryWrite(message.digest, writer.tag(7, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy6()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.ListArtifactsResponse_MonolithArtifact = new ListArtifactsResponse_MonolithArtifact$Type(); - var GetSignedArtifactURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetSignedArtifactURLRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); - } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ - 3: - message.name = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); + }); } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); + }); } }; - exports2.GetSignedArtifactURLRequest = new GetSignedArtifactURLRequest$Type(); - var GetSignedArtifactURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetSignedArtifactURLResponse", [ - { - no: 1, - name: "signed_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - ]); - } - create(value) { - const message = { signedUrl: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string signed_url */ - 1: - message.signedUrl = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.signedUrl !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.signedUrl); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.GetSignedArtifactURLResponse = new GetSignedArtifactURLResponse$Type(); - var DeleteArtifactRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.DeleteArtifactRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ - 3: - message.name = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - }; - exports2.DeleteArtifactRequest = new DeleteArtifactRequest$Type(); - var DeleteArtifactResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.DeleteArtifactResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "artifact_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - } - ]); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - create(value) { - const message = { ok: false, artifactId: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ - 2: - message.artifactId = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - }; - exports2.DeleteArtifactResponse = new DeleteArtifactResponse$Type(); - exports2.ArtifactService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.ArtifactService", [ - { name: "CreateArtifact", options: {}, I: exports2.CreateArtifactRequest, O: exports2.CreateArtifactResponse }, - { name: "FinalizeArtifact", options: {}, I: exports2.FinalizeArtifactRequest, O: exports2.FinalizeArtifactResponse }, - { name: "ListArtifacts", options: {}, I: exports2.ListArtifactsRequest, O: exports2.ListArtifactsResponse }, - { name: "GetSignedArtifactURL", options: {}, I: exports2.GetSignedArtifactURLRequest, O: exports2.GetSignedArtifactURLResponse }, - { name: "DeleteArtifact", options: {}, I: exports2.DeleteArtifactRequest, O: exports2.DeleteArtifactResponse }, - { name: "MigrateArtifact", options: {}, I: exports2.MigrateArtifactRequest, O: exports2.MigrateArtifactResponse }, - { name: "FinalizeMigratedArtifact", options: {}, I: exports2.FinalizeMigratedArtifactRequest, O: exports2.FinalizeMigratedArtifactResponse } - ]); - } -}); - -// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js -var require_artifact_twirp_client = __commonJS({ - "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArtifactServiceClientProtobuf = exports2.ArtifactServiceClientJSON = void 0; - var artifact_1 = require_artifact(); - var ArtifactServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateArtifact.bind(this); - this.FinalizeArtifact.bind(this); - this.ListArtifacts.bind(this); - this.GetSignedArtifactURL.bind(this); - this.DeleteArtifact.bind(this); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - CreateArtifact(request) { - const data = artifact_1.CreateArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/json", data); - return promise.then((data2) => artifact_1.CreateArtifactResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - FinalizeArtifact(request) { - const data = artifact_1.FinalizeArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/json", data); - return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - ListArtifacts(request) { - const data = artifact_1.ListArtifactsRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/json", data); - return promise.then((data2) => artifact_1.ListArtifactsResponse.fromJson(data2, { ignoreUnknownFields: true })); - } - GetSignedArtifactURL(request) { - const data = artifact_1.GetSignedArtifactURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + let socket; + req.on("socket", (sock) => { + socket = sock; }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/json", data); - return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); - } - DeleteArtifact(request) { - const data = artifact_1.DeleteArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/json", data); - return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromJson(data2, { - ignoreUnknownFields: true - })); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } - }; - exports2.ArtifactServiceClientJSON = ArtifactServiceClientJSON; - var ArtifactServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateArtifact.bind(this); - this.FinalizeArtifact.bind(this); - this.ListArtifacts.bind(this); - this.GetSignedArtifactURL.bind(this); - this.DeleteArtifact.bind(this); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - CreateArtifact(request) { - const data = artifact_1.CreateArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/protobuf", data); - return promise.then((data2) => artifact_1.CreateArtifactResponse.fromBinary(data2)); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - FinalizeArtifact(request) { - const data = artifact_1.FinalizeArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/protobuf", data); - return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromBinary(data2)); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; } - ListArtifacts(request) { - const data = artifact_1.ListArtifactsRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/protobuf", data); - return promise.then((data2) => artifact_1.ListArtifactsResponse.fromBinary(data2)); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - GetSignedArtifactURL(request) { - const data = artifact_1.GetSignedArtifactURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/protobuf", data); - return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromBinary(data2)); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - DeleteArtifact(request) { - const data = artifact_1.DeleteArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/protobuf", data); - return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromBinary(data2)); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - }; - exports2.ArtifactServiceClientProtobuf = ArtifactServiceClientProtobuf; - } -}); - -// node_modules/@actions/artifact/lib/generated/index.js -var require_generated = __commonJS({ - "node_modules/@actions/artifact/lib/generated/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); + } + })); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar4(require_timestamp(), exports2); - __exportStar4(require_wrappers(), exports2); - __exportStar4(require_artifact(), exports2); - __exportStar4(require_artifact_twirp_client(), exports2); + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/artifact/lib/internal/upload/retention.js -var require_retention = __commonJS({ - "node_modules/@actions/artifact/lib/internal/upload/retention.js"(exports2) { +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/auth.js +var require_auth3 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - __setModuleDefault4(result, mod); - return result; - }; - })(); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getExpiration = getExpiration; - var generated_1 = require_generated(); - var core14 = __importStar4(require_core()); - function getExpiration(retentionDays) { - if (!retentionDays) { - return void 0; + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - const maxRetentionDays = getRetentionDays(); - if (maxRetentionDays && maxRetentionDays < retentionDays) { - core14.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); - retentionDays = maxRetentionDays; + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; } - const expirationDate = /* @__PURE__ */ new Date(); - expirationDate.setDate(expirationDate.getDate() + retentionDays); - return generated_1.Timestamp.fromDate(expirationDate); - } - function getRetentionDays() { - const retentionDays = process.env["GITHUB_RETENTION_DAYS"]; - if (!retentionDays) { - return void 0; + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - const days = parseInt(retentionDays); - if (isNaN(days)) { - return void 0; + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - return days; - } - } -}); - -// node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js -var require_path_and_artifact_name_validation = __commonJS({ - "node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.validateArtifactName = validateArtifactName; - exports2.validateFilePath = validateFilePath; - var core_1 = require_core(); - var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ - ['"', ' Double quote "'], - [":", " Colon :"], - ["<", " Less than <"], - [">", " Greater than >"], - ["|", " Vertical bar |"], - ["*", " Asterisk *"], - ["?", " Question mark ?"], - ["\r", " Carriage return \\r"], - ["\n", " Line feed \\n"] - ]); - var invalidArtifactNameCharacters = new Map([ - ...invalidArtifactFilePathCharacters, - ["\\", " Backslash \\"], - ["/", " Forward slash /"] - ]); - function validateArtifactName(name) { - if (!name) { - throw new Error(`Provided artifact name input during validation is empty`); + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { - if (name.includes(invalidCharacterKey)) { - throw new Error(`The artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} - -These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } + options.headers["Authorization"] = `Bearer ${this.token}`; } - (0, core_1.info)(`Artifact name is valid!`); - } - function validateFilePath(path6) { - if (!path6) { - throw new Error(`Provided file path input during validation is empty`); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path6.includes(invalidCharacterKey)) { - throw new Error(`The path for one of the files in artifact is not valid: ${path6}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} - -The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. - `); + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; } - } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); @@ -78614,8 +82389,8 @@ var require_artifact_twirp_client2 = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.internalArtifactTwirpClient = internalArtifactTwirpClient; - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib7(); + var auth_1 = require_auth3(); var core_1 = require_core(); var generated_1 = require_generated(); var config_1 = require_config2(); @@ -100635,7 +104410,7 @@ var require_deflate_crc32_stream = __commonJS({ }); // node_modules/crc32-stream/lib/index.js -var require_lib3 = __commonJS({ +var require_lib8 = __commonJS({ "node_modules/crc32-stream/lib/index.js"(exports2, module2) { "use strict"; module2.exports = { @@ -100650,8 +104425,8 @@ var require_zip_archive_output_stream = __commonJS({ "node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js"(exports2, module2) { var inherits = require("util").inherits; var crc32 = require_crc32(); - var { CRC32Stream } = require_lib3(); - var { DeflateCRC32Stream } = require_lib3(); + var { CRC32Stream } = require_lib8(); + var { DeflateCRC32Stream } = require_lib8(); var ArchiveOutputStream = require_archive_output_stream(); var ZipArchiveEntry = require_zip_archive_entry(); var GeneralPurposeBit = require_general_purpose_bit(); @@ -105380,580 +109155,1578 @@ var require_unzip_stream = __commonJS({ return chunk.length; } }; - UnzipStream.prototype._prepareOutStream = function(vars, entry) { + UnzipStream.prototype._prepareOutStream = function(vars, entry) { + var self2 = this; + var isDirectory = vars.uncompressedSize === 0 && /[\/\\]$/.test(entry.path); + entry.path = entry.path.replace(/(?<=^|[/\\]+)[.][.]+(?=[/\\]+|$)/g, "."); + entry.type = isDirectory ? "Directory" : "File"; + entry.isDirectory = isDirectory; + var fileSizeKnown = !(vars.flags & 8); + if (fileSizeKnown) { + entry.size = vars.uncompressedSize; + } + var isVersionSupported = vars.versionsNeededToExtract <= 45; + this.outStreamInfo = { + stream: null, + limit: fileSizeKnown ? vars.compressedSize : -1, + written: 0 + }; + if (!fileSizeKnown) { + var pattern = new Buffer(4); + pattern.writeUInt32LE(SIG_DATA_DESCRIPTOR, 0); + var zip64Mode = vars.extra.zip64Mode; + var extraSize = zip64Mode ? 20 : 12; + var searchPattern = { + pattern, + requiredExtraSize: extraSize + }; + var matcherStream = new MatcherStream(searchPattern, function(matchedChunk, sizeSoFar) { + var vars2 = self2._readDataDescriptor(matchedChunk, zip64Mode); + var compressedSizeMatches = vars2.compressedSize === sizeSoFar; + if (!zip64Mode && !compressedSizeMatches && sizeSoFar >= FOUR_GIGS) { + var overflown = sizeSoFar - FOUR_GIGS; + while (overflown >= 0) { + compressedSizeMatches = vars2.compressedSize === overflown; + if (compressedSizeMatches) break; + overflown -= FOUR_GIGS; + } + } + if (!compressedSizeMatches) { + return; + } + self2.state = states.FILE_DATA_END; + var sliceOffset = zip64Mode ? 24 : 16; + if (self2.data.length > 0) { + self2.data = Buffer.concat([matchedChunk.slice(sliceOffset), self2.data]); + } else { + self2.data = matchedChunk.slice(sliceOffset); + } + return true; + }); + this.outStreamInfo.stream = matcherStream; + } else { + this.outStreamInfo.stream = new stream.PassThrough(); + } + var isEncrypted = vars.flags & 1 || vars.flags & 64; + if (isEncrypted || !isVersionSupported) { + var message = isEncrypted ? "Encrypted files are not supported!" : "Zip version " + Math.floor(vars.versionsNeededToExtract / 10) + "." + vars.versionsNeededToExtract % 10 + " is not supported"; + entry.skip = true; + setImmediate(() => { + self2.emit("error", new Error(message)); + }); + this.outStreamInfo.stream.pipe(new Entry().autodrain()); + return; + } + var isCompressed = vars.compressionMethod > 0; + if (isCompressed) { + var inflater = zlib.createInflateRaw(); + inflater.on("error", function(err) { + self2.state = states.ERROR; + self2.emit("error", err); + }); + this.outStreamInfo.stream.pipe(inflater).pipe(entry); + } else { + this.outStreamInfo.stream.pipe(entry); + } + if (this._drainAllEntries) { + entry.autodrain(); + } + }; + UnzipStream.prototype._readFile = function(data) { + var vars = binary2.parse(data).word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars; + return vars; + }; + UnzipStream.prototype._readExtraFields = function(data) { + var extra = {}; + var result = { parsed: extra }; + if (this.options.debug) { + result.debug = []; + } + var index = 0; + while (index < data.length) { + var vars = binary2.parse(data).skip(index).word16lu("extraId").word16lu("extraSize").vars; + index += 4; + var fieldType = void 0; + switch (vars.extraId) { + case 1: + fieldType = "Zip64 extended information extra field"; + var z64vars = binary2.parse(data.slice(index, index + vars.extraSize)).word64lu("uncompressedSize").word64lu("compressedSize").word64lu("offsetToLocalHeader").word32lu("diskStartNumber").vars; + if (z64vars.uncompressedSize !== null) { + extra.uncompressedSize = z64vars.uncompressedSize; + } + if (z64vars.compressedSize !== null) { + extra.compressedSize = z64vars.compressedSize; + } + extra.zip64Mode = true; + break; + case 10: + fieldType = "NTFS extra field"; + break; + case 21589: + fieldType = "extended timestamp"; + var timestampFields = data.readUInt8(index); + var offset = 1; + if (vars.extraSize >= offset + 4 && timestampFields & 1) { + extra.mtime = new Date(data.readUInt32LE(index + offset) * 1e3); + offset += 4; + } + if (vars.extraSize >= offset + 4 && timestampFields & 2) { + extra.atime = new Date(data.readUInt32LE(index + offset) * 1e3); + offset += 4; + } + if (vars.extraSize >= offset + 4 && timestampFields & 4) { + extra.ctime = new Date(data.readUInt32LE(index + offset) * 1e3); + } + break; + case 28789: + fieldType = "Info-ZIP Unicode Path Extra Field"; + var fieldVer = data.readUInt8(index); + if (fieldVer === 1) { + var offset = 1; + var nameCrc32 = data.readUInt32LE(index + offset); + offset += 4; + var pathBuffer = data.slice(index + offset); + extra.path = pathBuffer.toString(); + } + break; + case 13: + case 22613: + fieldType = vars.extraId === 13 ? "PKWARE Unix" : "Info-ZIP UNIX (type 1)"; + var offset = 0; + if (vars.extraSize >= 8) { + var atime = new Date(data.readUInt32LE(index + offset) * 1e3); + offset += 4; + var mtime = new Date(data.readUInt32LE(index + offset) * 1e3); + offset += 4; + extra.atime = atime; + extra.mtime = mtime; + if (vars.extraSize >= 12) { + var uid = data.readUInt16LE(index + offset); + offset += 2; + var gid = data.readUInt16LE(index + offset); + offset += 2; + extra.uid = uid; + extra.gid = gid; + } + } + break; + case 30805: + fieldType = "Info-ZIP UNIX (type 2)"; + var offset = 0; + if (vars.extraSize >= 4) { + var uid = data.readUInt16LE(index + offset); + offset += 2; + var gid = data.readUInt16LE(index + offset); + offset += 2; + extra.uid = uid; + extra.gid = gid; + } + break; + case 30837: + fieldType = "Info-ZIP New Unix"; + var offset = 0; + var extraVer = data.readUInt8(index); + offset += 1; + if (extraVer === 1) { + var uidSize = data.readUInt8(index + offset); + offset += 1; + if (uidSize <= 6) { + extra.uid = data.readUIntLE(index + offset, uidSize); + } + offset += uidSize; + var gidSize = data.readUInt8(index + offset); + offset += 1; + if (gidSize <= 6) { + extra.gid = data.readUIntLE(index + offset, gidSize); + } + } + break; + case 30062: + fieldType = "ASi Unix"; + var offset = 0; + if (vars.extraSize >= 14) { + var crc = data.readUInt32LE(index + offset); + offset += 4; + var mode = data.readUInt16LE(index + offset); + offset += 2; + var sizdev = data.readUInt32LE(index + offset); + offset += 4; + var uid = data.readUInt16LE(index + offset); + offset += 2; + var gid = data.readUInt16LE(index + offset); + offset += 2; + extra.mode = mode; + extra.uid = uid; + extra.gid = gid; + if (vars.extraSize > 14) { + var start = index + offset; + var end = index + vars.extraSize - 14; + var symlinkName = this._decodeString(data.slice(start, end)); + extra.symlink = symlinkName; + } + } + break; + } + if (this.options.debug) { + result.debug.push({ + extraId: "0x" + vars.extraId.toString(16), + description: fieldType, + data: data.slice(index, index + vars.extraSize).inspect() + }); + } + index += vars.extraSize; + } + return result; + }; + UnzipStream.prototype._readDataDescriptor = function(data, zip64Mode) { + if (zip64Mode) { + var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word64lu("compressedSize").word64lu("uncompressedSize").vars; + return vars; + } + var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").vars; + return vars; + }; + UnzipStream.prototype._readCentralDirectoryEntry = function(data) { + var vars = binary2.parse(data).word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars; + return vars; + }; + UnzipStream.prototype._readEndOfCentralDirectory64 = function(data) { + var vars = binary2.parse(data).word64lu("centralDirectoryRecordSize").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskNumberWithCentralDirectoryStart").word64lu("centralDirectoryEntries").word64lu("totalCentralDirectoryEntries").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars; + return vars; + }; + UnzipStream.prototype._readEndOfCentralDirectory = function(data) { + var vars = binary2.parse(data).word16lu("diskNumber").word16lu("diskStart").word16lu("centralDirectoryEntries").word16lu("totalCentralDirectoryEntries").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars; + return vars; + }; + var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 "; + UnzipStream.prototype._decodeString = function(buffer, isUtf8) { + if (isUtf8) { + return buffer.toString("utf8"); + } + if (this.options.decodeString) { + return this.options.decodeString(buffer); + } + let result = ""; + for (var i = 0; i < buffer.length; i++) { + result += cp437[buffer[i]]; + } + return result; + }; + UnzipStream.prototype._parseOrOutput = function(encoding, cb) { + var consume; + while ((consume = this.processDataChunk(this.data)) > 0) { + this.data = this.data.slice(consume); + if (this.data.length === 0) break; + } + if (this.state === states.FILE_DATA) { + if (this.outStreamInfo.limit >= 0) { + var remaining = this.outStreamInfo.limit - this.outStreamInfo.written; + var packet; + if (remaining < this.data.length) { + packet = this.data.slice(0, remaining); + this.data = this.data.slice(remaining); + } else { + packet = this.data; + this.data = new Buffer(""); + } + this.outStreamInfo.written += packet.length; + if (this.outStreamInfo.limit === this.outStreamInfo.written) { + this.state = states.START; + this.outStreamInfo.stream.end(packet, encoding, cb); + } else { + this.outStreamInfo.stream.write(packet, encoding, cb); + } + } else { + var packet = this.data; + this.data = new Buffer(""); + this.outStreamInfo.written += packet.length; + var outputStream = this.outStreamInfo.stream; + outputStream.write(packet, encoding, () => { + if (this.state === states.FILE_DATA_END) { + this.state = states.START; + return outputStream.end(cb); + } + cb(); + }); + } + return; + } + cb(); + }; + UnzipStream.prototype.drainAll = function() { + this._drainAllEntries = true; + }; + UnzipStream.prototype._transform = function(chunk, encoding, cb) { + var self2 = this; + if (self2.data.length > 0) { + self2.data = Buffer.concat([self2.data, chunk]); + } else { + self2.data = chunk; + } + var startDataLength = self2.data.length; + var done = function() { + if (self2.data.length > 0 && self2.data.length < startDataLength) { + startDataLength = self2.data.length; + self2._parseOrOutput(encoding, done); + return; + } + cb(); + }; + self2._parseOrOutput(encoding, done); + }; + UnzipStream.prototype._flush = function(cb) { + var self2 = this; + if (self2.data.length > 0) { + self2._parseOrOutput("buffer", function() { + if (self2.data.length > 0) return setImmediate(function() { + self2._flush(cb); + }); + cb(); + }); + return; + } + if (self2.state === states.FILE_DATA) { + return cb(new Error("Stream finished in an invalid state, uncompression failed")); + } + setImmediate(cb); + }; + module2.exports = UnzipStream; + } +}); + +// node_modules/unzip-stream/lib/parser-stream.js +var require_parser_stream = __commonJS({ + "node_modules/unzip-stream/lib/parser-stream.js"(exports2, module2) { + var Transform = require("stream").Transform; + var util = require("util"); + var UnzipStream = require_unzip_stream(); + function ParserStream(opts) { + if (!(this instanceof ParserStream)) { + return new ParserStream(opts); + } + var transformOpts = opts || {}; + Transform.call(this, { readableObjectMode: true }); + this.opts = opts || {}; + this.unzipStream = new UnzipStream(this.opts); + var self2 = this; + this.unzipStream.on("entry", function(entry) { + self2.push(entry); + }); + this.unzipStream.on("error", function(error4) { + self2.emit("error", error4); + }); + } + util.inherits(ParserStream, Transform); + ParserStream.prototype._transform = function(chunk, encoding, cb) { + this.unzipStream.write(chunk, encoding, cb); + }; + ParserStream.prototype._flush = function(cb) { + var self2 = this; + this.unzipStream.end(function() { + process.nextTick(function() { + self2.emit("close"); + }); + cb(); + }); + }; + ParserStream.prototype.on = function(eventName, fn) { + if (eventName === "entry") { + return Transform.prototype.on.call(this, "data", fn); + } + return Transform.prototype.on.call(this, eventName, fn); + }; + ParserStream.prototype.drainAll = function() { + this.unzipStream.drainAll(); + return this.pipe(new Transform({ objectMode: true, transform: function(d, e, cb) { + cb(); + } })); + }; + module2.exports = ParserStream; + } +}); + +// node_modules/mkdirp/index.js +var require_mkdirp = __commonJS({ + "node_modules/mkdirp/index.js"(exports2, module2) { + var path6 = require("path"); + var fs7 = require("fs"); + var _0777 = parseInt("0777", 8); + module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + function mkdirP(p, opts, f, made) { + if (typeof opts === "function") { + f = opts; + opts = {}; + } else if (!opts || typeof opts !== "object") { + opts = { mode: opts }; + } + var mode = opts.mode; + var xfs = opts.fs || fs7; + if (mode === void 0) { + mode = _0777; + } + if (!made) made = null; + var cb = f || /* istanbul ignore next */ + function() { + }; + p = path6.resolve(p); + xfs.mkdir(p, mode, function(er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case "ENOENT": + if (path6.dirname(p) === p) return cb(er); + mkdirP(path6.dirname(p), opts, function(er2, made2) { + if (er2) cb(er2, made2); + else mkdirP(p, opts, cb, made2); + }); + break; + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function(er2, stat) { + if (er2 || !stat.isDirectory()) cb(er, made); + else cb(null, made); + }); + break; + } + }); + } + mkdirP.sync = function sync(p, opts, made) { + if (!opts || typeof opts !== "object") { + opts = { mode: opts }; + } + var mode = opts.mode; + var xfs = opts.fs || fs7; + if (mode === void 0) { + mode = _0777; + } + if (!made) made = null; + p = path6.resolve(p); + try { + xfs.mkdirSync(p, mode); + made = made || p; + } catch (err0) { + switch (err0.code) { + case "ENOENT": + made = sync(path6.dirname(p), opts, made); + sync(p, opts, made); + break; + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + return made; + }; + } +}); + +// node_modules/unzip-stream/lib/extract.js +var require_extract2 = __commonJS({ + "node_modules/unzip-stream/lib/extract.js"(exports2, module2) { + var fs7 = require("fs"); + var path6 = require("path"); + var util = require("util"); + var mkdirp = require_mkdirp(); + var Transform = require("stream").Transform; + var UnzipStream = require_unzip_stream(); + function Extract(opts) { + if (!(this instanceof Extract)) + return new Extract(opts); + Transform.call(this); + this.opts = opts || {}; + this.unzipStream = new UnzipStream(this.opts); + this.unfinishedEntries = 0; + this.afterFlushWait = false; + this.createdDirectories = {}; var self2 = this; - var isDirectory = vars.uncompressedSize === 0 && /[\/\\]$/.test(entry.path); - entry.path = entry.path.replace(/(?<=^|[/\\]+)[.][.]+(?=[/\\]+|$)/g, "."); - entry.type = isDirectory ? "Directory" : "File"; - entry.isDirectory = isDirectory; - var fileSizeKnown = !(vars.flags & 8); - if (fileSizeKnown) { - entry.size = vars.uncompressedSize; - } - var isVersionSupported = vars.versionsNeededToExtract <= 45; - this.outStreamInfo = { - stream: null, - limit: fileSizeKnown ? vars.compressedSize : -1, - written: 0 + this.unzipStream.on("entry", this._processEntry.bind(this)); + this.unzipStream.on("error", function(error4) { + self2.emit("error", error4); + }); + } + util.inherits(Extract, Transform); + Extract.prototype._transform = function(chunk, encoding, cb) { + this.unzipStream.write(chunk, encoding, cb); + }; + Extract.prototype._flush = function(cb) { + var self2 = this; + var allDone = function() { + process.nextTick(function() { + self2.emit("close"); + }); + cb(); }; - if (!fileSizeKnown) { - var pattern = new Buffer(4); - pattern.writeUInt32LE(SIG_DATA_DESCRIPTOR, 0); - var zip64Mode = vars.extra.zip64Mode; - var extraSize = zip64Mode ? 20 : 12; - var searchPattern = { - pattern, - requiredExtraSize: extraSize - }; - var matcherStream = new MatcherStream(searchPattern, function(matchedChunk, sizeSoFar) { - var vars2 = self2._readDataDescriptor(matchedChunk, zip64Mode); - var compressedSizeMatches = vars2.compressedSize === sizeSoFar; - if (!zip64Mode && !compressedSizeMatches && sizeSoFar >= FOUR_GIGS) { - var overflown = sizeSoFar - FOUR_GIGS; - while (overflown >= 0) { - compressedSizeMatches = vars2.compressedSize === overflown; - if (compressedSizeMatches) break; - overflown -= FOUR_GIGS; - } - } - if (!compressedSizeMatches) { - return; - } - self2.state = states.FILE_DATA_END; - var sliceOffset = zip64Mode ? 24 : 16; - if (self2.data.length > 0) { - self2.data = Buffer.concat([matchedChunk.slice(sliceOffset), self2.data]); - } else { - self2.data = matchedChunk.slice(sliceOffset); - } - return true; + this.unzipStream.end(function() { + if (self2.unfinishedEntries > 0) { + self2.afterFlushWait = true; + return self2.on("await-finished", allDone); + } + allDone(); + }); + }; + Extract.prototype._processEntry = function(entry) { + var self2 = this; + var destPath = path6.join(this.opts.path, entry.path); + var directory = entry.isDirectory ? destPath : path6.dirname(destPath); + this.unfinishedEntries++; + var writeFileFn = function() { + var pipedStream = fs7.createWriteStream(destPath); + pipedStream.on("close", function() { + self2.unfinishedEntries--; + self2._notifyAwaiter(); }); - this.outStreamInfo.stream = matcherStream; - } else { - this.outStreamInfo.stream = new stream.PassThrough(); - } - var isEncrypted = vars.flags & 1 || vars.flags & 64; - if (isEncrypted || !isVersionSupported) { - var message = isEncrypted ? "Encrypted files are not supported!" : "Zip version " + Math.floor(vars.versionsNeededToExtract / 10) + "." + vars.versionsNeededToExtract % 10 + " is not supported"; - entry.skip = true; - setImmediate(() => { - self2.emit("error", new Error(message)); + pipedStream.on("error", function(error4) { + self2.emit("error", error4); }); - this.outStreamInfo.stream.pipe(new Entry().autodrain()); - return; + entry.pipe(pipedStream); + }; + if (this.createdDirectories[directory] || directory === ".") { + return writeFileFn(); } - var isCompressed = vars.compressionMethod > 0; - if (isCompressed) { - var inflater = zlib.createInflateRaw(); - inflater.on("error", function(err) { - self2.state = states.ERROR; - self2.emit("error", err); - }); - this.outStreamInfo.stream.pipe(inflater).pipe(entry); - } else { - this.outStreamInfo.stream.pipe(entry); + mkdirp(directory, function(err) { + if (err) return self2.emit("error", err); + self2.createdDirectories[directory] = true; + if (entry.isDirectory) { + self2.unfinishedEntries--; + self2._notifyAwaiter(); + return; + } + writeFileFn(); + }); + }; + Extract.prototype._notifyAwaiter = function() { + if (this.afterFlushWait && this.unfinishedEntries === 0) { + this.emit("await-finished"); + this.afterFlushWait = false; } - if (this._drainAllEntries) { - entry.autodrain(); + }; + module2.exports = Extract; + } +}); + +// node_modules/unzip-stream/unzip.js +var require_unzip = __commonJS({ + "node_modules/unzip-stream/unzip.js"(exports2) { + "use strict"; + exports2.Parse = require_parser_stream(); + exports2.Extract = require_extract2(); + } +}); + +// node_modules/@actions/artifact/lib/internal/download/download-artifact.js +var require_download_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/internal/download/download-artifact.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - UnzipStream.prototype._readFile = function(data) { - var vars = binary2.parse(data).word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars; - return vars; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; }; - UnzipStream.prototype._readExtraFields = function(data) { - var extra = {}; - var result = { parsed: extra }; - if (this.options.debug) { - result.debug = []; - } - var index = 0; - while (index < data.length) { - var vars = binary2.parse(data).skip(index).word16lu("extraId").word16lu("extraSize").vars; - index += 4; - var fieldType = void 0; - switch (vars.extraId) { - case 1: - fieldType = "Zip64 extended information extra field"; - var z64vars = binary2.parse(data.slice(index, index + vars.extraSize)).word64lu("uncompressedSize").word64lu("compressedSize").word64lu("offsetToLocalHeader").word32lu("diskStartNumber").vars; - if (z64vars.uncompressedSize !== null) { - extra.uncompressedSize = z64vars.uncompressedSize; - } - if (z64vars.compressedSize !== null) { - extra.compressedSize = z64vars.compressedSize; - } - extra.zip64Mode = true; - break; - case 10: - fieldType = "NTFS extra field"; - break; - case 21589: - fieldType = "extended timestamp"; - var timestampFields = data.readUInt8(index); - var offset = 1; - if (vars.extraSize >= offset + 4 && timestampFields & 1) { - extra.mtime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - } - if (vars.extraSize >= offset + 4 && timestampFields & 2) { - extra.atime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - } - if (vars.extraSize >= offset + 4 && timestampFields & 4) { - extra.ctime = new Date(data.readUInt32LE(index + offset) * 1e3); - } - break; - case 28789: - fieldType = "Info-ZIP Unicode Path Extra Field"; - var fieldVer = data.readUInt8(index); - if (fieldVer === 1) { - var offset = 1; - var nameCrc32 = data.readUInt32LE(index + offset); - offset += 4; - var pathBuffer = data.slice(index + offset); - extra.path = pathBuffer.toString(); - } - break; - case 13: - case 22613: - fieldType = vars.extraId === 13 ? "PKWARE Unix" : "Info-ZIP UNIX (type 1)"; - var offset = 0; - if (vars.extraSize >= 8) { - var atime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - var mtime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - extra.atime = atime; - extra.mtime = mtime; - if (vars.extraSize >= 12) { - var uid = data.readUInt16LE(index + offset); - offset += 2; - var gid = data.readUInt16LE(index + offset); - offset += 2; - extra.uid = uid; - extra.gid = gid; - } - } - break; - case 30805: - fieldType = "Info-ZIP UNIX (type 2)"; - var offset = 0; - if (vars.extraSize >= 4) { - var uid = data.readUInt16LE(index + offset); - offset += 2; - var gid = data.readUInt16LE(index + offset); - offset += 2; - extra.uid = uid; - extra.gid = gid; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.streamExtractExternal = streamExtractExternal; + exports2.downloadArtifactPublic = downloadArtifactPublic; + exports2.downloadArtifactInternal = downloadArtifactInternal; + var promises_1 = __importDefault4(require("fs/promises")); + var crypto = __importStar4(require("crypto")); + var stream = __importStar4(require("stream")); + var github2 = __importStar4(require_github()); + var core14 = __importStar4(require_core()); + var httpClient = __importStar4(require_lib7()); + var unzip_stream_1 = __importDefault4(require_unzip()); + var user_agent_1 = require_user_agent2(); + var config_1 = require_config2(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var generated_1 = require_generated(); + var util_1 = require_util11(); + var errors_1 = require_errors3(); + var scrubQueryParameters = (url) => { + const parsed = new URL(url); + parsed.search = ""; + return parsed.toString(); + }; + function exists(path6) { + return __awaiter4(this, void 0, void 0, function* () { + try { + yield promises_1.default.access(path6); + return true; + } catch (error4) { + if (error4.code === "ENOENT") { + return false; + } else { + throw error4; + } + } + }); + } + function streamExtract(url, directory) { + return __awaiter4(this, void 0, void 0, function* () { + let retryCount = 0; + while (retryCount < 5) { + try { + return yield streamExtractExternal(url, directory); + } catch (error4) { + retryCount++; + core14.debug(`Failed to download artifact after ${retryCount} retries due to ${error4.message}. Retrying in 5 seconds...`); + yield new Promise((resolve5) => setTimeout(resolve5, 5e3)); + } + } + throw new Error(`Artifact download failed after ${retryCount} retries.`); + }); + } + function streamExtractExternal(url_1, directory_1) { + return __awaiter4(this, arguments, void 0, function* (url, directory, opts = { timeout: 30 * 1e3 }) { + const client = new httpClient.HttpClient((0, user_agent_1.getUserAgentString)()); + const response = yield client.get(url); + if (response.message.statusCode !== 200) { + throw new Error(`Unexpected HTTP response from blob storage: ${response.message.statusCode} ${response.message.statusMessage}`); + } + let sha256Digest = void 0; + return new Promise((resolve5, reject) => { + const timerFn = () => { + const timeoutError = new Error(`Blob storage chunk did not respond in ${opts.timeout}ms`); + response.message.destroy(timeoutError); + reject(timeoutError); + }; + const timer = setTimeout(timerFn, opts.timeout); + const hashStream = crypto.createHash("sha256").setEncoding("hex"); + const passThrough = new stream.PassThrough(); + response.message.pipe(passThrough); + passThrough.pipe(hashStream); + const extractStream = passThrough; + extractStream.on("data", () => { + timer.refresh(); + }).on("error", (error4) => { + core14.debug(`response.message: Artifact download failed: ${error4.message}`); + clearTimeout(timer); + reject(error4); + }).pipe(unzip_stream_1.default.Extract({ path: directory })).on("close", () => { + clearTimeout(timer); + if (hashStream) { + hashStream.end(); + sha256Digest = hashStream.read(); + core14.info(`SHA256 digest of downloaded artifact is ${sha256Digest}`); } - break; - case 30837: - fieldType = "Info-ZIP New Unix"; - var offset = 0; - var extraVer = data.readUInt8(index); - offset += 1; - if (extraVer === 1) { - var uidSize = data.readUInt8(index + offset); - offset += 1; - if (uidSize <= 6) { - extra.uid = data.readUIntLE(index + offset, uidSize); - } - offset += uidSize; - var gidSize = data.readUInt8(index + offset); - offset += 1; - if (gidSize <= 6) { - extra.gid = data.readUIntLE(index + offset, gidSize); - } + resolve5({ sha256Digest: `sha256:${sha256Digest}` }); + }).on("error", (error4) => { + reject(error4); + }); + }); + }); + } + function downloadArtifactPublic(artifactId, repositoryOwner, repositoryName, token, options) { + return __awaiter4(this, void 0, void 0, function* () { + const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); + const api = github2.getOctokit(token); + let digestMismatch = false; + core14.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`); + const { headers, status } = yield api.rest.actions.downloadArtifact({ + owner: repositoryOwner, + repo: repositoryName, + artifact_id: artifactId, + archive_format: "zip", + request: { + redirect: "manual" + } + }); + if (status !== 302) { + throw new Error(`Unable to download artifact. Unexpected status: ${status}`); + } + const { location } = headers; + if (!location) { + throw new Error(`Unable to redirect to artifact download url`); + } + core14.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`); + try { + core14.info(`Starting download of artifact to: ${downloadPath}`); + const extractResponse = yield streamExtract(location, downloadPath); + core14.info(`Artifact download completed successfully.`); + if (options === null || options === void 0 ? void 0 : options.expectedHash) { + if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { + digestMismatch = true; + core14.debug(`Computed digest: ${extractResponse.sha256Digest}`); + core14.debug(`Expected digest: ${options.expectedHash}`); } - break; - case 30062: - fieldType = "ASi Unix"; - var offset = 0; - if (vars.extraSize >= 14) { - var crc = data.readUInt32LE(index + offset); - offset += 4; - var mode = data.readUInt16LE(index + offset); - offset += 2; - var sizdev = data.readUInt32LE(index + offset); - offset += 4; - var uid = data.readUInt16LE(index + offset); - offset += 2; - var gid = data.readUInt16LE(index + offset); - offset += 2; - extra.mode = mode; - extra.uid = uid; - extra.gid = gid; - if (vars.extraSize > 14) { - var start = index + offset; - var end = index + vars.extraSize - 14; - var symlinkName = this._decodeString(data.slice(start, end)); - extra.symlink = symlinkName; - } + } + } catch (error4) { + throw new Error(`Unable to download and extract artifact: ${error4.message}`); + } + return { downloadPath, digestMismatch }; + }); + } + function downloadArtifactInternal(artifactId, options) { + return __awaiter4(this, void 0, void 0, function* () { + const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + let digestMismatch = false; + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const listReq = { + workflowRunBackendId, + workflowJobRunBackendId, + idFilter: generated_1.Int64Value.create({ value: artifactId.toString() }) + }; + const { artifacts } = yield artifactClient.ListArtifacts(listReq); + if (artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`No artifacts found for ID: ${artifactId} +Are you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`); + } + if (artifacts.length > 1) { + core14.warning("Multiple artifacts found, defaulting to first."); + } + const signedReq = { + workflowRunBackendId: artifacts[0].workflowRunBackendId, + workflowJobRunBackendId: artifacts[0].workflowJobRunBackendId, + name: artifacts[0].name + }; + const { signedUrl } = yield artifactClient.GetSignedArtifactURL(signedReq); + core14.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`); + try { + core14.info(`Starting download of artifact to: ${downloadPath}`); + const extractResponse = yield streamExtract(signedUrl, downloadPath); + core14.info(`Artifact download completed successfully.`); + if (options === null || options === void 0 ? void 0 : options.expectedHash) { + if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { + digestMismatch = true; + core14.debug(`Computed digest: ${extractResponse.sha256Digest}`); + core14.debug(`Expected digest: ${options.expectedHash}`); } - break; + } + } catch (error4) { + throw new Error(`Unable to download and extract artifact: ${error4.message}`); } - if (this.options.debug) { - result.debug.push({ - extraId: "0x" + vars.extraId.toString(16), - description: fieldType, - data: data.slice(index, index + vars.extraSize).inspect() - }); + return { downloadPath, digestMismatch }; + }); + } + function resolveOrCreateDirectory() { + return __awaiter4(this, arguments, void 0, function* (downloadPath = (0, config_1.getGitHubWorkspaceDir)()) { + if (!(yield exists(downloadPath))) { + core14.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`); + yield promises_1.default.mkdir(downloadPath, { recursive: true }); + } else { + core14.debug(`Artifact destination folder already exists: ${downloadPath}`); } - index += vars.extraSize; + return downloadPath; + }); + } + } +}); + +// node_modules/@actions/artifact/lib/internal/find/retry-options.js +var require_retry_options = __commonJS({ + "node_modules/@actions/artifact/lib/internal/find/retry-options.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - return result; - }; - UnzipStream.prototype._readDataDescriptor = function(data, zip64Mode) { - if (zip64Mode) { - var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word64lu("compressedSize").word64lu("uncompressedSize").vars; - return vars; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRetryOptions = getRetryOptions; + var core14 = __importStar4(require_core()); + var defaultMaxRetryNumber = 5; + var defaultExemptStatusCodes = [400, 401, 403, 404, 422]; + function getRetryOptions(defaultOptions, retries = defaultMaxRetryNumber, exemptStatusCodes = defaultExemptStatusCodes) { + var _a; + if (retries <= 0) { + return [{ enabled: false }, defaultOptions.request]; } - var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").vars; - return vars; - }; - UnzipStream.prototype._readCentralDirectoryEntry = function(data) { - var vars = binary2.parse(data).word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars; - return vars; - }; - UnzipStream.prototype._readEndOfCentralDirectory64 = function(data) { - var vars = binary2.parse(data).word64lu("centralDirectoryRecordSize").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskNumberWithCentralDirectoryStart").word64lu("centralDirectoryEntries").word64lu("totalCentralDirectoryEntries").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars; - return vars; - }; - UnzipStream.prototype._readEndOfCentralDirectory = function(data) { - var vars = binary2.parse(data).word16lu("diskNumber").word16lu("diskStart").word16lu("centralDirectoryEntries").word16lu("totalCentralDirectoryEntries").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars; - return vars; - }; - var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 "; - UnzipStream.prototype._decodeString = function(buffer, isUtf8) { - if (isUtf8) { - return buffer.toString("utf8"); + const retryOptions = { + enabled: true + }; + if (exemptStatusCodes.length > 0) { + retryOptions.doNotRetry = exemptStatusCodes; } - if (this.options.decodeString) { - return this.options.decodeString(buffer); + const requestOptions = Object.assign(Object.assign({}, defaultOptions.request), { retries }); + core14.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a = retryOptions.doNotRetry) !== null && _a !== void 0 ? _a : "octokit default: [400, 401, 403, 404, 422]"})`); + return [retryOptions, requestOptions]; + } + } +}); + +// node_modules/@octokit/plugin-request-log/dist-node/index.js +var require_dist_node16 = __commonJS({ + "node_modules/@octokit/plugin-request-log/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var VERSION = "1.0.4"; + function requestLog(octokit) { + octokit.hook.wrap("request", (request, options) => { + octokit.log.debug("request", options); + const start = Date.now(); + const requestOptions = octokit.request.endpoint.parse(options); + const path6 = requestOptions.url.replace(options.baseUrl, ""); + return request(options).then((response) => { + octokit.log.info(`${requestOptions.method} ${path6} - ${response.status} in ${Date.now() - start}ms`); + return response; + }).catch((error4) => { + octokit.log.info(`${requestOptions.method} ${path6} - ${error4.status} in ${Date.now() - start}ms`); + throw error4; + }); + }); + } + requestLog.VERSION = VERSION; + exports2.requestLog = requestLog; + } +}); + +// node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js +var require_dist_node17 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + function _interopDefault(ex) { + return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex; + } + var Bottleneck = _interopDefault(require_light()); + async function errorRequest(octokit, state, error4, options) { + if (!error4.request || !error4.request.request) { + throw error4; } - let result = ""; - for (var i = 0; i < buffer.length; i++) { - result += cp437[buffer[i]]; + if (error4.status >= 400 && !state.doNotRetry.includes(error4.status)) { + const retries = options.request.retries != null ? options.request.retries : state.retries; + const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); + throw octokit.retry.retryRequest(error4, retries, retryAfter); } - return result; - }; - UnzipStream.prototype._parseOrOutput = function(encoding, cb) { - var consume; - while ((consume = this.processDataChunk(this.data)) > 0) { - this.data = this.data.slice(consume); - if (this.data.length === 0) break; + throw error4; + } + async function wrapRequest(state, request, options) { + const limiter = new Bottleneck(); + limiter.on("failed", function(error4, info7) { + const maxRetries = ~~error4.request.request.retries; + const after = ~~error4.request.request.retryAfter; + options.request.retryCount = info7.retryCount + 1; + if (maxRetries > info7.retryCount) { + return after * state.retryAfterBaseValue; + } + }); + return limiter.schedule(request, options); + } + var VERSION = "3.0.9"; + function retry3(octokit, octokitOptions) { + const state = Object.assign({ + enabled: true, + retryAfterBaseValue: 1e3, + doNotRetry: [400, 401, 403, 404, 422], + retries: 3 + }, octokitOptions.retry); + if (state.enabled) { + octokit.hook.error("request", errorRequest.bind(null, octokit, state)); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); } - if (this.state === states.FILE_DATA) { - if (this.outStreamInfo.limit >= 0) { - var remaining = this.outStreamInfo.limit - this.outStreamInfo.written; - var packet; - if (remaining < this.data.length) { - packet = this.data.slice(0, remaining); - this.data = this.data.slice(remaining); - } else { - packet = this.data; - this.data = new Buffer(""); - } - this.outStreamInfo.written += packet.length; - if (this.outStreamInfo.limit === this.outStreamInfo.written) { - this.state = states.START; - this.outStreamInfo.stream.end(packet, encoding, cb); - } else { - this.outStreamInfo.stream.write(packet, encoding, cb); + return { + retry: { + retryRequest: (error4, retries, retryAfter) => { + error4.request.request = Object.assign({}, error4.request.request, { + retries, + retryAfter + }); + return error4; } - } else { - var packet = this.data; - this.data = new Buffer(""); - this.outStreamInfo.written += packet.length; - var outputStream = this.outStreamInfo.stream; - outputStream.write(packet, encoding, () => { - if (this.state === states.FILE_DATA_END) { - this.state = states.START; - return outputStream.end(cb); - } - cb(); - }); } - return; - } - cb(); - }; - UnzipStream.prototype.drainAll = function() { - this._drainAllEntries = true; - }; - UnzipStream.prototype._transform = function(chunk, encoding, cb) { - var self2 = this; - if (self2.data.length > 0) { - self2.data = Buffer.concat([self2.data, chunk]); - } else { - self2.data = chunk; + }; + } + retry3.VERSION = VERSION; + exports2.VERSION = VERSION; + exports2.retry = retry3; + } +}); + +// node_modules/@actions/artifact/lib/internal/find/get-artifact.js +var require_get_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/internal/find/get-artifact.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - var startDataLength = self2.data.length; - var done = function() { - if (self2.data.length > 0 && self2.data.length < startDataLength) { - startDataLength = self2.data.length; - self2._parseOrOutput(encoding, done); - return; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); } - cb(); + __setModuleDefault4(result, mod); + return result; }; - self2._parseOrOutput(encoding, done); - }; - UnzipStream.prototype._flush = function(cb) { - var self2 = this; - if (self2.data.length > 0) { - self2._parseOrOutput("buffer", function() { - if (self2.data.length > 0) return setImmediate(function() { - self2._flush(cb); - }); - cb(); + })(); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); }); - return; } - if (self2.state === states.FILE_DATA) { - return cb(new Error("Stream finished in an invalid state, uncompression failed")); - } - setImmediate(cb); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - module2.exports = UnzipStream; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getArtifactPublic = getArtifactPublic; + exports2.getArtifactInternal = getArtifactInternal; + var github_1 = require_github(); + var plugin_retry_1 = require_dist_node17(); + var core14 = __importStar4(require_core()); + var utils_1 = require_utils4(); + var retry_options_1 = require_retry_options(); + var plugin_request_log_1 = require_dist_node16(); + var util_1 = require_util11(); + var user_agent_1 = require_user_agent2(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var generated_1 = require_generated(); + var errors_1 = require_errors3(); + function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { + return __awaiter4(this, void 0, void 0, function* () { + var _a; + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: void 0, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: void 0, + retry: retryOpts, + request: requestOpts + }; + const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + const getArtifactResp = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}", { + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + name: artifactName + }); + if (getArtifactResp.status !== 200) { + throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); + } + if (getArtifactResp.data.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} + Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. + For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); + } + let artifact2 = getArtifactResp.data.artifacts[0]; + if (getArtifactResp.data.artifacts.length > 1) { + artifact2 = getArtifactResp.data.artifacts.sort((a, b) => b.id - a.id)[0]; + core14.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.id})`); + } + return { + artifact: { + name: artifact2.name, + id: artifact2.id, + size: artifact2.size_in_bytes, + createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, + digest: artifact2.digest + } + }; + }); + } + function getArtifactInternal(artifactName) { + return __awaiter4(this, void 0, void 0, function* () { + var _a; + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const req = { + workflowRunBackendId, + workflowJobRunBackendId, + nameFilter: generated_1.StringValue.create({ value: artifactName }) + }; + const res = yield artifactClient.ListArtifacts(req); + if (res.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} + Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. + For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); + } + let artifact2 = res.artifacts[0]; + if (res.artifacts.length > 1) { + artifact2 = res.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; + core14.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); + } + return { + artifact: { + name: artifact2.name, + id: Number(artifact2.databaseId), + size: Number(artifact2.size), + createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, + digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value + } + }; + }); + } } }); -// node_modules/unzip-stream/lib/parser-stream.js -var require_parser_stream = __commonJS({ - "node_modules/unzip-stream/lib/parser-stream.js"(exports2, module2) { - var Transform = require("stream").Transform; - var util = require("util"); - var UnzipStream = require_unzip_stream(); - function ParserStream(opts) { - if (!(this instanceof ParserStream)) { - return new ParserStream(opts); +// node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js +var require_delete_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - var transformOpts = opts || {}; - Transform.call(this, { readableObjectMode: true }); - this.opts = opts || {}; - this.unzipStream = new UnzipStream(this.opts); - var self2 = this; - this.unzipStream.on("entry", function(entry) { - self2.push(entry); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - this.unzipStream.on("error", function(error4) { - self2.emit("error", error4); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.deleteArtifactPublic = deleteArtifactPublic; + exports2.deleteArtifactInternal = deleteArtifactInternal; + var core_1 = require_core(); + var github_1 = require_github(); + var user_agent_1 = require_user_agent2(); + var retry_options_1 = require_retry_options(); + var utils_1 = require_utils4(); + var plugin_request_log_1 = require_dist_node16(); + var plugin_retry_1 = require_dist_node17(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var util_1 = require_util11(); + var generated_1 = require_generated(); + var get_artifact_1 = require_get_artifact(); + var errors_1 = require_errors3(); + function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { + return __awaiter4(this, void 0, void 0, function* () { + var _a; + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: void 0, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: void 0, + retry: retryOpts, + request: requestOpts + }; + const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + const getArtifactResp = yield (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + const deleteArtifactResp = yield github2.rest.actions.deleteArtifact({ + owner: repositoryOwner, + repo: repositoryName, + artifact_id: getArtifactResp.artifact.id + }); + if (deleteArtifactResp.status !== 204) { + throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); + } + return { + id: getArtifactResp.artifact.id + }; }); } - util.inherits(ParserStream, Transform); - ParserStream.prototype._transform = function(chunk, encoding, cb) { - this.unzipStream.write(chunk, encoding, cb); - }; - ParserStream.prototype._flush = function(cb) { - var self2 = this; - this.unzipStream.end(function() { - process.nextTick(function() { - self2.emit("close"); - }); - cb(); + function deleteArtifactInternal(artifactName) { + return __awaiter4(this, void 0, void 0, function* () { + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const listReq = { + workflowRunBackendId, + workflowJobRunBackendId, + nameFilter: generated_1.StringValue.create({ value: artifactName }) + }; + const listRes = yield artifactClient.ListArtifacts(listReq); + if (listRes.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); + } + let artifact2 = listRes.artifacts[0]; + if (listRes.artifacts.length > 1) { + artifact2 = listRes.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; + (0, core_1.debug)(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); + } + const req = { + workflowRunBackendId: artifact2.workflowRunBackendId, + workflowJobRunBackendId: artifact2.workflowJobRunBackendId, + name: artifact2.name + }; + const res = yield artifactClient.DeleteArtifact(req); + (0, core_1.info)(`Artifact '${artifactName}' (ID: ${res.artifactId}) deleted`); + return { + id: Number(res.artifactId) + }; }); - }; - ParserStream.prototype.on = function(eventName, fn) { - if (eventName === "entry") { - return Transform.prototype.on.call(this, "data", fn); - } - return Transform.prototype.on.call(this, eventName, fn); - }; - ParserStream.prototype.drainAll = function() { - this.unzipStream.drainAll(); - return this.pipe(new Transform({ objectMode: true, transform: function(d, e, cb) { - cb(); - } })); - }; - module2.exports = ParserStream; + } } }); -// node_modules/mkdirp/index.js -var require_mkdirp = __commonJS({ - "node_modules/mkdirp/index.js"(exports2, module2) { - var path6 = require("path"); - var fs7 = require("fs"); - var _0777 = parseInt("0777", 8); - module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - function mkdirP(p, opts, f, made) { - if (typeof opts === "function") { - f = opts; - opts = {}; - } else if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - var mode = opts.mode; - var xfs = opts.fs || fs7; - if (mode === void 0) { - mode = _0777; +// node_modules/@actions/artifact/lib/internal/find/list-artifacts.js +var require_list_artifacts = __commonJS({ + "node_modules/@actions/artifact/lib/internal/find/list-artifacts.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - if (!made) made = null; - var cb = f || /* istanbul ignore next */ - function() { - }; - p = path6.resolve(p); - xfs.mkdir(p, mode, function(er) { - if (!er) { - made = made || p; - return cb(null, made); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - switch (er.code) { - case "ENOENT": - if (path6.dirname(p) === p) return cb(er); - mkdirP(path6.dirname(p), opts, function(er2, made2) { - if (er2) cb(er2, made2); - else mkdirP(p, opts, cb, made2); - }); - break; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function(er2, stat) { - if (er2 || !stat.isDirectory()) cb(er, made); - else cb(null, made); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.listArtifactsPublic = listArtifactsPublic; + exports2.listArtifactsInternal = listArtifactsInternal; + var core_1 = require_core(); + var github_1 = require_github(); + var user_agent_1 = require_user_agent2(); + var retry_options_1 = require_retry_options(); + var utils_1 = require_utils4(); + var plugin_request_log_1 = require_dist_node16(); + var plugin_retry_1 = require_dist_node17(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var util_1 = require_util11(); + var config_1 = require_config2(); + var generated_1 = require_generated(); + var maximumArtifactCount = (0, config_1.getMaxArtifactListCount)(); + var paginationCount = 100; + var maxNumberOfPages = Math.ceil(maximumArtifactCount / paginationCount); + function listArtifactsPublic(workflowRunId_1, repositoryOwner_1, repositoryName_1, token_1) { + return __awaiter4(this, arguments, void 0, function* (workflowRunId, repositoryOwner, repositoryName, token, latest = false) { + (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`); + let artifacts = []; + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: void 0, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: void 0, + retry: retryOpts, + request: requestOpts + }; + const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + let currentPageNumber = 1; + const { data: listArtifactResponse } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + per_page: paginationCount, + page: currentPageNumber + }); + let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount); + const totalArtifactCount = listArtifactResponse.total_count; + if (totalArtifactCount > maximumArtifactCount) { + (0, core_1.warning)(`Workflow run ${workflowRunId} has ${totalArtifactCount} artifacts, exceeding the limit of ${maximumArtifactCount}. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`); + numberOfPages = maxNumberOfPages; + } + for (const artifact2 of listArtifactResponse.artifacts) { + artifacts.push({ + name: artifact2.name, + id: artifact2.id, + size: artifact2.size_in_bytes, + createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, + digest: artifact2.digest + }); + } + currentPageNumber++; + for (currentPageNumber; currentPageNumber <= numberOfPages; currentPageNumber++) { + (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`); + const { data: listArtifactResponse2 } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + per_page: paginationCount, + page: currentPageNumber + }); + for (const artifact2 of listArtifactResponse2.artifacts) { + artifacts.push({ + name: artifact2.name, + id: artifact2.id, + size: artifact2.size_in_bytes, + createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, + digest: artifact2.digest }); - break; + } } + if (latest) { + artifacts = filterLatest(artifacts); + } + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; }); } - mkdirP.sync = function sync(p, opts, made) { - if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - var mode = opts.mode; - var xfs = opts.fs || fs7; - if (mode === void 0) { - mode = _0777; - } - if (!made) made = null; - p = path6.resolve(p); - try { - xfs.mkdirSync(p, mode); - made = made || p; - } catch (err0) { - switch (err0.code) { - case "ENOENT": - made = sync(path6.dirname(p), opts, made); - sync(p, opts, made); - break; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; + function listArtifactsInternal() { + return __awaiter4(this, arguments, void 0, function* (latest = false) { + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const req = { + workflowRunBackendId, + workflowJobRunBackendId + }; + const res = yield artifactClient.ListArtifacts(req); + let artifacts = res.artifacts.map((artifact2) => { + var _a; + return { + name: artifact2.name, + id: Number(artifact2.databaseId), + size: Number(artifact2.size), + createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, + digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value + }; + }); + if (latest) { + artifacts = filterLatest(artifacts); + } + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; + }); + } + function filterLatest(artifacts) { + artifacts.sort((a, b) => b.id - a.id); + const latestArtifacts = []; + const seenArtifactNames = /* @__PURE__ */ new Set(); + for (const artifact2 of artifacts) { + if (!seenArtifactNames.has(artifact2.name)) { + latestArtifacts.push(artifact2); + seenArtifactNames.add(artifact2.name); } } - return made; - }; + return latestArtifacts; + } } }); -// node_modules/unzip-stream/lib/extract.js -var require_extract2 = __commonJS({ - "node_modules/unzip-stream/lib/extract.js"(exports2, module2) { - var fs7 = require("fs"); - var path6 = require("path"); - var util = require("util"); - var mkdirp = require_mkdirp(); - var Transform = require("stream").Transform; - var UnzipStream = require_unzip_stream(); - function Extract(opts) { - if (!(this instanceof Extract)) - return new Extract(opts); - Transform.call(this); - this.opts = opts || {}; - this.unzipStream = new UnzipStream(this.opts); - this.unfinishedEntries = 0; - this.afterFlushWait = false; - this.createdDirectories = {}; - var self2 = this; - this.unzipStream.on("entry", this._processEntry.bind(this)); - this.unzipStream.on("error", function(error4) { - self2.emit("error", error4); - }); - } - util.inherits(Extract, Transform); - Extract.prototype._transform = function(chunk, encoding, cb) { - this.unzipStream.write(chunk, encoding, cb); - }; - Extract.prototype._flush = function(cb) { - var self2 = this; - var allDone = function() { - process.nextTick(function() { - self2.emit("close"); +// node_modules/@actions/artifact/lib/internal/client.js +var require_client2 = __commonJS({ + "node_modules/@actions/artifact/lib/internal/client.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); }); - cb(); - }; - this.unzipStream.end(function() { - if (self2.unfinishedEntries > 0) { - self2.afterFlushWait = true; - return self2.on("await-finished", allDone); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - allDone(); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - Extract.prototype._processEntry = function(entry) { - var self2 = this; - var destPath = path6.join(this.opts.path, entry.path); - var directory = entry.isDirectory ? destPath : path6.dirname(destPath); - this.unfinishedEntries++; - var writeFileFn = function() { - var pipedStream = fs7.createWriteStream(destPath); - pipedStream.on("close", function() { - self2.unfinishedEntries--; - self2._notifyAwaiter(); + var __rest4 = exports2 && exports2.__rest || function(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DefaultArtifactClient = void 0; + var core_1 = require_core(); + var config_1 = require_config2(); + var upload_artifact_1 = require_upload_artifact(); + var download_artifact_1 = require_download_artifact(); + var delete_artifact_1 = require_delete_artifact(); + var get_artifact_1 = require_get_artifact(); + var list_artifacts_1 = require_list_artifacts(); + var errors_1 = require_errors3(); + var DefaultArtifactClient2 = class { + uploadArtifact(name, files, rootDirectory, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options); + } catch (error4) { + (0, core_1.warning)(`Artifact upload failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } }); - pipedStream.on("error", function(error4) { - self2.emit("error", error4); + } + downloadArtifact(artifactId, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest4(options, ["findBy"]); + return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions); + } + return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options); + } catch (error4) { + (0, core_1.warning)(`Download Artifact failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } }); - entry.pipe(pipedStream); - }; - if (this.createdDirectories[directory] || directory === ".") { - return writeFileFn(); } - mkdirp(directory, function(err) { - if (err) return self2.emit("error", err); - self2.createdDirectories[directory] = true; - if (entry.isDirectory) { - self2.unfinishedEntries--; - self2._notifyAwaiter(); - return; - } - writeFileFn(); - }); - }; - Extract.prototype._notifyAwaiter = function() { - if (this.afterFlushWait && this.unfinishedEntries === 0) { - this.emit("await-finished"); - this.afterFlushWait = false; + listArtifacts(options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; + return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest); + } + return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest); + } catch (error4) { + (0, core_1.warning)(`Listing Artifacts failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); + } + getArtifact(artifactName, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; + return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + } + return (0, get_artifact_1.getArtifactInternal)(artifactName); + } catch (error4) { + (0, core_1.warning)(`Get Artifact failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); + } + deleteArtifact(artifactName, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { repositoryOwner, repositoryName, workflowRunId, token } } = options; + return (0, delete_artifact_1.deleteArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + } + return (0, delete_artifact_1.deleteArtifactInternal)(artifactName); + } catch (error4) { + (0, core_1.warning)(`Delete Artifact failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); } }; - module2.exports = Extract; + exports2.DefaultArtifactClient = DefaultArtifactClient2; } }); -// node_modules/unzip-stream/unzip.js -var require_unzip = __commonJS({ - "node_modules/unzip-stream/unzip.js"(exports2) { +// node_modules/@actions/artifact/lib/internal/shared/interfaces.js +var require_interfaces2 = __commonJS({ + "node_modules/@actions/artifact/lib/internal/shared/interfaces.js"(exports2) { "use strict"; - exports2.Parse = require_parser_stream(); - exports2.Extract = require_extract2(); + Object.defineProperty(exports2, "__esModule", { value: true }); } }); -// node_modules/@actions/artifact/lib/internal/download/download-artifact.js -var require_download_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/internal/download/download-artifact.js"(exports2) { +// node_modules/@actions/artifact/lib/artifact.js +var require_artifact2 = __commonJS({ + "node_modules/@actions/artifact/lib/artifact.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -105968,251 +110741,80 @@ var require_download_artifact = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); - } - __setModuleDefault4(result, mod); - return result; - }; - })(); - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.streamExtractExternal = streamExtractExternal; - exports2.downloadArtifactPublic = downloadArtifactPublic; - exports2.downloadArtifactInternal = downloadArtifactInternal; - var promises_1 = __importDefault4(require("fs/promises")); - var crypto = __importStar4(require("crypto")); - var stream = __importStar4(require("stream")); - var github2 = __importStar4(require_github()); - var core14 = __importStar4(require_core()); - var httpClient = __importStar4(require_lib()); - var unzip_stream_1 = __importDefault4(require_unzip()); - var user_agent_1 = require_user_agent2(); - var config_1 = require_config2(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var generated_1 = require_generated(); - var util_1 = require_util11(); - var errors_1 = require_errors3(); - var scrubQueryParameters = (url) => { - const parsed = new URL(url); - parsed.search = ""; - return parsed.toString(); - }; - function exists(path6) { - return __awaiter4(this, void 0, void 0, function* () { - try { - yield promises_1.default.access(path6); - return true; - } catch (error4) { - if (error4.code === "ENOENT") { - return false; - } else { - throw error4; - } - } - }); - } - function streamExtract(url, directory) { - return __awaiter4(this, void 0, void 0, function* () { - let retryCount = 0; - while (retryCount < 5) { - try { - return yield streamExtractExternal(url, directory); - } catch (error4) { - retryCount++; - core14.debug(`Failed to download artifact after ${retryCount} retries due to ${error4.message}. Retrying in 5 seconds...`); - yield new Promise((resolve5) => setTimeout(resolve5, 5e3)); - } - } - throw new Error(`Artifact download failed after ${retryCount} retries.`); - }); - } - function streamExtractExternal(url_1, directory_1) { - return __awaiter4(this, arguments, void 0, function* (url, directory, opts = { timeout: 30 * 1e3 }) { - const client = new httpClient.HttpClient((0, user_agent_1.getUserAgentString)()); - const response = yield client.get(url); - if (response.message.statusCode !== 200) { - throw new Error(`Unexpected HTTP response from blob storage: ${response.message.statusCode} ${response.message.statusMessage}`); - } - let sha256Digest = void 0; - return new Promise((resolve5, reject) => { - const timerFn = () => { - const timeoutError = new Error(`Blob storage chunk did not respond in ${opts.timeout}ms`); - response.message.destroy(timeoutError); - reject(timeoutError); - }; - const timer = setTimeout(timerFn, opts.timeout); - const hashStream = crypto.createHash("sha256").setEncoding("hex"); - const passThrough = new stream.PassThrough(); - response.message.pipe(passThrough); - passThrough.pipe(hashStream); - const extractStream = passThrough; - extractStream.on("data", () => { - timer.refresh(); - }).on("error", (error4) => { - core14.debug(`response.message: Artifact download failed: ${error4.message}`); - clearTimeout(timer); - reject(error4); - }).pipe(unzip_stream_1.default.Extract({ path: directory })).on("close", () => { - clearTimeout(timer); - if (hashStream) { - hashStream.end(); - sha256Digest = hashStream.read(); - core14.info(`SHA256 digest of downloaded artifact is ${sha256Digest}`); - } - resolve5({ sha256Digest: `sha256:${sha256Digest}` }); - }).on("error", (error4) => { - reject(error4); - }); - }); - }); - } - function downloadArtifactPublic(artifactId, repositoryOwner, repositoryName, token, options) { - return __awaiter4(this, void 0, void 0, function* () { - const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); - const api = github2.getOctokit(token); - let digestMismatch = false; - core14.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`); - const { headers, status } = yield api.rest.actions.downloadArtifact({ - owner: repositoryOwner, - repo: repositoryName, - artifact_id: artifactId, - archive_format: "zip", - request: { - redirect: "manual" - } - }); - if (status !== 302) { - throw new Error(`Unable to download artifact. Unexpected status: ${status}`); - } - const { location } = headers; - if (!location) { - throw new Error(`Unable to redirect to artifact download url`); - } - core14.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`); - try { - core14.info(`Starting download of artifact to: ${downloadPath}`); - const extractResponse = yield streamExtract(location, downloadPath); - core14.info(`Artifact download completed successfully.`); - if (options === null || options === void 0 ? void 0 : options.expectedHash) { - if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { - digestMismatch = true; - core14.debug(`Computed digest: ${extractResponse.sha256Digest}`); - core14.debug(`Expected digest: ${options.expectedHash}`); - } - } - } catch (error4) { - throw new Error(`Unable to download and extract artifact: ${error4.message}`); - } - return { downloadPath, digestMismatch }; - }); - } - function downloadArtifactInternal(artifactId, options) { - return __awaiter4(this, void 0, void 0, function* () { - const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - let digestMismatch = false; - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const listReq = { - workflowRunBackendId, - workflowJobRunBackendId, - idFilter: generated_1.Int64Value.create({ value: artifactId.toString() }) - }; - const { artifacts } = yield artifactClient.ListArtifacts(listReq); - if (artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`No artifacts found for ID: ${artifactId} -Are you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`); - } - if (artifacts.length > 1) { - core14.warning("Multiple artifacts found, defaulting to first."); - } - const signedReq = { - workflowRunBackendId: artifacts[0].workflowRunBackendId, - workflowJobRunBackendId: artifacts[0].workflowJobRunBackendId, - name: artifacts[0].name - }; - const { signedUrl } = yield artifactClient.GetSignedArtifactURL(signedReq); - core14.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`); - try { - core14.info(`Starting download of artifact to: ${downloadPath}`); - const extractResponse = yield streamExtract(signedUrl, downloadPath); - core14.info(`Artifact download completed successfully.`); - if (options === null || options === void 0 ? void 0 : options.expectedHash) { - if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { - digestMismatch = true; - core14.debug(`Computed digest: ${extractResponse.sha256Digest}`); - core14.debug(`Expected digest: ${options.expectedHash}`); - } - } - } catch (error4) { - throw new Error(`Unable to download and extract artifact: ${error4.message}`); + var client_1 = require_client2(); + __exportStar4(require_interfaces2(), exports2); + __exportStar4(require_errors3(), exports2); + __exportStar4(require_client2(), exports2); + var client = new client_1.DefaultArtifactClient(); + exports2.default = client; + } +}); + +// node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js +var require_path_and_artifact_name_validation2 = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkArtifactFilePath = exports2.checkArtifactName = void 0; + var core_1 = require_core(); + var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ + ['"', ' Double quote "'], + [":", " Colon :"], + ["<", " Less than <"], + [">", " Greater than >"], + ["|", " Vertical bar |"], + ["*", " Asterisk *"], + ["?", " Question mark ?"], + ["\r", " Carriage return \\r"], + ["\n", " Line feed \\n"] + ]); + var invalidArtifactNameCharacters = new Map([ + ...invalidArtifactFilePathCharacters, + ["\\", " Backslash \\"], + ["/", " Forward slash /"] + ]); + function checkArtifactName(name) { + if (!name) { + throw new Error(`Artifact name: ${name}, is incorrectly provided`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { + if (name.includes(invalidCharacterKey)) { + throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} + +These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); } - return { downloadPath, digestMismatch }; - }); + } + (0, core_1.info)(`Artifact name is valid!`); } - function resolveOrCreateDirectory() { - return __awaiter4(this, arguments, void 0, function* (downloadPath = (0, config_1.getGitHubWorkspaceDir)()) { - if (!(yield exists(downloadPath))) { - core14.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`); - yield promises_1.default.mkdir(downloadPath, { recursive: true }); - } else { - core14.debug(`Artifact destination folder already exists: ${downloadPath}`); + exports2.checkArtifactName = checkArtifactName; + function checkArtifactFilePath(path6) { + if (!path6) { + throw new Error(`Artifact path: ${path6}, is incorrectly provided`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { + if (path6.includes(invalidCharacterKey)) { + throw new Error(`Artifact path is not valid: ${path6}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} + +The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. + `); } - return downloadPath; - }); + } } + exports2.checkArtifactFilePath = checkArtifactFilePath; } }); -// node_modules/@actions/artifact/lib/internal/find/retry-options.js -var require_retry_options = __commonJS({ - "node_modules/@actions/artifact/lib/internal/find/retry-options.js"(exports2) { +// node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js +var require_upload_specification = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -106232,560 +110834,573 @@ var require_retry_options = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); - } - __setModuleDefault4(result, mod); - return result; - }; - })(); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRetryOptions = getRetryOptions; - var core14 = __importStar4(require_core()); - var defaultMaxRetryNumber = 5; - var defaultExemptStatusCodes = [400, 401, 403, 404, 422]; - function getRetryOptions(defaultOptions, retries = defaultMaxRetryNumber, exemptStatusCodes = defaultExemptStatusCodes) { - var _a; - if (retries <= 0) { - return [{ enabled: false }, defaultOptions.request]; + exports2.getUploadSpecification = void 0; + var fs7 = __importStar4(require("fs")); + var core_1 = require_core(); + var path_1 = require("path"); + var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); + function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { + const specifications = []; + if (!fs7.existsSync(rootDirectory)) { + throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); } - const retryOptions = { - enabled: true - }; - if (exemptStatusCodes.length > 0) { - retryOptions.doNotRetry = exemptStatusCodes; + if (!fs7.statSync(rootDirectory).isDirectory()) { + throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); } - const requestOptions = Object.assign(Object.assign({}, defaultOptions.request), { retries }); - core14.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a = retryOptions.doNotRetry) !== null && _a !== void 0 ? _a : "octokit default: [400, 401, 403, 404, 422]"})`); - return [retryOptions, requestOptions]; + rootDirectory = (0, path_1.normalize)(rootDirectory); + rootDirectory = (0, path_1.resolve)(rootDirectory); + for (let file of artifactFiles) { + if (!fs7.existsSync(file)) { + throw new Error(`File ${file} does not exist`); + } + if (!fs7.statSync(file).isDirectory()) { + file = (0, path_1.normalize)(file); + file = (0, path_1.resolve)(file); + if (!file.startsWith(rootDirectory)) { + throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); + } + const uploadPath = file.replace(rootDirectory, ""); + (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath); + specifications.push({ + absoluteFilePath: file, + uploadFilePath: (0, path_1.join)(artifactName, uploadPath) + }); + } else { + (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`); + } + } + return specifications; } + exports2.getUploadSpecification = getUploadSpecification; } }); -// node_modules/@octokit/plugin-request-log/dist-node/index.js -var require_dist_node16 = __commonJS({ - "node_modules/@octokit/plugin-request-log/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var VERSION = "1.0.4"; - function requestLog(octokit) { - octokit.hook.wrap("request", (request, options) => { - octokit.log.debug("request", options); - const start = Date.now(); - const requestOptions = octokit.request.endpoint.parse(options); - const path6 = requestOptions.url.replace(options.baseUrl, ""); - return request(options).then((response) => { - octokit.log.info(`${requestOptions.method} ${path6} - ${response.status} in ${Date.now() - start}ms`); - return response; - }).catch((error4) => { - octokit.log.info(`${requestOptions.method} ${path6} - ${error4.status} in ${Date.now() - start}ms`); - throw error4; - }); - }); +// node_modules/tmp/lib/tmp.js +var require_tmp = __commonJS({ + "node_modules/tmp/lib/tmp.js"(exports2, module2) { + var fs7 = require("fs"); + var os = require("os"); + var path6 = require("path"); + var crypto = require("crypto"); + var _c = { fs: fs7.constants, os: os.constants }; + var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + var TEMPLATE_PATTERN = /XXXXXX/; + var DEFAULT_TRIES = 3; + var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR); + var IS_WIN32 = os.platform() === "win32"; + var EBADF = _c.EBADF || _c.os.errno.EBADF; + var ENOENT = _c.ENOENT || _c.os.errno.ENOENT; + var DIR_MODE = 448; + var FILE_MODE = 384; + var EXIT = "exit"; + var _removeObjects = []; + var FN_RMDIR_SYNC = fs7.rmdirSync.bind(fs7); + var _gracefulCleanup = false; + function rimraf(dirPath, callback) { + return fs7.rm(dirPath, { recursive: true }, callback); } - requestLog.VERSION = VERSION; - exports2.requestLog = requestLog; - } -}); - -// node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js -var require_dist_node17 = __commonJS({ - "node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function _interopDefault(ex) { - return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex; + function FN_RIMRAF_SYNC(dirPath) { + return fs7.rmSync(dirPath, { recursive: true }); } - var Bottleneck = _interopDefault(require_light()); - async function errorRequest(octokit, state, error4, options) { - if (!error4.request || !error4.request.request) { - throw error4; - } - if (error4.status >= 400 && !state.doNotRetry.includes(error4.status)) { - const retries = options.request.retries != null ? options.request.retries : state.retries; - const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); - throw octokit.retry.retryRequest(error4, retries, retryAfter); - } - throw error4; + function tmpName(options, callback) { + const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; + _assertAndSanitizeOptions(opts, function(err, sanitizedOptions) { + if (err) return cb(err); + let tries = sanitizedOptions.tries; + (function _getUniqueName() { + try { + const name = _generateTmpName(sanitizedOptions); + fs7.stat(name, function(err2) { + if (!err2) { + if (tries-- > 0) return _getUniqueName(); + return cb(new Error("Could not get a unique tmp filename, max tries reached " + name)); + } + cb(null, name); + }); + } catch (err2) { + cb(err2); + } + })(); + }); } - async function wrapRequest(state, request, options) { - const limiter = new Bottleneck(); - limiter.on("failed", function(error4, info7) { - const maxRetries = ~~error4.request.request.retries; - const after = ~~error4.request.request.retryAfter; - options.request.retryCount = info7.retryCount + 1; - if (maxRetries > info7.retryCount) { - return after * state.retryAfterBaseValue; + function tmpNameSync(options) { + const args = _parseArguments(options), opts = args[0]; + const sanitizedOptions = _assertAndSanitizeOptionsSync(opts); + let tries = sanitizedOptions.tries; + do { + const name = _generateTmpName(sanitizedOptions); + try { + fs7.statSync(name); + } catch (e) { + return name; } + } while (tries-- > 0); + throw new Error("Could not get a unique tmp filename, max tries reached"); + } + function file(options, callback) { + const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; + tmpName(opts, function _tmpNameCreated(err, name) { + if (err) return cb(err); + fs7.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { + if (err2) return cb(err2); + if (opts.discardDescriptor) { + return fs7.close(fd, function _discardCallback(possibleErr) { + return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false)); + }); + } else { + const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; + cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); + } + }); }); - return limiter.schedule(request, options); } - var VERSION = "3.0.9"; - function retry3(octokit, octokitOptions) { - const state = Object.assign({ - enabled: true, - retryAfterBaseValue: 1e3, - doNotRetry: [400, 401, 403, 404, 422], - retries: 3 - }, octokitOptions.retry); - if (state.enabled) { - octokit.hook.error("request", errorRequest.bind(null, octokit, state)); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); + function fileSync(options) { + const args = _parseArguments(options), opts = args[0]; + const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; + const name = tmpNameSync(opts); + let fd = fs7.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); + if (opts.discardDescriptor) { + fs7.closeSync(fd); + fd = void 0; } return { - retry: { - retryRequest: (error4, retries, retryAfter) => { - error4.request.request = Object.assign({}, error4.request.request, { - retries, - retryAfter - }); - return error4; - } - } + name, + fd, + removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) }; } - retry3.VERSION = VERSION; - exports2.VERSION = VERSION; - exports2.retry = retry3; - } -}); - -// node_modules/@actions/artifact/lib/internal/find/get-artifact.js -var require_get_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/internal/find/get-artifact.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); + function dir(options, callback) { + const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; + tmpName(opts, function _tmpNameCreated(err, name) { + if (err) return cb(err); + fs7.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { + if (err2) return cb(err2); + cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); + }); + }); + } + function dirSync(options) { + const args = _parseArguments(options), opts = args[0]; + const name = tmpNameSync(opts); + fs7.mkdirSync(name, opts.mode || DIR_MODE); + return { + name, + removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + function _removeFileAsync(fdPath, next) { + const _handler = function(err) { + if (err && !_isENOENT(err)) { + return next(err); } - __setModuleDefault4(result, mod); - return result; + next(); }; - })(); - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); + if (0 <= fdPath[0]) + fs7.close(fdPath[0], function() { + fs7.unlink(fdPath[1], _handler); }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + else fs7.unlink(fdPath[1], _handler); + } + function _removeFileSync(fdPath) { + let rethrownException = null; + try { + if (0 <= fdPath[0]) fs7.closeSync(fdPath[0]); + } catch (e) { + if (!_isEBADF(e) && !_isENOENT(e)) throw e; + } finally { + try { + fs7.unlinkSync(fdPath[1]); + } catch (e) { + if (!_isENOENT(e)) rethrownException = e; } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + } + if (rethrownException !== null) { + throw rethrownException; + } + } + function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { + const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); + const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + return sync ? removeCallbackSync : removeCallback; + } + function _prepareTmpDirRemoveCallback(name, opts, sync) { + const removeFunction = opts.unsafeCleanup ? rimraf : fs7.rmdir.bind(fs7); + const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; + const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); + const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + return sync ? removeCallbackSync : removeCallback; + } + function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { + let called = false; + return function _cleanupCallback(next) { + if (!called) { + const toRemove = cleanupCallbackSync || _cleanupCallback; + const index = _removeObjects.indexOf(toRemove); + if (index >= 0) _removeObjects.splice(index, 1); + called = true; + if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { + return removeFunction(fileOrDirName); + } else { + return removeFunction(fileOrDirName, next || function() { + }); } } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getArtifactPublic = getArtifactPublic; - exports2.getArtifactInternal = getArtifactInternal; - var github_1 = require_github(); - var plugin_retry_1 = require_dist_node17(); - var core14 = __importStar4(require_core()); - var utils_1 = require_utils4(); - var retry_options_1 = require_retry_options(); - var plugin_request_log_1 = require_dist_node16(); - var util_1 = require_util11(); - var user_agent_1 = require_user_agent2(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var generated_1 = require_generated(); - var errors_1 = require_errors3(); - function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { - return __awaiter4(this, void 0, void 0, function* () { - var _a; - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: void 0, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: void 0, - retry: retryOpts, - request: requestOpts - }; - const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - const getArtifactResp = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}", { - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - name: artifactName - }); - if (getArtifactResp.status !== 200) { - throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); - } - if (getArtifactResp.data.artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} - Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. - For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); + }; + } + function _garbageCollector() { + if (!_gracefulCleanup) return; + while (_removeObjects.length) { + try { + _removeObjects[0](); + } catch (e) { } - let artifact2 = getArtifactResp.data.artifacts[0]; - if (getArtifactResp.data.artifacts.length > 1) { - artifact2 = getArtifactResp.data.artifacts.sort((a, b) => b.id - a.id)[0]; - core14.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.id})`); + } + } + function _randomChars(howMany) { + let value = [], rnd = null; + try { + rnd = crypto.randomBytes(howMany); + } catch (e) { + rnd = crypto.pseudoRandomBytes(howMany); + } + for (let i = 0; i < howMany; i++) { + value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); + } + return value.join(""); + } + function _isUndefined(obj) { + return typeof obj === "undefined"; + } + function _parseArguments(options, callback) { + if (typeof options === "function") { + return [{}, options]; + } + if (_isUndefined(options)) { + return [{}, callback]; + } + const actualOptions = {}; + for (const key of Object.getOwnPropertyNames(options)) { + actualOptions[key] = options[key]; + } + return [actualOptions, callback]; + } + function _resolvePath(name, tmpDir, cb) { + const pathToResolve = path6.isAbsolute(name) ? name : path6.join(tmpDir, name); + fs7.stat(pathToResolve, function(err) { + if (err) { + fs7.realpath(path6.dirname(pathToResolve), function(err2, parentDir) { + if (err2) return cb(err2); + cb(null, path6.join(parentDir, path6.basename(pathToResolve))); + }); + } else { + fs7.realpath(path6, cb); } - return { - artifact: { - name: artifact2.name, - id: artifact2.id, - size: artifact2.size_in_bytes, - createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, - digest: artifact2.digest - } - }; }); } - function getArtifactInternal(artifactName) { - return __awaiter4(this, void 0, void 0, function* () { - var _a; - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const req = { - workflowRunBackendId, - workflowJobRunBackendId, - nameFilter: generated_1.StringValue.create({ value: artifactName }) - }; - const res = yield artifactClient.ListArtifacts(req); - if (res.artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} - Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. - For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); - } - let artifact2 = res.artifacts[0]; - if (res.artifacts.length > 1) { - artifact2 = res.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; - core14.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); + function _resolvePathSync(name, tmpDir) { + const pathToResolve = path6.isAbsolute(name) ? name : path6.join(tmpDir, name); + try { + fs7.statSync(pathToResolve); + return fs7.realpathSync(pathToResolve); + } catch (_err) { + const parentDir = fs7.realpathSync(path6.dirname(pathToResolve)); + return path6.join(parentDir, path6.basename(pathToResolve)); + } + } + function _generateTmpName(opts) { + const tmpDir = opts.tmpdir; + if (!_isUndefined(opts.name)) { + return path6.join(tmpDir, opts.dir, opts.name); + } + if (!_isUndefined(opts.template)) { + return path6.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); + } + const name = [ + opts.prefix ? opts.prefix : "tmp", + "-", + process.pid, + "-", + _randomChars(12), + opts.postfix ? "-" + opts.postfix : "" + ].join(""); + return path6.join(tmpDir, opts.dir, name); + } + function _assertOptionsBase(options) { + if (!_isUndefined(options.name)) { + const name = options.name; + if (path6.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`); + const basename = path6.basename(name); + if (basename === ".." || basename === "." || basename !== name) + throw new Error(`name option must not contain a path, found "${name}".`); + } + if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) { + throw new Error(`Invalid template, found "${options.template}".`); + } + if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) { + throw new Error(`Invalid tries, found "${options.tries}".`); + } + options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; + options.keep = !!options.keep; + options.detachDescriptor = !!options.detachDescriptor; + options.discardDescriptor = !!options.discardDescriptor; + options.unsafeCleanup = !!options.unsafeCleanup; + options.prefix = _isUndefined(options.prefix) ? "" : options.prefix; + options.postfix = _isUndefined(options.postfix) ? "" : options.postfix; + } + function _getRelativePath(option, name, tmpDir, cb) { + if (_isUndefined(name)) return cb(null); + _resolvePath(name, tmpDir, function(err, resolvedPath) { + if (err) return cb(err); + const relativePath = path6.relative(tmpDir, resolvedPath); + if (!resolvedPath.startsWith(tmpDir)) { + return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`)); } - return { - artifact: { - name: artifact2.name, - id: Number(artifact2.databaseId), - size: Number(artifact2.size), - createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, - digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value - } - }; + cb(null, relativePath); }); } - } -}); - -// node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js -var require_delete_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); + function _getRelativePathSync(option, name, tmpDir) { + if (_isUndefined(name)) return; + const resolvedPath = _resolvePathSync(name, tmpDir); + const relativePath = path6.relative(tmpDir, resolvedPath); + if (!resolvedPath.startsWith(tmpDir)) { + throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`); } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + return relativePath; + } + function _assertAndSanitizeOptions(options, cb) { + _getTmpDir(options, function(err, tmpDir) { + if (err) return cb(err); + options.tmpdir = tmpDir; + try { + _assertOptionsBase(options, tmpDir); + } catch (err2) { + return cb(err2); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.deleteArtifactPublic = deleteArtifactPublic; - exports2.deleteArtifactInternal = deleteArtifactInternal; - var core_1 = require_core(); - var github_1 = require_github(); - var user_agent_1 = require_user_agent2(); - var retry_options_1 = require_retry_options(); - var utils_1 = require_utils4(); - var plugin_request_log_1 = require_dist_node16(); - var plugin_retry_1 = require_dist_node17(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var util_1 = require_util11(); - var generated_1 = require_generated(); - var get_artifact_1 = require_get_artifact(); - var errors_1 = require_errors3(); - function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { - return __awaiter4(this, void 0, void 0, function* () { - var _a; - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: void 0, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: void 0, - retry: retryOpts, - request: requestOpts - }; - const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - const getArtifactResp = yield (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - const deleteArtifactResp = yield github2.rest.actions.deleteArtifact({ - owner: repositoryOwner, - repo: repositoryName, - artifact_id: getArtifactResp.artifact.id + _getRelativePath("dir", options.dir, tmpDir, function(err2, dir2) { + if (err2) return cb(err2); + options.dir = _isUndefined(dir2) ? "" : dir2; + _getRelativePath("template", options.template, tmpDir, function(err3, template) { + if (err3) return cb(err3); + options.template = template; + cb(null, options); + }); }); - if (deleteArtifactResp.status !== 204) { - throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); - } - return { - id: getArtifactResp.artifact.id - }; }); } - function deleteArtifactInternal(artifactName) { - return __awaiter4(this, void 0, void 0, function* () { - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const listReq = { - workflowRunBackendId, - workflowJobRunBackendId, - nameFilter: generated_1.StringValue.create({ value: artifactName }) - }; - const listRes = yield artifactClient.ListArtifacts(listReq); - if (listRes.artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); - } - let artifact2 = listRes.artifacts[0]; - if (listRes.artifacts.length > 1) { - artifact2 = listRes.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; - (0, core_1.debug)(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); - } - const req = { - workflowRunBackendId: artifact2.workflowRunBackendId, - workflowJobRunBackendId: artifact2.workflowJobRunBackendId, - name: artifact2.name - }; - const res = yield artifactClient.DeleteArtifact(req); - (0, core_1.info)(`Artifact '${artifactName}' (ID: ${res.artifactId}) deleted`); - return { - id: Number(res.artifactId) - }; - }); + function _assertAndSanitizeOptionsSync(options) { + const tmpDir = options.tmpdir = _getTmpDirSync(options); + _assertOptionsBase(options, tmpDir); + const dir2 = _getRelativePathSync("dir", options.dir, tmpDir); + options.dir = _isUndefined(dir2) ? "" : dir2; + options.template = _getRelativePathSync("template", options.template, tmpDir); + return options; + } + function _isEBADF(error4) { + return _isExpectedError(error4, -EBADF, "EBADF"); + } + function _isENOENT(error4) { + return _isExpectedError(error4, -ENOENT, "ENOENT"); + } + function _isExpectedError(error4, errno, code) { + return IS_WIN32 ? error4.code === code : error4.code === code && error4.errno === errno; + } + function setGracefulCleanup() { + _gracefulCleanup = true; + } + function _getTmpDir(options, cb) { + return fs7.realpath(options && options.tmpdir || os.tmpdir(), cb); + } + function _getTmpDirSync(options) { + return fs7.realpathSync(options && options.tmpdir || os.tmpdir()); } + process.addListener(EXIT, _garbageCollector); + Object.defineProperty(module2.exports, "tmpdir", { + enumerable: true, + configurable: false, + get: function() { + return _getTmpDirSync(); + } + }); + module2.exports.dir = dir; + module2.exports.dirSync = dirSync; + module2.exports.file = file; + module2.exports.fileSync = fileSync; + module2.exports.tmpName = tmpName; + module2.exports.tmpNameSync = tmpNameSync; + module2.exports.setGracefulCleanup = setGracefulCleanup; } }); -// node_modules/@actions/artifact/lib/internal/find/list-artifacts.js -var require_list_artifacts = __commonJS({ - "node_modules/@actions/artifact/lib/internal/find/list-artifacts.js"(exports2) { +// node_modules/tmp-promise/index.js +var require_tmp_promise = __commonJS({ + "node_modules/tmp-promise/index.js"(exports2, module2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); + var { promisify } = require("util"); + var tmp = require_tmp(); + module2.exports.fileSync = tmp.fileSync; + var fileWithOptions = promisify( + (options, cb) => tmp.file( + options, + (err, path6, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path6, fd, cleanup: promisify(cleanup) }) + ) + ); + module2.exports.file = async (options) => fileWithOptions(options); + module2.exports.withFile = async function withFile(fn, options) { + const { path: path6, fd, cleanup } = await module2.exports.file(options); + try { + return await fn({ path: path6, fd }); + } finally { + await cleanup(); + } + }; + module2.exports.dirSync = tmp.dirSync; + var dirWithOptions = promisify( + (options, cb) => tmp.dir( + options, + (err, path6, cleanup) => err ? cb(err) : cb(void 0, { path: path6, cleanup: promisify(cleanup) }) + ) + ); + module2.exports.dir = async (options) => dirWithOptions(options); + module2.exports.withDir = async function withDir(fn, options) { + const { path: path6, cleanup } = await module2.exports.dir(options); + try { + return await fn({ path: path6 }); + } finally { + await cleanup(); } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); }; + module2.exports.tmpNameSync = tmp.tmpNameSync; + module2.exports.tmpName = promisify(tmp.tmpName); + module2.exports.tmpdir = tmp.tmpdir; + module2.exports.setGracefulCleanup = tmp.setGracefulCleanup; + } +}); + +// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/proxy.js +var require_proxy7 = __commonJS({ + "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listArtifactsPublic = listArtifactsPublic; - exports2.listArtifactsInternal = listArtifactsInternal; - var core_1 = require_core(); - var github_1 = require_github(); - var user_agent_1 = require_user_agent2(); - var retry_options_1 = require_retry_options(); - var utils_1 = require_utils4(); - var plugin_request_log_1 = require_dist_node16(); - var plugin_retry_1 = require_dist_node17(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var util_1 = require_util11(); - var config_1 = require_config2(); - var generated_1 = require_generated(); - var maximumArtifactCount = (0, config_1.getMaxArtifactListCount)(); - var paginationCount = 100; - var maxNumberOfPages = Math.ceil(maximumArtifactCount / paginationCount); - function listArtifactsPublic(workflowRunId_1, repositoryOwner_1, repositoryName_1, token_1) { - return __awaiter4(this, arguments, void 0, function* (workflowRunId, repositoryOwner, repositoryName, token, latest = false) { - (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`); - let artifacts = []; - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: void 0, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: void 0, - retry: retryOpts, - request: requestOpts - }; - const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - let currentPageNumber = 1; - const { data: listArtifactResponse } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - per_page: paginationCount, - page: currentPageNumber - }); - let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount); - const totalArtifactCount = listArtifactResponse.total_count; - if (totalArtifactCount > maximumArtifactCount) { - (0, core_1.warning)(`Workflow run ${workflowRunId} has ${totalArtifactCount} artifacts, exceeding the limit of ${maximumArtifactCount}. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`); - numberOfPages = maxNumberOfPages; - } - for (const artifact2 of listArtifactResponse.artifacts) { - artifacts.push({ - name: artifact2.name, - id: artifact2.id, - size: artifact2.size_in_bytes, - createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, - digest: artifact2.digest - }); - } - currentPageNumber++; - for (currentPageNumber; currentPageNumber <= numberOfPages; currentPageNumber++) { - (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`); - const { data: listArtifactResponse2 } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - per_page: paginationCount, - page: currentPageNumber - }); - for (const artifact2 of listArtifactResponse2.artifacts) { - artifacts.push({ - name: artifact2.name, - id: artifact2.id, - size: artifact2.size_in_bytes, - createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, - digest: artifact2.digest - }); - } - } - if (latest) { - artifacts = filterLatest(artifacts); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); - return { - artifacts - }; - }); - } - function listArtifactsInternal() { - return __awaiter4(this, arguments, void 0, function* (latest = false) { - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const req = { - workflowRunBackendId, - workflowJobRunBackendId - }; - const res = yield artifactClient.ListArtifacts(req); - let artifacts = res.artifacts.map((artifact2) => { - var _a; - return { - name: artifact2.name, - id: Number(artifact2.databaseId), - size: Number(artifact2.size), - createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, - digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value - }; - }); - if (latest) { - artifacts = filterLatest(artifacts); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); - return { - artifacts - }; - }); + } else { + return void 0; + } } - function filterLatest(artifacts) { - artifacts.sort((a, b) => b.id - a.id); - const latestArtifacts = []; - const seenArtifactNames = /* @__PURE__ */ new Set(); - for (const artifact2 of artifacts) { - if (!seenArtifactNames.has(artifact2.name)) { - latestArtifacts.push(artifact2); - seenArtifactNames.add(artifact2.name); + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - return latestArtifacts; + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@actions/artifact/lib/internal/client.js -var require_client2 = __commonJS({ - "node_modules/@actions/artifact/lib/internal/client.js"(exports2) { +// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/index.js +var require_lib9 = __commonJS({ + "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve5) { @@ -106813,703 +111428,668 @@ var require_client2 = __commonJS({ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __rest4 = exports2 && exports2.__rest || function(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DefaultArtifactClient = void 0; - var core_1 = require_core(); - var config_1 = require_config2(); - var upload_artifact_1 = require_upload_artifact(); - var download_artifact_1 = require_download_artifact(); - var delete_artifact_1 = require_delete_artifact(); - var get_artifact_1 = require_get_artifact(); - var list_artifacts_1 = require_list_artifacts(); - var errors_1 = require_errors3(); - var DefaultArtifactClient2 = class { - uploadArtifact(name, files, rootDirectory, options) { + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy7()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); + } + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options); - } catch (error4) { - (0, core_1.warning)(`Artifact upload failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); }); } - downloadArtifact(artifactId, options) { + readBodyBuffer() { return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest4(options, ["findBy"]); - return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions); - } - return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options); - } catch (error4) { - (0, core_1.warning)(`Download Artifact failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); }); } - listArtifacts(options) { - return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; - return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest); - } - return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest); - } catch (error4) { - (0, core_1.warning)(`Listing Artifacts failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); }); } - getArtifact(artifactName, options) { + get(requestUrl, additionalHeaders) { return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; - return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - } - return (0, get_artifact_1.getArtifactInternal)(artifactName); - } catch (error4) { - (0, core_1.warning)(`Get Artifact failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } + return this.request("GET", requestUrl, null, additionalHeaders || {}); }); } - deleteArtifact(artifactName, options) { + del(requestUrl, additionalHeaders) { return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { repositoryOwner, repositoryName, workflowRunId, token } } = options; - return (0, delete_artifact_1.deleteArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - } - return (0, delete_artifact_1.deleteArtifactInternal)(artifactName); - } catch (error4) { - (0, core_1.warning)(`Delete Artifact failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); }); } - }; - exports2.DefaultArtifactClient = DefaultArtifactClient2; - } -}); - -// node_modules/@actions/artifact/lib/internal/shared/interfaces.js -var require_interfaces2 = __commonJS({ - "node_modules/@actions/artifact/lib/internal/shared/interfaces.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@actions/artifact/lib/artifact.js -var require_artifact2 = __commonJS({ - "node_modules/@actions/artifact/lib/artifact.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - var client_1 = require_client2(); - __exportStar4(require_interfaces2(), exports2); - __exportStar4(require_errors3(), exports2); - __exportStar4(require_client2(), exports2); - var client = new client_1.DefaultArtifactClient(); - exports2.default = client; - } -}); - -// node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js -var require_path_and_artifact_name_validation2 = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.checkArtifactFilePath = exports2.checkArtifactName = void 0; - var core_1 = require_core(); - var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ - ['"', ' Double quote "'], - [":", " Colon :"], - ["<", " Less than <"], - [">", " Greater than >"], - ["|", " Vertical bar |"], - ["*", " Asterisk *"], - ["?", " Question mark ?"], - ["\r", " Carriage return \\r"], - ["\n", " Line feed \\n"] - ]); - var invalidArtifactNameCharacters = new Map([ - ...invalidArtifactFilePathCharacters, - ["\\", " Backslash \\"], - ["/", " Forward slash /"] - ]); - function checkArtifactName(name) { - if (!name) { - throw new Error(`Artifact name: ${name}, is incorrectly provided`); + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { - if (name.includes(invalidCharacterKey)) { - throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} - -These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); - } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - (0, core_1.info)(`Artifact name is valid!`); - } - exports2.checkArtifactName = checkArtifactName; - function checkArtifactFilePath(path6) { - if (!path6) { - throw new Error(`Artifact path: ${path6}, is incorrectly provided`); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path6.includes(invalidCharacterKey)) { - throw new Error(`Artifact path is not valid: ${path6}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} - -The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. - `); - } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - } - exports2.checkArtifactFilePath = checkArtifactFilePath; - } -}); - -// node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js -var require_upload_specification = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - __setModuleDefault4(result, mod); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUploadSpecification = void 0; - var fs7 = __importStar4(require("fs")); - var core_1 = require_core(); - var path_1 = require("path"); - var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); - function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { - const specifications = []; - if (!fs7.existsSync(rootDirectory)) { - throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - if (!fs7.statSync(rootDirectory).isDirectory()) { - throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - rootDirectory = (0, path_1.normalize)(rootDirectory); - rootDirectory = (0, path_1.resolve)(rootDirectory); - for (let file of artifactFiles) { - if (!fs7.existsSync(file)) { - throw new Error(`File ${file} does not exist`); - } - if (!fs7.statSync(file).isDirectory()) { - file = (0, path_1.normalize)(file); - file = (0, path_1.resolve)(file); - if (!file.startsWith(rootDirectory)) { - throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - const uploadPath = file.replace(rootDirectory, ""); - (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath); - specifications.push({ - absoluteFilePath: file, - uploadFilePath: (0, path_1.join)(artifactName, uploadPath) - }); - } else { - (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`); + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return specifications; - } - exports2.getUploadSpecification = getUploadSpecification; - } -}); - -// node_modules/tmp/lib/tmp.js -var require_tmp = __commonJS({ - "node_modules/tmp/lib/tmp.js"(exports2, module2) { - var fs7 = require("fs"); - var os = require("os"); - var path6 = require("path"); - var crypto = require("crypto"); - var _c = { fs: fs7.constants, os: os.constants }; - var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - var TEMPLATE_PATTERN = /XXXXXX/; - var DEFAULT_TRIES = 3; - var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR); - var IS_WIN32 = os.platform() === "win32"; - var EBADF = _c.EBADF || _c.os.errno.EBADF; - var ENOENT = _c.ENOENT || _c.os.errno.ENOENT; - var DIR_MODE = 448; - var FILE_MODE = 384; - var EXIT = "exit"; - var _removeObjects = []; - var FN_RMDIR_SYNC = fs7.rmdirSync.bind(fs7); - var _gracefulCleanup = false; - function rimraf(dirPath, callback) { - return fs7.rm(dirPath, { recursive: true }, callback); - } - function FN_RIMRAF_SYNC(dirPath) { - return fs7.rmSync(dirPath, { recursive: true }); - } - function tmpName(options, callback) { - const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; - _assertAndSanitizeOptions(opts, function(err, sanitizedOptions) { - if (err) return cb(err); - let tries = sanitizedOptions.tries; - (function _getUniqueName() { - try { - const name = _generateTmpName(sanitizedOptions); - fs7.stat(name, function(err2) { - if (!err2) { - if (tries-- > 0) return _getUniqueName(); - return cb(new Error("Could not get a unique tmp filename, max tries reached " + name)); + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); } - cb(null, name); - }); - } catch (err2) { - cb(err2); + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; } - })(); - }); - } - function tmpNameSync(options) { - const args = _parseArguments(options), opts = args[0]; - const sanitizedOptions = _assertAndSanitizeOptionsSync(opts); - let tries = sanitizedOptions.tries; - do { - const name = _generateTmpName(sanitizedOptions); - try { - fs7.statSync(name); - } catch (e) { - return name; + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - } while (tries-- > 0); - throw new Error("Could not get a unique tmp filename, max tries reached"); - } - function file(options, callback) { - const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; - tmpName(opts, function _tmpNameCreated(err, name) { - if (err) return cb(err); - fs7.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { - if (err2) return cb(err2); - if (opts.discardDescriptor) { - return fs7.close(fd, function _discardCallback(possibleErr) { - return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false)); - }); - } else { - const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; - cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); }); - }); - } - function fileSync(options) { - const args = _parseArguments(options), opts = args[0]; - const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; - const name = tmpNameSync(opts); - let fd = fs7.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); - if (opts.discardDescriptor) { - fs7.closeSync(fd); - fd = void 0; - } - return { - name, - fd, - removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) - }; - } - function dir(options, callback) { - const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; - tmpName(opts, function _tmpNameCreated(err, name) { - if (err) return cb(err); - fs7.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { - if (err2) return cb(err2); - cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); + let socket; + req.on("socket", (sock) => { + socket = sock; }); - }); - } - function dirSync(options) { - const args = _parseArguments(options), opts = args[0]; - const name = tmpNameSync(opts); - fs7.mkdirSync(name, opts.mode || DIR_MODE); - return { - name, - removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) - }; - } - function _removeFileAsync(fdPath, next) { - const _handler = function(err) { - if (err && !_isENOENT(err)) { - return next(err); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - next(); - }; - if (0 <= fdPath[0]) - fs7.close(fdPath[0], function() { - fs7.unlink(fdPath[1], _handler); - }); - else fs7.unlink(fdPath[1], _handler); - } - function _removeFileSync(fdPath) { - let rethrownException = null; - try { - if (0 <= fdPath[0]) fs7.closeSync(fdPath[0]); - } catch (e) { - if (!_isEBADF(e) && !_isENOENT(e)) throw e; - } finally { - try { - fs7.unlinkSync(fdPath[1]); - } catch (e) { - if (!_isENOENT(e)) rethrownException = e; + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } } + return info7; } - if (rethrownException !== null) { - throw rethrownException; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - } - function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { - const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); - const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); - return sync ? removeCallbackSync : removeCallback; - } - function _prepareTmpDirRemoveCallback(name, opts, sync) { - const removeFunction = opts.unsafeCleanup ? rimraf : fs7.rmdir.bind(fs7); - const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; - const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); - const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); - return sync ? removeCallbackSync : removeCallback; - } - function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { - let called = false; - return function _cleanupCallback(next) { - if (!called) { - const toRemove = cleanupCallbackSync || _cleanupCallback; - const index = _removeObjects.indexOf(toRemove); - if (index >= 0) _removeObjects.splice(index, 1); - called = true; - if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { - return removeFunction(fileOrDirName); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - return removeFunction(fileOrDirName, next || function() { - }); + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - }; - } - function _garbageCollector() { - if (!_gracefulCleanup) return; - while (_removeObjects.length) { - try { - _removeObjects[0](); - } catch (e) { + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - } - function _randomChars(howMany) { - let value = [], rnd = null; - try { - rnd = crypto.randomBytes(howMany); - } catch (e) { - rnd = crypto.pseudoRandomBytes(howMany); - } - for (let i = 0; i < howMany; i++) { - value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - return value.join(""); - } - function _isUndefined(obj) { - return typeof obj === "undefined"; - } - function _parseArguments(options, callback) { - if (typeof options === "function") { - return [{}, options]; + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); + }); } - if (_isUndefined(options)) { - return [{}, callback]; + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); + } + })); + }); } - const actualOptions = {}; - for (const key of Object.getOwnPropertyNames(options)) { - actualOptions[key] = options[key]; + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/auth.js +var require_auth4 = __commonJS({ + "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/auth.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - return [actualOptions, callback]; - } - function _resolvePath(name, tmpDir, cb) { - const pathToResolve = path6.isAbsolute(name) ? name : path6.join(tmpDir, name); - fs7.stat(pathToResolve, function(err) { - if (err) { - fs7.realpath(path6.dirname(pathToResolve), function(err2, parentDir) { - if (err2) return cb(err2); - cb(null, path6.join(parentDir, path6.basename(pathToResolve))); - }); - } else { - fs7.realpath(path6, cb); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - } - function _resolvePathSync(name, tmpDir) { - const pathToResolve = path6.isAbsolute(name) ? name : path6.join(tmpDir, name); - try { - fs7.statSync(pathToResolve); - return fs7.realpathSync(pathToResolve); - } catch (_err) { - const parentDir = fs7.realpathSync(path6.dirname(pathToResolve)); - return path6.join(parentDir, path6.basename(pathToResolve)); - } - } - function _generateTmpName(opts) { - const tmpDir = opts.tmpdir; - if (!_isUndefined(opts.name)) { - return path6.join(tmpDir, opts.dir, opts.name); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - if (!_isUndefined(opts.template)) { - return path6.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; } - const name = [ - opts.prefix ? opts.prefix : "tmp", - "-", - process.pid, - "-", - _randomChars(12), - opts.postfix ? "-" + opts.postfix : "" - ].join(""); - return path6.join(tmpDir, opts.dir, name); - } - function _assertOptionsBase(options) { - if (!_isUndefined(options.name)) { - const name = options.name; - if (path6.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`); - const basename = path6.basename(name); - if (basename === ".." || basename === "." || basename !== name) - throw new Error(`name option must not contain a path, found "${name}".`); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) { - throw new Error(`Invalid template, found "${options.template}".`); + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) { - throw new Error(`Invalid tries, found "${options.tries}".`); + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; } - options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; - options.keep = !!options.keep; - options.detachDescriptor = !!options.detachDescriptor; - options.discardDescriptor = !!options.discardDescriptor; - options.unsafeCleanup = !!options.unsafeCleanup; - options.prefix = _isUndefined(options.prefix) ? "" : options.prefix; - options.postfix = _isUndefined(options.postfix) ? "" : options.postfix; - } - function _getRelativePath(option, name, tmpDir, cb) { - if (_isUndefined(name)) return cb(null); - _resolvePath(name, tmpDir, function(err, resolvedPath) { - if (err) return cb(err); - const relativePath = path6.relative(tmpDir, resolvedPath); - if (!resolvedPath.startsWith(tmpDir)) { - return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`)); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } - cb(null, relativePath); - }); - } - function _getRelativePathSync(option, name, tmpDir) { - if (_isUndefined(name)) return; - const resolvedPath = _resolvePathSync(name, tmpDir); - const relativePath = path6.relative(tmpDir, resolvedPath); - if (!resolvedPath.startsWith(tmpDir)) { - throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`); + options.headers["Authorization"] = `Bearer ${this.token}`; } - return relativePath; - } - function _assertAndSanitizeOptions(options, cb) { - _getTmpDir(options, function(err, tmpDir) { - if (err) return cb(err); - options.tmpdir = tmpDir; - try { - _assertOptionsBase(options, tmpDir); - } catch (err2) { - return cb(err2); - } - _getRelativePath("dir", options.dir, tmpDir, function(err2, dir2) { - if (err2) return cb(err2); - options.dir = _isUndefined(dir2) ? "" : dir2; - _getRelativePath("template", options.template, tmpDir, function(err3, template) { - if (err3) return cb(err3); - options.template = template; - cb(null, options); - }); - }); - }); - } - function _assertAndSanitizeOptionsSync(options) { - const tmpDir = options.tmpdir = _getTmpDirSync(options); - _assertOptionsBase(options, tmpDir); - const dir2 = _getRelativePathSync("dir", options.dir, tmpDir); - options.dir = _isUndefined(dir2) ? "" : dir2; - options.template = _getRelativePathSync("template", options.template, tmpDir); - return options; - } - function _isEBADF(error4) { - return _isExpectedError(error4, -EBADF, "EBADF"); - } - function _isENOENT(error4) { - return _isExpectedError(error4, -ENOENT, "ENOENT"); - } - function _isExpectedError(error4, errno, code) { - return IS_WIN32 ? error4.code === code : error4.code === code && error4.errno === errno; - } - function setGracefulCleanup() { - _gracefulCleanup = true; - } - function _getTmpDir(options, cb) { - return fs7.realpath(options && options.tmpdir || os.tmpdir(), cb); - } - function _getTmpDirSync(options) { - return fs7.realpathSync(options && options.tmpdir || os.tmpdir()); - } - process.addListener(EXIT, _garbageCollector); - Object.defineProperty(module2.exports, "tmpdir", { - enumerable: true, - configurable: false, - get: function() { - return _getTmpDirSync(); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - }); - module2.exports.dir = dir; - module2.exports.dirSync = dirSync; - module2.exports.file = file; - module2.exports.fileSync = fileSync; - module2.exports.tmpName = tmpName; - module2.exports.tmpNameSync = tmpNameSync; - module2.exports.setGracefulCleanup = setGracefulCleanup; - } -}); - -// node_modules/tmp-promise/index.js -var require_tmp_promise = __commonJS({ - "node_modules/tmp-promise/index.js"(exports2, module2) { - "use strict"; - var { promisify } = require("util"); - var tmp = require_tmp(); - module2.exports.fileSync = tmp.fileSync; - var fileWithOptions = promisify( - (options, cb) => tmp.file( - options, - (err, path6, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path6, fd, cleanup: promisify(cleanup) }) - ) - ); - module2.exports.file = async (options) => fileWithOptions(options); - module2.exports.withFile = async function withFile(fn, options) { - const { path: path6, fd, cleanup } = await module2.exports.file(options); - try { - return await fn({ path: path6, fd }); - } finally { - await cleanup(); + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } }; - module2.exports.dirSync = tmp.dirSync; - var dirWithOptions = promisify( - (options, cb) => tmp.dir( - options, - (err, path6, cleanup) => err ? cb(err) : cb(void 0, { path: path6, cleanup: promisify(cleanup) }) - ) - ); - module2.exports.dir = async (options) => dirWithOptions(options); - module2.exports.withDir = async function withDir(fn, options) { - const { path: path6, cleanup } = await module2.exports.dir(options); - try { - return await fn({ path: path6 }); - } finally { - await cleanup(); + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } }; - module2.exports.tmpNameSync = tmp.tmpNameSync; - module2.exports.tmpName = promisify(tmp.tmpName); - module2.exports.tmpdir = tmp.tmpdir; - module2.exports.setGracefulCleanup = tmp.setGracefulCleanup; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); @@ -107923,8 +112503,8 @@ var require_utils7 = __commonJS({ var crypto_1 = __importDefault4(require("crypto")); var fs_1 = require("fs"); var core_1 = require_core(); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib9(); + var auth_1 = require_auth4(); var config_variables_1 = require_config_variables(); var crc64_1 = __importDefault4(require_crc64()); function getExponentialRetryTimeInMilliseconds(retryCount) { @@ -108577,7 +113157,7 @@ var require_upload_http_client = __commonJS({ var url_1 = require("url"); var perf_hooks_1 = require("perf_hooks"); var status_reporter_1 = require_status_reporter(); - var http_client_1 = require_lib(); + var http_client_1 = require_lib9(); var http_manager_1 = require_http_manager(); var upload_gzip_1 = require_upload_gzip(); var requestUtils_1 = require_requestUtils2(); @@ -113751,7 +118331,7 @@ var supportedAnalysisKinds = new Set(Object.values(AnalysisKind)); var core6 = __toESM(require_core()); // src/config/db-config.ts -var jsonschema = __toESM(require_lib2()); +var jsonschema = __toESM(require_lib3()); var semver2 = __toESM(require_semver2()); var PACK_IDENTIFIER_PATTERN = (function() { const alphaNumeric = "[a-z0-9]"; @@ -114299,7 +118879,7 @@ var semver5 = __toESM(require_semver2()); // src/tools-download.ts var core9 = __toESM(require_core()); -var import_http_client = __toESM(require_lib()); +var import_http_client = __toESM(require_lib6()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); var semver6 = __toESM(require_semver2()); diff --git a/lib/analyze-action.js b/lib/analyze-action.js index 16c5a4a29e..9902826d1a 100644 --- a/lib/analyze-action.js +++ b/lib/analyze-action.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -19875,9 +19875,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -19934,737 +20016,826 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url2, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url2, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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 (isPlainObject(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, url2] = route.split(" "); - options = Object.assign(url2 ? { method, url: url2 } : { 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(url2, parameters) { - const separator = /\?/.test(url2) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url2; - } - return url2 + 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+)|(?:(? a.concat(b), []); - } - function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - } - function encodeReserved(str2) { - return str2.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(str2) { - return encodeURIComponent(str2).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; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - function isDefined2(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context2, operator, key, modifier) { - var value = context2[key], result = []; - if (isDefined2(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)); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - result.push(encodeValue(operator, value[k], k)); + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; } - }); + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } } - }); + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - } else { - if (operator === ";") { - if (isDefined2(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; - } - function expand(template, context2) { - 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(context2, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); } - } else { - return encodeReserved(literal); + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } - } - function parse(options) { - let method = options.method.toUpperCase(); - let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url2); - url2 = parseUrl(url2).expand(parameters); - if (!/^http/.test(url2)) { - url2 = options.baseUrl + url2; - } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(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(","); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (url2.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - } - if (["GET", "HEAD"].includes(method)) { - url2 = addQueryParameters(url2, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + req.end(); } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return Object.assign( - { method, url: url2, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); - } - function endpointWithDefaults(defaults, route, options) { - return parse(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 - }); - } - var endpoint = withDefaults(null, DEFAULTS); - } -}); - -// node_modules/deprecation/dist-node/index.js -var require_dist_node3 = __commonJS({ - "node_modules/deprecation/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var Deprecation = class extends Error { - constructor(message) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - this.name = "Deprecation"; + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; } - }; - exports2.Deprecation = Deprecation; - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - return ret; + return additionalHeaders[header] || clientHeader || _default2; } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; + var httpClient = __importStar4(require_lib2()); + var undici_1 = require_undici(); + function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error("Parameter token or opts.auth is required"); + } else if (token && options.auth) { + throw new Error("Parameters token and opts.auth may not both be specified"); + } + return typeof options.auth === "string" ? options.auth : `token ${token}`; + } + exports2.getAuthString = getAuthString; + function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + exports2.getProxyAgent = getProxyAgent; + function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); + } + exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; + function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url2, opts) => __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url2, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; + return proxyFetch; } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; } + exports2.getApiBaseUrl = getApiBaseUrl; } }); -// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node4 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { "use strict"; - var __create2 = Object.create; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - RequestError: () => RequestError - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_deprecation = require_dist_node3(); - var import_once = __toESM2(require_once()); - var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - request: () => request - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node2(); - var import_universal_user_agent = require_dist_node(); - var VERSION = "8.4.1"; - function isPlainObject(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); - } - var import_request_error = require_dist_node4(); - function getBufferResponse(response) { - return response.arrayBuffer(); - } - function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url2; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - 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" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } - }).then(async (response) => { - url2 = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url: url2, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url: url2, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url: url2, - status, - headers, - data - }, - request: requestOptions - }); - throw error4; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url: url2, - headers, - data - }; - }).catch((error4) => { - if (error4 instanceof import_request_error.RequestError) - throw error4; - else if (error4.name === "AbortError") - throw error4; - let message = error4.message; - if (error4.name === "TypeError" && "cause" in error4) { - if (error4.cause instanceof Error) { - message = error4.cause.message; - } else if (typeof error4.cause === "string") { - message = error4.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); - } - 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 getBufferResponse(response); - } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; - } - function withDefaults(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: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - } - var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } - }); - } -}); - -// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node6 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint + endpoint: () => endpoint }); module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); @@ -21218,9 +21179,101 @@ var require_dist_node6 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node7 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/deprecation/dist-node/index.js +var require_dist_node3 = __commonJS({ + "node_modules/deprecation/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var Deprecation = class extends Error { + constructor(message) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "Deprecation"; + } + }; + exports2.Deprecation = Deprecation; + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node4 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; var __create2 = Object.create; var __defProp2 = Object.defineProperty; @@ -21310,9 +21363,9 @@ var require_dist_node7 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js -var require_dist_node8 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js +var require_dist_node5 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21336,7 +21389,7 @@ var require_dist_node8 = __commonJS({ request: () => request }); module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node6(); + var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; function isPlainObject(value) { @@ -21350,7 +21403,7 @@ var require_dist_node8 = __commonJS({ 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); } - var import_request_error = require_dist_node7(); + var import_request_error = require_dist_node4(); function getBufferResponse(response) { return response.arrayBuffer(); } @@ -21520,9 +21573,9 @@ var require_dist_node8 = __commonJS({ } }); -// node_modules/@octokit/graphql/dist-node/index.js -var require_dist_node9 = __commonJS({ - "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node6 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21541,129 +21594,340 @@ var require_dist_node9 = __commonJS({ return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export2(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint }); - module2.exports = __toCommonJS2(index_exports); - var import_request3 = require_dist_node8(); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); - var VERSION = "7.1.1"; - var import_request2 = require_dist_node8(); - var import_request = require_dist_node8(); - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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; + }, {}); } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + function isPlainObject(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 (isPlainObject(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]; } } - }; - 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`) - ); + return obj; + } + function merge2(defaults, route, options) { + if (typeof route === "string") { + let [method, url2] = route.split(" "); + options = Object.assign(url2 ? { method, url: url2 } : { 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); } - 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` - ) - ); + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; + } + function addQueryParameters(url2, parameters) { + const separator = /\?/.test(url2) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url2; + } + return url2 + 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+)|(?:(? { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } + function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; } - if (!result.variables) { - result.variables = {}; + } + return result; + } + function encodeReserved(str2) { + return str2.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, "]"); } - 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 part; + }).join(""); + } + function encodeUnreserved(str2) { + return encodeURIComponent(str2).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; } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; + } + function isDefined2(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context2, operator, key, modifier) { + var value = context2[key], result = []; + if (isDefined2(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)); } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(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(",")); + } + } } - return response.data.data; - }); + } else { + if (operator === ";") { + if (isDefined2(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; } - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); + function parseUrl(template) { + return { + expand: expand.bind(null, template) }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); } - var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" - }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" + function expand(template, context2) { + 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(context2, 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 parse(options) { + let method = options.method.toUpperCase(); + let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url2); + url2 = parseUrl(url2).expand(parameters); + if (!/^http/.test(url2)) { + url2 = options.baseUrl + url2; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(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 (url2.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url2 = addQueryParameters(url2, 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: url2, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); + } + function endpointWithDefaults(defaults, route, options) { + return parse(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 }); } + var endpoint = withDefaults(null, DEFAULTS); } }); -// node_modules/@octokit/auth-token/dist-node/index.js -var require_dist_node10 = __commonJS({ - "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node7 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; + var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) @@ -21677,53 +21941,490 @@ var require_dist_node10 = __commonJS({ } return to; }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - createTokenAuth: () => createTokenAuth + RequestError: () => RequestError }); module2.exports = __toCommonJS2(dist_src_exports); - 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, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); - } - 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" - ); + var import_deprecation = require_dist_node3(); + var import_once = __toESM2(require_once()); + var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + request: () => request + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_endpoint = require_dist_node6(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "8.4.1"; + function isPlainObject(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); + } + var import_request_error = require_dist_node7(); + function getBufferResponse(response) { + return response.arrayBuffer(); + } + function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url2; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + 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" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url2 = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url: url2, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url: url2, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url: url2, + status, + headers, + data + }, + request: requestOptions + }); + throw error4; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url: url2, + headers, + data + }; + }).catch((error4) => { + if (error4 instanceof import_request_error.RequestError) + throw error4; + else if (error4.name === "AbortError") + throw error4; + let message = error4.message; + if (error4.name === "TypeError" && "cause" in error4) { + if (error4.cause instanceof Error) { + message = error4.cause.message; + } else if (typeof error4.cause === "string") { + message = error4.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); + } + 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 getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; + } + function withDefaults(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: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + } + var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }); + } +}); + +// node_modules/@octokit/graphql/dist-node/index.js +var require_dist_node9 = __commonJS({ + "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export2(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest + }); + module2.exports = __toCommonJS2(index_exports); + var import_request3 = require_dist_node8(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "7.1.1"; + var import_request2 = require_dist_node8(); + var import_request = require_dist_node8(); + 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.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + }; + 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 withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); + } + } +}); + +// node_modules/@octokit/auth-token/dist-node/index.js +var require_dist_node10 = __commonJS({ + "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + createTokenAuth: () => createTokenAuth + }); + module2.exports = __toCommonJS2(dist_src_exports); + 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, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + 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) + }); }; } }); @@ -26499,7 +27200,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -29372,7 +30073,7 @@ var require_validator = __commonJS({ }); // node_modules/jsonschema/lib/index.js -var require_lib2 = __commonJS({ +var require_lib3 = __commonJS({ "node_modules/jsonschema/lib/index.js"(exports2, module2) { "use strict"; var Validator3 = module2.exports.Validator = require_validator(); @@ -32511,958 +33212,1763 @@ var require_cacheUtils = __commonJS({ } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); - var HttpPipeline = class _HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = void 0; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - this._policies.push({ - policy, - options - }); - this._orderedPolicies = void 0; + } else { + return void 0; } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { - removedPolicies.push(policyDescriptor.policy); - return false; - } else { - return true; - } - }); - this._orderedPolicies = void 0; - return removedPolicies; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - clone() { - return new _HttpPipeline(this._policies); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - static create() { - return new _HttpPipeline(); + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - orderPolicies() { - const result = []; - const policyMap = /* @__PURE__ */ new Map(); - function createPhase(name) { - return { - name, - policies: /* @__PURE__ */ new Set(), - hasRun: false, - hasAfterPolicies: false - }; - } - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } else if (phase === "Serialize") { - return serializePhase; - } else if (phase === "Deserialize") { - return deserializePhase; - } else if (phase === "Sign") { - return signPhase; - } else { - return noPhase; - } - } - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: /* @__PURE__ */ new Set(), - dependants: /* @__PURE__ */ new Set() - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); - } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); - } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); - } - } - } - } - function walkPhase(phase) { - phase.hasRun = true; - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - continue; - } - if (node.dependsOn.size === 0) { - result.push(node.policy); - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); - } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - walkPhase(noPhase); - } - return; - } - if (phase.hasAfterPolicies) { - walkPhase(noPhase); - } - } - } - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - walkPhases(); - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return result; } - }; - function createEmptyPipeline() { - return HttpPipeline.create(); + return false; } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@azure/logger/dist/index.js -var require_dist = __commonJS({ - "node_modules/@azure/logger/dist/index.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var os5 = require("os"); - var util = require("util"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); - function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os5.EOL}`); - } - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; - var enabledString; - var enabledNamespaces = []; - var skippedNamespaces = []; - var debuggers = []; - if (debugEnvVariable) { - enable(debugEnvVariable); - } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log - }); - function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); - } else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); - } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - } - function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - } - return false; - } - function disable() { - const result = enabledString || ""; - enable(""); - return result; - } - function createDebugger(namespace) { - const newDebugger = Object.assign(debug6, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend: extend3 - }); - function debug6(...args) { - if (!newDebugger.enabled) { - return; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } - newDebugger.log(...args); - } - debuggers.push(newDebugger); - return newDebugger; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return false; - } - function extend3(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; - } - var debug5 = debugObj; - var registeredLoggers = /* @__PURE__ */ new Set(); - var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; - var azureLogLevel; - var AzureLogger = debug5("azure"); - AzureLogger.log = (...args) => { - debug5.log(...args); }; - var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; - if (logLevelFromEnv) { - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); - } else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - } - function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); + }); } - azureLogLevel = level; - const enabledNamespaces2 = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces2.push(logger.namespace); - } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); + }); } - debug5.enable(enabledNamespaces2.join(",")); - } - function getLogLevel() { - return azureLogLevel; - } - var levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 }; - function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") - }; - } - function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); - }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces2 = debug5.disable(); - debug5.enable(enabledNamespaces2 + "," + logger.namespace); + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - registeredLoggers.add(logger); - return logger; - } - function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); - } - function isAzureLogLevel(logLevel) { - return AZURE_LOG_LEVELS.includes(logLevel); - } - exports2.AzureLogger = AzureLogger; - exports2.createClientLogger = createClientLogger; - exports2.getLogLevel = getLogLevel; - exports2.setLogLevel = setLogLevel; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js -var require_log = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_dist(); - exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - } -}); - -// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js -var require_createAbortablePromise = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createAbortablePromise = createAbortablePromise; - var abort_controller_1 = require_commonjs(); - function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve8, reject) => { - function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - function removeListeners() { - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - function onAbort() { - cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); - removeListeners(); - rejectOnAbort(); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { - return rejectOnAbort(); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - try { - buildPromise((x) => { - removeListeners(); - resolve8(x); - }, (x) => { - removeListeners(); - reject(x); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); }); - } catch (err) { - reject(err); + data.pipe(req); + } else { + req.end(); } - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); - }); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/random.js -var require_random = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - function getRandomIntegerInclusive(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - const offset = Math.floor(Math.random() * (max - min + 1)); - return offset + min; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/delay.js -var require_delay = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay2; - exports2.calculateRetryDelay = calculateRetryDelay; - var createAbortablePromise_js_1 = require_createAbortablePromise(); - var random_js_1 = require_random(); - var StandardAbortMessage = "The delay was aborted."; - function delay2(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve8) => { - token = setTimeout(resolve8, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage - }); - } - function calculateRetryDelay(retryAttempt, config) { - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); - return { retryAfterInMs }; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js -var require_aborterUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cancelablePromiseRace = cancelablePromiseRace; - async function cancelablePromiseRace(abortablePromiseBuilders, options) { - var _a, _b; - const aborter = new AbortController(); - function abortHandler() { - aborter.abort(); } - (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); - try { - return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); - } finally { - aborter.abort(); - (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/object.js -var require_object = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isObject = isObject2; - function isObject2(input) { - return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/error.js -var require_error = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isError = isError; - exports2.getErrorMessage = getErrorMessage2; - var object_js_1 = require_object(); - function isError(e) { - if ((0, object_js_1.isObject)(e)) { - const hasName = typeof e.name === "string"; - const hasMessage = typeof e.message === "string"; - return hasName && hasMessage; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return false; - } - function getErrorMessage2(e) { - if (isError(e)) { - return e.message; - } else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } else { - stringified = String(e); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - } catch (err) { - stringified = "[unable to stringify input]"; } - return `Unknown error ${stringified}`; + return info6; } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.computeSha256Hash = computeSha256Hash; - var crypto_1 = require("crypto"); - async function computeSha256Hmac(key, stringToSign, encoding) { - const decodedKey = Buffer.from(key, "base64"); - return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); - } - async function computeSha256Hash(content, encoding) { - return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/typeGuards.js -var require_typeGuards = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isDefined = isDefined2; - exports2.isObjectWithProperties = isObjectWithProperties; - exports2.objectHasProperty = objectHasProperty; - function isDefined2(thing) { - return typeof thing !== "undefined" && thing !== null; - } - function isObjectWithProperties(thing, properties) { - if (!isDefined2(thing) || typeof thing !== "object") { - return false; - } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - return true; - } - function objectHasProperty(thing, property) { - return isDefined2(thing) && typeof thing === "object" && property in thing; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js -var require_uuidUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomUUID = randomUUID2; - var crypto_1 = require("crypto"); - var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; - function randomUUID2() { - return uuidFunction(); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js -var require_checkEnvironment = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { - "use strict"; - var _a; - var _b; - var _c; - var _d; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; - exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; - exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); - exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; - exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; - exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); - exports2.isNode = exports2.isNodeLike; - exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; - exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; - } -}); - -// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js -var require_bytesEncoding = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - function uint8ArrayToString(bytes, format) { - return Buffer.from(bytes).toString(format); - } - function stringToUint8Array(value, format) { - return Buffer.from(value, format); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/index.js -var require_commonjs2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; - var delay_js_1 = require_delay(); - Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { - return delay_js_1.delay; - } }); - Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { - return delay_js_1.calculateRetryDelay; - } }); - var aborterUtils_js_1 = require_aborterUtils(); - Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { - return aborterUtils_js_1.cancelablePromiseRace; - } }); - var createAbortablePromise_js_1 = require_createAbortablePromise(); - Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { - return createAbortablePromise_js_1.createAbortablePromise; - } }); - var random_js_1 = require_random(); - Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { - return random_js_1.getRandomIntegerInclusive; - } }); - var object_js_1 = require_object(); - Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { - return object_js_1.isObject; - } }); - var error_js_1 = require_error(); - Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { - return error_js_1.isError; - } }); - Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { - return error_js_1.getErrorMessage; - } }); - var sha256_js_1 = require_sha256(); - Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hash; - } }); - Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hmac; - } }); - var typeGuards_js_1 = require_typeGuards(); - Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { - return typeGuards_js_1.isDefined; - } }); - Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { - return typeGuards_js_1.isObjectWithProperties; - } }); - Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { - return typeGuards_js_1.objectHasProperty; - } }); - var uuidUtils_js_1 = require_uuidUtils(); - Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { - return uuidUtils_js_1.randomUUID; - } }); - var checkEnvironment_js_1 = require_checkEnvironment(); - Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBrowser; - } }); - Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBun; - } }); - Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNode; - } }); - Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeLike; - } }); - Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeRuntime; - } }); - Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { - return checkEnvironment_js_1.isDeno; - } }); - Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { - return checkEnvironment_js_1.isReactNative; - } }); - Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { - return checkEnvironment_js_1.isWebWorker; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js -var require_sanitizer = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = void 0; - var core_util_1 = require_commonjs2(); - var RedactedString = "REDACTED"; - var defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate" - ]; - var defaultAllowedQueryParameters = ["api-version"]; - var Sanitizer = class { - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { - allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); - allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); - } - sanitize(obj) { - const seen = /* @__PURE__ */ new Set(); - return JSON.stringify(obj, (key, value) => { - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); - } - if (key === "headers") { - return this.sanitizeHeaders(value); - } else if (key === "url") { - return this.sanitizeUrl(value); - } else if (key === "query") { - return this.sanitizeQuery(value); - } else if (key === "body") { - return void 0; - } else if (key === "response") { - return void 0; - } else if (key === "operationSpec") { - return void 0; - } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - } - return value; - }, 2); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - sanitizeUrl(value) { - if (typeof value !== "string" || value === null || value === "") { - return value; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const url2 = new URL(value); - if (!url2.search) { - return value; + if (!useProxy) { + agent = this._agent; } - for (const [key] of url2.searchParams) { - if (!this.allowedQueryParameters.has(key.toLowerCase())) { - url2.searchParams.set(key, RedactedString); - } + if (agent) { + return agent; } - return url2.toString(); - } - sanitizeHeaders(obj) { - const sanitized = {}; - for (const key of Object.keys(obj)) { - if (this.allowedHeaderNames.has(key.toLowerCase())) { - sanitized[key] = obj[key]; + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - sanitized[key] = RedactedString; + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - return sanitized; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - sanitizeQuery(value) { - if (typeof value !== "object" || value === null) { - return value; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (this.allowedQueryParameters.has(k.toLowerCase())) { - sanitized[k] = value[k]; - } else { - sanitized[k] = RedactedString; - } + if (proxyAgent) { + return proxyAgent; } - return sanitized; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); + } + })); + }); } }; - exports2.Sanitizer = Sanitizer; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js -var require_logPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log(); - var sanitizer_js_1 = require_sanitizer(); - exports2.logPolicyName = "logPolicy"; - function logPolicy(options = {}) { - var _a; - const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - return { - name: exports2.logPolicyName, - async sendRequest(request, next) { - if (!logger.enabled) { - return next(request); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - logger(`Request: ${sanitizer.sanitize(request)}`); - const response = await next(request); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); - return response; } - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js -var require_redirectPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - exports2.redirectPolicyName = "redirectPolicy"; - var allowedRedirect = ["GET", "HEAD"]; - function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: exports2.redirectPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return handleRedirect(next, response, maxRetries); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - }; - } - async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { - const url2 = new URL(locationHeader, request.url); - request.url = url2.toString(); - if (status === 303) { - request.method = "GET"; - request.headers.delete("Content-Length"); - delete request.body; + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } - request.headers.delete("Authorization"); - const res = await next(request); - return handleRedirect(next, res, maxRetries, currentRetries + 1); - } - return response; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; + } + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; + } + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } + }; + function createEmptyPipeline() { + return HttpPipeline.create(); + } + } +}); + +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os5 = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; + } + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os5.EOL}`); + } + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); + } + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log + }); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } + } + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; + } + function disable() { + const result = enabledString || ""; + enable(""); + return result; + } + function createDebugger(namespace) { + const newDebugger = Object.assign(debug6, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug6(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; + } + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; + } + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; + } + var debug5 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug5("azure"); + AzureLogger.log = (...args) => { + debug5.log(...args); + }; + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + } + } + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); + } + } + debug5.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 + }; + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; + } + function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; + } + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces2 = debug5.disable(); + debug5.enable(enabledNamespaces2 + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; + } + function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + } + function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); + } + exports2.AzureLogger = AzureLogger; + exports2.createClientLogger = createClientLogger; + exports2.getLogLevel = getLogLevel; + exports2.setLogLevel = setLogLevel; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js +var require_log = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError; + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve8, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve8(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/random.js +var require_random = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; + function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay2; + exports2.calculateRetryDelay = calculateRetryDelay; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var random_js_1 = require_random(); + var StandardAbortMessage = "The delay was aborted."; + function delay2(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve8) => { + token = setTimeout(resolve8, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage + }); + } + function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); + } + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/object.js +var require_object = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isObject = isObject2; + function isObject2(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isError = isError; + exports2.getErrorMessage = getErrorMessage2; + var object_js_1 = require_object(); + function isError(e) { + if ((0, object_js_1.isObject)(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; + } + function getErrorMessage2(e) { + if (isError(e)) { + return e.message; + } else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } else { + stringified = String(e); + } + } catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.computeSha256Hmac = computeSha256Hmac; + exports2.computeSha256Hash = computeSha256Hash; + var crypto_1 = require("crypto"); + async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); + } + async function computeSha256Hash(content, encoding) { + return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isDefined = isDefined2; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined2(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined2(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined2(thing) && typeof thing === "object" && property in thing; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js +var require_uuidUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { + "use strict"; + var _a; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.randomUUID = randomUUID2; + var crypto_1 = require("crypto"); + var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; + function randomUUID2() { + return uuidFunction(); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js +var require_checkEnvironment = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { + "use strict"; + var _a; + var _b; + var _c; + var _d; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; + exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; + exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); + exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; + exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; + exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); + exports2.isNode = exports2.isNodeLike; + exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; + exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js +var require_bytesEncoding = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.uint8ArrayToString = uint8ArrayToString; + exports2.stringToUint8Array = stringToUint8Array; + function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); + } + function stringToUint8Array(value, format) { + return Buffer.from(value, format); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; + var delay_js_1 = require_delay(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { + return delay_js_1.calculateRetryDelay; + } }); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var random_js_1 = require_random(); + Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { + return random_js_1.getRandomIntegerInclusive; + } }); + var object_js_1 = require_object(); + Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { + return object_js_1.isObject; + } }); + var error_js_1 = require_error(); + Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { + return error_js_1.isError; + } }); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var sha256_js_1 = require_sha256(); + Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hash; + } }); + Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hmac; + } }); + var typeGuards_js_1 = require_typeGuards(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + var uuidUtils_js_1 = require_uuidUtils(); + Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { + return uuidUtils_js_1.randomUUID; + } }); + var checkEnvironment_js_1 = require_checkEnvironment(); + Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBrowser; + } }); + Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBun; + } }); + Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNode; + } }); + Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeLike; + } }); + Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeRuntime; + } }); + Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { + return checkEnvironment_js_1.isDeno; + } }); + Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { + return checkEnvironment_js_1.isReactNative; + } }); + Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { + return checkEnvironment_js_1.isWebWorker; + } }); + var bytesEncoding_js_1 = require_bytesEncoding(); + Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { + return bytesEncoding_js_1.uint8ArrayToString; + } }); + Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { + return bytesEncoding_js_1.stringToUint8Array; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js +var require_sanitizer = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Sanitizer = void 0; + var core_util_1 = require_commonjs2(); + var RedactedString = "REDACTED"; + var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" + ]; + var defaultAllowedQueryParameters = ["api-version"]; + var Sanitizer = class { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); + } + if (key === "headers") { + return this.sanitizeHeaders(value); + } else if (key === "url") { + return this.sanitizeUrl(value); + } else if (key === "query") { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }, 2); + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; + } + const url2 = new URL(value); + if (!url2.search) { + return value; + } + for (const [key] of url2.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url2.searchParams.set(key, RedactedString); + } + } + return url2.toString(); + } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } + }; + exports2.Sanitizer = Sanitizer; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js +var require_logPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logPolicyName = void 0; + exports2.logPolicy = logPolicy; + var log_js_1 = require_log(); + var sanitizer_js_1 = require_sanitizer(); + exports2.logPolicyName = "logPolicy"; + function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + return { + name: exports2.logPolicyName, + async sendRequest(request, next) { + if (!logger.enabled) { + return next(request); + } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.redirectPolicyName = void 0; + exports2.redirectPolicy = redirectPolicy; + exports2.redirectPolicyName = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; + return { + name: exports2.redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + } + }; + } + async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url2 = new URL(locationHeader, request.url); + request.url = url2.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; + } + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); + } + return response; } } }); @@ -67946,7 +69452,7 @@ var require_requestUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; var core15 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var constants_1 = require_constants7(); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -68114,7 +69620,7 @@ var require_downloadUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; var core15 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var storage_blob_1 = require_dist7(); var buffer = __importStar4(require("buffer")); var fs17 = __importStar4(require("fs")); @@ -68691,8 +70197,8 @@ var require_cacheHttpClient = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; var core15 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib4(); + var auth_1 = require_auth2(); var fs17 = __importStar4(require("fs")); var url_1 = require("url"); var utils = __importStar4(require_cacheUtils()); @@ -69668,2706 +71174,4406 @@ var require_binary_reader = __commonJS({ return this.buf.subarray(start, start + len); } /** - * Read a `string` field, length-delimited data converted to UTF-8 text. + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); + } + }; + exports2.BinaryReader = BinaryReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js +var require_assert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; + function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } + } + exports2.assert = assert; + function assertNever2(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + } + exports2.assertNever = assertNever2; + var FLOAT32_MAX = 34028234663852886e22; + var FLOAT32_MIN = -34028234663852886e22; + var UINT32_MAX = 4294967295; + var INT32_MAX = 2147483647; + var INT32_MIN = -2147483648; + function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid int 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error("invalid int 32: " + arg); + } + exports2.assertInt32 = assertInt32; + function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid uint 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error("invalid uint 32: " + arg); + } + exports2.assertUInt32 = assertUInt32; + function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error("invalid float 32: " + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error("invalid float 32: " + arg); + } + exports2.assertFloat32 = assertFloat32; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js +var require_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var assert_1 = require_assert(); + var defaultsWrite = { + writeUnknownFields: true, + writerFactory: () => new BinaryWriter() + }; + function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.binaryWriteOptions = binaryWriteOptions; + var BinaryWriter = class { + constructor(textEncoder) { + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; + } + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; + } + this.chunks = []; + return bytes; + } + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; + } + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + let chunk = this.finish(); + let prev = this.stack.pop(); + if (!prev) + throw new Error("invalid state, fork stack empty"); + this.chunks = prev.chunks; + this.buf = prev.buf; + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type2) { + return this.uint32((fieldNo << 3 | type2) >>> 0); + } + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; + } + this.chunks.push(chunk); + return this; + } + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); + while (value > 127) { + this.buf.push(value & 127 | 128); + value = value >>> 7; + } + this.buf.push(value); + return this; + } + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; + } + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); + return this.raw(value); + } + /** + * Write a `string` value, length-delimited data converted to UTF-8 text. + */ + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Write a `float` value, 32-bit floating point number. + */ + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `double` value, a 64-bit floating point number. + */ + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); + } + /** + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + */ + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + */ + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + */ + sint32(value) { + assert_1.assertInt32(value); + value = (value << 1 ^ value >> 31) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + */ + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + */ + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `int64` value, a signed 64-bit varint. + */ + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + /** + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. */ - string() { - return this.textDecoder.decode(this.bytes()); + sint64(value) { + let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; + } + /** + * Write a `uint64` value, an unsigned 64-bit varint. + */ + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; } }; - exports2.BinaryReader = BinaryReader; + exports2.BinaryWriter = BinaryWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js -var require_assert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js +var require_json_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; - function assert(condition, msg) { - if (!condition) { - throw new Error(msg); + exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; + var defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0 + }; + var defaultsRead = { + ignoreUnknownFields: false + }; + function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; + } + exports2.jsonReadOptions = jsonReadOptions; + function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.jsonWriteOptions = jsonWriteOptions; + function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; + return c; + } + exports2.mergeJsonOptions = mergeJsonOptions; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js +var require_message_type_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MESSAGE_TYPE = void 0; + exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js +var require_lower_camel_case = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.lowerCamelCase = void 0; + function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == "_") { + capNext = true; + } else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } else if (i == 0) { + sb.push(next.toLowerCase()); + } else { + sb.push(next); + } } + return sb.join(""); } - exports2.assert = assert; - function assertNever2(value, msg) { - throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + exports2.lowerCamelCase = lowerCamelCase; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js +var require_reflection_info = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; + var lower_camel_case_1 = require_lower_camel_case(); + var ScalarType; + (function(ScalarType2) { + ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; + ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; + ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; + ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; + ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; + ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; + ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; + ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; + ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; + ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; + ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; + ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; + ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; + ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; + ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; + })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); + var LongType; + (function(LongType2) { + LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; + LongType2[LongType2["STRING"] = 1] = "STRING"; + LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; + })(LongType = exports2.LongType || (exports2.LongType = {})); + var RepeatType; + (function(RepeatType2) { + RepeatType2[RepeatType2["NO"] = 0] = "NO"; + RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; + RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; + })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); + function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; + return field; } - exports2.assertNever = assertNever2; - var FLOAT32_MAX = 34028234663852886e22; - var FLOAT32_MIN = -34028234663852886e22; - var UINT32_MAX = 4294967295; - var INT32_MAX = 2147483647; - var INT32_MIN = -2147483648; - function assertInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid int 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) - throw new Error("invalid int 32: " + arg); + exports2.normalizeFieldInfo = normalizeFieldInfo; + function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; } - exports2.assertInt32 = assertInt32; - function assertUInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid uint 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) - throw new Error("invalid uint 32: " + arg); + exports2.readFieldOptions = readFieldOptions; + function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.assertUInt32 = assertUInt32; - function assertFloat32(arg) { - if (typeof arg !== "number") - throw new Error("invalid float 32: " + typeof arg); - if (!Number.isFinite(arg)) - return; - if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) - throw new Error("invalid float 32: " + arg); + exports2.readFieldOption = readFieldOption; + function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.assertFloat32 = assertFloat32; + exports2.readMessageOption = readMessageOption; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js -var require_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js +var require_oneof = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; - var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); - var assert_1 = require_assert(); - var defaultsWrite = { - writeUnknownFields: true, - writerFactory: () => new BinaryWriter() - }; - function binaryWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; + function isOneofGroup(any) { + if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === void 0) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; + } } - exports2.binaryWriteOptions = binaryWriteOptions; - var BinaryWriter = class { - constructor(textEncoder) { - this.stack = []; - this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); - this.chunks = []; - this.buf = []; + exports2.isOneofGroup = isOneofGroup; + function getOneofValue(oneof, kind) { + return oneof[kind]; + } + exports2.getOneofValue = getOneofValue; + function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; } - /** - * Return all bytes written and reset this writer. - */ - finish() { - this.chunks.push(new Uint8Array(this.buf)); - let len = 0; - for (let i = 0; i < this.chunks.length; i++) - len += this.chunks[i].length; - let bytes = new Uint8Array(len); - let offset = 0; - for (let i = 0; i < this.chunks.length; i++) { - bytes.set(this.chunks[i], offset); - offset += this.chunks[i].length; - } - this.chunks = []; - return bytes; + oneof.oneofKind = kind; + if (value !== void 0) { + oneof[kind] = value; } - /** - * Start a new fork for length-delimited data like a message - * or a packed repeated field. - * - * Must be joined later with `join()`. - */ - fork() { - this.stack.push({ chunks: this.chunks, buf: this.buf }); - this.chunks = []; - this.buf = []; - return this; + } + exports2.setOneofValue = setOneofValue; + function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; } - /** - * Join the last fork. Write its length and bytes, then - * return to the previous state. - */ - join() { - let chunk = this.finish(); - let prev = this.stack.pop(); - if (!prev) - throw new Error("invalid state, fork stack empty"); - this.chunks = prev.chunks; - this.buf = prev.buf; - this.uint32(chunk.byteLength); - return this.raw(chunk); + oneof.oneofKind = kind; + if (value !== void 0 && kind !== void 0) { + oneof[kind] = value; + } + } + exports2.setUnknownOneofValue = setUnknownOneofValue; + function clearOneofValue(oneof) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = void 0; + } + exports2.clearOneofValue = clearOneofValue; + function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === void 0) { + return void 0; + } + return oneof[oneof.oneofKind]; + } + exports2.getSelectedOneofValue = getSelectedOneofValue; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js +var require_reflection_type_check = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionTypeCheck = void 0; + var reflection_info_1 = require_reflection_info(); + var oneof_1 = require_oneof(); + var ReflectionTypeCheck = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + } + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); + } + } else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; + } + } + } + this.data = { req, known, oneofs: Object.values(oneofs) }; } /** - * Writes a tag (field number and wire type). + * Is the argument a valid message as specified by the + * reflection information? * - * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. * - * Generated code should compute the tag ahead of time and call `uint32()`. + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. */ - tag(fieldNo, type2) { - return this.uint32((fieldNo << 3 | type2) >>> 0); + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === void 0 || typeof message != "object") + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + if (keys.some((k) => !data.known.includes(k))) + return false; + } + if (depth < 1) { + return true; + } + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === void 0) + continue; + const field = this.fields.find((f) => f.localName === group.oneofKind); + if (!field) + return false; + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + for (const field of this.fields) { + if (field.oneof !== void 0) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; + } + return true; } - /** - * Write a chunk of raw bytes. - */ - raw(chunk) { - if (this.buf.length) { - this.chunks.push(new Uint8Array(this.buf)); - this.buf = []; + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === void 0) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != "object" || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } + break; } - this.chunks.push(chunk); - return this; + return true; } - /** - * Write a `uint32` value, an unsigned 32 bit varint. - */ - uint32(value) { - assert_1.assertUInt32(value); - while (value > 127) { - this.buf.push(value & 127 | 128); - value = value >>> 7; + message(arg, type2, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type2.isAssignable(arg, depth); + } + return type2.is(arg, depth); + } + messages(arg, type2, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.isAssignable(arg[i], depth - 1)) + return false; + } else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.is(arg[i], depth - 1)) + return false; + } + return true; + } + scalar(arg, type2, longType) { + let argType = typeof arg; + switch (type2) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == "boolean"; + case reflection_info_1.ScalarType.STRING: + return argType == "string"; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == "number" && !isNaN(arg); + default: + return argType == "number" && Number.isInteger(arg); } - this.buf.push(value); - return this; } - /** - * Write a `int32` value, a signed 32 bit varint. - */ - int32(value) { - assert_1.assertInt32(value); - goog_varint_1.varint32write(value, this.buf); - return this; + scalars(arg, type2, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type2, longType)) + return false; + } + return true; } - /** - * Write a `bool` value, a variant. - */ - bool(value) { - this.buf.push(value ? 1 : 0); - return this; + mapKeys(map2, type2, depth) { + let keys = Object.keys(map2); + switch (type2) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); + default: + return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + } } - /** - * Write a `bytes` value, length-delimited arbitrary data. - */ - bytes(value) { - this.uint32(value.byteLength); - return this.raw(value); + }; + exports2.ReflectionTypeCheck = ReflectionTypeCheck; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js +var require_reflection_long_convert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionLongConvert = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionLongConvert(long, type2) { + switch (type2) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + return long.toString(); } - /** - * Write a `string` value, length-delimited data converted to UTF-8 text. - */ - string(value) { - let chunk = this.textEncoder.encode(value); - this.uint32(chunk.byteLength); - return this.raw(chunk); + } + exports2.reflectionLongConvert = reflectionLongConvert; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js +var require_reflection_json_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonReader = void 0; + var json_typings_1 = require_json_typings(); + var base64_1 = require_base642(); + var reflection_info_1 = require_reflection_info(); + var pb_long_1 = require_pb_long(); + var assert_1 = require_assert(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var ReflectionJsonReader = class { + constructor(info6) { + this.info = info6; } - /** - * Write a `float` value, 32-bit floating point number. - */ - float(value) { - assert_1.assertFloat32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setFloat32(0, value, true); - return this.raw(chunk); + prepare() { + var _a; + if (this.fMap === void 0) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } + } } - /** - * Write a `double` value, a 64-bit floating point number. - */ - double(value) { - let chunk = new Uint8Array(8); - new DataView(chunk.buffer).setFloat64(0, value, true); - return this.raw(chunk); + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + } } /** - * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. */ - fixed32(value) { - assert_1.assertUInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setUint32(0, value, true); - return this.raw(chunk); + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + let target; + if (field.oneof) { + if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { + continue; + } + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } else { + target = message; + } + if (field.kind == "map") { + if (jsonValue === null) { + continue; + } + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + const fieldObj = target[localName]; + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + let val2; + switch (field.V.kind) { + case "message": + val2 = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val2; + } + } else if (field.repeat) { + if (jsonValue === null) + continue; + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + const fieldArr = target[localName]; + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val2; + switch (field.kind) { + case "message": + val2 = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name, jsonValue); + fieldArr.push(val2); + } + } else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { + this.assert(field.oneof === void 0, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + if (jsonValue === null) + continue; + let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + target[localName] = val2; + break; + case "scalar": + if (jsonValue === null) + continue; + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } + } } /** - * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). */ - sfixed32(value) { - assert_1.assertInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setInt32(0, value, true); - return this.raw(chunk); + enum(type2, json2, fieldName, ignoreUnknownFields) { + if (type2[0] == "google.protobuf.NullValue") + assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); + if (json2 === null) + return 0; + switch (typeof json2) { + case "number": + assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); + return json2; + case "string": + let localEnumName = json2; + if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) + localEnumName = json2.substring(type2[2].length); + let enumNumber = type2[1][localEnumName]; + if (typeof enumNumber === "undefined" && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); + return enumNumber; + } + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); } - /** - * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. - */ - sint32(value) { - assert_1.assertInt32(value); - value = (value << 1 ^ value >> 31) >>> 0; - goog_varint_1.varint32write(value, this.buf); - return this; + scalar(json2, type2, longType, fieldName) { + let e; + try { + switch (type2) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json2 === null) + return 0; + if (json2 === "NaN") + return Number.NaN; + if (json2 === "Infinity") + return Number.POSITIVE_INFINITY; + if (json2 === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json2 === "") { + e = "empty string"; + break; + } + if (typeof json2 == "string" && json2.trim().length !== json2.length) { + e = "extra whitespace"; + break; + } + if (typeof json2 != "string" && typeof json2 != "number") { + break; + } + let float2 = Number(json2); + if (Number.isNaN(float2)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float2)) { + e = "too large or small"; + break; + } + if (type2 == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float2); + return float2; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json2 === null) + return 0; + let int32; + if (typeof json2 == "number") + int32 = json2; + else if (json2 === "") + e = "empty string"; + else if (typeof json2 == "string") { + if (json2.trim().length !== json2.length) + e = "extra whitespace"; + else + int32 = Number(json2); + } + if (int32 === void 0) + break; + if (type2 == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json2 === null) + return false; + if (typeof json2 !== "boolean") + break; + return json2; + // string: + case reflection_info_1.ScalarType.STRING: + if (json2 === null) + return ""; + if (typeof json2 !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json2); + } catch (e2) { + e2 = "invalid UTF8"; + break; + } + return json2; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json2 === null || json2 === "") + return new Uint8Array(0); + if (typeof json2 !== "string") + break; + return base64_1.base64decode(json2); + } + } catch (error4) { + e = error4.message; + } + this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - /** - * Write a `fixed64` value, a signed, fixed-length 64-bit integer. - */ - sfixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbLong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + }; + exports2.ReflectionJsonReader = ReflectionJsonReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js +var require_reflection_json_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonWriter = void 0; + var base64_1 = require_base642(); + var pb_long_1 = require_pb_long(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); + var ReflectionJsonWriter = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; } /** - * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + * Converts the message to a JSON object, based on the field descriptors. */ - fixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbULong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + write(message, options) { + const json2 = {}, source = message; + for (const field of this.fields) { + if (!field.oneof) { + let jsonValue2 = this.field(field, source[field.localName], options); + if (jsonValue2 !== void 0) + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; + continue; + } + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; + const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== void 0); + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + } + return json2; } - /** - * Write a `int64` value, a signed 64-bit varint. - */ - int64(value) { - let long = pb_long_1.PbLong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + field(field, value, options) { + let jsonValue = void 0; + if (field.kind == "map") { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); + const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + } + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); + const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val2 = this.message(messageType, value[i], field.name, options); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + } + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } + } + return jsonValue; } /** - * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + * Returns `null` as the default for google.protobuf.NullValue. */ - sint64(value) { - let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; - goog_varint_1.varint64write(lo, hi, this.buf); - return this; + enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type2[0] == "google.protobuf.NullValue") + return !emitDefaultValues && !optional ? void 0 : null; + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + if (value === 0 && !emitDefaultValues && !optional) + return void 0; + assert_1.assert(typeof value == "number"); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type2[1].hasOwnProperty(value)) + return value; + if (type2[2]) + return type2[2] + type2[1][value]; + return type2[1][value]; } - /** - * Write a `uint64` value, an unsigned 64-bit varint. - */ - uint64(value) { - let long = pb_long_1.PbULong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + message(type2, value, fieldName, options) { + if (value === void 0) + return options.emitDefaultValues ? null : void 0; + return type2.internalJsonWrite(value, options); } - }; - exports2.BinaryWriter = BinaryWriter; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js -var require_json_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; - var defaultsWrite = { - emitDefaultValues: false, - enumAsInteger: false, - useProtoFieldName: false, - prettySpaces: 0 - }; - var defaultsRead = { - ignoreUnknownFields: false - }; - function jsonReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.jsonReadOptions = jsonReadOptions; - function jsonWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.jsonWriteOptions = jsonWriteOptions; - function mergeJsonOptions(a, b) { - var _a, _b; - let c = Object.assign(Object.assign({}, a), b); - c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; - return c; - } - exports2.mergeJsonOptions = mergeJsonOptions; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js -var require_message_type_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MESSAGE_TYPE = void 0; - exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js -var require_lower_camel_case = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.lowerCamelCase = void 0; - function lowerCamelCase(snakeCase) { - let capNext = false; - const sb = []; - for (let i = 0; i < snakeCase.length; i++) { - let next = snakeCase.charAt(i); - if (next == "_") { - capNext = true; - } else if (/\d/.test(next)) { - sb.push(next); - capNext = true; - } else if (capNext) { - sb.push(next.toUpperCase()); - capNext = false; - } else if (i == 0) { - sb.push(next.toLowerCase()); - } else { - sb.push(next); + scalar(type2, value, fieldName, optional, emitDefaultValues) { + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + const ed = emitDefaultValues || optional; + switch (type2) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assert(typeof value == "number"); + if (Number.isNaN(value)) + return "NaN"; + if (value === Number.POSITIVE_INFINITY) + return "Infinity"; + if (value === Number.NEGATIVE_INFINITY) + return "-Infinity"; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? "" : void 0; + assert_1.assert(typeof value == "string"); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : void 0; + assert_1.assert(typeof value == "boolean"); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return void 0; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return void 0; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : void 0; + return base64_1.base64encode(value); } } - return sb.join(""); - } - exports2.lowerCamelCase = lowerCamelCase; + }; + exports2.ReflectionJsonWriter = ReflectionJsonWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js -var require_reflection_info = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js +var require_reflection_scalar_default = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; - var lower_camel_case_1 = require_lower_camel_case(); - var ScalarType; - (function(ScalarType2) { - ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; - ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; - ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; - ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; - ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; - ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; - ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; - ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; - ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; - ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; - ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; - ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; - ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; - ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; - ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; - })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); - var LongType; - (function(LongType2) { - LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; - LongType2[LongType2["STRING"] = 1] = "STRING"; - LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; - })(LongType = exports2.LongType || (exports2.LongType = {})); - var RepeatType; - (function(RepeatType2) { - RepeatType2[RepeatType2["NO"] = 0] = "NO"; - RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; - RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; - })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); - function normalizeFieldInfo(field) { - var _a, _b, _c, _d; - field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); - field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); - field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; - field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; - return field; - } - exports2.normalizeFieldInfo = normalizeFieldInfo; - function readFieldOptions(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readFieldOptions = readFieldOptions; - function readFieldOption(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readFieldOption = readFieldOption; - function readMessageOption(messageType, extensionName, extensionType) { - const options = messageType.options; - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + exports2.reflectionScalarDefault = void 0; + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var pb_long_1 = require_pb_long(); + function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { + switch (type2) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + return 0; } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.readMessageOption = readMessageOption; + exports2.reflectionScalarDefault = reflectionScalarDefault; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js -var require_oneof = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js +var require_reflection_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; - function isOneofGroup(any) { - if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { - return false; - } - switch (typeof any.oneofKind) { - case "string": - if (any[any.oneofKind] === void 0) - return false; - return Object.keys(any).length == 2; - case "undefined": - return Object.keys(any).length == 1; - default: - return false; - } - } - exports2.isOneofGroup = isOneofGroup; - function getOneofValue(oneof, kind) { - return oneof[kind]; - } - exports2.getOneofValue = getOneofValue; - function setOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== void 0) { - oneof[kind] = value; + exports2.ReflectionBinaryReader = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var ReflectionBinaryReader = class { + constructor(info6) { + this.info = info6; } - } - exports2.setOneofValue = setOneofValue; - function setUnknownOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + } } - oneof.oneofKind = kind; - if (value !== void 0 && kind !== void 0) { - oneof[kind] = value; + /** + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(reader, message, options, length) { + this.prepare(); + const end = length === void 0 ? reader.len : reader.pos + length; + while (reader.pos < end) { + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; + } + let target = message, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + target = target[field.oneof]; + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : void 0; + if (repeated) { + let arr = target[localName]; + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } else + arr.push(this.scalar(reader, T, L)); + } else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + target[localName][mapKey] = mapVal; + break; + } + } } - } - exports2.setUnknownOneofValue = setUnknownOneofValue; - function clearOneofValue(oneof) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + /** + * Read a map field, expecting key field = 1, value field = 2 + */ + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = void 0; + let val2 = void 0; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val2 = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val2 = reader.int32(); + break; + case "message": + val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } + } + if (key === void 0) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val2 === void 0) + switch (field.V.kind) { + case "scalar": + val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val2 = 0; + break; + case "message": + val2 = field.V.T().create(); + break; + } + return [key, val2]; } - oneof.oneofKind = void 0; - } - exports2.clearOneofValue = clearOneofValue; - function getSelectedOneofValue(oneof) { - if (oneof.oneofKind === void 0) { - return void 0; + scalar(reader, type2, longType) { + switch (type2) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } } - return oneof[oneof.oneofKind]; - } - exports2.getSelectedOneofValue = getSelectedOneofValue; + }; + exports2.ReflectionBinaryReader = ReflectionBinaryReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js -var require_reflection_type_check = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js +var require_reflection_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionTypeCheck = void 0; + exports2.ReflectionBinaryWriter = void 0; + var binary_format_contract_1 = require_binary_format_contract(); var reflection_info_1 = require_reflection_info(); - var oneof_1 = require_oneof(); - var ReflectionTypeCheck = class { + var assert_1 = require_assert(); + var pb_long_1 = require_pb_long(); + var ReflectionBinaryWriter = class { constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + this.info = info6; } prepare() { - if (this.data) - return; - const req = [], known = [], oneofs = []; - for (let field of this.fields) { - if (field.oneof) { - if (!oneofs.includes(field.oneof)) { - oneofs.push(field.oneof); - req.push(field.oneof); - known.push(field.oneof); - } - } else { - known.push(field.localName); - switch (field.kind) { - case "scalar": - case "enum": - if (!field.opt || field.repeat) - req.push(field.localName); - break; - case "message": - if (field.repeat) - req.push(field.localName); - break; - case "map": - req.push(field.localName); - break; - } - } + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); } - this.data = { req, known, oneofs: Object.values(oneofs) }; } /** - * Is the argument a valid message as specified by the - * reflection information? - * - * Checks all field types recursively. The `depth` - * specifies how deep into the structure the check will be. - * - * With a depth of 0, only the presence of fields - * is checked. - * - * With a depth of 1 or more, the field types are checked. - * - * With a depth of 2 or more, the members of map, repeated - * and message fields are checked. - * - * Message fields will be checked recursively with depth - 1. - * - * The number of map entries / repeated values being checked - * is < depth. + * Writes the message to binary format. */ - is(message, depth, allowExcessProperties = false) { - if (depth < 0) - return true; - if (message === null || message === void 0 || typeof message != "object") - return false; + write(message, writer, options) { this.prepare(); - let keys = Object.keys(message), data = this.data; - if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) - return false; - if (!allowExcessProperties) { - if (keys.some((k) => !data.known.includes(k))) - return false; - } - if (depth < 1) { - return true; - } - for (const name of data.oneofs) { - const group = message[name]; - if (!oneof_1.isOneofGroup(group)) - return false; - if (group.oneofKind === void 0) - continue; - const field = this.fields.find((f) => f.localName === group.oneofKind); - if (!field) - return false; - if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) - return false; - } for (const field of this.fields) { - if (field.oneof !== void 0) - continue; - if (!this.field(message[field.localName], field, allowExcessProperties, depth)) - return false; + let value, emitDefault, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; + value = group[localName]; + emitDefault = true; + } else { + value = message[localName]; + emitDefault = false; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } else if (value === void 0) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == "object" && value !== null); + for (const [key, val2] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val2); + break; + } } - return true; + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); } - field(arg, field, allowExcessProperties, depth) { - let repeated = field.repeat; - switch (field.kind) { + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); + break; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == "true" || key == "false"); + keyValue = key == "true"; + break; + } + this.scalar(writer, field.K, 1, keyValue, true); + switch (field.V.kind) { case "scalar": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, field.T, depth, field.L); - return this.scalar(arg, field.T, field.L); + this.scalar(writer, field.V.T, 2, value, true); + break; case "enum": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); - return this.scalar(arg, reflection_info_1.ScalarType.INT32); + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; case "message": - if (arg === void 0) - return true; - if (repeated) - return this.messages(arg, field.T(), allowExcessProperties, depth); - return this.message(arg, field.T(), allowExcessProperties, depth); - case "map": - if (typeof arg != "object" || arg === null) - return false; - if (depth < 2) - return true; - if (!this.mapKeys(arg, field.K, depth)) - return false; - switch (field.V.kind) { - case "scalar": - return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); - case "enum": - return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); - case "message": - return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); - } + this.message(writer, options, field.V.T(), 2, value); break; } - return true; + writer.join(); } - message(arg, type2, allowExcessProperties, depth) { - if (allowExcessProperties) { - return type2.isAssignable(arg, depth); - } - return type2.is(arg, depth); + message(writer, options, handler, fieldNo, value) { + if (value === void 0) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); } - messages(arg, type2, allowExcessProperties, depth) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (allowExcessProperties) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.isAssignable(arg[i], depth - 1)) - return false; - } else { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.is(arg[i], depth - 1)) - return false; + /** + * Write a single scalar value. + */ + scalar(writer, type2, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type2, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); } - return true; } - scalar(arg, type2, longType) { - let argType = typeof arg; + /** + * Write an array of scalar values in packed format. + */ + packed(writer, type2, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let [, method] = this.scalarInfo(type2); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + writer.join(); + } + /** + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. + */ + scalarInfo(type2, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === void 0; + let d = value === 0; switch (type2) { - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - switch (longType) { - case reflection_info_1.LongType.BIGINT: - return argType == "bigint"; - case reflection_info_1.LongType.NUMBER: - return argType == "number" && !isNaN(arg); - default: - return argType == "string"; - } - case reflection_info_1.ScalarType.BOOL: - return argType == "boolean"; + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; case reflection_info_1.ScalarType.STRING: - return argType == "string"; - case reflection_info_1.ScalarType.BYTES: - return arg instanceof Uint8Array; + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; case reflection_info_1.ScalarType.FLOAT: - return argType == "number" && !isNaN(arg); - default: - return argType == "number" && Number.isInteger(arg); - } - } - scalars(arg, type2, depth, longType) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (Array.isArray(arg)) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!this.scalar(arg[i], type2, longType)) - return false; - } - return true; - } - mapKeys(map2, type2, depth) { - let keys = Object.keys(map2); - switch (type2) { - case reflection_info_1.ScalarType.INT32: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); - case reflection_info_1.ScalarType.BOOL: - return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); - default: - return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; } + return [t, m, i || d]; } }; - exports2.ReflectionTypeCheck = ReflectionTypeCheck; + exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js -var require_reflection_long_convert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js +var require_reflection_create = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionLongConvert = void 0; + exports2.reflectionCreate = void 0; + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var message_type_contract_1 = require_message_type_contract(); + function reflectionCreate(type2) { + const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); + for (let field of type2.fields) { + let name = field.localName; + if (field.opt) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: void 0 }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } + } + return msg; + } + exports2.reflectionCreate = reflectionCreate; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js +var require_reflection_merge_partial = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionMergePartial = void 0; + function reflectionMergePartial(info6, target, source) { + let fieldValue, input = source, output; + for (let field of info6.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { + continue; + } + fieldValue = group[name]; + output = target[field.oneof]; + output.oneofKind = group.oneofKind; + if (fieldValue == void 0) { + delete output[name]; + continue; + } + } else { + fieldValue = input[name]; + output = target; + if (fieldValue == void 0) { + continue; + } + } + if (field.repeat) + output[name].length = fieldValue.length; + switch (field.kind) { + case "scalar": + case "enum": + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; + else + output[name] = fieldValue; + break; + case "message": + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === void 0) + output[name] = T.create(fieldValue); + else + T.mergePartial(output[name], fieldValue); + break; + case "map": + switch (field.V.kind) { + case "scalar": + case "enum": + Object.assign(output[name], fieldValue); + break; + case "message": + let T2 = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T2.create(fieldValue[k]); + break; + } + break; + } + } + } + exports2.reflectionMergePartial = reflectionMergePartial; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js +var require_reflection_equals = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionEquals = void 0; var reflection_info_1 = require_reflection_info(); - function reflectionLongConvert(long, type2) { - switch (type2) { - case reflection_info_1.LongType.BIGINT: - return long.toBigInt(); - case reflection_info_1.LongType.NUMBER: - return long.toNumber(); - default: - return long.toString(); + function reflectionEquals(info6, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info6.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) + return false; + break; + } } + return true; + } + exports2.reflectionEquals = reflectionEquals; + var objectValues = Object.values; + function primitiveEq(type2, a, b) { + if (a === b) + return true; + if (type2 !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; + } + function repeatedPrimitiveEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type2, a[i], b[i])) + return false; + return true; + } + function repeatedMsgEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type2.equals(a[i], b[i])) + return false; + return true; } - exports2.reflectionLongConvert = reflectionLongConvert; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js -var require_reflection_json_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js +var require_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonReader = void 0; - var json_typings_1 = require_json_typings(); - var base64_1 = require_base642(); + exports2.MessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); var reflection_info_1 = require_reflection_info(); - var pb_long_1 = require_pb_long(); - var assert_1 = require_assert(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var ReflectionJsonReader = class { - constructor(info6) { - this.info = info6; + var reflection_type_check_1 = require_reflection_type_check(); + var reflection_json_reader_1 = require_reflection_json_reader(); + var reflection_json_writer_1 = require_reflection_json_writer(); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + var reflection_create_1 = require_reflection_create(); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + var json_typings_1 = require_json_typings(); + var json_format_contract_1 = require_json_format_contract(); + var reflection_equals_1 = require_reflection_equals(); + var binary_writer_1 = require_binary_writer(); + var binary_reader_1 = require_binary_reader(); + var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); + var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; + var MessageType = class { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + messageTypeDescriptor.value = this; + this.messagePrototype = Object.create(null, baseDescriptors); + this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); + this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); + this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } - prepare() { - var _a; - if (this.fMap === void 0) { - this.fMap = {}; - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - for (const field of fieldsInput) { - this.fMap[field.name] = field; - this.fMap[field.jsonName] = field; - this.fMap[field.localName] = field; - } + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== void 0) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); } + return message; } - // Cannot parse JSON for #. - assert(condition, fieldName, jsonValue) { - if (!condition) { - let what = json_typings_1.typeofJsonValue(jsonValue); - if (what == "number" || what == "boolean") - what = jsonValue.toString(); - throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + /** + * Clone the message. + * + * Unknown fields are discarded. + */ + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; + } + /** + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. + */ + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); + } + /** + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); + } + /** + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); + } + /** + * Copy partial data into the target message. + */ + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); + } + /** + * Create a new message from binary format. + */ + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + } + /** + * Read a new message from a JSON value. + */ + fromJson(json2, options) { + return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + } + /** + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. + */ + fromJsonString(json2, options) { + let value = JSON.parse(json2); + return this.fromJson(value, options); + } + /** + * Write the message to canonical JSON value. + */ + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + } + /** + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` + */ + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + } + /** + * Write the message to binary format. + */ + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + } + /** + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. + */ + internalJsonRead(json2, options, target) { + if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json2, message, options); + return message; } + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); } /** - * Reads a message from canonical JSON format into the target message. + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); + } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. * - * If a message field is already present, it will be merged with the - * new data. + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. */ - read(input, message, options) { - this.prepare(); - const oneofsHandled = []; - for (const [jsonKey, jsonValue] of Object.entries(input)) { - const field = this.fMap[jsonKey]; - if (!field) { - if (!options.ignoreUnknownFields) - throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); - continue; - } - const localName = field.localName; - let target; - if (field.oneof) { - if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { - continue; - } - if (oneofsHandled.includes(field.oneof)) - throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); - oneofsHandled.push(field.oneof); - target = message[field.oneof] = { - oneofKind: localName - }; - } else { - target = message; - } - if (field.kind == "map") { - if (jsonValue === null) { - continue; - } - this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); - const fieldObj = target[localName]; - for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { - this.assert(jsonObjValue !== null, field.name + " map value", null); - let val2; - switch (field.V.kind) { - case "message": - val2 = field.V.T().internalJsonRead(jsonObjValue, options); - break; - case "enum": - val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); - let key = jsonObjKey; - if (field.K == reflection_info_1.ScalarType.BOOL) - key = key == "true" ? true : key == "false" ? false : key; - key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); - fieldObj[key] = val2; - } - } else if (field.repeat) { - if (jsonValue === null) - continue; - this.assert(Array.isArray(jsonValue), field.name, jsonValue); - const fieldArr = target[localName]; - for (const jsonItem of jsonValue) { - this.assert(jsonItem !== null, field.name, null); - let val2; - switch (field.kind) { - case "message": - val2 = field.T().internalJsonRead(jsonItem, options); - break; - case "enum": - val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonItem, field.T, field.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name, jsonValue); - fieldArr.push(val2); - } - } else { - switch (field.kind) { - case "message": - if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { - this.assert(field.oneof === void 0, field.name + " (oneof member)", null); - continue; - } - target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); - break; - case "enum": - if (jsonValue === null) - continue; - let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - target[localName] = val2; - break; - case "scalar": - if (jsonValue === null) - continue; - target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); - break; - } - } - } + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; } /** - * Returns `false` for unrecognized string representations. + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. * - * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. */ - enum(type2, json2, fieldName, ignoreUnknownFields) { - if (type2[0] == "google.protobuf.NullValue") - assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); - if (json2 === null) - return 0; - switch (typeof json2) { - case "number": - assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); - return json2; - case "string": - let localEnumName = json2; - if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) - localEnumName = json2.substring(type2[2].length); - let enumNumber = type2[1][localEnumName]; - if (typeof enumNumber === "undefined" && ignoreUnknownFields) { - return false; - } - assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); - return enumNumber; - } - assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; } - scalar(json2, type2, longType, fieldName) { - let e; - try { - switch (type2) { - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - if (json2 === null) - return 0; - if (json2 === "NaN") - return Number.NaN; - if (json2 === "Infinity") - return Number.POSITIVE_INFINITY; - if (json2 === "-Infinity") - return Number.NEGATIVE_INFINITY; - if (json2 === "") { - e = "empty string"; - break; - } - if (typeof json2 == "string" && json2.trim().length !== json2.length) { - e = "extra whitespace"; - break; - } - if (typeof json2 != "string" && typeof json2 != "number") { - break; - } - let float2 = Number(json2); - if (Number.isNaN(float2)) { - e = "not a number"; - break; - } - if (!Number.isFinite(float2)) { - e = "too large or small"; - break; - } - if (type2 == reflection_info_1.ScalarType.FLOAT) - assert_1.assertFloat32(float2); - return float2; - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - if (json2 === null) - return 0; - let int32; - if (typeof json2 == "number") - int32 = json2; - else if (json2 === "") - e = "empty string"; - else if (typeof json2 == "string") { - if (json2.trim().length !== json2.length) - e = "extra whitespace"; - else - int32 = Number(json2); - } - if (int32 === void 0) - break; - if (type2 == reflection_info_1.ScalarType.UINT32) - assert_1.assertUInt32(int32); - else - assert_1.assertInt32(int32); - return int32; - // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.UINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); - // bool: - case reflection_info_1.ScalarType.BOOL: - if (json2 === null) - return false; - if (typeof json2 !== "boolean") - break; - return json2; - // string: - case reflection_info_1.ScalarType.STRING: - if (json2 === null) - return ""; - if (typeof json2 !== "string") { - e = "extra whitespace"; - break; - } - try { - encodeURIComponent(json2); - } catch (e2) { - e2 = "invalid UTF8"; - break; - } - return json2; - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - if (json2 === null || json2 === "") - return new Uint8Array(0); - if (typeof json2 !== "string") - break; - return base64_1.base64decode(json2); - } - } catch (error4) { - e = error4.message; + }; + exports2.MessageType = MessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js +var require_reflection_contains_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.containsMessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; + } + exports2.containsMessageType = containsMessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js +var require_enum_object = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; + function isEnumObject(arg) { + if (typeof arg != "object" || arg === null) { + return false; + } + if (!arg.hasOwnProperty(0)) { + return false; + } + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + let nam = arg[num]; + if (nam === void 0) + return false; + if (arg[nam] !== num) + return false; + } else { + let num2 = arg[k]; + if (num2 === void 0) + return false; + if (typeof num2 !== "number") + return false; + if (arg[num2] === void 0) + return false; } - this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - }; - exports2.ReflectionJsonReader = ReflectionJsonReader; + return true; + } + exports2.isEnumObject = isEnumObject; + function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; + } + exports2.listEnumValues = listEnumValues; + function listEnumNames(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.name); + } + exports2.listEnumNames = listEnumNames; + function listEnumNumbers(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + } + exports2.listEnumNumbers = listEnumNumbers; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js -var require_reflection_json_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonWriter = void 0; + var json_typings_1 = require_json_typings(); + Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { + return json_typings_1.typeofJsonValue; + } }); + Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { + return json_typings_1.isJsonObject; + } }); var base64_1 = require_base642(); + Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { + return base64_1.base64decode; + } }); + Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { + return base64_1.base64encode; + } }); + var protobufjs_utf8_1 = require_protobufjs_utf8(); + Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { + return protobufjs_utf8_1.utf8read; + } }); + var binary_format_contract_1 = require_binary_format_contract(); + Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { + return binary_format_contract_1.WireType; + } }); + Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { + return binary_format_contract_1.mergeBinaryOptions; + } }); + Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { + return binary_format_contract_1.UnknownFieldHandler; + } }); + var binary_reader_1 = require_binary_reader(); + Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { + return binary_reader_1.BinaryReader; + } }); + Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { + return binary_reader_1.binaryReadOptions; + } }); + var binary_writer_1 = require_binary_writer(); + Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { + return binary_writer_1.BinaryWriter; + } }); + Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { + return binary_writer_1.binaryWriteOptions; + } }); var pb_long_1 = require_pb_long(); + Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { + return pb_long_1.PbLong; + } }); + Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { + return pb_long_1.PbULong; + } }); + var json_format_contract_1 = require_json_format_contract(); + Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonReadOptions; + } }); + Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonWriteOptions; + } }); + Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { + return json_format_contract_1.mergeJsonOptions; + } }); + var message_type_contract_1 = require_message_type_contract(); + Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { + return message_type_contract_1.MESSAGE_TYPE; + } }); + var message_type_1 = require_message_type(); + Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { + return message_type_1.MessageType; + } }); var reflection_info_1 = require_reflection_info(); + Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { + return reflection_info_1.ScalarType; + } }); + Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { + return reflection_info_1.LongType; + } }); + Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { + return reflection_info_1.RepeatType; + } }); + Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { + return reflection_info_1.normalizeFieldInfo; + } }); + Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { + return reflection_info_1.readFieldOptions; + } }); + Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { + return reflection_info_1.readFieldOption; + } }); + Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { + return reflection_info_1.readMessageOption; + } }); + var reflection_type_check_1 = require_reflection_type_check(); + Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { + return reflection_type_check_1.ReflectionTypeCheck; + } }); + var reflection_create_1 = require_reflection_create(); + Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { + return reflection_create_1.reflectionCreate; + } }); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { + return reflection_scalar_default_1.reflectionScalarDefault; + } }); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { + return reflection_merge_partial_1.reflectionMergePartial; + } }); + var reflection_equals_1 = require_reflection_equals(); + Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { + return reflection_equals_1.reflectionEquals; + } }); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { + return reflection_binary_reader_1.ReflectionBinaryReader; + } }); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { + return reflection_binary_writer_1.ReflectionBinaryWriter; + } }); + var reflection_json_reader_1 = require_reflection_json_reader(); + Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { + return reflection_json_reader_1.ReflectionJsonReader; + } }); + var reflection_json_writer_1 = require_reflection_json_writer(); + Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { + return reflection_json_writer_1.ReflectionJsonWriter; + } }); + var reflection_contains_message_type_1 = require_reflection_contains_message_type(); + Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { + return reflection_contains_message_type_1.containsMessageType; + } }); + var oneof_1 = require_oneof(); + Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { + return oneof_1.isOneofGroup; + } }); + Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { + return oneof_1.setOneofValue; + } }); + Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { + return oneof_1.getOneofValue; + } }); + Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { + return oneof_1.clearOneofValue; + } }); + Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { + return oneof_1.getSelectedOneofValue; + } }); + var enum_object_1 = require_enum_object(); + Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { + return enum_object_1.listEnumValues; + } }); + Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { + return enum_object_1.listEnumNames; + } }); + Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { + return enum_object_1.listEnumNumbers; + } }); + Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { + return enum_object_1.isEnumObject; + } }); + var lower_camel_case_1 = require_lower_camel_case(); + Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { + return lower_camel_case_1.lowerCamelCase; + } }); var assert_1 = require_assert(); - var ReflectionJsonWriter = class { - constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { + return assert_1.assert; + } }); + Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { + return assert_1.assertNever; + } }); + Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { + return assert_1.assertInt32; + } }); + Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { + return assert_1.assertUInt32; + } }); + Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { + return assert_1.assertFloat32; + } }); + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js +var require_reflection_info2 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + var runtime_1 = require_commonjs11(); + function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + m.serverStreaming = !!m.serverStreaming; + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; + return m; + } + exports2.normalizeMethodInfo = normalizeMethodInfo; + function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readMethodOptions = readMethodOptions; + function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; } - /** - * Converts the message to a JSON object, based on the field descriptors. - */ - write(message, options) { - const json2 = {}, source = message; - for (const field of this.fields) { - if (!field.oneof) { - let jsonValue2 = this.field(field, source[field.localName], options); - if (jsonValue2 !== void 0) - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; - continue; - } - const group = source[field.oneof]; - if (group.oneofKind !== field.localName) - continue; - const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; - let jsonValue = this.field(field, group[field.localName], opt); - assert_1.assert(jsonValue !== void 0); - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; - } - return json2; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - field(field, value, options) { - let jsonValue = void 0; - if (field.kind == "map") { - assert_1.assert(typeof value == "object" && value !== null); - const jsonObj = {}; - switch (field.V.kind) { - case "scalar": - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "message": - const messageType = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.message(messageType, entryValue, field.name, options); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "enum": - const enumInfo = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); - const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - } - if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) - jsonValue = jsonObj; - } else if (field.repeat) { - assert_1.assert(Array.isArray(value)); - const jsonArr = []; - switch (field.kind) { - case "scalar": - for (let i = 0; i < value.length; i++) { - const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "enum": - const enumInfo = field.T(); - for (let i = 0; i < value.length; i++) { - assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); - const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "message": - const messageType = field.T(); - for (let i = 0; i < value.length; i++) { - const val2 = this.message(messageType, value[i], field.name, options); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - } - if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) - jsonValue = jsonArr; - } else { - switch (field.kind) { - case "scalar": - jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); - break; - case "enum": - jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); - break; - case "message": - jsonValue = this.message(field.T(), value, field.name, options); - break; - } - } - return jsonValue; + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMethodOption = readMethodOption; + function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return void 0; } - /** - * Returns `null` as the default for google.protobuf.NullValue. - */ - enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { - if (type2[0] == "google.protobuf.NullValue") - return !emitDefaultValues && !optional ? void 0 : null; - if (value === void 0) { - assert_1.assert(optional); - return void 0; - } - if (value === 0 && !emitDefaultValues && !optional) - return void 0; - assert_1.assert(typeof value == "number"); - assert_1.assert(Number.isInteger(value)); - if (enumAsInteger || !type2[1].hasOwnProperty(value)) - return value; - if (type2[2]) - return type2[2] + type2[1][value]; - return type2[1][value]; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - message(type2, value, fieldName, options) { - if (value === void 0) - return options.emitDefaultValues ? null : void 0; - return type2.internalJsonWrite(value, options); + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readServiceOption = readServiceOption; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js +var require_service_type = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServiceType = void 0; + var reflection_info_1 = require_reflection_info2(); + var ServiceType = class { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; } - scalar(type2, value, fieldName, optional, emitDefaultValues) { - if (value === void 0) { - assert_1.assert(optional); - return void 0; + }; + exports2.ServiceType = ServiceType; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js +var require_rpc_error = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcError = void 0; + var RpcError = class extends Error { + constructor(message, code = "UNKNOWN", meta) { + super(message); + this.name = "RpcError"; + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; + } + toString() { + const l = [this.name + ": " + this.message]; + if (this.code) { + l.push(""); + l.push("Code: " + this.code); } - const ed = emitDefaultValues || optional; - switch (type2) { - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertInt32(value); - return value; - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertUInt32(value); - return value; - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.FLOAT: - assert_1.assertFloat32(value); - case reflection_info_1.ScalarType.DOUBLE: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assert(typeof value == "number"); - if (Number.isNaN(value)) - return "NaN"; - if (value === Number.POSITIVE_INFINITY) - return "Infinity"; - if (value === Number.NEGATIVE_INFINITY) - return "-Infinity"; - return value; - // string: - case reflection_info_1.ScalarType.STRING: - if (value === "") - return ed ? "" : void 0; - assert_1.assert(typeof value == "string"); - return value; - // bool: - case reflection_info_1.ScalarType.BOOL: - if (value === false) - return ed ? false : void 0; - assert_1.assert(typeof value == "boolean"); - return value; - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let ulong = pb_long_1.PbULong.from(value); - if (ulong.isZero() && !ed) - return void 0; - return ulong.toString(); - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let long = pb_long_1.PbLong.from(value); - if (long.isZero() && !ed) - return void 0; - return long.toString(); - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - assert_1.assert(value instanceof Uint8Array); - if (!value.byteLength) - return ed ? "" : void 0; - return base64_1.base64encode(value); + if (this.serviceName && this.methodName) { + l.push("Method: " + this.serviceName + "/" + this.methodName); + } + let m = Object.entries(this.meta); + if (m.length) { + l.push(""); + l.push("Meta:"); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); + } } + return l.join("\n"); } }; - exports2.ReflectionJsonWriter = ReflectionJsonWriter; + exports2.RpcError = RpcError; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js -var require_reflection_scalar_default = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js +var require_rpc_options = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionScalarDefault = void 0; - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var pb_long_1 = require_pb_long(); - function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { - switch (type2) { - case reflection_info_1.ScalarType.BOOL: - return false; - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return 0; - case reflection_info_1.ScalarType.BYTES: - return new Uint8Array(0); - case reflection_info_1.ScalarType.STRING: - return ""; - default: - return 0; + exports2.mergeRpcOptions = void 0; + var runtime_1 = require_commonjs11(); + function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val2 = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); + break; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); + break; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); + break; + } + } + return o; + } + exports2.mergeRpcOptions = mergeRpcOptions; + function copy(a, into) { + if (!a) + return; + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; } } - exports2.reflectionScalarDefault = reflectionScalarDefault; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js -var require_reflection_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js +var require_deferred = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryReader = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var ReflectionBinaryReader = class { - constructor(info6) { - this.info = info6; - } - prepare() { - var _a; - if (!this.fieldNoToField) { - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + exports2.Deferred = exports2.DeferredState = void 0; + var DeferredState; + (function(DeferredState2) { + DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; + DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; + DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; + })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); + var Deferred = class { + /** + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. + */ + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve8, reject) => { + this._resolve = resolve8; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch((_) => { + }); } } /** - * Reads a message from binary format into the target message. + * Get the current state of the promise. + */ + get state() { + return this._state; + } + /** + * Get the deferred promise. + */ + get promise() { + return this._promise; + } + /** + * Resolve the promise. Throws if the promise is already resolved or rejected. + */ + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; + } + /** + * Reject the promise. Throws if the promise is already resolved or rejected. + */ + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; + } + /** + * Resolve the promise. Ignore if not pending. + */ + resolvePending(val2) { + if (this._state === DeferredState.PENDING) + this.resolve(val2); + } + /** + * Reject the promise. Ignore if not pending. + */ + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); + } + }; + exports2.Deferred = Deferred; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js +var require_rpc_output_stream = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcOutputStreamController = void 0; + var deferred_1 = require_deferred(); + var runtime_1 = require_commonjs11(); + var RpcOutputStreamController = class { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [] + }; + this._closed = false; + this._itState = { q: [] }; + } + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); + } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); + } + // --- Controller API + /** + * Is this stream already closed by a completion or error? + */ + get closed() { + return this._closed !== false; + } + /** + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. + */ + notifyNext(message, error4, complete) { + runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); + if (message) + this.notifyMessage(message); + if (error4) + this.notifyError(error4); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, "stream is closed"); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach((l) => l(message)); + this._lis.nxt.forEach((l) => l(message, void 0, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. * - * If a message field is already present, it will be merged with the - * new data. + * Triggers onNext and onError callbacks. */ - read(reader, message, options, length) { - this.prepare(); - const end = length === void 0 ? reader.len : reader.pos + length; - while (reader.pos < end) { - const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); - if (!field) { - let u = options.readUnknownField; - if (u == "throw") - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); - continue; - } - let target = message, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - target = target[field.oneof]; - if (target.oneofKind !== localName) - target = message[field.oneof] = { - oneofKind: localName - }; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - let L = field.kind == "scalar" ? field.L : void 0; - if (repeated) { - let arr = target[localName]; - if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { - let e = reader.uint32() + reader.pos; - while (reader.pos < e) - arr.push(this.scalar(reader, T, L)); - } else - arr.push(this.scalar(reader, T, L)); - } else - target[localName] = this.scalar(reader, T, L); - break; - case "message": - if (repeated) { - let arr = target[localName]; - let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); - arr.push(msg); - } else - target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); - break; - case "map": - let [mapKey, mapVal] = this.mapEntry(field, reader, options); - target[localName][mapKey] = mapVal; - break; - } - } + notifyError(error4) { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = error4; + this.pushIt(error4); + this._lis.err.forEach((l) => l(error4)); + this._lis.nxt.forEach((l) => l(void 0, error4, false)); + this.clearLis(); } /** - * Read a map field, expecting key field = 1, value field = 2 + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. */ - mapEntry(field, reader, options) { - let length = reader.uint32(); - let end = reader.pos + length; - let key = void 0; - let val2 = void 0; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case 1: - if (field.K == reflection_info_1.ScalarType.BOOL) - key = reader.bool().toString(); - else - key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); - break; - case 2: - switch (field.V.kind) { - case "scalar": - val2 = this.scalar(reader, field.V.T, field.V.L); - break; - case "enum": - val2 = reader.int32(); - break; - case "message": - val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); - break; - } - break; - default: - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + notifyComplete() { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach((l) => l()); + this._lis.nxt.forEach((l) => l(void 0, void 0, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); + runtime_1.assert(!state.p, "iterator contract broken"); + let first = state.q.shift(); + if (first) + return "value" in first ? Promise.resolve(first) : Promise.reject(first); + state.p = new deferred_1.Deferred(); + return state.p.promise; } + }; + } + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (state.p) { + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + "value" in result ? p.resolve(result) : p.reject(result); + delete state.p; + } else { + state.q.push(result); } - if (key === void 0) { - let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); - key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + }; + exports2.RpcOutputStreamController = RpcOutputStreamController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js +var require_unary_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - if (val2 === void 0) - switch (field.V.kind) { - case "scalar": - val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); - break; - case "enum": - val2 = 0; - break; - case "message": - val2 = field.V.T().create(); - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return [key, val2]; - } - scalar(reader, type2, longType) { - switch (type2) { - case reflection_info_1.ScalarType.INT32: - return reader.int32(); - case reflection_info_1.ScalarType.STRING: - return reader.string(); - case reflection_info_1.ScalarType.BOOL: - return reader.bool(); - case reflection_info_1.ScalarType.DOUBLE: - return reader.double(); - case reflection_info_1.ScalarType.FLOAT: - return reader.float(); - case reflection_info_1.ScalarType.INT64: - return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); - case reflection_info_1.ScalarType.UINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); - case reflection_info_1.ScalarType.FIXED32: - return reader.fixed32(); - case reflection_info_1.ScalarType.BYTES: - return reader.bytes(); - case reflection_info_1.ScalarType.UINT32: - return reader.uint32(); - case reflection_info_1.ScalarType.SFIXED32: - return reader.sfixed32(); - case reflection_info_1.ScalarType.SFIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); - case reflection_info_1.ScalarType.SINT32: - return reader.sint32(); - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UnaryCall = void 0; + var UnaryCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryReader = ReflectionBinaryReader; + exports2.UnaryCall = UnaryCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js -var require_reflection_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js +var require_server_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryWriter = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var pb_long_1 = require_pb_long(); - var ReflectionBinaryWriter = class { - constructor(info6) { - this.info = info6; - } - prepare() { - if (!this.fields) { - const fieldsInput = this.info.fields ? this.info.fields.concat() : []; - this.fields = fieldsInput.sort((a, b) => a.no - b.no); - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - /** - * Writes the message to binary format. - */ - write(message, writer, options) { - this.prepare(); - for (const field of this.fields) { - let value, emitDefault, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - const group = message[field.oneof]; - if (group.oneofKind !== localName) - continue; - value = group[localName]; - emitDefault = true; - } else { - value = message[localName]; - emitDefault = false; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (repeated) { - assert_1.assert(Array.isArray(value)); - if (repeated == reflection_info_1.RepeatType.PACKED) - this.packed(writer, T, field.no, value); - else - for (const item of value) - this.scalar(writer, T, field.no, item, true); - } else if (value === void 0) - assert_1.assert(field.opt); - else - this.scalar(writer, T, field.no, value, emitDefault || field.opt); - break; - case "message": - if (repeated) { - assert_1.assert(Array.isArray(value)); - for (const item of value) - this.message(writer, options, field.T(), field.no, item); - } else { - this.message(writer, options, field.T(), field.no, value); - } - break; - case "map": - assert_1.assert(typeof value == "object" && value !== null); - for (const [key, val2] of Object.entries(value)) - this.mapEntry(writer, options, field, key, val2); - break; + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - let u = options.writeUnknownFields; - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); - } - mapEntry(writer, options, field, key, value) { - writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let keyValue = key; - switch (field.K) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - keyValue = Number.parseInt(key); - break; - case reflection_info_1.ScalarType.BOOL: - assert_1.assert(key == "true" || key == "false"); - keyValue = key == "true"; - break; - } - this.scalar(writer, field.K, 1, keyValue, true); - switch (field.V.kind) { - case "scalar": - this.scalar(writer, field.V.T, 2, value, true); - break; - case "enum": - this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); - break; - case "message": - this.message(writer, options, field.V.T(), 2, value); - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - writer.join(); - } - message(writer, options, handler, fieldNo, value) { - if (value === void 0) - return; - handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); - writer.join(); - } - /** - * Write a single scalar value. - */ - scalar(writer, type2, fieldNo, value, emitDefault) { - let [wireType, method, isDefault] = this.scalarInfo(type2, value); - if (!isDefault || emitDefault) { - writer.tag(fieldNo, wireType); - writer[method](value); + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerStreamingCall = void 0; + var ServerStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } /** - * Write an array of scalar values in packed format. + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. */ - packed(writer, type2, fieldNo, value) { - if (!value.length) - return; - assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); - writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let [, method] = this.scalarInfo(type2); - for (let i = 0; i < value.length; i++) - writer[method](value[i]); - writer.join(); + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } - /** - * Get information for writing a scalar value. - * - * Returns tuple: - * [0]: appropriate WireType - * [1]: name of the appropriate method of IBinaryWriter - * [2]: whether the given value is a default value - * - * If argument `value` is omitted, [2] is always false. - */ - scalarInfo(type2, value) { - let t = binary_format_contract_1.WireType.Varint; - let m; - let i = value === void 0; - let d = value === 0; - switch (type2) { - case reflection_info_1.ScalarType.INT32: - m = "int32"; - break; - case reflection_info_1.ScalarType.STRING: - d = i || !value.length; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "string"; - break; - case reflection_info_1.ScalarType.BOOL: - d = value === false; - m = "bool"; - break; - case reflection_info_1.ScalarType.UINT32: - m = "uint32"; - break; - case reflection_info_1.ScalarType.DOUBLE: - t = binary_format_contract_1.WireType.Bit64; - m = "double"; - break; - case reflection_info_1.ScalarType.FLOAT: - t = binary_format_contract_1.WireType.Bit32; - m = "float"; - break; - case reflection_info_1.ScalarType.INT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "int64"; - break; - case reflection_info_1.ScalarType.UINT64: - d = i || pb_long_1.PbULong.from(value).isZero(); - m = "uint64"; - break; - case reflection_info_1.ScalarType.FIXED64: - d = i || pb_long_1.PbULong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "fixed64"; - break; - case reflection_info_1.ScalarType.BYTES: - d = i || !value.byteLength; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "bytes"; - break; - case reflection_info_1.ScalarType.FIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "fixed32"; - break; - case reflection_info_1.ScalarType.SFIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "sfixed32"; - break; - case reflection_info_1.ScalarType.SFIXED64: - d = i || pb_long_1.PbLong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "sfixed64"; - break; - case reflection_info_1.ScalarType.SINT32: - m = "sint32"; - break; - case reflection_info_1.ScalarType.SINT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "sint64"; - break; - } - return [t, m, i || d]; + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + exports2.ServerStreamingCall = ServerStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js -var require_reflection_create = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js +var require_client_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionCreate = void 0; - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var message_type_contract_1 = require_message_type_contract(); - function reflectionCreate(type2) { - const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); - for (let field of type2.fields) { - let name = field.localName; - if (field.opt) - continue; - if (field.oneof) - msg[field.oneof] = { oneofKind: void 0 }; - else if (field.repeat) - msg[name] = []; - else - switch (field.kind) { - case "scalar": - msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); - break; - case "enum": - msg[name] = 0; - break; - case "map": - msg[name] = {}; - break; - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - return msg; - } - exports2.reflectionCreate = reflectionCreate; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js -var require_reflection_merge_partial = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionMergePartial = void 0; - function reflectionMergePartial(info6, target, source) { - let fieldValue, input = source, output; - for (let field of info6.fields) { - let name = field.localName; - if (field.oneof) { - const group = input[field.oneof]; - if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { - continue; - } - fieldValue = group[name]; - output = target[field.oneof]; - output.oneofKind = group.oneofKind; - if (fieldValue == void 0) { - delete output[name]; - continue; + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - } else { - fieldValue = input[name]; - output = target; - if (fieldValue == void 0) { - continue; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - if (field.repeat) - output[name].length = fieldValue.length; - switch (field.kind) { - case "scalar": - case "enum": - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = fieldValue[i]; - else - output[name] = fieldValue; - break; - case "message": - let T = field.T(); - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = T.create(fieldValue[i]); - else if (output[name] === void 0) - output[name] = T.create(fieldValue); - else - T.mergePartial(output[name], fieldValue); - break; - case "map": - switch (field.V.kind) { - case "scalar": - case "enum": - Object.assign(output[name], fieldValue); - break; - case "message": - let T2 = field.V.T(); - for (let k of Object.keys(fieldValue)) - output[name][k] = T2.create(fieldValue[k]); - break; - } - break; + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ClientStreamingCall = void 0; + var ClientStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; } - } - exports2.reflectionMergePartial = reflectionMergePartial; + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.ClientStreamingCall = ClientStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js -var require_reflection_equals = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js +var require_duplex_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionEquals = void 0; - var reflection_info_1 = require_reflection_info(); - function reflectionEquals(info6, a, b) { - if (a === b) - return true; - if (!a || !b) - return false; - for (let field of info6.fields) { - let localName = field.localName; - let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; - let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; - switch (field.kind) { - case "enum": - case "scalar": - let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) - return false; - break; - case "map": - if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) - return false; - break; - case "message": - let T = field.T(); - if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) - return false; - break; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DuplexStreamingCall = void 0; + var DuplexStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers + }; + }); } - return true; - } - exports2.reflectionEquals = reflectionEquals; - var objectValues = Object.values; - function primitiveEq(type2, a, b) { - if (a === b) - return true; - if (type2 !== reflection_info_1.ScalarType.BYTES) - return false; - let ba = a; - let bb = b; - if (ba.length !== bb.length) - return false; - for (let i = 0; i < ba.length; i++) - if (ba[i] != bb[i]) - return false; - return true; - } - function repeatedPrimitiveEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!primitiveEq(type2, a[i], b[i])) - return false; - return true; - } - function repeatedMsgEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!type2.equals(a[i], b[i])) - return false; - return true; - } + }; + exports2.DuplexStreamingCall = DuplexStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js -var require_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js +var require_test_transport = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_type_check_1 = require_reflection_type_check(); - var reflection_json_reader_1 = require_reflection_json_reader(); - var reflection_json_writer_1 = require_reflection_json_writer(); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - var reflection_create_1 = require_reflection_create(); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - var json_typings_1 = require_json_typings(); - var json_format_contract_1 = require_json_format_contract(); - var reflection_equals_1 = require_reflection_equals(); - var binary_writer_1 = require_binary_writer(); - var binary_reader_1 = require_binary_reader(); - var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); - var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; - var MessageType = class { - constructor(name, fields, options) { - this.defaultCheckDepth = 16; - this.typeName = name; - this.fields = fields.map(reflection_info_1.normalizeFieldInfo); - this.options = options !== null && options !== void 0 ? options : {}; - messageTypeDescriptor.value = this; - this.messagePrototype = Object.create(null, baseDescriptors); - this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); - this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); - this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); - this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); - this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - create(value) { - let message = reflection_create_1.reflectionCreate(this); - if (value !== void 0) { - reflection_merge_partial_1.reflectionMergePartial(this, message, value); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - return message; - } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TestTransport = void 0; + var rpc_error_1 = require_rpc_error(); + var runtime_1 = require_commonjs11(); + var rpc_output_stream_1 = require_rpc_output_stream(); + var rpc_options_1 = require_rpc_options(); + var unary_call_1 = require_unary_call(); + var server_streaming_call_1 = require_server_streaming_call(); + var client_streaming_call_1 = require_client_streaming_call(); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + var TestTransport = class _TestTransport { /** - * Clone the message. - * - * Unknown fields are discarded. + * Initialize with mock data. Omitted fields have default value. */ - clone(message) { - let copy = this.create(); - reflection_merge_partial_1.reflectionMergePartial(this, copy, message); - return copy; + constructor(data) { + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; } /** - * Determines whether two message of the same type have the same field values. - * Checks for deep equality, traversing repeated fields, oneof groups, maps - * and messages recursively. - * Will also return true if both messages are `undefined`. + * Sent message(s) during the last operation. */ - equals(a, b) { - return reflection_equals_1.reflectionEquals(this, a, b); + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; + } else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; } /** - * Is the given value assignable to our message type - * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + * Sending message(s) completed? */ - is(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, false); + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } else if (typeof this.lastInput == "object") { + return true; + } + return false; } - /** - * Is the given value assignable to our message type, - * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? - */ - isAssignable(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, true); + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); } - /** - * Copy partial data into the target message. - */ - mergePartial(target, source) { - reflection_merge_partial_1.reflectionMergePartial(this, target, source); + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } else if (this.data.response !== void 0) { + r = this.data.response; + } else { + r = method.O.create(); + } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); } /** - * Create a new message from binary format. + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. */ - fromBinary(data, options) { - let opt = binary_reader_1.binaryReadOptions(options); - return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + streamResponses(method, stream2, abort) { + return __awaiter4(this, void 0, void 0, function* () { + const messages = []; + if (this.data.response === void 0) { + messages.push(method.O.create()); + } else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + try { + yield delay2(this.responseDelay, abort)(void 0); + } catch (error4) { + stream2.notifyError(error4); + return; + } + if (this.data.response instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.response); + return; + } + for (let msg of messages) { + stream2.notifyMessage(msg); + try { + yield delay2(this.betweenResponseDelay, abort)(void 0); + } catch (error4) { + stream2.notifyError(error4); + return; + } + } + if (this.data.status instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.status); + return; + } + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.trailers); + return; + } + stream2.notifyComplete(); + }); } - /** - * Read a new message from a JSON value. - */ - fromJson(json2, options) { - return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); } - /** - * Read a new message from a JSON string. - * This is equivalent to `T.fromJson(JSON.parse(json))`. - */ - fromJsonString(json2, options) { - let value = JSON.parse(json2); - return this.fromJson(value, options); + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); } - /** - * Write the message to canonical JSON value. - */ - toJson(message, options) { - return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } } - /** - * Convert the message to canonical JSON string. - * This is equivalent to `JSON.stringify(T.toJson(t))` - */ - toJsonString(message, options) { + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); + } + unary(method, input, options) { var _a; - let value = this.toJson(message, options); - return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); } - /** - * Write the message to binary format. - */ - toBinary(message, options) { - let opt = binary_writer_1.binaryWriteOptions(options); - return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); } - /** - * This is an internal method. If you just want to read a message from - * JSON, use `fromJson()` or `fromJsonString()`. - * - * Reads JSON value and merges the fields into the target - * according to protobuf rules. If the target is omitted, - * a new instance is created first. - */ - internalJsonRead(json2, options, target) { - if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refJsonReader.read(json2, message, options); - return message; + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + } + }; + exports2.TestTransport = TestTransport; + TestTransport.defaultHeaders = { + responseHeader: "test" + }; + TestTransport.defaultStatus = { + code: "OK", + detail: "all good" + }; + TestTransport.defaultTrailers = { + responseTrailer: "test" + }; + function delay2(ms, abort) { + return (v) => new Promise((resolve8, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } else { + const id = setTimeout(() => resolve8(v), ms); + if (abort) { + abort.addEventListener("abort", (ev) => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } } - throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); + }); + } + var TestInputStream = class { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; } - /** - * This is an internal method. If you just want to write a message - * to JSON, use `toJson()` or `toJsonString(). - * - * Writes JSON value and returns it. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.write(message, options); + get sent() { + return this._sent; } - /** - * This is an internal method. If you just want to write a message - * in binary format, use `toBinary()`. - * - * Serializes the message in binary format and appends it to the given - * writer. Returns passed writer. - */ - internalBinaryWrite(message, writer, options) { - this.refBinWriter.write(message, writer, options); - return writer; + get completed() { + return this._completed; } - /** - * This is an internal method. If you just want to read a message from - * binary data, use `fromBinary()`. - * - * Reads data from binary format and merges the fields into - * the target according to protobuf rules. If the target is - * omitted, a new instance is created first. - */ - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refBinReader.read(reader, message, options, length); - return message; + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); + } + const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; + return Promise.resolve(void 0).then(() => { + this._sent.push(message); + }).then(delay2(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); + } + const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; + return Promise.resolve(void 0).then(() => { + this._completed = true; + }).then(delay2(delayMs, this.abort)); } }; - exports2.MessageType = MessageType; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js -var require_reflection_contains_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.containsMessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - function containsMessageType(msg) { - return msg[message_type_contract_1.MESSAGE_TYPE] != null; - } - exports2.containsMessageType = containsMessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js -var require_enum_object = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js +var require_rpc_interceptor = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; - function isEnumObject(arg) { - if (typeof arg != "object" || arg === null) { - return false; + exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; + var runtime_1 = require_commonjs11(); + function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + } + return tail(method, input, options); } - if (!arg.hasOwnProperty(0)) { - return false; + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); } - for (let k of Object.keys(arg)) { - let num = parseInt(k); - if (!Number.isNaN(num)) { - let nam = arg[num]; - if (nam === void 0) - return false; - if (arg[nam] !== num) - return false; - } else { - let num2 = arg[k]; - if (num2 === void 0) - return false; - if (typeof num2 !== "number") - return false; - if (arg[num2] === void 0) - return false; + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); } + return tail(method, options); } - return true; + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); + } + runtime_1.assertNever(kind); } - exports2.isEnumObject = isEnumObject; - function listEnumValues(enumObject) { - if (!isEnumObject(enumObject)) - throw new Error("not a typescript enum object"); - let values = []; - for (let [name, number] of Object.entries(enumObject)) - if (typeof number == "number") - values.push({ name, number }); - return values; + exports2.stackIntercept = stackIntercept; + function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); } - exports2.listEnumValues = listEnumValues; - function listEnumNames(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.name); + exports2.stackUnaryInterceptors = stackUnaryInterceptors; + function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); } - exports2.listEnumNames = listEnumNames; - function listEnumNumbers(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; + function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); } - exports2.listEnumNumbers = listEnumNumbers; + exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; + function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); + } + exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/index.js -var require_commonjs11 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js +var require_server_call_context = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var json_typings_1 = require_json_typings(); - Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { - return json_typings_1.typeofJsonValue; - } }); - Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { - return json_typings_1.isJsonObject; - } }); - var base64_1 = require_base642(); - Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { - return base64_1.base64decode; - } }); - Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { - return base64_1.base64encode; - } }); - var protobufjs_utf8_1 = require_protobufjs_utf8(); - Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { - return protobufjs_utf8_1.utf8read; - } }); - var binary_format_contract_1 = require_binary_format_contract(); - Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { - return binary_format_contract_1.WireType; - } }); - Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { - return binary_format_contract_1.mergeBinaryOptions; - } }); - Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { - return binary_format_contract_1.UnknownFieldHandler; - } }); - var binary_reader_1 = require_binary_reader(); - Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { - return binary_reader_1.BinaryReader; - } }); - Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { - return binary_reader_1.binaryReadOptions; - } }); - var binary_writer_1 = require_binary_writer(); - Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { - return binary_writer_1.BinaryWriter; - } }); - Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { - return binary_writer_1.binaryWriteOptions; - } }); - var pb_long_1 = require_pb_long(); - Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { - return pb_long_1.PbLong; - } }); - Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { - return pb_long_1.PbULong; - } }); - var json_format_contract_1 = require_json_format_contract(); - Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonReadOptions; - } }); - Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonWriteOptions; - } }); - Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { - return json_format_contract_1.mergeJsonOptions; - } }); - var message_type_contract_1 = require_message_type_contract(); - Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { - return message_type_contract_1.MESSAGE_TYPE; - } }); - var message_type_1 = require_message_type(); - Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { - return message_type_1.MessageType; - } }); - var reflection_info_1 = require_reflection_info(); - Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { - return reflection_info_1.ScalarType; - } }); - Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { - return reflection_info_1.LongType; - } }); - Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { - return reflection_info_1.RepeatType; - } }); - Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { - return reflection_info_1.normalizeFieldInfo; - } }); - Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { - return reflection_info_1.readFieldOptions; - } }); - Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { - return reflection_info_1.readFieldOption; - } }); - Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { - return reflection_info_1.readMessageOption; - } }); - var reflection_type_check_1 = require_reflection_type_check(); - Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { - return reflection_type_check_1.ReflectionTypeCheck; - } }); - var reflection_create_1 = require_reflection_create(); - Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { - return reflection_create_1.reflectionCreate; - } }); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { - return reflection_scalar_default_1.reflectionScalarDefault; - } }); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { - return reflection_merge_partial_1.reflectionMergePartial; - } }); - var reflection_equals_1 = require_reflection_equals(); - Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { - return reflection_equals_1.reflectionEquals; - } }); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { - return reflection_binary_reader_1.ReflectionBinaryReader; + exports2.ServerCallContextController = void 0; + var ServerCallContextController = class { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; + } + /** + * Set the call cancelled. + * + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. + */ + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } + } + } + /** + * Send response headers. + */ + sendResponseHeaders(data) { + this._sendRH(data); + } + /** + * Is the call cancelled? + * + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. + */ + get cancelled() { + return this._cancelled; + } + /** + * Add a callback for cancellation. + */ + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; + } + }; + exports2.ServerCallContextController = ServerCallContextController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var service_type_1 = require_service_type(); + Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { + return service_type_1.ServiceType; } }); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { - return reflection_binary_writer_1.ReflectionBinaryWriter; + var reflection_info_1 = require_reflection_info2(); + Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { + return reflection_info_1.readMethodOptions; } }); - var reflection_json_reader_1 = require_reflection_json_reader(); - Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { - return reflection_json_reader_1.ReflectionJsonReader; + Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { + return reflection_info_1.readMethodOption; } }); - var reflection_json_writer_1 = require_reflection_json_writer(); - Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { - return reflection_json_writer_1.ReflectionJsonWriter; + Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { + return reflection_info_1.readServiceOption; } }); - var reflection_contains_message_type_1 = require_reflection_contains_message_type(); - Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { - return reflection_contains_message_type_1.containsMessageType; + var rpc_error_1 = require_rpc_error(); + Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { + return rpc_error_1.RpcError; } }); - var oneof_1 = require_oneof(); - Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { - return oneof_1.isOneofGroup; + var rpc_options_1 = require_rpc_options(); + Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { + return rpc_options_1.mergeRpcOptions; } }); - Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { - return oneof_1.setOneofValue; + var rpc_output_stream_1 = require_rpc_output_stream(); + Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { + return rpc_output_stream_1.RpcOutputStreamController; } }); - Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { - return oneof_1.getOneofValue; + var test_transport_1 = require_test_transport(); + Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { + return test_transport_1.TestTransport; } }); - Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { - return oneof_1.clearOneofValue; + var deferred_1 = require_deferred(); + Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { + return deferred_1.Deferred; } }); - Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { - return oneof_1.getSelectedOneofValue; + Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { + return deferred_1.DeferredState; } }); - var enum_object_1 = require_enum_object(); - Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { - return enum_object_1.listEnumValues; + var duplex_streaming_call_1 = require_duplex_streaming_call(); + Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { + return duplex_streaming_call_1.DuplexStreamingCall; } }); - Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { - return enum_object_1.listEnumNames; + var client_streaming_call_1 = require_client_streaming_call(); + Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { + return client_streaming_call_1.ClientStreamingCall; } }); - Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { - return enum_object_1.listEnumNumbers; + var server_streaming_call_1 = require_server_streaming_call(); + Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { + return server_streaming_call_1.ServerStreamingCall; } }); - Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { - return enum_object_1.isEnumObject; + var unary_call_1 = require_unary_call(); + Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { + return unary_call_1.UnaryCall; } }); - var lower_camel_case_1 = require_lower_camel_case(); - Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { - return lower_camel_case_1.lowerCamelCase; + var rpc_interceptor_1 = require_rpc_interceptor(); + Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { + return rpc_interceptor_1.stackIntercept; } }); - var assert_1 = require_assert(); - Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { - return assert_1.assert; + Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackDuplexStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { - return assert_1.assertNever; + Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackClientStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { - return assert_1.assertInt32; + Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackServerStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { - return assert_1.assertUInt32; + Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackUnaryInterceptors; } }); - Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { - return assert_1.assertFloat32; + var server_call_context_1 = require_server_call_context(); + Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { + return server_call_context_1.ServerCallContextController; } }); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js -var require_reflection_info2 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js +var require_cachescope = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + exports2.CacheScope = void 0; var runtime_1 = require_commonjs11(); - function normalizeMethodInfo(method, service) { - var _a, _b, _c; - let m = method; - m.service = service; - m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); - m.serverStreaming = !!m.serverStreaming; - m.clientStreaming = !!m.clientStreaming; - m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; - m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; - return m; - } - exports2.normalizeMethodInfo = normalizeMethodInfo; - function readMethodOptions(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readMethodOptions = readMethodOptions; - function readMethodOption(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var CacheScope$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheScope", [ + { + no: 1, + name: "scope", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "permission", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + create(value) { + const message = { scope: "", permission: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string scope */ + 1: + message.scope = reader.string(); + break; + case /* int64 permission */ + 2: + message.permission = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.scope !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); + if (message.permission !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheScope = new CacheScope$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js +var require_cachemetadata = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheMetadata = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachescope_1 = require_cachescope(); + var CacheMetadata$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheMetadata", [ + { + no: 1, + name: "repository_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } + ]); + } + create(value) { + const message = { repositoryId: "0", scope: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 repository_id */ + 1: + message.repositoryId = reader.int64().toString(); + break; + case /* repeated github.actions.results.entities.v1.CacheScope scope */ + 2: + message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.repositoryId !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); + for (let i = 0; i < message.scope.length; i++) + cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheMetadata = new CacheMetadata$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js +var require_cache2 = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachemetadata_1 = require_cachemetadata(); + var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* string version */ + 3: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readMethodOption = readMethodOption; - function readServiceOption(service, extensionName, extensionType) { - const options = service.options; - if (!options) { - return void 0; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.version !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + }; + exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); + var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readServiceOption = readServiceOption; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js -var require_service_type = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceType = void 0; - var reflection_info_1 = require_reflection_info2(); - var ServiceType = class { - constructor(typeName, methods, options) { - this.typeName = typeName; - this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); - this.options = options !== null && options !== void 0 ? options : {}; + create(value) { + const message = { ok: false, signedUploadUrl: "", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.ServiceType = ServiceType; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js -var require_rpc_error = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcError = void 0; - var RpcError = class extends Error { - constructor(message, code = "UNKNOWN", meta) { - super(message); - this.name = "RpcError"; - Object.setPrototypeOf(this, new.target.prototype); - this.code = code; - this.meta = meta !== null && meta !== void 0 ? meta : {}; + exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); + var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size_bytes", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - toString() { - const l = [this.name + ": " + this.message]; - if (this.code) { - l.push(""); - l.push("Code: " + this.code); - } - if (this.serviceName && this.methodName) { - l.push("Method: " + this.serviceName + "/" + this.methodName); + create(value) { + const message = { key: "", sizeBytes: "0", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* int64 size_bytes */ + 3: + message.sizeBytes = reader.int64().toString(); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } - let m = Object.entries(this.meta); - if (m.length) { - l.push(""); - l.push("Meta:"); - for (let [k, v] of m) { - l.push(` ${k}: ${v}`); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.sizeBytes !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); + var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "entry_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, entryId: "0", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* int64 entry_id */ + 2: + message.entryId = reader.int64().toString(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - return l.join("\n"); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.entryId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.RpcError = RpcError; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js -var require_rpc_options = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeRpcOptions = void 0; - var runtime_1 = require_commonjs11(); - function mergeRpcOptions(defaults, options) { - if (!options) - return defaults; - let o = {}; - copy(defaults, o); - copy(options, o); - for (let key of Object.keys(options)) { - let val2 = options[key]; - switch (key) { - case "jsonOptions": - o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); - break; - case "binaryOptions": - o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); - break; - case "meta": - o.meta = {}; - copy(defaults.meta, o.meta); - copy(options.meta, o.meta); - break; - case "interceptors": - o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); - break; + exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); + var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "restore_keys", + kind: "scalar", + repeat: 2, + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", restoreKeys: [], version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* repeated string restore_keys */ + 3: + message.restoreKeys.push(reader.string()); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } + return message; } - return o; - } - exports2.mergeRpcOptions = mergeRpcOptions; - function copy(a, into) { - if (!a) - return; - let c = into; - for (let [k, v] of Object.entries(a)) { - if (v instanceof Date) - c[k] = new Date(v.getTime()); - else if (Array.isArray(v)) - c[k] = v.concat(); - else - c[k] = v; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + for (let i = 0; i < message.restoreKeys.length; i++) + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); + var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_download_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "matched_key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_download_url */ + 2: + message.signedDownloadUrl = reader.string(); + break; + case /* string matched_key */ + 3: + message.matchedKey = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedDownloadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); + if (message.matchedKey !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); + exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ + { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, + { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, + { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } + ]); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js -var require_deferred = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js +var require_cache_twirp_client = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Deferred = exports2.DeferredState = void 0; - var DeferredState; - (function(DeferredState2) { - DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; - DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; - DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; - })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); - var Deferred = class { - /** - * @param preventUnhandledRejectionWarning - prevents the warning - * "Unhandled Promise rejection" by adding a noop rejection handler. - * Working with calls returned from the runtime-rpc package in an - * async function usually means awaiting one call property after - * the other. This means that the "status" is not being awaited when - * an earlier await for the "headers" is rejected. This causes the - * "unhandled promise reject" warning. A more correct behaviour for - * calls might be to become aware whether at least one of the - * promises is handled and swallow the rejection warning for the - * others. - */ - constructor(preventUnhandledRejectionWarning = true) { - this._state = DeferredState.PENDING; - this._promise = new Promise((resolve8, reject) => { - this._resolve = resolve8; - this._reject = reject; + exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; + var cache_1 = require_cache2(); + var CacheServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); + } + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false }); - if (preventUnhandledRejectionWarning) { - this._promise.catch((_) => { - }); - } + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Get the current state of the promise. - */ - get state() { - return this._state; + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Get the deferred promise. - */ - get promise() { - return this._promise; + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Resolve the promise. Throws if the promise is already resolved or rejected. - */ - resolve(value) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); - this._resolve(value); - this._state = DeferredState.RESOLVED; + }; + exports2.CacheServiceClientJSON = CacheServiceClientJSON; + var CacheServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - /** - * Reject the promise. Throws if the promise is already resolved or rejected. - */ - reject(reason) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); - this._reject(reason); - this._state = DeferredState.REJECTED; + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); } - /** - * Resolve the promise. Ignore if not pending. - */ - resolvePending(val2) { - if (this._state === DeferredState.PENDING) - this.resolve(val2); + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); } - /** - * Reject the promise. Ignore if not pending. - */ - rejectPending(reason) { - if (this._state === DeferredState.PENDING) - this.reject(reason); + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.Deferred = Deferred; + exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js -var require_rpc_output_stream = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/util.js +var require_util10 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcOutputStreamController = void 0; - var deferred_1 = require_deferred(); - var runtime_1 = require_commonjs11(); - var RpcOutputStreamController = class { - constructor() { - this._lis = { - nxt: [], - msg: [], - err: [], - cmp: [] - }; - this._closed = false; - this._itState = { q: [] }; + exports2.maskSecretUrls = exports2.maskSigUrl = void 0; + var core_1 = require_core(); + function maskSigUrl(url2) { + if (!url2) + return; + try { + const parsedUrl = new URL(url2); + const signature = parsedUrl.searchParams.get("sig"); + if (signature) { + (0, core_1.setSecret)(signature); + (0, core_1.setSecret)(encodeURIComponent(signature)); + } + } catch (error4) { + (0, core_1.debug)(`Failed to parse URL: ${url2} ${error4 instanceof Error ? error4.message : String(error4)}`); } - // --- RpcOutputStream callback API - onNext(callback) { - return this.addLis(callback, this._lis.nxt); + } + exports2.maskSigUrl = maskSigUrl; + function maskSecretUrls(body) { + if (typeof body !== "object" || body === null) { + (0, core_1.debug)("body is not an object or is null"); + return; } - onMessage(callback) { - return this.addLis(callback, this._lis.msg); + if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { + maskSigUrl(body.signed_upload_url); } - onError(callback) { - return this.addLis(callback, this._lis.err); + if ("signed_download_url" in body && typeof body.signed_download_url === "string") { + maskSigUrl(body.signed_download_url); } - onComplete(callback) { - return this.addLis(callback, this._lis.cmp); + } + exports2.maskSecretUrls = maskSecretUrls; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js +var require_cacheTwirpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - addLis(callback, list) { - list.push(callback); - return () => { - let i = list.indexOf(callback); - if (i >= 0) - list.splice(i, 1); - }; + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.internalCacheTwirpClient = void 0; + var core_1 = require_core(); + var user_agent_1 = require_user_agent(); + var errors_1 = require_errors2(); + var config_1 = require_config(); + var cacheUtils_1 = require_cacheUtils(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib4(); + var cache_twirp_client_1 = require_cache_twirp_client(); + var util_1 = require_util10(); + var CacheServiceClient = class { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3e3; + this.retryMultiplier = 1.5; + const token = (0, cacheUtils_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getCacheServiceURL)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; + } + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) + ]); } - // remove all listeners - clearLis() { - for (let l of Object.values(this._lis)) - l.splice(0, l.length); + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { + return __awaiter4(this, void 0, void 0, function* () { + const url2 = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url2}`); + const headers = { + "Content-Type": contentType + }; + try { + const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { + return this.httpClient.post(url2, JSON.stringify(data), headers); + })); + return body; + } catch (error4) { + throw new Error(`Failed to ${method}: ${error4.message}`); + } + }); } - // --- Controller API - /** - * Is this stream already closed by a completion or error? - */ - get closed() { - return this._closed !== false; + retryableRequest(operation) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ""; + let rawBody = ""; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, util_1.maskSecretUrls)(body); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } catch (error4) { + if (error4 instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + } + if (error4 instanceof errors_1.UsageError) { + throw error4; + } + if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { + throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + } + isRetryable = true; + errorMessage = error4.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; + } + throw new Error(`Request failed`); + }); } - /** - * Emit message, close with error, or close successfully, but only one - * at a time. - * Can be used to wrap a stream by using the other stream's `onNext`. - */ - notifyNext(message, error4, complete) { - runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); - if (message) - this.notifyMessage(message); - if (error4) - this.notifyError(error4); - if (complete) - this.notifyComplete(); + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; } - /** - * Emits a new message. Throws if stream is closed. - * - * Triggers onNext and onMessage callbacks. - */ - notifyMessage(message) { - runtime_1.assert(!this.closed, "stream is closed"); - this.pushIt({ value: message, done: false }); - this._lis.msg.forEach((l) => l(message)); - this._lis.nxt.forEach((l) => l(message, void 0, false)); + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); } - /** - * Closes the stream with an error. Throws if stream is closed. - * - * Triggers onNext and onError callbacks. - */ - notifyError(error4) { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = error4; - this.pushIt(error4); - this._lis.err.forEach((l) => l(error4)); - this._lis.nxt.forEach((l) => l(void 0, error4, false)); - this.clearLis(); + sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => setTimeout(resolve8, milliseconds)); + }); } - /** - * Closes the stream successfully. Throws if stream is closed. - * - * Triggers onNext and onComplete callbacks. - */ - notifyComplete() { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = true; - this.pushIt({ value: null, done: true }); - this._lis.cmp.forEach((l) => l()); - this._lis.nxt.forEach((l) => l(void 0, void 0, true)); - this.clearLis(); + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error("attempt should be a positive integer"); + } + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } - /** - * Creates an async iterator (that can be used with `for await {...}`) - * to consume the stream. - * - * Some things to note: - * - If an error occurs, the `for await` will throw it. - * - If an error occurred before the `for await` was started, `for await` - * will re-throw it. - * - If the stream is already complete, the `for await` will be empty. - * - If your `for await` consumes slower than the stream produces, - * for example because you are relaying messages in a slow operation, - * messages are queued. - */ - [Symbol.asyncIterator]() { - if (this._closed === true) - this.pushIt({ value: null, done: true }); - else if (this._closed !== false) - this.pushIt(this._closed); - return { - next: () => { - let state = this._itState; - runtime_1.assert(state, "bad state"); - runtime_1.assert(!state.p, "iterator contract broken"); - let first = state.q.shift(); - if (first) - return "value" in first ? Promise.resolve(first) : Promise.reject(first); - state.p = new deferred_1.Deferred(); - return state.p.promise; - } - }; + }; + function internalCacheTwirpClient(options) { + const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new cache_twirp_client_1.CacheServiceClientJSON(client); + } + exports2.internalCacheTwirpClient = internalCacheTwirpClient; + } +}); + +// node_modules/@actions/cache/lib/internal/tar.js +var require_tar = __commonJS({ + "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - // "push" a new iterator result. - // this either resolves a pending promise, or enqueues the result. - pushIt(result) { - let state = this._itState; - if (state.p) { - const p = state.p; - runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); - "value" in result ? p.resolve(result) : p.reject(result); - delete state.p; - } else { - state.q.push(result); - } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.RpcOutputStreamController = RpcOutputStreamController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js -var require_unary_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve8) { @@ -72396,47 +75602,221 @@ var require_unary_call = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UnaryCall = void 0; - var UnaryCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * If you are only interested in the final outcome of this call, - * you can await it to receive a `FinishedUnaryCall`. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - response, - status, - trailers - }; - }); - } - }; - exports2.UnaryCall = UnaryCall; + exports2.createTar = exports2.extractTar = exports2.listTar = void 0; + var exec_1 = require_exec(); + var io7 = __importStar4(require_io()); + var fs_1 = require("fs"); + var path16 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var IS_WINDOWS = process.platform === "win32"; + function getTarPath() { + return __awaiter4(this, void 0, void 0, function* () { + switch (process.platform) { + case "win32": { + const gnuTar = yield utils.getGnuTarPathOnWindows(); + const systemTar = constants_1.SystemTarPathOnWindows; + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else if ((0, fs_1.existsSync)(systemTar)) { + return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; + } + break; + } + case "darwin": { + const gnuTar = yield io7.which("gtar", false); + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else { + return { + path: yield io7.which("tar", true), + type: constants_1.ArchiveToolType.BSD + }; + } + } + default: + break; + } + return { + path: yield io7.which("tar", true), + type: constants_1.ArchiveToolType.GNU + }; + }); + } + function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + const args = [`"${tarPath.path}"`]; + const cacheFileName = utils.getCacheFileName(compressionMethod); + const tarFile = "cache.tar"; + const workingDirectory = getWorkingDirectory(); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (type2) { + case "create": + args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); + break; + case "extract": + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path16.sep}`, "g"), "/")); + break; + case "list": + args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "-P"); + break; + } + if (tarPath.type === constants_1.ArchiveToolType.GNU) { + switch (process.platform) { + case "win32": + args.push("--force-local"); + break; + case "darwin": + args.push("--delay-directory-restore"); + break; + } + } + return args; + }); + } + function getCommands(compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + let args; + const tarPath = yield getTarPath(); + const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); + const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + if (BSD_TAR_ZSTD && type2 !== "create") { + args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; + } else { + args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; + } + if (BSD_TAR_ZSTD) { + return args; + } + return [args.join(" ")]; + }); + } + function getWorkingDirectory() { + var _a; + return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); + } + function getDecompressionProgram(tarPath, compressionMethod, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -d --long=30 --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path16.sep}`, "g"), "/") + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -d --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path16.sep}`, "g"), "/") + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; + default: + return ["-z"]; + } + }); + } + function getCompressionProgram(tarPath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheFileName = utils.getCacheFileName(compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --long=30 --force -o", + cacheFileName.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), + constants_1.TarFilename + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --force -o", + cacheFileName.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), + constants_1.TarFilename + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; + default: + return ["-z"]; + } + }); + } + function execCommands(commands, cwd) { + return __awaiter4(this, void 0, void 0, function* () { + for (const command of commands) { + try { + yield (0, exec_1.exec)(command, void 0, { + cwd, + env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) + }); + } catch (error4) { + throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + } + } + }); + } + function listTar(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const commands = yield getCommands(compressionMethod, "list", archivePath); + yield execCommands(commands); + }); + } + exports2.listTar = listTar; + function extractTar2(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const workingDirectory = getWorkingDirectory(); + yield io7.mkdirP(workingDirectory); + const commands = yield getCommands(compressionMethod, "extract", archivePath); + yield execCommands(commands); + }); + } + exports2.extractTar = extractTar2; + function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + (0, fs_1.writeFileSync)(path16.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); + const commands = yield getCommands(compressionMethod, "create"); + yield execCommands(commands, archiveFolder); + }); + } + exports2.createTar = createTar; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js -var require_server_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { +// node_modules/@actions/cache/lib/cache.js +var require_cache3 = __commonJS({ + "node_modules/@actions/cache/lib/cache.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve8) { @@ -72450,200 +75830,421 @@ var require_server_streaming_call = __commonJS({ } catch (e) { reject(e); } - } - function rejected(value) { + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + var core15 = __importStar4(require_core()); + var path16 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var cacheHttpClient = __importStar4(require_cacheHttpClient()); + var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); + var config_1 = require_config(); + var tar_1 = require_tar(); + var http_client_1 = require_lib4(); + var ValidationError = class _ValidationError extends Error { + constructor(message) { + super(message); + this.name = "ValidationError"; + Object.setPrototypeOf(this, _ValidationError.prototype); + } + }; + exports2.ValidationError = ValidationError; + var ReserveCacheError2 = class _ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = "ReserveCacheError"; + Object.setPrototypeOf(this, _ReserveCacheError.prototype); + } + }; + exports2.ReserveCacheError = ReserveCacheError2; + var FinalizeCacheError = class _FinalizeCacheError extends Error { + constructor(message) { + super(message); + this.name = "FinalizeCacheError"; + Object.setPrototypeOf(this, _FinalizeCacheError.prototype); + } + }; + exports2.FinalizeCacheError = FinalizeCacheError; + function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); + } + } + function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } + } + function isFeatureAvailable() { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + switch (cacheServiceVersion) { + case "v2": + return !!process.env["ACTIONS_RESULTS_URL"]; + case "v1": + default: + return !!process.env["ACTIONS_CACHE_URL"]; + } + } + exports2.isFeatureAvailable = isFeatureAvailable; + function restoreCache4(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core15.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + switch (cacheServiceVersion) { + case "v2": + return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + case "v1": + default: + return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + } + }); + } + exports2.restoreCache = restoreCache4; + function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core15.debug("Resolved Keys:"); + core15.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + let archivePath = ""; + try { + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod, + enableCrossOsArchive + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + return void 0; + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core15.info("Lookup only - skipping download"); + return cacheEntry.cacheKey; + } + archivePath = path16.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core15.debug(`Archive Path: ${archivePath}`); + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core15.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core15.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core15.info("Cache restored successfully"); + return cacheEntry.cacheKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core15.error(`Failed to restore: ${error4.message}`); + } else { + core15.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core15.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core15.debug("Resolved Keys:"); + core15.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + let archivePath = ""; + try { + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + const compressionMethod = yield utils.getCompressionMethod(); + const request = { + key: primaryKey, + restoreKeys, + version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) + }; + const response = yield twirpClient.GetCacheEntryDownloadURL(request); + if (!response.ok) { + core15.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); + return void 0; + } + const isRestoreKeyMatch = request.key !== response.matchedKey; + if (isRestoreKeyMatch) { + core15.info(`Cache hit for restore-key: ${response.matchedKey}`); + } else { + core15.info(`Cache hit for: ${response.matchedKey}`); + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core15.info("Lookup only - skipping download"); + return response.matchedKey; + } + archivePath = path16.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core15.debug(`Archive path: ${archivePath}`); + core15.debug(`Starting download of archive to: ${archivePath}`); + yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core15.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + if (core15.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core15.info("Cache restored successfully"); + return response.matchedKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core15.error(`Failed to restore: ${error4.message}`); + } else { + core15.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + if (archivePath) { + yield utils.unlinkFile(archivePath); + } + } catch (error4) { + core15.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function saveCache4(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core15.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + checkKey(key); + switch (cacheServiceVersion) { + case "v2": + return yield saveCacheV2(paths, key, options, enableCrossOsArchive); + case "v1": + default: + return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + } + }); + } + exports2.saveCache = saveCache4; + function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { + var _a, _b, _c, _d, _e; + return __awaiter4(this, void 0, void 0, function* () { + const compressionMethod = yield utils.getCompressionMethod(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core15.debug("Cache Paths:"); + core15.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path16.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core15.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core15.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const fileSizeLimit = 10 * 1024 * 1024 * 1024; + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core15.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core15.debug("Reserving Cache"); + const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod, + enableCrossOsArchive, + cacheSize: archiveFileSize + }); + if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { + cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { + throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); + } else { + throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); + } + core15.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError2.name) { + core15.info(`Failed to save: ${typedError.message}`); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core15.error(`Failed to save: ${typedError.message}`); + } else { + core15.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + yield utils.unlinkFile(archivePath); + } catch (error4) { + core15.debug(`Failed to delete archive: ${error4}`); } } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return cacheId; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerStreamingCall = void 0; - var ServerStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * You should first setup some listeners to the `request` to - * see the actual messages the server replied with. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - status, - trailers + } + function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); + const compressionMethod = yield utils.getCompressionMethod(); + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core15.debug("Cache Paths:"); + core15.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path16.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core15.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core15.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core15.debug(`File Size: ${archiveFileSize}`); + options.archiveSizeBytes = archiveFileSize; + core15.debug("Reserving Cache"); + const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); + const request = { + key, + version }; - }); - } - }; - exports2.ServerStreamingCall = ServerStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js -var require_client_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { + let signedUploadUrl; try { - step(generator.next(value)); - } catch (e) { - reject(e); + const response = yield twirpClient.CreateCacheEntry(request); + if (!response.ok) { + if (response.message) { + core15.warning(`Cache reservation failed: ${response.message}`); + } + throw new Error(response.message || "Response was not ok"); + } + signedUploadUrl = response.signedUploadUrl; + } catch (error4) { + core15.debug(`Failed to reserve cache: ${error4}`); + throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); } - } - function rejected(value) { + core15.debug(`Attempting to upload cache located at: ${archivePath}`); + yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); + const finalizeRequest = { + key, + version, + sizeBytes: `${archiveFileSize}` + }; + const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); + core15.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); + if (!finalizeResponse.ok) { + if (finalizeResponse.message) { + throw new FinalizeCacheError(finalizeResponse.message); + } + throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); + } + cacheId = parseInt(finalizeResponse.entryId); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError2.name) { + core15.info(`Failed to save: ${typedError.message}`); + } else if (typedError.name === FinalizeCacheError.name) { + core15.warning(typedError.message); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core15.error(`Failed to save: ${typedError.message}`); + } else { + core15.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + yield utils.unlinkFile(archivePath); + } catch (error4) { + core15.debug(`Failed to delete archive: ${error4}`); } } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return cacheId; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ClientStreamingCall = void 0; - var ClientStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - response, - status, - trailers - }; - }); - } - }; - exports2.ClientStreamingCall = ClientStreamingCall; + } } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js -var require_duplex_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { +// node_modules/@actions/tool-cache/lib/manifest.js +var require_manifest = __commonJS({ + "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DuplexStreamingCall = void 0; - var DuplexStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - status, - trailers - }; - }); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.DuplexStreamingCall = DuplexStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js -var require_test_transport = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve8) { @@ -72666,1204 +76267,824 @@ var require_test_transport = __commonJS({ } } function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TestTransport = void 0; - var rpc_error_1 = require_rpc_error(); - var runtime_1 = require_commonjs11(); - var rpc_output_stream_1 = require_rpc_output_stream(); - var rpc_options_1 = require_rpc_options(); - var unary_call_1 = require_unary_call(); - var server_streaming_call_1 = require_server_streaming_call(); - var client_streaming_call_1 = require_client_streaming_call(); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - var TestTransport = class _TestTransport { - /** - * Initialize with mock data. Omitted fields have default value. - */ - constructor(data) { - this.suppressUncaughtRejections = true; - this.headerDelay = 10; - this.responseDelay = 50; - this.betweenResponseDelay = 10; - this.afterResponseDelay = 10; - this.data = data !== null && data !== void 0 ? data : {}; - } - /** - * Sent message(s) during the last operation. - */ - get sentMessages() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.sent; - } else if (typeof this.lastInput == "object") { - return [this.lastInput.single]; - } - return []; - } - /** - * Sending message(s) completed? - */ - get sendComplete() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.completed; - } else if (typeof this.lastInput == "object") { - return true; - } - return false; - } - // Creates a promise for response headers from the mock data. - promiseHeaders() { - var _a; - const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; - return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); - } - // Creates a promise for a single, valid, message from the mock data. - promiseSingleResponse(method) { - if (this.data.response instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.response); - } - let r; - if (Array.isArray(this.data.response)) { - runtime_1.assert(this.data.response.length > 0); - r = this.data.response[0]; - } else if (this.data.response !== void 0) { - r = this.data.response; - } else { - r = method.O.create(); - } - runtime_1.assert(method.O.is(r)); - return Promise.resolve(r); - } - /** - * Pushes response messages from the mock data to the output stream. - * If an error response, status or trailers are mocked, the stream is - * closed with the respective error. - * Otherwise, stream is completed successfully. - * - * The returned promise resolves when the stream is closed. It should - * not reject. If it does, code is broken. - */ - streamResponses(method, stream2, abort) { - return __awaiter4(this, void 0, void 0, function* () { - const messages = []; - if (this.data.response === void 0) { - messages.push(method.O.create()); - } else if (Array.isArray(this.data.response)) { - for (let msg of this.data.response) { - runtime_1.assert(method.O.is(msg)); - messages.push(msg); - } - } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { - runtime_1.assert(method.O.is(this.data.response)); - messages.push(this.data.response); - } - try { - yield delay2(this.responseDelay, abort)(void 0); - } catch (error4) { - stream2.notifyError(error4); - return; - } - if (this.data.response instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.response); - return; - } - for (let msg of messages) { - stream2.notifyMessage(msg); - try { - yield delay2(this.betweenResponseDelay, abort)(void 0); - } catch (error4) { - stream2.notifyError(error4); - return; - } - } - if (this.data.status instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.status); - return; - } - if (this.data.trailers instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.trailers); - return; - } - stream2.notifyComplete(); - }); - } - // Creates a promise for response status from the mock data. - promiseStatus() { - var _a; - const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; - return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); - } - // Creates a promise for response trailers from the mock data. - promiseTrailers() { - var _a; - const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; - return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); - } - maybeSuppressUncaught(...promise) { - if (this.suppressUncaughtRejections) { - for (let p of promise) { - p.catch(() => { - }); - } - } - } - mergeOptions(options) { - return rpc_options_1.mergeRpcOptions({}, options); - } - unary(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); - } - serverStreaming(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); - } - clientStreaming(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); - } - duplex(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); - } - }; - exports2.TestTransport = TestTransport; - TestTransport.defaultHeaders = { - responseHeader: "test" - }; - TestTransport.defaultStatus = { - code: "OK", - detail: "all good" - }; - TestTransport.defaultTrailers = { - responseTrailer: "test" + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - function delay2(ms, abort) { - return (v) => new Promise((resolve8, reject) => { - if (abort === null || abort === void 0 ? void 0 : abort.aborted) { - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - } else { - const id = setTimeout(() => resolve8(v), ms); - if (abort) { - abort.addEventListener("abort", (ev) => { - clearTimeout(id); - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; + var semver8 = __importStar4(require_semver2()); + var core_1 = require_core(); + var os5 = require("os"); + var cp = require("child_process"); + var fs17 = require("fs"); + function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os5.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); + if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + file = candidate.files.find((item) => { + (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module2.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } else { + chk = semver8.satisfies(osVersion, item.platform_version); + } + } + return chk; }); + if (file) { + (0, core_1.debug)(`matched ${candidate.version}`); + match = candidate; + break; + } } } + if (match && file) { + result = Object.assign({}, match); + result.files = [file]; + } + return result; }); } - var TestInputStream = class { - constructor(data, abort) { - this._completed = false; - this._sent = []; - this.data = data; - this.abort = abort; - } - get sent() { - return this._sent; - } - get completed() { - return this._completed; - } - send(message) { - if (this.data.inputMessage instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputMessage); + exports2._findMatch = _findMatch; + function _getOsVersion() { + const plat = os5.platform(); + let version = ""; + if (plat === "darwin") { + version = cp.execSync("sw_vers -productVersion").toString(); + } else if (plat === "linux") { + const lsbContents = module2.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split("\n"); + for (const line of lines) { + const parts = line.split("="); + if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { + version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); + break; + } + } } - const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; - return Promise.resolve(void 0).then(() => { - this._sent.push(message); - }).then(delay2(delayMs, this.abort)); } - complete() { - if (this.data.inputComplete instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputComplete); - } - const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; - return Promise.resolve(void 0).then(() => { - this._completed = true; - }).then(delay2(delayMs, this.abort)); + return version; + } + exports2._getOsVersion = _getOsVersion; + function _readLinuxVersionFile() { + const lsbReleaseFile = "/etc/lsb-release"; + const osReleaseFile = "/etc/os-release"; + let contents = ""; + if (fs17.existsSync(lsbReleaseFile)) { + contents = fs17.readFileSync(lsbReleaseFile).toString(); + } else if (fs17.existsSync(osReleaseFile)) { + contents = fs17.readFileSync(osReleaseFile).toString(); } - }; + return contents; + } + exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js -var require_rpc_interceptor = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; - var runtime_1 = require_commonjs11(); - function stackIntercept(kind, transport, method, options, input) { - var _a, _b, _c, _d; - if (kind == "unary") { - let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); - for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); - } - return tail(method, input, options); - } - if (kind == "serverStreaming") { - let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); - for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); - } - return tail(method, input, options); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - if (kind == "clientStreaming") { - let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); - for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - return tail(method, options); - } - if (kind == "duplex") { - let tail = (mtd, opt) => transport.duplex(mtd, opt); - for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - return tail(method, options); + } else { + return void 0; } - runtime_1.assertNever(kind); - } - exports2.stackIntercept = stackIntercept; - function stackUnaryInterceptors(transport, method, input, options) { - return stackIntercept("unary", transport, method, options, input); - } - exports2.stackUnaryInterceptors = stackUnaryInterceptors; - function stackServerStreamingInterceptors(transport, method, input, options) { - return stackIntercept("serverStreaming", transport, method, options, input); } - exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; - function stackClientStreamingInterceptors(transport, method, options) { - return stackIntercept("clientStreaming", transport, method, options); - } - exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; - function stackDuplexStreamingInterceptors(transport, method, options) { - return stackIntercept("duplex", transport, method, options); - } - exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js -var require_server_call_context = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerCallContextController = void 0; - var ServerCallContextController = class { - constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { - this._cancelled = false; - this._listeners = []; - this.method = method; - this.headers = headers; - this.deadline = deadline; - this.trailers = {}; - this._sendRH = sendResponseHeadersFn; - this.status = defaultStatus; + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - /** - * Set the call cancelled. - * - * Invokes all callbacks registered with onCancel() and - * sets `cancelled = true`. - */ - notifyCancelled() { - if (!this._cancelled) { - this._cancelled = true; - for (let l of this._listeners) { - l(); - } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - /** - * Send response headers. - */ - sendResponseHeaders(data) { - this._sendRH(data); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - /** - * Is the call cancelled? - * - * When the client closes the connection before the server - * is done, the call is cancelled. - * - * If you want to cancel a request on the server, throw a - * RpcError with the CANCELLED status code. - */ - get cancelled() { - return this._cancelled; + get username() { + return this._decodedUsername; } - /** - * Add a callback for cancellation. - */ - onCancel(callback) { - const l = this._listeners; - l.push(callback); - return () => { - let i = l.indexOf(callback); - if (i >= 0) - l.splice(i, 1); - }; + get password() { + return this._decodedPassword; } }; - exports2.ServerCallContextController = ServerCallContextController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js -var require_commonjs12 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var service_type_1 = require_service_type(); - Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { - return service_type_1.ServiceType; - } }); - var reflection_info_1 = require_reflection_info2(); - Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { - return reflection_info_1.readMethodOptions; - } }); - Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { - return reflection_info_1.readMethodOption; - } }); - Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { - return reflection_info_1.readServiceOption; - } }); - var rpc_error_1 = require_rpc_error(); - Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { - return rpc_error_1.RpcError; - } }); - var rpc_options_1 = require_rpc_options(); - Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { - return rpc_options_1.mergeRpcOptions; - } }); - var rpc_output_stream_1 = require_rpc_output_stream(); - Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { - return rpc_output_stream_1.RpcOutputStreamController; - } }); - var test_transport_1 = require_test_transport(); - Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { - return test_transport_1.TestTransport; - } }); - var deferred_1 = require_deferred(); - Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { - return deferred_1.Deferred; - } }); - Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { - return deferred_1.DeferredState; - } }); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { - return duplex_streaming_call_1.DuplexStreamingCall; - } }); - var client_streaming_call_1 = require_client_streaming_call(); - Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { - return client_streaming_call_1.ClientStreamingCall; - } }); - var server_streaming_call_1 = require_server_streaming_call(); - Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { - return server_streaming_call_1.ServerStreamingCall; - } }); - var unary_call_1 = require_unary_call(); - Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { - return unary_call_1.UnaryCall; - } }); - var rpc_interceptor_1 = require_rpc_interceptor(); - Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { - return rpc_interceptor_1.stackIntercept; - } }); - Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackDuplexStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackClientStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackServerStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackUnaryInterceptors; - } }); - var server_call_context_1 = require_server_call_context(); - Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { - return server_call_context_1.ServerCallContextController; - } }); } }); -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js -var require_cachescope = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheScope = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var CacheScope$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheScope", [ - { - no: 1, - name: "scope", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "permission", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - ]); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - create(value) { - const message = { scope: "", permission: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string scope */ - 1: - message.scope = reader.string(); - break; - case /* int64 permission */ - 2: - message.permission = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); + }); } - internalBinaryWrite(message, writer, options) { - if (message.scope !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); - if (message.permission !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); + }); } }; - exports2.CacheScope = new CacheScope$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js -var require_cachemetadata = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheMetadata = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachescope_1 = require_cachescope(); - var CacheMetadata$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheMetadata", [ - { - no: 1, - name: "repository_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } - ]); - } - create(value) { - const message = { repositoryId: "0", scope: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int64 repository_id */ - 1: - message.repositoryId = reader.int64().toString(); - break; - case /* repeated github.actions.results.entities.v1.CacheScope scope */ - 2: - message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.repositoryId !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); - for (let i = 0; i < message.scope.length; i++) - cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.CacheMetadata = new CacheMetadata$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js -var require_cache2 = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachemetadata_1 = require_cachemetadata(); - var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - create(value) { - const message = { key: "", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* string version */ - 3: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.version !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - }; - exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); - var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_upload_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - create(value) { - const message = { ok: false, signedUploadUrl: "", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_upload_url */ - 2: - message.signedUploadUrl = reader.string(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - }; - exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); - var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "size_bytes", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - create(value) { - const message = { key: "", sizeBytes: "0", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* int64 size_bytes */ - 3: - message.sizeBytes = reader.int64().toString(); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - return message; + this._disposed = true; } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.sizeBytes !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); } - }; - exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); - var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "entry_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } - ]); - } - create(value) { - const message = { ok: false, entryId: "0", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 entry_id */ - 2: - message.entryId = reader.int64().toString(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.entryId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } - }; - exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); - var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "restore_keys", - kind: "scalar", - repeat: 2, - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } - ]); + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } - create(value) { - const message = { key: "", restoreKeys: [], version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* repeated string restore_keys */ - 3: - message.restoreKeys.push(reader.string()); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - for (let i = 0; i < message.restoreKeys.length; i++) - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - }; - exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); - var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_download_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "matched_key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - ]); - } - create(value) { - const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + } + return info6; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_download_url */ - 2: - message.signedDownloadUrl = reader.string(); - break; - case /* string matched_key */ - 3: - message.matchedKey = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - return message; + return lowercaseKeys(headers || {}); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedDownloadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); - if (message.matchedKey !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - }; - exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); - exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ - { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, - { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, - { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } - ]); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js -var require_cache_twirp_client = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; - var cache_1 = require_cache2(); - var CacheServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false - }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { - ignoreUnknownFields: true + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); + } + })); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); - } - }; - exports2.CacheServiceClientJSON = CacheServiceClientJSON; - var CacheServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); - } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); - } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); - } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/cache/lib/internal/shared/util.js -var require_util10 = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.maskSecretUrls = exports2.maskSigUrl = void 0; - var core_1 = require_core(); - function maskSigUrl(url2) { - if (!url2) - return; - try { - const parsedUrl = new URL(url2); - const signature = parsedUrl.searchParams.get("sig"); - if (signature) { - (0, core_1.setSecret)(signature); - (0, core_1.setSecret)(encodeURIComponent(signature)); - } - } catch (error4) { - (0, core_1.debug)(`Failed to parse URL: ${url2} ${error4 instanceof Error ? error4.message : String(error4)}`); - } - } - exports2.maskSigUrl = maskSigUrl; - function maskSecretUrls(body) { - if (typeof body !== "object" || body === null) { - (0, core_1.debug)("body is not an object or is null"); - return; - } - if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { - maskSigUrl(body.signed_upload_url); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - if ("signed_download_url" in body && typeof body.signed_download_url === "string") { - maskSigUrl(body.signed_download_url); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - } - exports2.maskSecretUrls = maskSecretUrls; - } -}); - -// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js -var require_cacheTwirpClient = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { - "use strict"; + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve8) { @@ -73892,154 +77113,56 @@ var require_cacheTwirpClient = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.internalCacheTwirpClient = void 0; - var core_1 = require_core(); - var user_agent_1 = require_user_agent(); - var errors_1 = require_errors2(); - var config_1 = require_config(); - var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); - var cache_twirp_client_1 = require_cache_twirp_client(); - var util_1 = require_util10(); - var CacheServiceClient = class { - constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { - this.maxAttempts = 5; - this.baseRetryIntervalMilliseconds = 3e3; - this.retryMultiplier = 1.5; - const token = (0, cacheUtils_1.getRuntimeToken)(); - this.baseUrl = (0, config_1.getCacheServiceURL)(); - if (maxAttempts) { - this.maxAttempts = maxAttempts; - } - if (baseRetryIntervalMilliseconds) { - this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + exports2.RetryHelper = void 0; + var core15 = __importStar4(require_core()); + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); } - if (retryMultiplier) { - this.retryMultiplier = retryMultiplier; + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); } - this.httpClient = new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(token) - ]); - } - // This function satisfies the Rpc interface. It is compatible with the JSON - // JSON generated client. - request(service, method, contentType, data) { - return __awaiter4(this, void 0, void 0, function* () { - const url2 = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; - (0, core_1.debug)(`[Request] ${method} ${url2}`); - const headers = { - "Content-Type": contentType - }; - try { - const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { - return this.httpClient.post(url2, JSON.stringify(data), headers); - })); - return body; - } catch (error4) { - throw new Error(`Failed to ${method}: ${error4.message}`); - } - }); } - retryableRequest(operation) { + execute(action, isRetryable) { return __awaiter4(this, void 0, void 0, function* () { - let attempt = 0; - let errorMessage = ""; - let rawBody = ""; + let attempt = 1; while (attempt < this.maxAttempts) { - let isRetryable = false; try { - const response = yield operation(); - const statusCode = response.message.statusCode; - rawBody = yield response.readBody(); - (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); - (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); - const body = JSON.parse(rawBody); - (0, util_1.maskSecretUrls)(body); - (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); - if (this.isSuccessStatusCode(statusCode)) { - return { response, body }; - } - isRetryable = this.isRetryableHttpStatusCode(statusCode); - errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; - if (body.msg) { - if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { - throw new errors_1.UsageError(); - } - errorMessage = `${errorMessage}: ${body.msg}`; - } - } catch (error4) { - if (error4 instanceof SyntaxError) { - (0, core_1.debug)(`Raw Body: ${rawBody}`); - } - if (error4 instanceof errors_1.UsageError) { - throw error4; - } - if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { - throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; } - isRetryable = true; - errorMessage = error4.message; - } - if (!isRetryable) { - throw new Error(`Received non-retryable error: ${errorMessage}`); - } - if (attempt + 1 === this.maxAttempts) { - throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + core15.info(err.message); } - const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); - (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); - yield this.sleep(retryTimeMilliseconds); + const seconds = this.getSleepAmount(); + core15.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); attempt++; } - throw new Error(`Request failed`); + return yield action(); }); } - isSuccessStatusCode(statusCode) { - if (!statusCode) - return false; - return statusCode >= 200 && statusCode < 300; - } - isRetryableHttpStatusCode(statusCode) { - if (!statusCode) - return false; - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.GatewayTimeout, - http_client_1.HttpCodes.InternalServerError, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.TooManyRequests - ]; - return retryableStatusCodes.includes(statusCode); + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; } - sleep(milliseconds) { + sleep(seconds) { return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve8) => setTimeout(resolve8, milliseconds)); + return new Promise((resolve8) => setTimeout(resolve8, seconds * 1e3)); }); } - getExponentialRetryTimeMilliseconds(attempt) { - if (attempt < 0) { - throw new Error("attempt should be a positive integer"); - } - if (attempt === 0) { - return this.baseRetryIntervalMilliseconds; - } - const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); - const maxTime = minTime * this.retryMultiplier; - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); - } }; - function internalCacheTwirpClient(options) { - const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); - return new cache_twirp_client_1.CacheServiceClientJSON(client); - } - exports2.internalCacheTwirpClient = internalCacheTwirpClient; + exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/cache/lib/internal/tar.js -var require_tar = __commonJS({ - "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74096,866 +77219,610 @@ var require_tar = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTar = exports2.extractTar = exports2.listTar = void 0; - var exec_1 = require_exec(); + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; + var core15 = __importStar4(require_core()); var io7 = __importStar4(require_io()); - var fs_1 = require("fs"); + var crypto2 = __importStar4(require("crypto")); + var fs17 = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os5 = __importStar4(require("os")); var path16 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var constants_1 = require_constants7(); + var httpm = __importStar4(require_lib5()); + var semver8 = __importStar4(require_semver2()); + var stream2 = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError2 = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + exports2.HTTPError = HTTPError2; var IS_WINDOWS = process.platform === "win32"; - function getTarPath() { + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url2, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - switch (process.platform) { - case "win32": { - const gnuTar = yield utils.getGnuTarPathOnWindows(); - const systemTar = constants_1.SystemTarPathOnWindows; - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else if ((0, fs_1.existsSync)(systemTar)) { - return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; - } - break; - } - case "darwin": { - const gnuTar = yield io7.which("gtar", false); - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else { - return { - path: yield io7.which("tar", true), - type: constants_1.ArchiveToolType.BSD - }; + dest = dest || path16.join(_getTempDirectory(), crypto2.randomUUID()); + yield io7.mkdirP(path16.dirname(dest)); + core15.debug(`Downloading ${url2}`); + core15.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url2, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError2 && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; } } - default: - break; - } - return { - path: yield io7.which("tar", true), - type: constants_1.ArchiveToolType.GNU - }; + return true; + }); }); } - function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url2, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - const args = [`"${tarPath.path}"`]; - const cacheFileName = utils.getCacheFileName(compressionMethod); - const tarFile = "cache.tar"; - const workingDirectory = getWorkingDirectory(); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (type2) { - case "create": - args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); - break; - case "extract": - args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path16.sep}`, "g"), "/")); - break; - case "list": - args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), "-P"); - break; + if (fs17.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); } - if (tarPath.type === constants_1.ArchiveToolType.GNU) { - switch (process.platform) { - case "win32": - args.push("--force-local"); - break; - case "darwin": - args.push("--delay-directory-restore"); - break; + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core15.debug("set auth"); + if (headers === void 0) { + headers = {}; } + headers.authorization = auth; } - return args; - }); - } - function getCommands(compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - let args; - const tarPath = yield getTarPath(); - const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); - const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - if (BSD_TAR_ZSTD && type2 !== "create") { - args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; - } else { - args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; - } - if (BSD_TAR_ZSTD) { - return args; + const response = yield http.get(url2, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError2(response.message.statusCode); + core15.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; } - return [args.join(" ")]; - }); - } - function getWorkingDirectory() { - var _a; - return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); - } - function getDecompressionProgram(tarPath, compressionMethod, archivePath) { - return __awaiter4(this, void 0, void 0, function* () { - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -d --long=30 --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path16.sep}`, "g"), "/") - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -d --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path16.sep}`, "g"), "/") - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; - default: - return ["-z"]; + const pipeline = util.promisify(stream2.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; + try { + yield pipeline(readStream, fs17.createWriteStream(dest)); + core15.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core15.debug("download failed"); + try { + yield io7.rmRF(dest); + } catch (err) { + core15.debug(`Failed to delete '${dest}'. ${err.message}`); + } + } } }); } - function getCompressionProgram(tarPath, compressionMethod) { + function extract7z(file, dest, _7zPath) { return __awaiter4(this, void 0, void 0, function* () { - const cacheFileName = utils.getCacheFileName(compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --long=30 --force -o", - cacheFileName.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), - constants_1.TarFilename - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { + try { + const logLevel = core15.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --force -o", - cacheFileName.replace(new RegExp(`\\${path16.sep}`, "g"), "/"), - constants_1.TarFilename - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; - default: - return ["-z"]; - } - }); - } - function execCommands(commands, cwd) { - return __awaiter4(this, void 0, void 0, function* () { - for (const command of commands) { + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } else { + const escapedScript = path16.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true + }; try { - yield (0, exec_1.exec)(command, void 0, { - cwd, - env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) - }); - } catch (error4) { - throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + const powershellPath = yield io7.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); } } + return dest; }); } - function listTar(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const commands = yield getCommands(compressionMethod, "list", archivePath); - yield execCommands(commands); - }); - } - exports2.listTar = listTar; - function extractTar2(archivePath, compressionMethod) { + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { return __awaiter4(this, void 0, void 0, function* () { - const workingDirectory = getWorkingDirectory(); - yield io7.mkdirP(workingDirectory); - const commands = yield getCommands(compressionMethod, "extract", archivePath); - yield execCommands(commands); + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + core15.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + core15.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + if (core15.isDebug() && !flags.includes("v")) { + args.push("-v"); + } + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); + } + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); + } + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; }); } exports2.extractTar = extractTar2; - function createTar(archiveFolder, sourceDirectories, compressionMethod) { + function extractXar(file, dest, flags = []) { return __awaiter4(this, void 0, void 0, function* () { - (0, fs_1.writeFileSync)(path16.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); - const commands = yield getCommands(compressionMethod, "create"); - yield execCommands(commands, archiveFolder); + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + args.push("-x", "-C", dest, "-f", file); + if (core15.isDebug()) { + args.push("-v"); + } + const xarPath = yield io7.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; }); } - exports2.createTar = createTar; - } -}); - -// node_modules/@actions/cache/lib/cache.js -var require_cache3 = __commonJS({ - "node_modules/@actions/cache/lib/cache.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } else { + yield extractZipNix(file, dest); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return dest; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; - var core15 = __importStar4(require_core()); - var path16 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var cacheHttpClient = __importStar4(require_cacheHttpClient()); - var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); - var config_1 = require_config(); - var tar_1 = require_tar(); - var http_client_1 = require_lib(); - var ValidationError = class _ValidationError extends Error { - constructor(message) { - super(message); - this.name = "ValidationError"; - Object.setPrototypeOf(this, _ValidationError.prototype); - } - }; - exports2.ValidationError = ValidationError; - var ReserveCacheError2 = class _ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = "ReserveCacheError"; - Object.setPrototypeOf(this, _ReserveCacheError.prototype); - } - }; - exports2.ReserveCacheError = ReserveCacheError2; - var FinalizeCacheError = class _FinalizeCacheError extends Error { - constructor(message) { - super(message); - this.name = "FinalizeCacheError"; - Object.setPrototypeOf(this, _FinalizeCacheError.prototype); - } - }; - exports2.FinalizeCacheError = FinalizeCacheError; - function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } - } - function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); - } - } - function isFeatureAvailable() { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - switch (cacheServiceVersion) { - case "v2": - return !!process.env["ACTIONS_RESULTS_URL"]; - case "v1": - default: - return !!process.env["ACTIONS_CACHE_URL"]; - } } - exports2.isFeatureAvailable = isFeatureAvailable; - function restoreCache4(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core15.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - switch (cacheServiceVersion) { - case "v2": - return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - case "v1": - default: - return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io7.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core15.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io7.which("powershell", true); + core15.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); } }); } - exports2.restoreCache = restoreCache4; - function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + function extractZipNix(file, dest) { return __awaiter4(this, void 0, void 0, function* () { - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core15.debug("Resolved Keys:"); - core15.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); - } - const compressionMethod = yield utils.getCompressionMethod(); - let archivePath = ""; - try { - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod, - enableCrossOsArchive - }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - return void 0; - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core15.info("Lookup only - skipping download"); - return cacheEntry.cacheKey; - } - archivePath = path16.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core15.debug(`Archive Path: ${archivePath}`); - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core15.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core15.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core15.info("Cache restored successfully"); - return cacheEntry.cacheKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core15.error(`Failed to restore: ${error4.message}`); - } else { - core15.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core15.debug(`Failed to delete archive: ${error4}`); - } + const unzipPath = yield io7.which("unzip", true); + const args = [file]; + if (!core15.isDebug()) { + args.unshift("-q"); } - return void 0; + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); }); } - function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + function cacheDir(sourceDir, tool, version, arch2) { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core15.debug("Resolved Keys:"); - core15.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); + version = semver8.clean(version) || version; + arch2 = arch2 || os5.arch(); + core15.debug(`Caching tool ${tool} ${version} ${arch2}`); + core15.debug(`source dir: ${sourceDir}`); + if (!fs17.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); } - let archivePath = ""; - try { - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - const compressionMethod = yield utils.getCompressionMethod(); - const request = { - key: primaryKey, - restoreKeys, - version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) - }; - const response = yield twirpClient.GetCacheEntryDownloadURL(request); - if (!response.ok) { - core15.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); - return void 0; - } - const isRestoreKeyMatch = request.key !== response.matchedKey; - if (isRestoreKeyMatch) { - core15.info(`Cache hit for restore-key: ${response.matchedKey}`); - } else { - core15.info(`Cache hit for: ${response.matchedKey}`); - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core15.info("Lookup only - skipping download"); - return response.matchedKey; - } - archivePath = path16.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core15.debug(`Archive path: ${archivePath}`); - core15.debug(`Starting download of archive to: ${archivePath}`); - yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core15.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - if (core15.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core15.info("Cache restored successfully"); - return response.matchedKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core15.error(`Failed to restore: ${error4.message}`); - } else { - core15.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - if (archivePath) { - yield utils.unlinkFile(archivePath); - } - } catch (error4) { - core15.debug(`Failed to delete archive: ${error4}`); - } + const destPath = yield _createToolPath(tool, version, arch2); + for (const itemName of fs17.readdirSync(sourceDir)) { + const s = path16.join(sourceDir, itemName); + yield io7.cp(s, destPath, { recursive: true }); } - return void 0; + _completeToolPath(tool, version, arch2); + return destPath; }); } - function saveCache4(paths, key, options, enableCrossOsArchive = false) { + exports2.cacheDir = cacheDir; + function cacheFile(sourceFile, targetFile, tool, version, arch2) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core15.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - checkKey(key); - switch (cacheServiceVersion) { - case "v2": - return yield saveCacheV2(paths, key, options, enableCrossOsArchive); - case "v1": - default: - return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + version = semver8.clean(version) || version; + arch2 = arch2 || os5.arch(); + core15.debug(`Caching tool ${tool} ${version} ${arch2}`); + core15.debug(`source file: ${sourceFile}`); + if (!fs17.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); } + const destFolder = yield _createToolPath(tool, version, arch2); + const destPath = path16.join(destFolder, targetFile); + core15.debug(`destination file ${destPath}`); + yield io7.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch2); + return destFolder; }); } - exports2.saveCache = saveCache4; - function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { - var _a, _b, _c, _d, _e; - return __awaiter4(this, void 0, void 0, function* () { - const compressionMethod = yield utils.getCompressionMethod(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core15.debug("Cache Paths:"); - core15.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch2) { + if (!toolName) { + throw new Error("toolName parameter is required"); + } + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); + } + arch2 = arch2 || os5.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions2(toolName, arch2); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; + } + let toolPath = ""; + if (versionSpec) { + versionSpec = semver8.clean(versionSpec) || ""; + const cachePath = path16.join(_getCacheDirectory(), toolName, versionSpec, arch2); + core15.debug(`checking cache: ${cachePath}`); + if (fs17.existsSync(cachePath) && fs17.existsSync(`${cachePath}.complete`)) { + core15.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); + toolPath = cachePath; + } else { + core15.debug("not found"); } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path16.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core15.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core15.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const fileSizeLimit = 10 * 1024 * 1024 * 1024; - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core15.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); - } - core15.debug("Reserving Cache"); - const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod, - enableCrossOsArchive, - cacheSize: archiveFileSize - }); - if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { - cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; - } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { - throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); - } else { - throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); - } - core15.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError2.name) { - core15.info(`Failed to save: ${typedError.message}`); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core15.error(`Failed to save: ${typedError.message}`); - } else { - core15.warning(`Failed to save: ${typedError.message}`); + } + return toolPath; + } + exports2.find = find2; + function findAllVersions2(toolName, arch2) { + const versions = []; + arch2 = arch2 || os5.arch(); + const toolPath = path16.join(_getCacheDirectory(), toolName); + if (fs17.existsSync(toolPath)) { + const children = fs17.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path16.join(toolPath, child, arch2 || ""); + if (fs17.existsSync(fullPath) && fs17.existsSync(`${fullPath}.complete`)) { + versions.push(child); } } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core15.debug(`Failed to delete archive: ${error4}`); - } } - return cacheId; - }); + } + return versions; } - function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + exports2.findAllVersions = findAllVersions2; + function getManifestFromRepo(owner, repo, auth, branch = "master") { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); - const compressionMethod = yield utils.getCompressionMethod(); - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core15.debug("Cache Paths:"); - core15.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core15.debug("set auth"); + headers.authorization = auth; } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path16.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core15.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core15.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core15.debug(`File Size: ${archiveFileSize}`); - options.archiveSizeBytes = archiveFileSize; - core15.debug("Reserving Cache"); - const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); - const request = { - key, - version - }; - let signedUploadUrl; - try { - const response = yield twirpClient.CreateCacheEntry(request); - if (!response.ok) { - if (response.message) { - core15.warning(`Cache reservation failed: ${response.message}`); - } - throw new Error(response.message || "Response was not ok"); - } - signedUploadUrl = response.signedUploadUrl; - } catch (error4) { - core15.debug(`Failed to reserve cache: ${error4}`); - throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); - } - core15.debug(`Attempting to upload cache located at: ${archivePath}`); - yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); - const finalizeRequest = { - key, - version, - sizeBytes: `${archiveFileSize}` - }; - const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); - core15.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); - if (!finalizeResponse.ok) { - if (finalizeResponse.message) { - throw new FinalizeCacheError(finalizeResponse.message); - } - throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); - } - cacheId = parseInt(finalizeResponse.entryId); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError2.name) { - core15.info(`Failed to save: ${typedError.message}`); - } else if (typedError.name === FinalizeCacheError.name) { - core15.warning(typedError.message); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core15.error(`Failed to save: ${typedError.message}`); - } else { - core15.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core15.debug(`Failed to delete archive: ${error4}`); - } + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; } - return cacheId; - }); - } - } -}); - -// node_modules/@actions/tool-cache/lib/manifest.js -var require_manifest = __commonJS({ - "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; } } - function rejected(value) { + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + releases = JSON.parse(versionsRaw); + } catch (_a) { + core15.debug("Invalid json"); } } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return releases; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver8 = __importStar4(require_semver2()); - var core_1 = require_core(); - var os5 = require("os"); - var cp = require("child_process"); - var fs17 = require("fs"); - function _findMatch(versionSpec, stable, candidates, archFilter) { + } + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os5.arch()) { return __awaiter4(this, void 0, void 0, function* () { - const platFilter = os5.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { - file = candidate.files.find((item) => { - (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module2.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } else { - chk = semver8.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - (0, core_1.debug)(`matched ${candidate.version}`); - match = candidate; - break; - } - } - } - if (match && file) { - result = Object.assign({}, match); - result.files = [file]; + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; + }); + } + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!dest) { + dest = path16.join(_getTempDirectory(), crypto2.randomUUID()); } - return result; + yield io7.mkdirP(dest); + return dest; }); } - exports2._findMatch = _findMatch; - function _getOsVersion() { - const plat = os5.platform(); + function _createToolPath(tool, version, arch2) { + return __awaiter4(this, void 0, void 0, function* () { + const folderPath = path16.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); + core15.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io7.rmRF(folderPath); + yield io7.rmRF(markerPath); + yield io7.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch2) { + const folderPath = path16.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); + const markerPath = `${folderPath}.complete`; + fs17.writeFileSync(markerPath, ""); + core15.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver8.clean(versionSpec) || ""; + core15.debug(`isExplicit: ${c}`); + const valid3 = semver8.valid(c) != null; + core15.debug(`explicit? ${valid3}`); + return valid3; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { let version = ""; - if (plat === "darwin") { - version = cp.execSync("sw_vers -productVersion").toString(); - } else if (plat === "linux") { - const lsbContents = module2.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split("\n"); - for (const line of lines) { - const parts = line.split("="); - if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { - version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); - break; - } - } + core15.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver8.gt(a, b)) { + return 1; + } + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver8.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; } } + if (version) { + core15.debug(`matched: ${version}`); + } else { + core15.debug("match not found"); + } return version; } - exports2._getOsVersion = _getOsVersion; - function _readLinuxVersionFile() { - const lsbReleaseFile = "/etc/lsb-release"; - const osReleaseFile = "/etc/os-release"; - let contents = ""; - if (fs17.existsSync(lsbReleaseFile)) { - contents = fs17.readFileSync(lsbReleaseFile).toString(); - } else if (fs17.existsSync(osReleaseFile)) { - contents = fs17.readFileSync(osReleaseFile).toString(); - } - return contents; + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); } - exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + module2.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return true; + } + return a !== a && b !== b; }; + } +}); + +// node_modules/@actions/http-client/lib/proxy.js +var require_proxy5 = __commonJS({ + "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core15 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); + exports2.getProxyUrl = getProxyUrl; + exports2.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - execute(action, isRetryable) { - return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core15.info(err.message); - } - const seconds = this.getSleepAmount(); - core15.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - return yield action(); - }); + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + get username() { + return this._decodedUsername; } - sleep(seconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve8) => setTimeout(resolve8, seconds * 1e3)); - }); + get password() { + return this._decodedPassword; } }; - exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib6 = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74975,15 +77842,25 @@ var require_tool_cache = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve8) { @@ -75012,523 +77889,616 @@ var require_tool_cache = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core15 = __importStar4(require_core()); - var io7 = __importStar4(require_io()); - var crypto2 = __importStar4(require("crypto")); - var fs17 = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os5 = __importStar4(require("os")); - var path16 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver8 = __importStar4(require_semver2()); - var stream2 = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError2 = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy5()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.HTTPError = HTTPError2; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url2, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path16.join(_getTempDirectory(), crypto2.randomUUID()); - yield io7.mkdirP(path16.dirname(dest)); - core15.debug(`Downloading ${url2}`); - core15.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url2, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError2 && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url2, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs17.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); }); - if (auth) { - core15.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - headers.authorization = auth; - } - const response = yield http.get(url2, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError2(response.message.statusCode); - core15.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; - } - const pipeline = util.promisify(stream2.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs17.createWriteStream(dest)); - core15.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core15.debug("download failed"); - try { - yield io7.rmRF(dest); - } catch (err) { - core15.debug(`Failed to delete '${dest}'. ${err.message}`); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core15.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } else { - const escapedScript = path16.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io7.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core15.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - core15.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core15.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - args.push("-x", "-C", dest, "-f", file); - if (core15.isDebug()) { - args.push("-v"); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - const xarPath = yield io7.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io7.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core15.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io7.which("powershell", true); - core15.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); - } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io7.which("unzip", true); - const args = [file]; - if (!core15.isDebug()) { - args.unshift("-q"); + req.end(); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir(sourceDir, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch2 = arch2 || os5.arch(); - core15.debug(`Caching tool ${tool} ${version} ${arch2}`); - core15.debug(`source dir: ${sourceDir}`); - if (!fs17.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const destPath = yield _createToolPath(tool, version, arch2); - for (const itemName of fs17.readdirSync(sourceDir)) { - const s = path16.join(sourceDir, itemName); - yield io7.cp(s, destPath, { recursive: true }); + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - _completeToolPath(tool, version, arch2); - return destPath; - }); - } - exports2.cacheDir = cacheDir; - function cacheFile(sourceFile, targetFile, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch2 = arch2 || os5.arch(); - core15.debug(`Caching tool ${tool} ${version} ${arch2}`); - core15.debug(`source file: ${sourceFile}`); - if (!fs17.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } } - const destFolder = yield _createToolPath(tool, version, arch2); - const destPath = path16.join(destFolder, targetFile); - core15.debug(`destination file ${destPath}`); - yield io7.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch2); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch2) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); + return info6; } - arch2 = arch2 || os5.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions2(toolName, arch2); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver8.clean(versionSpec) || ""; - const cachePath = path16.join(_getCacheDirectory(), toolName, versionSpec, arch2); - core15.debug(`checking cache: ${cachePath}`); - if (fs17.existsSync(cachePath) && fs17.existsSync(`${cachePath}.complete`)) { - core15.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); - toolPath = cachePath; - } else { - core15.debug("not found"); + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return toolPath; - } - exports2.find = find2; - function findAllVersions2(toolName, arch2) { - const versions = []; - arch2 = arch2 || os5.arch(); - const toolPath = path16.join(_getCacheDirectory(), toolName); - if (fs17.existsSync(toolPath)) { - const children = fs17.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path16.join(toolPath, child, arch2 || ""); - if (fs17.existsSync(fullPath) && fs17.existsSync(`${fullPath}.complete`)) { - versions.push(child); + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; } } } + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; + } + } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return versions; - } - exports2.findAllVersions = findAllVersions2; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core15.debug("set auth"); - headers.authorization = auth; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + if (!useProxy) { + agent = this._agent; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; - } + if (agent) { + return agent; } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core15.debug("Invalid json"); - } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os5.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path16.join(_getTempDirectory(), crypto2.randomUUID()); + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - yield io7.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path16.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); - core15.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io7.rmRF(folderPath); - yield io7.rmRF(markerPath); - yield io7.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch2) { - const folderPath = path16.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); - const markerPath = `${folderPath}.complete`; - fs17.writeFileSync(markerPath, ""); - core15.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver8.clean(versionSpec) || ""; - core15.debug(`isExplicit: ${c}`); - const valid3 = semver8.valid(c) != null; - core15.debug(`explicit? ${valid3}`); - return valid3; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core15.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver8.gt(a, b)) { - return 1; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver8.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } + return agent; } - if (version) { - core15.debug(`matched: ${version}`); - } else { - core15.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; + if (proxyAgent) { + return proxyAgent; } - return true; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); + } + })); + }); } - return a !== a && b !== b; }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -83914,7 +86884,7 @@ function shouldStoreCache(kind) { } // src/config/db-config.ts -var jsonschema = __toESM(require_lib2()); +var jsonschema = __toESM(require_lib3()); var semver2 = __toESM(require_semver2()); var PACK_IDENTIFIER_PATTERN = (function() { const alphaNumeric = "[a-z0-9]"; @@ -85400,7 +88370,7 @@ var os2 = __toESM(require("os")); var path7 = __toESM(require("path")); var import_perf_hooks = require("perf_hooks"); var core9 = __toESM(require_core()); -var import_http_client = __toESM(require_lib()); +var import_http_client = __toESM(require_lib6()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); var semver6 = __toESM(require_semver2()); @@ -87575,7 +90545,7 @@ var path14 = __toESM(require("path")); var url = __toESM(require("url")); var import_zlib = __toESM(require("zlib")); var core13 = __toESM(require_core()); -var jsonschema2 = __toESM(require_lib2()); +var jsonschema2 = __toESM(require_lib3()); // src/fingerprints.ts var fs14 = __toESM(require("fs")); diff --git a/lib/autobuild-action.js b/lib/autobuild-action.js index 8dbdd76bcd..21369af272 100644 --- a/lib/autobuild-action.js +++ b/lib/autobuild-action.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -19875,9 +19875,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -19934,737 +20016,826 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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 (isPlainObject(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+)|(?:(? a.concat(b), []); - } - function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - } - function encodeReserved(str2) { - return str2.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(str2) { - return encodeURIComponent(str2).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; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - function isDefined2(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context2, operator, key, modifier) { - var value = context2[key], result = []; - if (isDefined2(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)); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - result.push(encodeValue(operator, value[k], k)); + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; } - }); + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } } - }); + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - } else { - if (operator === ";") { - if (isDefined2(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; - } - function expand(template, context2) { - 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(context2, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); } - } else { - return encodeReserved(literal); + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } - } - function parse(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 = omit(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 = omit(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(","); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + req.end(); } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); - } - function endpointWithDefaults(defaults, route, options) { - return parse(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 - }); - } - var endpoint = withDefaults(null, DEFAULTS); - } -}); - -// node_modules/deprecation/dist-node/index.js -var require_dist_node3 = __commonJS({ - "node_modules/deprecation/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var Deprecation = class extends Error { - constructor(message) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - this.name = "Deprecation"; + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; } - }; - exports2.Deprecation = Deprecation; - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - return ret; + return additionalHeaders[header] || clientHeader || _default2; } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; + var httpClient = __importStar4(require_lib2()); + var undici_1 = require_undici(); + function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error("Parameter token or opts.auth is required"); + } else if (token && options.auth) { + throw new Error("Parameters token and opts.auth may not both be specified"); + } + return typeof options.auth === "string" ? options.auth : `token ${token}`; + } + exports2.getAuthString = getAuthString; + function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + exports2.getProxyAgent = getProxyAgent; + function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); + } + exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; + function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; + return proxyFetch; } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; } + exports2.getApiBaseUrl = getApiBaseUrl; } }); -// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node4 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { "use strict"; - var __create2 = Object.create; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - RequestError: () => RequestError - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_deprecation = require_dist_node3(); - var import_once = __toESM2(require_once()); - var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - request: () => request - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node2(); - var import_universal_user_agent = require_dist_node(); - var VERSION = "8.4.1"; - function isPlainObject(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); - } - var import_request_error = require_dist_node4(); - function getBufferResponse(response) { - return response.arrayBuffer(); - } - function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - 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" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } - }).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error4; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error4) => { - if (error4 instanceof import_request_error.RequestError) - throw error4; - else if (error4.name === "AbortError") - throw error4; - let message = error4.message; - if (error4.name === "TypeError" && "cause" in error4) { - if (error4.cause instanceof Error) { - message = error4.cause.message; - } else if (typeof error4.cause === "string") { - message = error4.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); - } - 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 getBufferResponse(response); - } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; - } - function withDefaults(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: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - } - var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } - }); - } -}); - -// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node6 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint + endpoint: () => endpoint }); module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); @@ -21218,9 +21179,101 @@ var require_dist_node6 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node7 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/deprecation/dist-node/index.js +var require_dist_node3 = __commonJS({ + "node_modules/deprecation/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var Deprecation = class extends Error { + constructor(message) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "Deprecation"; + } + }; + exports2.Deprecation = Deprecation; + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node4 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; var __create2 = Object.create; var __defProp2 = Object.defineProperty; @@ -21310,9 +21363,9 @@ var require_dist_node7 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js -var require_dist_node8 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js +var require_dist_node5 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21336,7 +21389,7 @@ var require_dist_node8 = __commonJS({ request: () => request }); module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node6(); + var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; function isPlainObject(value) { @@ -21350,7 +21403,7 @@ var require_dist_node8 = __commonJS({ 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); } - var import_request_error = require_dist_node7(); + var import_request_error = require_dist_node4(); function getBufferResponse(response) { return response.arrayBuffer(); } @@ -21520,9 +21573,9 @@ var require_dist_node8 = __commonJS({ } }); -// node_modules/@octokit/graphql/dist-node/index.js -var require_dist_node9 = __commonJS({ - "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node6 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21541,129 +21594,340 @@ var require_dist_node9 = __commonJS({ return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export2(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint }); - module2.exports = __toCommonJS2(index_exports); - var import_request3 = require_dist_node8(); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); - var VERSION = "7.1.1"; - var import_request2 = require_dist_node8(); - var import_request = require_dist_node8(); - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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; + }, {}); } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + function isPlainObject(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 (isPlainObject(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]; } } - }; - 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`) - ); + 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); } - 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` - ) - ); + 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+)|(?:(? { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } + function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; } - if (!result.variables) { - result.variables = {}; + } + return result; + } + function encodeReserved(str2) { + return str2.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, "]"); } - 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 part; + }).join(""); + } + function encodeUnreserved(str2) { + return encodeURIComponent(str2).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; } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; + } + function isDefined2(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context2, operator, key, modifier) { + var value = context2[key], result = []; + if (isDefined2(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)); } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(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(",")); + } + } } - return response.data.data; - }); + } else { + if (operator === ";") { + if (isDefined2(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; } - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); + function parseUrl(template) { + return { + expand: expand.bind(null, template) }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); } - var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" - }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" + function expand(template, context2) { + 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(context2, 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 parse(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 = omit(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 = omit(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(/(? { + 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 parse(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 }); } + var endpoint = withDefaults(null, DEFAULTS); } }); -// node_modules/@octokit/auth-token/dist-node/index.js -var require_dist_node10 = __commonJS({ - "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node7 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; + var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) @@ -21677,53 +21941,490 @@ var require_dist_node10 = __commonJS({ } return to; }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - createTokenAuth: () => createTokenAuth + RequestError: () => RequestError }); module2.exports = __toCommonJS2(dist_src_exports); - 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, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); - } - 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" - ); + var import_deprecation = require_dist_node3(); + var import_once = __toESM2(require_once()); + var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + request: () => request + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_endpoint = require_dist_node6(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "8.4.1"; + function isPlainObject(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); + } + var import_request_error = require_dist_node7(); + function getBufferResponse(response) { + return response.arrayBuffer(); + } + function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + 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" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error4; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error4) => { + if (error4 instanceof import_request_error.RequestError) + throw error4; + else if (error4.name === "AbortError") + throw error4; + let message = error4.message; + if (error4.name === "TypeError" && "cause" in error4) { + if (error4.cause instanceof Error) { + message = error4.cause.message; + } else if (typeof error4.cause === "string") { + message = error4.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); + } + 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 getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; + } + function withDefaults(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: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + } + var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }); + } +}); + +// node_modules/@octokit/graphql/dist-node/index.js +var require_dist_node9 = __commonJS({ + "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export2(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest + }); + module2.exports = __toCommonJS2(index_exports); + var import_request3 = require_dist_node8(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "7.1.1"; + var import_request2 = require_dist_node8(); + var import_request = require_dist_node8(); + 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.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + }; + 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 withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); + } + } +}); + +// node_modules/@octokit/auth-token/dist-node/index.js +var require_dist_node10 = __commonJS({ + "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + createTokenAuth: () => createTokenAuth + }); + module2.exports = __toCommonJS2(dist_src_exports); + 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, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + 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) + }); }; } }); @@ -26499,7 +27200,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -29372,7 +30073,7 @@ var require_validator = __commonJS({ }); // node_modules/jsonschema/lib/index.js -var require_lib2 = __commonJS({ +var require_lib3 = __commonJS({ "node_modules/jsonschema/lib/index.js"(exports2, module2) { "use strict"; var Validator2 = module2.exports.Validator = require_validator(); @@ -32511,958 +33212,1763 @@ var require_cacheUtils = __commonJS({ } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); - var HttpPipeline = class _HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = void 0; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - this._policies.push({ - policy, - options - }); - this._orderedPolicies = void 0; + } else { + return void 0; } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { - removedPolicies.push(policyDescriptor.policy); - return false; - } else { - return true; - } - }); - this._orderedPolicies = void 0; - return removedPolicies; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - clone() { - return new _HttpPipeline(this._policies); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - static create() { - return new _HttpPipeline(); + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - orderPolicies() { - const result = []; - const policyMap = /* @__PURE__ */ new Map(); - function createPhase(name) { - return { - name, - policies: /* @__PURE__ */ new Set(), - hasRun: false, - hasAfterPolicies: false - }; - } - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } else if (phase === "Serialize") { - return serializePhase; - } else if (phase === "Deserialize") { - return deserializePhase; - } else if (phase === "Sign") { - return signPhase; - } else { - return noPhase; - } - } - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: /* @__PURE__ */ new Set(), - dependants: /* @__PURE__ */ new Set() - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); - } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); - } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); - } - } - } - } - function walkPhase(phase) { - phase.hasRun = true; - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - continue; - } - if (node.dependsOn.size === 0) { - result.push(node.policy); - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); - } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - walkPhase(noPhase); - } - return; - } - if (phase.hasAfterPolicies) { - walkPhase(noPhase); - } - } - } - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - walkPhases(); - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return result; } - }; - function createEmptyPipeline() { - return HttpPipeline.create(); + return false; } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@azure/logger/dist/index.js -var require_dist = __commonJS({ - "node_modules/@azure/logger/dist/index.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var os2 = require("os"); - var util = require("util"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); - function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os2.EOL}`); - } - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; - var enabledString; - var enabledNamespaces = []; - var skippedNamespaces = []; - var debuggers = []; - if (debugEnvVariable) { - enable(debugEnvVariable); - } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log - }); - function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); - } else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); - } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - } - function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - } - return false; - } - function disable() { - const result = enabledString || ""; - enable(""); - return result; - } - function createDebugger(namespace) { - const newDebugger = Object.assign(debug6, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend: extend3 - }); - function debug6(...args) { - if (!newDebugger.enabled) { - return; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } - newDebugger.log(...args); - } - debuggers.push(newDebugger); - return newDebugger; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return false; - } - function extend3(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; - } - var debug5 = debugObj; - var registeredLoggers = /* @__PURE__ */ new Set(); - var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; - var azureLogLevel; - var AzureLogger = debug5("azure"); - AzureLogger.log = (...args) => { - debug5.log(...args); }; - var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; - if (logLevelFromEnv) { - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); - } else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - } - function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); + }); } - azureLogLevel = level; - const enabledNamespaces2 = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces2.push(logger.namespace); - } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); + }); } - debug5.enable(enabledNamespaces2.join(",")); - } - function getLogLevel() { - return azureLogLevel; - } - var levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 }; - function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") - }; - } - function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); - }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces2 = debug5.disable(); - debug5.enable(enabledNamespaces2 + "," + logger.namespace); + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - registeredLoggers.add(logger); - return logger; - } - function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); - } - function isAzureLogLevel(logLevel) { - return AZURE_LOG_LEVELS.includes(logLevel); - } - exports2.AzureLogger = AzureLogger; - exports2.createClientLogger = createClientLogger; - exports2.getLogLevel = getLogLevel; - exports2.setLogLevel = setLogLevel; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js -var require_log = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_dist(); - exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - } -}); - -// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js -var require_createAbortablePromise = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createAbortablePromise = createAbortablePromise; - var abort_controller_1 = require_commonjs(); - function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve5, reject) => { - function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - function removeListeners() { - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - function onAbort() { - cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); - removeListeners(); - rejectOnAbort(); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { - return rejectOnAbort(); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - try { - buildPromise((x) => { - removeListeners(); - resolve5(x); - }, (x) => { - removeListeners(); - reject(x); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); }); - } catch (err) { - reject(err); + data.pipe(req); + } else { + req.end(); } - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); - }); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/random.js -var require_random = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - function getRandomIntegerInclusive(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - const offset = Math.floor(Math.random() * (max - min + 1)); - return offset + min; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/delay.js -var require_delay = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay; - exports2.calculateRetryDelay = calculateRetryDelay; - var createAbortablePromise_js_1 = require_createAbortablePromise(); - var random_js_1 = require_random(); - var StandardAbortMessage = "The delay was aborted."; - function delay(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve5) => { - token = setTimeout(resolve5, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage - }); - } - function calculateRetryDelay(retryAttempt, config) { - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); - return { retryAfterInMs }; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js -var require_aborterUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cancelablePromiseRace = cancelablePromiseRace; - async function cancelablePromiseRace(abortablePromiseBuilders, options) { - var _a, _b; - const aborter = new AbortController(); - function abortHandler() { - aborter.abort(); } - (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); - try { - return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); - } finally { - aborter.abort(); - (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/object.js -var require_object = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isObject = isObject2; - function isObject2(input) { - return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/error.js -var require_error = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isError = isError; - exports2.getErrorMessage = getErrorMessage2; - var object_js_1 = require_object(); - function isError(e) { - if ((0, object_js_1.isObject)(e)) { - const hasName = typeof e.name === "string"; - const hasMessage = typeof e.message === "string"; - return hasName && hasMessage; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return false; - } - function getErrorMessage2(e) { - if (isError(e)) { - return e.message; - } else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } else { - stringified = String(e); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - } catch (err) { - stringified = "[unable to stringify input]"; } - return `Unknown error ${stringified}`; + return info6; } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.computeSha256Hash = computeSha256Hash; - var crypto_1 = require("crypto"); - async function computeSha256Hmac(key, stringToSign, encoding) { - const decodedKey = Buffer.from(key, "base64"); - return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); - } - async function computeSha256Hash(content, encoding) { - return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/typeGuards.js -var require_typeGuards = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isDefined = isDefined2; - exports2.isObjectWithProperties = isObjectWithProperties; - exports2.objectHasProperty = objectHasProperty; - function isDefined2(thing) { - return typeof thing !== "undefined" && thing !== null; - } - function isObjectWithProperties(thing, properties) { - if (!isDefined2(thing) || typeof thing !== "object") { - return false; - } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - return true; - } - function objectHasProperty(thing, property) { - return isDefined2(thing) && typeof thing === "object" && property in thing; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js -var require_uuidUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomUUID = randomUUID; - var crypto_1 = require("crypto"); - var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; - function randomUUID() { - return uuidFunction(); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js -var require_checkEnvironment = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { - "use strict"; - var _a; - var _b; - var _c; - var _d; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; - exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; - exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); - exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; - exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; - exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); - exports2.isNode = exports2.isNodeLike; - exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; - exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; - } -}); - -// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js -var require_bytesEncoding = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - function uint8ArrayToString(bytes, format) { - return Buffer.from(bytes).toString(format); - } - function stringToUint8Array(value, format) { - return Buffer.from(value, format); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/index.js -var require_commonjs2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; - var delay_js_1 = require_delay(); - Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { - return delay_js_1.delay; - } }); - Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { - return delay_js_1.calculateRetryDelay; - } }); - var aborterUtils_js_1 = require_aborterUtils(); - Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { - return aborterUtils_js_1.cancelablePromiseRace; - } }); - var createAbortablePromise_js_1 = require_createAbortablePromise(); - Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { - return createAbortablePromise_js_1.createAbortablePromise; - } }); - var random_js_1 = require_random(); - Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { - return random_js_1.getRandomIntegerInclusive; - } }); - var object_js_1 = require_object(); - Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { - return object_js_1.isObject; - } }); - var error_js_1 = require_error(); - Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { - return error_js_1.isError; - } }); - Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { - return error_js_1.getErrorMessage; - } }); - var sha256_js_1 = require_sha256(); - Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hash; - } }); - Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hmac; - } }); - var typeGuards_js_1 = require_typeGuards(); - Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { - return typeGuards_js_1.isDefined; - } }); - Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { - return typeGuards_js_1.isObjectWithProperties; - } }); - Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { - return typeGuards_js_1.objectHasProperty; - } }); - var uuidUtils_js_1 = require_uuidUtils(); - Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { - return uuidUtils_js_1.randomUUID; - } }); - var checkEnvironment_js_1 = require_checkEnvironment(); - Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBrowser; - } }); - Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBun; - } }); - Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNode; - } }); - Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeLike; - } }); - Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeRuntime; - } }); - Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { - return checkEnvironment_js_1.isDeno; - } }); - Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { - return checkEnvironment_js_1.isReactNative; - } }); - Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { - return checkEnvironment_js_1.isWebWorker; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js -var require_sanitizer = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = void 0; - var core_util_1 = require_commonjs2(); - var RedactedString = "REDACTED"; - var defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate" - ]; - var defaultAllowedQueryParameters = ["api-version"]; - var Sanitizer = class { - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { - allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); - allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); - } - sanitize(obj) { - const seen = /* @__PURE__ */ new Set(); - return JSON.stringify(obj, (key, value) => { - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); - } - if (key === "headers") { - return this.sanitizeHeaders(value); - } else if (key === "url") { - return this.sanitizeUrl(value); - } else if (key === "query") { - return this.sanitizeQuery(value); - } else if (key === "body") { - return void 0; - } else if (key === "response") { - return void 0; - } else if (key === "operationSpec") { - return void 0; - } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - } - return value; - }, 2); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - sanitizeUrl(value) { - if (typeof value !== "string" || value === null || value === "") { - return value; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const url = new URL(value); - if (!url.search) { - return value; + if (!useProxy) { + agent = this._agent; } - for (const [key] of url.searchParams) { - if (!this.allowedQueryParameters.has(key.toLowerCase())) { - url.searchParams.set(key, RedactedString); - } + if (agent) { + return agent; } - return url.toString(); - } - sanitizeHeaders(obj) { - const sanitized = {}; - for (const key of Object.keys(obj)) { - if (this.allowedHeaderNames.has(key.toLowerCase())) { - sanitized[key] = obj[key]; + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - sanitized[key] = RedactedString; + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - return sanitized; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - sanitizeQuery(value) { - if (typeof value !== "object" || value === null) { - return value; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (this.allowedQueryParameters.has(k.toLowerCase())) { - sanitized[k] = value[k]; - } else { - sanitized[k] = RedactedString; - } + if (proxyAgent) { + return proxyAgent; } - return sanitized; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); + } + })); + }); } }; - exports2.Sanitizer = Sanitizer; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js -var require_logPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log(); - var sanitizer_js_1 = require_sanitizer(); - exports2.logPolicyName = "logPolicy"; - function logPolicy(options = {}) { - var _a; - const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - return { - name: exports2.logPolicyName, - async sendRequest(request, next) { - if (!logger.enabled) { - return next(request); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - logger(`Request: ${sanitizer.sanitize(request)}`); - const response = await next(request); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); - return response; } - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js -var require_redirectPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - exports2.redirectPolicyName = "redirectPolicy"; - var allowedRedirect = ["GET", "HEAD"]; - function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: exports2.redirectPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return handleRedirect(next, response, maxRetries); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - }; - } - async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { - const url = new URL(locationHeader, request.url); - request.url = url.toString(); - if (status === 303) { - request.method = "GET"; - request.headers.delete("Content-Length"); - delete request.body; + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } - request.headers.delete("Authorization"); - const res = await next(request); - return handleRedirect(next, res, maxRetries, currentRetries + 1); - } - return response; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; + } + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; + } + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } + }; + function createEmptyPipeline() { + return HttpPipeline.create(); + } + } +}); + +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os2 = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; + } + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os2.EOL}`); + } + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); + } + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log + }); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } + } + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; + } + function disable() { + const result = enabledString || ""; + enable(""); + return result; + } + function createDebugger(namespace) { + const newDebugger = Object.assign(debug6, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug6(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; + } + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; + } + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; + } + var debug5 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug5("azure"); + AzureLogger.log = (...args) => { + debug5.log(...args); + }; + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + } + } + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); + } + } + debug5.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 + }; + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; + } + function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; + } + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces2 = debug5.disable(); + debug5.enable(enabledNamespaces2 + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; + } + function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + } + function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); + } + exports2.AzureLogger = AzureLogger; + exports2.createClientLogger = createClientLogger; + exports2.getLogLevel = getLogLevel; + exports2.setLogLevel = setLogLevel; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js +var require_log = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError; + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve5, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve5(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/random.js +var require_random = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; + function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay; + exports2.calculateRetryDelay = calculateRetryDelay; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var random_js_1 = require_random(); + var StandardAbortMessage = "The delay was aborted."; + function delay(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve5) => { + token = setTimeout(resolve5, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage + }); + } + function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); + } + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/object.js +var require_object = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isObject = isObject2; + function isObject2(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isError = isError; + exports2.getErrorMessage = getErrorMessage2; + var object_js_1 = require_object(); + function isError(e) { + if ((0, object_js_1.isObject)(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; + } + function getErrorMessage2(e) { + if (isError(e)) { + return e.message; + } else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } else { + stringified = String(e); + } + } catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.computeSha256Hmac = computeSha256Hmac; + exports2.computeSha256Hash = computeSha256Hash; + var crypto_1 = require("crypto"); + async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); + } + async function computeSha256Hash(content, encoding) { + return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isDefined = isDefined2; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined2(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined2(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined2(thing) && typeof thing === "object" && property in thing; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js +var require_uuidUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { + "use strict"; + var _a; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.randomUUID = randomUUID; + var crypto_1 = require("crypto"); + var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; + function randomUUID() { + return uuidFunction(); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js +var require_checkEnvironment = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { + "use strict"; + var _a; + var _b; + var _c; + var _d; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; + exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; + exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); + exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; + exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; + exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); + exports2.isNode = exports2.isNodeLike; + exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; + exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js +var require_bytesEncoding = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.uint8ArrayToString = uint8ArrayToString; + exports2.stringToUint8Array = stringToUint8Array; + function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); + } + function stringToUint8Array(value, format) { + return Buffer.from(value, format); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; + var delay_js_1 = require_delay(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { + return delay_js_1.calculateRetryDelay; + } }); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var random_js_1 = require_random(); + Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { + return random_js_1.getRandomIntegerInclusive; + } }); + var object_js_1 = require_object(); + Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { + return object_js_1.isObject; + } }); + var error_js_1 = require_error(); + Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { + return error_js_1.isError; + } }); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var sha256_js_1 = require_sha256(); + Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hash; + } }); + Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hmac; + } }); + var typeGuards_js_1 = require_typeGuards(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + var uuidUtils_js_1 = require_uuidUtils(); + Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { + return uuidUtils_js_1.randomUUID; + } }); + var checkEnvironment_js_1 = require_checkEnvironment(); + Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBrowser; + } }); + Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBun; + } }); + Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNode; + } }); + Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeLike; + } }); + Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeRuntime; + } }); + Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { + return checkEnvironment_js_1.isDeno; + } }); + Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { + return checkEnvironment_js_1.isReactNative; + } }); + Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { + return checkEnvironment_js_1.isWebWorker; + } }); + var bytesEncoding_js_1 = require_bytesEncoding(); + Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { + return bytesEncoding_js_1.uint8ArrayToString; + } }); + Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { + return bytesEncoding_js_1.stringToUint8Array; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js +var require_sanitizer = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Sanitizer = void 0; + var core_util_1 = require_commonjs2(); + var RedactedString = "REDACTED"; + var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" + ]; + var defaultAllowedQueryParameters = ["api-version"]; + var Sanitizer = class { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); + } + if (key === "headers") { + return this.sanitizeHeaders(value); + } else if (key === "url") { + return this.sanitizeUrl(value); + } else if (key === "query") { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }, 2); + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; + } + const url = new URL(value); + if (!url.search) { + return value; + } + for (const [key] of url.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url.searchParams.set(key, RedactedString); + } + } + return url.toString(); + } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } + }; + exports2.Sanitizer = Sanitizer; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js +var require_logPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logPolicyName = void 0; + exports2.logPolicy = logPolicy; + var log_js_1 = require_log(); + var sanitizer_js_1 = require_sanitizer(); + exports2.logPolicyName = "logPolicy"; + function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + return { + name: exports2.logPolicyName, + async sendRequest(request, next) { + if (!logger.enabled) { + return next(request); + } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.redirectPolicyName = void 0; + exports2.redirectPolicy = redirectPolicy; + exports2.redirectPolicyName = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; + return { + name: exports2.redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + } + }; + } + async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url = new URL(locationHeader, request.url); + request.url = url.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; + } + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); + } + return response; } } }); @@ -67946,7 +69452,7 @@ var require_requestUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var constants_1 = require_constants7(); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -68114,7 +69620,7 @@ var require_downloadUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var storage_blob_1 = require_dist7(); var buffer = __importStar4(require("buffer")); var fs7 = __importStar4(require("fs")); @@ -68691,8 +70197,8 @@ var require_cacheHttpClient = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib4(); + var auth_1 = require_auth2(); var fs7 = __importStar4(require("fs")); var url_1 = require("url"); var utils = __importStar4(require_cacheUtils()); @@ -69668,2706 +71174,4406 @@ var require_binary_reader = __commonJS({ return this.buf.subarray(start, start + len); } /** - * Read a `string` field, length-delimited data converted to UTF-8 text. + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); + } + }; + exports2.BinaryReader = BinaryReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js +var require_assert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; + function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } + } + exports2.assert = assert; + function assertNever2(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + } + exports2.assertNever = assertNever2; + var FLOAT32_MAX = 34028234663852886e22; + var FLOAT32_MIN = -34028234663852886e22; + var UINT32_MAX = 4294967295; + var INT32_MAX = 2147483647; + var INT32_MIN = -2147483648; + function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid int 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error("invalid int 32: " + arg); + } + exports2.assertInt32 = assertInt32; + function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid uint 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error("invalid uint 32: " + arg); + } + exports2.assertUInt32 = assertUInt32; + function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error("invalid float 32: " + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error("invalid float 32: " + arg); + } + exports2.assertFloat32 = assertFloat32; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js +var require_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var assert_1 = require_assert(); + var defaultsWrite = { + writeUnknownFields: true, + writerFactory: () => new BinaryWriter() + }; + function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.binaryWriteOptions = binaryWriteOptions; + var BinaryWriter = class { + constructor(textEncoder) { + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; + } + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; + } + this.chunks = []; + return bytes; + } + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; + } + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + let chunk = this.finish(); + let prev = this.stack.pop(); + if (!prev) + throw new Error("invalid state, fork stack empty"); + this.chunks = prev.chunks; + this.buf = prev.buf; + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type2) { + return this.uint32((fieldNo << 3 | type2) >>> 0); + } + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; + } + this.chunks.push(chunk); + return this; + } + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); + while (value > 127) { + this.buf.push(value & 127 | 128); + value = value >>> 7; + } + this.buf.push(value); + return this; + } + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; + } + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); + return this.raw(value); + } + /** + * Write a `string` value, length-delimited data converted to UTF-8 text. + */ + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Write a `float` value, 32-bit floating point number. + */ + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `double` value, a 64-bit floating point number. + */ + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); + } + /** + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + */ + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + */ + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + */ + sint32(value) { + assert_1.assertInt32(value); + value = (value << 1 ^ value >> 31) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + */ + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + */ + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `int64` value, a signed 64-bit varint. + */ + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + /** + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. */ - string() { - return this.textDecoder.decode(this.bytes()); + sint64(value) { + let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; + } + /** + * Write a `uint64` value, an unsigned 64-bit varint. + */ + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; } }; - exports2.BinaryReader = BinaryReader; + exports2.BinaryWriter = BinaryWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js -var require_assert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js +var require_json_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; - function assert(condition, msg) { - if (!condition) { - throw new Error(msg); + exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; + var defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0 + }; + var defaultsRead = { + ignoreUnknownFields: false + }; + function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; + } + exports2.jsonReadOptions = jsonReadOptions; + function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.jsonWriteOptions = jsonWriteOptions; + function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; + return c; + } + exports2.mergeJsonOptions = mergeJsonOptions; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js +var require_message_type_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MESSAGE_TYPE = void 0; + exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js +var require_lower_camel_case = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.lowerCamelCase = void 0; + function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == "_") { + capNext = true; + } else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } else if (i == 0) { + sb.push(next.toLowerCase()); + } else { + sb.push(next); + } } + return sb.join(""); } - exports2.assert = assert; - function assertNever2(value, msg) { - throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + exports2.lowerCamelCase = lowerCamelCase; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js +var require_reflection_info = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; + var lower_camel_case_1 = require_lower_camel_case(); + var ScalarType; + (function(ScalarType2) { + ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; + ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; + ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; + ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; + ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; + ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; + ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; + ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; + ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; + ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; + ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; + ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; + ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; + ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; + ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; + })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); + var LongType; + (function(LongType2) { + LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; + LongType2[LongType2["STRING"] = 1] = "STRING"; + LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; + })(LongType = exports2.LongType || (exports2.LongType = {})); + var RepeatType; + (function(RepeatType2) { + RepeatType2[RepeatType2["NO"] = 0] = "NO"; + RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; + RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; + })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); + function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; + return field; } - exports2.assertNever = assertNever2; - var FLOAT32_MAX = 34028234663852886e22; - var FLOAT32_MIN = -34028234663852886e22; - var UINT32_MAX = 4294967295; - var INT32_MAX = 2147483647; - var INT32_MIN = -2147483648; - function assertInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid int 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) - throw new Error("invalid int 32: " + arg); + exports2.normalizeFieldInfo = normalizeFieldInfo; + function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; } - exports2.assertInt32 = assertInt32; - function assertUInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid uint 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) - throw new Error("invalid uint 32: " + arg); + exports2.readFieldOptions = readFieldOptions; + function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.assertUInt32 = assertUInt32; - function assertFloat32(arg) { - if (typeof arg !== "number") - throw new Error("invalid float 32: " + typeof arg); - if (!Number.isFinite(arg)) - return; - if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) - throw new Error("invalid float 32: " + arg); + exports2.readFieldOption = readFieldOption; + function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.assertFloat32 = assertFloat32; + exports2.readMessageOption = readMessageOption; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js -var require_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js +var require_oneof = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; - var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); - var assert_1 = require_assert(); - var defaultsWrite = { - writeUnknownFields: true, - writerFactory: () => new BinaryWriter() - }; - function binaryWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; + function isOneofGroup(any) { + if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === void 0) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; + } } - exports2.binaryWriteOptions = binaryWriteOptions; - var BinaryWriter = class { - constructor(textEncoder) { - this.stack = []; - this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); - this.chunks = []; - this.buf = []; + exports2.isOneofGroup = isOneofGroup; + function getOneofValue(oneof, kind) { + return oneof[kind]; + } + exports2.getOneofValue = getOneofValue; + function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; } - /** - * Return all bytes written and reset this writer. - */ - finish() { - this.chunks.push(new Uint8Array(this.buf)); - let len = 0; - for (let i = 0; i < this.chunks.length; i++) - len += this.chunks[i].length; - let bytes = new Uint8Array(len); - let offset = 0; - for (let i = 0; i < this.chunks.length; i++) { - bytes.set(this.chunks[i], offset); - offset += this.chunks[i].length; - } - this.chunks = []; - return bytes; + oneof.oneofKind = kind; + if (value !== void 0) { + oneof[kind] = value; } - /** - * Start a new fork for length-delimited data like a message - * or a packed repeated field. - * - * Must be joined later with `join()`. - */ - fork() { - this.stack.push({ chunks: this.chunks, buf: this.buf }); - this.chunks = []; - this.buf = []; - return this; + } + exports2.setOneofValue = setOneofValue; + function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; } - /** - * Join the last fork. Write its length and bytes, then - * return to the previous state. - */ - join() { - let chunk = this.finish(); - let prev = this.stack.pop(); - if (!prev) - throw new Error("invalid state, fork stack empty"); - this.chunks = prev.chunks; - this.buf = prev.buf; - this.uint32(chunk.byteLength); - return this.raw(chunk); + oneof.oneofKind = kind; + if (value !== void 0 && kind !== void 0) { + oneof[kind] = value; + } + } + exports2.setUnknownOneofValue = setUnknownOneofValue; + function clearOneofValue(oneof) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = void 0; + } + exports2.clearOneofValue = clearOneofValue; + function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === void 0) { + return void 0; + } + return oneof[oneof.oneofKind]; + } + exports2.getSelectedOneofValue = getSelectedOneofValue; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js +var require_reflection_type_check = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionTypeCheck = void 0; + var reflection_info_1 = require_reflection_info(); + var oneof_1 = require_oneof(); + var ReflectionTypeCheck = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + } + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); + } + } else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; + } + } + } + this.data = { req, known, oneofs: Object.values(oneofs) }; } /** - * Writes a tag (field number and wire type). + * Is the argument a valid message as specified by the + * reflection information? * - * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. * - * Generated code should compute the tag ahead of time and call `uint32()`. + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. */ - tag(fieldNo, type2) { - return this.uint32((fieldNo << 3 | type2) >>> 0); + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === void 0 || typeof message != "object") + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + if (keys.some((k) => !data.known.includes(k))) + return false; + } + if (depth < 1) { + return true; + } + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === void 0) + continue; + const field = this.fields.find((f) => f.localName === group.oneofKind); + if (!field) + return false; + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + for (const field of this.fields) { + if (field.oneof !== void 0) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; + } + return true; } - /** - * Write a chunk of raw bytes. - */ - raw(chunk) { - if (this.buf.length) { - this.chunks.push(new Uint8Array(this.buf)); - this.buf = []; + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === void 0) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != "object" || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } + break; } - this.chunks.push(chunk); - return this; + return true; } - /** - * Write a `uint32` value, an unsigned 32 bit varint. - */ - uint32(value) { - assert_1.assertUInt32(value); - while (value > 127) { - this.buf.push(value & 127 | 128); - value = value >>> 7; + message(arg, type2, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type2.isAssignable(arg, depth); + } + return type2.is(arg, depth); + } + messages(arg, type2, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.isAssignable(arg[i], depth - 1)) + return false; + } else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.is(arg[i], depth - 1)) + return false; + } + return true; + } + scalar(arg, type2, longType) { + let argType = typeof arg; + switch (type2) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == "boolean"; + case reflection_info_1.ScalarType.STRING: + return argType == "string"; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == "number" && !isNaN(arg); + default: + return argType == "number" && Number.isInteger(arg); } - this.buf.push(value); - return this; } - /** - * Write a `int32` value, a signed 32 bit varint. - */ - int32(value) { - assert_1.assertInt32(value); - goog_varint_1.varint32write(value, this.buf); - return this; + scalars(arg, type2, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type2, longType)) + return false; + } + return true; } - /** - * Write a `bool` value, a variant. - */ - bool(value) { - this.buf.push(value ? 1 : 0); - return this; + mapKeys(map2, type2, depth) { + let keys = Object.keys(map2); + switch (type2) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); + default: + return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + } } - /** - * Write a `bytes` value, length-delimited arbitrary data. - */ - bytes(value) { - this.uint32(value.byteLength); - return this.raw(value); + }; + exports2.ReflectionTypeCheck = ReflectionTypeCheck; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js +var require_reflection_long_convert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionLongConvert = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionLongConvert(long, type2) { + switch (type2) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + return long.toString(); } - /** - * Write a `string` value, length-delimited data converted to UTF-8 text. - */ - string(value) { - let chunk = this.textEncoder.encode(value); - this.uint32(chunk.byteLength); - return this.raw(chunk); + } + exports2.reflectionLongConvert = reflectionLongConvert; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js +var require_reflection_json_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonReader = void 0; + var json_typings_1 = require_json_typings(); + var base64_1 = require_base642(); + var reflection_info_1 = require_reflection_info(); + var pb_long_1 = require_pb_long(); + var assert_1 = require_assert(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var ReflectionJsonReader = class { + constructor(info6) { + this.info = info6; } - /** - * Write a `float` value, 32-bit floating point number. - */ - float(value) { - assert_1.assertFloat32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setFloat32(0, value, true); - return this.raw(chunk); + prepare() { + var _a; + if (this.fMap === void 0) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } + } } - /** - * Write a `double` value, a 64-bit floating point number. - */ - double(value) { - let chunk = new Uint8Array(8); - new DataView(chunk.buffer).setFloat64(0, value, true); - return this.raw(chunk); + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + } } /** - * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. */ - fixed32(value) { - assert_1.assertUInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setUint32(0, value, true); - return this.raw(chunk); + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + let target; + if (field.oneof) { + if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { + continue; + } + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } else { + target = message; + } + if (field.kind == "map") { + if (jsonValue === null) { + continue; + } + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + const fieldObj = target[localName]; + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + let val2; + switch (field.V.kind) { + case "message": + val2 = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val2; + } + } else if (field.repeat) { + if (jsonValue === null) + continue; + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + const fieldArr = target[localName]; + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val2; + switch (field.kind) { + case "message": + val2 = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name, jsonValue); + fieldArr.push(val2); + } + } else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { + this.assert(field.oneof === void 0, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + if (jsonValue === null) + continue; + let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + target[localName] = val2; + break; + case "scalar": + if (jsonValue === null) + continue; + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } + } } /** - * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). */ - sfixed32(value) { - assert_1.assertInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setInt32(0, value, true); - return this.raw(chunk); + enum(type2, json2, fieldName, ignoreUnknownFields) { + if (type2[0] == "google.protobuf.NullValue") + assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); + if (json2 === null) + return 0; + switch (typeof json2) { + case "number": + assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); + return json2; + case "string": + let localEnumName = json2; + if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) + localEnumName = json2.substring(type2[2].length); + let enumNumber = type2[1][localEnumName]; + if (typeof enumNumber === "undefined" && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); + return enumNumber; + } + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); } - /** - * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. - */ - sint32(value) { - assert_1.assertInt32(value); - value = (value << 1 ^ value >> 31) >>> 0; - goog_varint_1.varint32write(value, this.buf); - return this; + scalar(json2, type2, longType, fieldName) { + let e; + try { + switch (type2) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json2 === null) + return 0; + if (json2 === "NaN") + return Number.NaN; + if (json2 === "Infinity") + return Number.POSITIVE_INFINITY; + if (json2 === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json2 === "") { + e = "empty string"; + break; + } + if (typeof json2 == "string" && json2.trim().length !== json2.length) { + e = "extra whitespace"; + break; + } + if (typeof json2 != "string" && typeof json2 != "number") { + break; + } + let float2 = Number(json2); + if (Number.isNaN(float2)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float2)) { + e = "too large or small"; + break; + } + if (type2 == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float2); + return float2; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json2 === null) + return 0; + let int32; + if (typeof json2 == "number") + int32 = json2; + else if (json2 === "") + e = "empty string"; + else if (typeof json2 == "string") { + if (json2.trim().length !== json2.length) + e = "extra whitespace"; + else + int32 = Number(json2); + } + if (int32 === void 0) + break; + if (type2 == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json2 === null) + return false; + if (typeof json2 !== "boolean") + break; + return json2; + // string: + case reflection_info_1.ScalarType.STRING: + if (json2 === null) + return ""; + if (typeof json2 !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json2); + } catch (e2) { + e2 = "invalid UTF8"; + break; + } + return json2; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json2 === null || json2 === "") + return new Uint8Array(0); + if (typeof json2 !== "string") + break; + return base64_1.base64decode(json2); + } + } catch (error4) { + e = error4.message; + } + this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - /** - * Write a `fixed64` value, a signed, fixed-length 64-bit integer. - */ - sfixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbLong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + }; + exports2.ReflectionJsonReader = ReflectionJsonReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js +var require_reflection_json_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonWriter = void 0; + var base64_1 = require_base642(); + var pb_long_1 = require_pb_long(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); + var ReflectionJsonWriter = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; } /** - * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + * Converts the message to a JSON object, based on the field descriptors. */ - fixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbULong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + write(message, options) { + const json2 = {}, source = message; + for (const field of this.fields) { + if (!field.oneof) { + let jsonValue2 = this.field(field, source[field.localName], options); + if (jsonValue2 !== void 0) + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; + continue; + } + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; + const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== void 0); + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + } + return json2; } - /** - * Write a `int64` value, a signed 64-bit varint. - */ - int64(value) { - let long = pb_long_1.PbLong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + field(field, value, options) { + let jsonValue = void 0; + if (field.kind == "map") { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); + const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + } + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); + const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val2 = this.message(messageType, value[i], field.name, options); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + } + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } + } + return jsonValue; } /** - * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + * Returns `null` as the default for google.protobuf.NullValue. */ - sint64(value) { - let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; - goog_varint_1.varint64write(lo, hi, this.buf); - return this; + enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type2[0] == "google.protobuf.NullValue") + return !emitDefaultValues && !optional ? void 0 : null; + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + if (value === 0 && !emitDefaultValues && !optional) + return void 0; + assert_1.assert(typeof value == "number"); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type2[1].hasOwnProperty(value)) + return value; + if (type2[2]) + return type2[2] + type2[1][value]; + return type2[1][value]; } - /** - * Write a `uint64` value, an unsigned 64-bit varint. - */ - uint64(value) { - let long = pb_long_1.PbULong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + message(type2, value, fieldName, options) { + if (value === void 0) + return options.emitDefaultValues ? null : void 0; + return type2.internalJsonWrite(value, options); } - }; - exports2.BinaryWriter = BinaryWriter; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js -var require_json_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; - var defaultsWrite = { - emitDefaultValues: false, - enumAsInteger: false, - useProtoFieldName: false, - prettySpaces: 0 - }; - var defaultsRead = { - ignoreUnknownFields: false - }; - function jsonReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.jsonReadOptions = jsonReadOptions; - function jsonWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.jsonWriteOptions = jsonWriteOptions; - function mergeJsonOptions(a, b) { - var _a, _b; - let c = Object.assign(Object.assign({}, a), b); - c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; - return c; - } - exports2.mergeJsonOptions = mergeJsonOptions; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js -var require_message_type_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MESSAGE_TYPE = void 0; - exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js -var require_lower_camel_case = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.lowerCamelCase = void 0; - function lowerCamelCase(snakeCase) { - let capNext = false; - const sb = []; - for (let i = 0; i < snakeCase.length; i++) { - let next = snakeCase.charAt(i); - if (next == "_") { - capNext = true; - } else if (/\d/.test(next)) { - sb.push(next); - capNext = true; - } else if (capNext) { - sb.push(next.toUpperCase()); - capNext = false; - } else if (i == 0) { - sb.push(next.toLowerCase()); - } else { - sb.push(next); + scalar(type2, value, fieldName, optional, emitDefaultValues) { + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + const ed = emitDefaultValues || optional; + switch (type2) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assert(typeof value == "number"); + if (Number.isNaN(value)) + return "NaN"; + if (value === Number.POSITIVE_INFINITY) + return "Infinity"; + if (value === Number.NEGATIVE_INFINITY) + return "-Infinity"; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? "" : void 0; + assert_1.assert(typeof value == "string"); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : void 0; + assert_1.assert(typeof value == "boolean"); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return void 0; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return void 0; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : void 0; + return base64_1.base64encode(value); } } - return sb.join(""); - } - exports2.lowerCamelCase = lowerCamelCase; + }; + exports2.ReflectionJsonWriter = ReflectionJsonWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js -var require_reflection_info = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js +var require_reflection_scalar_default = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; - var lower_camel_case_1 = require_lower_camel_case(); - var ScalarType; - (function(ScalarType2) { - ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; - ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; - ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; - ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; - ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; - ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; - ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; - ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; - ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; - ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; - ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; - ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; - ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; - ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; - ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; - })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); - var LongType; - (function(LongType2) { - LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; - LongType2[LongType2["STRING"] = 1] = "STRING"; - LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; - })(LongType = exports2.LongType || (exports2.LongType = {})); - var RepeatType; - (function(RepeatType2) { - RepeatType2[RepeatType2["NO"] = 0] = "NO"; - RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; - RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; - })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); - function normalizeFieldInfo(field) { - var _a, _b, _c, _d; - field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); - field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); - field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; - field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; - return field; - } - exports2.normalizeFieldInfo = normalizeFieldInfo; - function readFieldOptions(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readFieldOptions = readFieldOptions; - function readFieldOption(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readFieldOption = readFieldOption; - function readMessageOption(messageType, extensionName, extensionType) { - const options = messageType.options; - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + exports2.reflectionScalarDefault = void 0; + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var pb_long_1 = require_pb_long(); + function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { + switch (type2) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + return 0; } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.readMessageOption = readMessageOption; + exports2.reflectionScalarDefault = reflectionScalarDefault; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js -var require_oneof = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js +var require_reflection_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; - function isOneofGroup(any) { - if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { - return false; - } - switch (typeof any.oneofKind) { - case "string": - if (any[any.oneofKind] === void 0) - return false; - return Object.keys(any).length == 2; - case "undefined": - return Object.keys(any).length == 1; - default: - return false; - } - } - exports2.isOneofGroup = isOneofGroup; - function getOneofValue(oneof, kind) { - return oneof[kind]; - } - exports2.getOneofValue = getOneofValue; - function setOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== void 0) { - oneof[kind] = value; + exports2.ReflectionBinaryReader = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var ReflectionBinaryReader = class { + constructor(info6) { + this.info = info6; } - } - exports2.setOneofValue = setOneofValue; - function setUnknownOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + } } - oneof.oneofKind = kind; - if (value !== void 0 && kind !== void 0) { - oneof[kind] = value; + /** + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(reader, message, options, length) { + this.prepare(); + const end = length === void 0 ? reader.len : reader.pos + length; + while (reader.pos < end) { + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; + } + let target = message, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + target = target[field.oneof]; + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : void 0; + if (repeated) { + let arr = target[localName]; + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } else + arr.push(this.scalar(reader, T, L)); + } else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + target[localName][mapKey] = mapVal; + break; + } + } } - } - exports2.setUnknownOneofValue = setUnknownOneofValue; - function clearOneofValue(oneof) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + /** + * Read a map field, expecting key field = 1, value field = 2 + */ + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = void 0; + let val2 = void 0; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val2 = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val2 = reader.int32(); + break; + case "message": + val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } + } + if (key === void 0) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val2 === void 0) + switch (field.V.kind) { + case "scalar": + val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val2 = 0; + break; + case "message": + val2 = field.V.T().create(); + break; + } + return [key, val2]; } - oneof.oneofKind = void 0; - } - exports2.clearOneofValue = clearOneofValue; - function getSelectedOneofValue(oneof) { - if (oneof.oneofKind === void 0) { - return void 0; + scalar(reader, type2, longType) { + switch (type2) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } } - return oneof[oneof.oneofKind]; - } - exports2.getSelectedOneofValue = getSelectedOneofValue; + }; + exports2.ReflectionBinaryReader = ReflectionBinaryReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js -var require_reflection_type_check = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js +var require_reflection_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionTypeCheck = void 0; + exports2.ReflectionBinaryWriter = void 0; + var binary_format_contract_1 = require_binary_format_contract(); var reflection_info_1 = require_reflection_info(); - var oneof_1 = require_oneof(); - var ReflectionTypeCheck = class { + var assert_1 = require_assert(); + var pb_long_1 = require_pb_long(); + var ReflectionBinaryWriter = class { constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + this.info = info6; } prepare() { - if (this.data) - return; - const req = [], known = [], oneofs = []; - for (let field of this.fields) { - if (field.oneof) { - if (!oneofs.includes(field.oneof)) { - oneofs.push(field.oneof); - req.push(field.oneof); - known.push(field.oneof); - } - } else { - known.push(field.localName); - switch (field.kind) { - case "scalar": - case "enum": - if (!field.opt || field.repeat) - req.push(field.localName); - break; - case "message": - if (field.repeat) - req.push(field.localName); - break; - case "map": - req.push(field.localName); - break; - } - } + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); } - this.data = { req, known, oneofs: Object.values(oneofs) }; } /** - * Is the argument a valid message as specified by the - * reflection information? - * - * Checks all field types recursively. The `depth` - * specifies how deep into the structure the check will be. - * - * With a depth of 0, only the presence of fields - * is checked. - * - * With a depth of 1 or more, the field types are checked. - * - * With a depth of 2 or more, the members of map, repeated - * and message fields are checked. - * - * Message fields will be checked recursively with depth - 1. - * - * The number of map entries / repeated values being checked - * is < depth. + * Writes the message to binary format. */ - is(message, depth, allowExcessProperties = false) { - if (depth < 0) - return true; - if (message === null || message === void 0 || typeof message != "object") - return false; + write(message, writer, options) { this.prepare(); - let keys = Object.keys(message), data = this.data; - if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) - return false; - if (!allowExcessProperties) { - if (keys.some((k) => !data.known.includes(k))) - return false; - } - if (depth < 1) { - return true; - } - for (const name of data.oneofs) { - const group = message[name]; - if (!oneof_1.isOneofGroup(group)) - return false; - if (group.oneofKind === void 0) - continue; - const field = this.fields.find((f) => f.localName === group.oneofKind); - if (!field) - return false; - if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) - return false; - } for (const field of this.fields) { - if (field.oneof !== void 0) - continue; - if (!this.field(message[field.localName], field, allowExcessProperties, depth)) - return false; + let value, emitDefault, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; + value = group[localName]; + emitDefault = true; + } else { + value = message[localName]; + emitDefault = false; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } else if (value === void 0) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == "object" && value !== null); + for (const [key, val2] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val2); + break; + } } - return true; + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); } - field(arg, field, allowExcessProperties, depth) { - let repeated = field.repeat; - switch (field.kind) { + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); + break; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == "true" || key == "false"); + keyValue = key == "true"; + break; + } + this.scalar(writer, field.K, 1, keyValue, true); + switch (field.V.kind) { case "scalar": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, field.T, depth, field.L); - return this.scalar(arg, field.T, field.L); + this.scalar(writer, field.V.T, 2, value, true); + break; case "enum": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); - return this.scalar(arg, reflection_info_1.ScalarType.INT32); + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; case "message": - if (arg === void 0) - return true; - if (repeated) - return this.messages(arg, field.T(), allowExcessProperties, depth); - return this.message(arg, field.T(), allowExcessProperties, depth); - case "map": - if (typeof arg != "object" || arg === null) - return false; - if (depth < 2) - return true; - if (!this.mapKeys(arg, field.K, depth)) - return false; - switch (field.V.kind) { - case "scalar": - return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); - case "enum": - return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); - case "message": - return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); - } + this.message(writer, options, field.V.T(), 2, value); break; } - return true; + writer.join(); } - message(arg, type2, allowExcessProperties, depth) { - if (allowExcessProperties) { - return type2.isAssignable(arg, depth); - } - return type2.is(arg, depth); + message(writer, options, handler, fieldNo, value) { + if (value === void 0) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); } - messages(arg, type2, allowExcessProperties, depth) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (allowExcessProperties) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.isAssignable(arg[i], depth - 1)) - return false; - } else { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.is(arg[i], depth - 1)) - return false; + /** + * Write a single scalar value. + */ + scalar(writer, type2, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type2, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); } - return true; } - scalar(arg, type2, longType) { - let argType = typeof arg; + /** + * Write an array of scalar values in packed format. + */ + packed(writer, type2, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let [, method] = this.scalarInfo(type2); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + writer.join(); + } + /** + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. + */ + scalarInfo(type2, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === void 0; + let d = value === 0; switch (type2) { - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - switch (longType) { - case reflection_info_1.LongType.BIGINT: - return argType == "bigint"; - case reflection_info_1.LongType.NUMBER: - return argType == "number" && !isNaN(arg); - default: - return argType == "string"; - } - case reflection_info_1.ScalarType.BOOL: - return argType == "boolean"; + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; case reflection_info_1.ScalarType.STRING: - return argType == "string"; - case reflection_info_1.ScalarType.BYTES: - return arg instanceof Uint8Array; + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; case reflection_info_1.ScalarType.FLOAT: - return argType == "number" && !isNaN(arg); - default: - return argType == "number" && Number.isInteger(arg); - } - } - scalars(arg, type2, depth, longType) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (Array.isArray(arg)) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!this.scalar(arg[i], type2, longType)) - return false; - } - return true; - } - mapKeys(map2, type2, depth) { - let keys = Object.keys(map2); - switch (type2) { - case reflection_info_1.ScalarType.INT32: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); - case reflection_info_1.ScalarType.BOOL: - return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); - default: - return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; } + return [t, m, i || d]; } }; - exports2.ReflectionTypeCheck = ReflectionTypeCheck; + exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js -var require_reflection_long_convert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js +var require_reflection_create = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionLongConvert = void 0; + exports2.reflectionCreate = void 0; + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var message_type_contract_1 = require_message_type_contract(); + function reflectionCreate(type2) { + const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); + for (let field of type2.fields) { + let name = field.localName; + if (field.opt) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: void 0 }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } + } + return msg; + } + exports2.reflectionCreate = reflectionCreate; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js +var require_reflection_merge_partial = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionMergePartial = void 0; + function reflectionMergePartial(info6, target, source) { + let fieldValue, input = source, output; + for (let field of info6.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { + continue; + } + fieldValue = group[name]; + output = target[field.oneof]; + output.oneofKind = group.oneofKind; + if (fieldValue == void 0) { + delete output[name]; + continue; + } + } else { + fieldValue = input[name]; + output = target; + if (fieldValue == void 0) { + continue; + } + } + if (field.repeat) + output[name].length = fieldValue.length; + switch (field.kind) { + case "scalar": + case "enum": + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; + else + output[name] = fieldValue; + break; + case "message": + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === void 0) + output[name] = T.create(fieldValue); + else + T.mergePartial(output[name], fieldValue); + break; + case "map": + switch (field.V.kind) { + case "scalar": + case "enum": + Object.assign(output[name], fieldValue); + break; + case "message": + let T2 = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T2.create(fieldValue[k]); + break; + } + break; + } + } + } + exports2.reflectionMergePartial = reflectionMergePartial; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js +var require_reflection_equals = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionEquals = void 0; var reflection_info_1 = require_reflection_info(); - function reflectionLongConvert(long, type2) { - switch (type2) { - case reflection_info_1.LongType.BIGINT: - return long.toBigInt(); - case reflection_info_1.LongType.NUMBER: - return long.toNumber(); - default: - return long.toString(); + function reflectionEquals(info6, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info6.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) + return false; + break; + } } + return true; + } + exports2.reflectionEquals = reflectionEquals; + var objectValues = Object.values; + function primitiveEq(type2, a, b) { + if (a === b) + return true; + if (type2 !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; + } + function repeatedPrimitiveEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type2, a[i], b[i])) + return false; + return true; + } + function repeatedMsgEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type2.equals(a[i], b[i])) + return false; + return true; } - exports2.reflectionLongConvert = reflectionLongConvert; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js -var require_reflection_json_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js +var require_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonReader = void 0; - var json_typings_1 = require_json_typings(); - var base64_1 = require_base642(); + exports2.MessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); var reflection_info_1 = require_reflection_info(); - var pb_long_1 = require_pb_long(); - var assert_1 = require_assert(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var ReflectionJsonReader = class { - constructor(info6) { - this.info = info6; + var reflection_type_check_1 = require_reflection_type_check(); + var reflection_json_reader_1 = require_reflection_json_reader(); + var reflection_json_writer_1 = require_reflection_json_writer(); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + var reflection_create_1 = require_reflection_create(); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + var json_typings_1 = require_json_typings(); + var json_format_contract_1 = require_json_format_contract(); + var reflection_equals_1 = require_reflection_equals(); + var binary_writer_1 = require_binary_writer(); + var binary_reader_1 = require_binary_reader(); + var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); + var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; + var MessageType = class { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + messageTypeDescriptor.value = this; + this.messagePrototype = Object.create(null, baseDescriptors); + this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); + this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); + this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } - prepare() { - var _a; - if (this.fMap === void 0) { - this.fMap = {}; - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - for (const field of fieldsInput) { - this.fMap[field.name] = field; - this.fMap[field.jsonName] = field; - this.fMap[field.localName] = field; - } + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== void 0) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); } + return message; } - // Cannot parse JSON for #. - assert(condition, fieldName, jsonValue) { - if (!condition) { - let what = json_typings_1.typeofJsonValue(jsonValue); - if (what == "number" || what == "boolean") - what = jsonValue.toString(); - throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + /** + * Clone the message. + * + * Unknown fields are discarded. + */ + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; + } + /** + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. + */ + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); + } + /** + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); + } + /** + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); + } + /** + * Copy partial data into the target message. + */ + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); + } + /** + * Create a new message from binary format. + */ + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + } + /** + * Read a new message from a JSON value. + */ + fromJson(json2, options) { + return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + } + /** + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. + */ + fromJsonString(json2, options) { + let value = JSON.parse(json2); + return this.fromJson(value, options); + } + /** + * Write the message to canonical JSON value. + */ + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + } + /** + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` + */ + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + } + /** + * Write the message to binary format. + */ + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + } + /** + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. + */ + internalJsonRead(json2, options, target) { + if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json2, message, options); + return message; } + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); } /** - * Reads a message from canonical JSON format into the target message. + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); + } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. * - * If a message field is already present, it will be merged with the - * new data. + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. */ - read(input, message, options) { - this.prepare(); - const oneofsHandled = []; - for (const [jsonKey, jsonValue] of Object.entries(input)) { - const field = this.fMap[jsonKey]; - if (!field) { - if (!options.ignoreUnknownFields) - throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); - continue; - } - const localName = field.localName; - let target; - if (field.oneof) { - if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { - continue; - } - if (oneofsHandled.includes(field.oneof)) - throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); - oneofsHandled.push(field.oneof); - target = message[field.oneof] = { - oneofKind: localName - }; - } else { - target = message; - } - if (field.kind == "map") { - if (jsonValue === null) { - continue; - } - this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); - const fieldObj = target[localName]; - for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { - this.assert(jsonObjValue !== null, field.name + " map value", null); - let val2; - switch (field.V.kind) { - case "message": - val2 = field.V.T().internalJsonRead(jsonObjValue, options); - break; - case "enum": - val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); - let key = jsonObjKey; - if (field.K == reflection_info_1.ScalarType.BOOL) - key = key == "true" ? true : key == "false" ? false : key; - key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); - fieldObj[key] = val2; - } - } else if (field.repeat) { - if (jsonValue === null) - continue; - this.assert(Array.isArray(jsonValue), field.name, jsonValue); - const fieldArr = target[localName]; - for (const jsonItem of jsonValue) { - this.assert(jsonItem !== null, field.name, null); - let val2; - switch (field.kind) { - case "message": - val2 = field.T().internalJsonRead(jsonItem, options); - break; - case "enum": - val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonItem, field.T, field.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name, jsonValue); - fieldArr.push(val2); - } - } else { - switch (field.kind) { - case "message": - if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { - this.assert(field.oneof === void 0, field.name + " (oneof member)", null); - continue; - } - target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); - break; - case "enum": - if (jsonValue === null) - continue; - let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - target[localName] = val2; - break; - case "scalar": - if (jsonValue === null) - continue; - target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); - break; - } - } - } + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; } /** - * Returns `false` for unrecognized string representations. + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. * - * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. */ - enum(type2, json2, fieldName, ignoreUnknownFields) { - if (type2[0] == "google.protobuf.NullValue") - assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); - if (json2 === null) - return 0; - switch (typeof json2) { - case "number": - assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); - return json2; - case "string": - let localEnumName = json2; - if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) - localEnumName = json2.substring(type2[2].length); - let enumNumber = type2[1][localEnumName]; - if (typeof enumNumber === "undefined" && ignoreUnknownFields) { - return false; - } - assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); - return enumNumber; - } - assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; } - scalar(json2, type2, longType, fieldName) { - let e; - try { - switch (type2) { - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - if (json2 === null) - return 0; - if (json2 === "NaN") - return Number.NaN; - if (json2 === "Infinity") - return Number.POSITIVE_INFINITY; - if (json2 === "-Infinity") - return Number.NEGATIVE_INFINITY; - if (json2 === "") { - e = "empty string"; - break; - } - if (typeof json2 == "string" && json2.trim().length !== json2.length) { - e = "extra whitespace"; - break; - } - if (typeof json2 != "string" && typeof json2 != "number") { - break; - } - let float2 = Number(json2); - if (Number.isNaN(float2)) { - e = "not a number"; - break; - } - if (!Number.isFinite(float2)) { - e = "too large or small"; - break; - } - if (type2 == reflection_info_1.ScalarType.FLOAT) - assert_1.assertFloat32(float2); - return float2; - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - if (json2 === null) - return 0; - let int32; - if (typeof json2 == "number") - int32 = json2; - else if (json2 === "") - e = "empty string"; - else if (typeof json2 == "string") { - if (json2.trim().length !== json2.length) - e = "extra whitespace"; - else - int32 = Number(json2); - } - if (int32 === void 0) - break; - if (type2 == reflection_info_1.ScalarType.UINT32) - assert_1.assertUInt32(int32); - else - assert_1.assertInt32(int32); - return int32; - // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.UINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); - // bool: - case reflection_info_1.ScalarType.BOOL: - if (json2 === null) - return false; - if (typeof json2 !== "boolean") - break; - return json2; - // string: - case reflection_info_1.ScalarType.STRING: - if (json2 === null) - return ""; - if (typeof json2 !== "string") { - e = "extra whitespace"; - break; - } - try { - encodeURIComponent(json2); - } catch (e2) { - e2 = "invalid UTF8"; - break; - } - return json2; - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - if (json2 === null || json2 === "") - return new Uint8Array(0); - if (typeof json2 !== "string") - break; - return base64_1.base64decode(json2); - } - } catch (error4) { - e = error4.message; + }; + exports2.MessageType = MessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js +var require_reflection_contains_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.containsMessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; + } + exports2.containsMessageType = containsMessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js +var require_enum_object = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; + function isEnumObject(arg) { + if (typeof arg != "object" || arg === null) { + return false; + } + if (!arg.hasOwnProperty(0)) { + return false; + } + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + let nam = arg[num]; + if (nam === void 0) + return false; + if (arg[nam] !== num) + return false; + } else { + let num2 = arg[k]; + if (num2 === void 0) + return false; + if (typeof num2 !== "number") + return false; + if (arg[num2] === void 0) + return false; } - this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - }; - exports2.ReflectionJsonReader = ReflectionJsonReader; + return true; + } + exports2.isEnumObject = isEnumObject; + function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; + } + exports2.listEnumValues = listEnumValues; + function listEnumNames(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.name); + } + exports2.listEnumNames = listEnumNames; + function listEnumNumbers(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + } + exports2.listEnumNumbers = listEnumNumbers; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js -var require_reflection_json_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonWriter = void 0; + var json_typings_1 = require_json_typings(); + Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { + return json_typings_1.typeofJsonValue; + } }); + Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { + return json_typings_1.isJsonObject; + } }); var base64_1 = require_base642(); + Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { + return base64_1.base64decode; + } }); + Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { + return base64_1.base64encode; + } }); + var protobufjs_utf8_1 = require_protobufjs_utf8(); + Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { + return protobufjs_utf8_1.utf8read; + } }); + var binary_format_contract_1 = require_binary_format_contract(); + Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { + return binary_format_contract_1.WireType; + } }); + Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { + return binary_format_contract_1.mergeBinaryOptions; + } }); + Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { + return binary_format_contract_1.UnknownFieldHandler; + } }); + var binary_reader_1 = require_binary_reader(); + Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { + return binary_reader_1.BinaryReader; + } }); + Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { + return binary_reader_1.binaryReadOptions; + } }); + var binary_writer_1 = require_binary_writer(); + Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { + return binary_writer_1.BinaryWriter; + } }); + Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { + return binary_writer_1.binaryWriteOptions; + } }); var pb_long_1 = require_pb_long(); + Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { + return pb_long_1.PbLong; + } }); + Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { + return pb_long_1.PbULong; + } }); + var json_format_contract_1 = require_json_format_contract(); + Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonReadOptions; + } }); + Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonWriteOptions; + } }); + Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { + return json_format_contract_1.mergeJsonOptions; + } }); + var message_type_contract_1 = require_message_type_contract(); + Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { + return message_type_contract_1.MESSAGE_TYPE; + } }); + var message_type_1 = require_message_type(); + Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { + return message_type_1.MessageType; + } }); var reflection_info_1 = require_reflection_info(); + Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { + return reflection_info_1.ScalarType; + } }); + Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { + return reflection_info_1.LongType; + } }); + Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { + return reflection_info_1.RepeatType; + } }); + Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { + return reflection_info_1.normalizeFieldInfo; + } }); + Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { + return reflection_info_1.readFieldOptions; + } }); + Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { + return reflection_info_1.readFieldOption; + } }); + Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { + return reflection_info_1.readMessageOption; + } }); + var reflection_type_check_1 = require_reflection_type_check(); + Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { + return reflection_type_check_1.ReflectionTypeCheck; + } }); + var reflection_create_1 = require_reflection_create(); + Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { + return reflection_create_1.reflectionCreate; + } }); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { + return reflection_scalar_default_1.reflectionScalarDefault; + } }); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { + return reflection_merge_partial_1.reflectionMergePartial; + } }); + var reflection_equals_1 = require_reflection_equals(); + Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { + return reflection_equals_1.reflectionEquals; + } }); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { + return reflection_binary_reader_1.ReflectionBinaryReader; + } }); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { + return reflection_binary_writer_1.ReflectionBinaryWriter; + } }); + var reflection_json_reader_1 = require_reflection_json_reader(); + Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { + return reflection_json_reader_1.ReflectionJsonReader; + } }); + var reflection_json_writer_1 = require_reflection_json_writer(); + Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { + return reflection_json_writer_1.ReflectionJsonWriter; + } }); + var reflection_contains_message_type_1 = require_reflection_contains_message_type(); + Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { + return reflection_contains_message_type_1.containsMessageType; + } }); + var oneof_1 = require_oneof(); + Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { + return oneof_1.isOneofGroup; + } }); + Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { + return oneof_1.setOneofValue; + } }); + Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { + return oneof_1.getOneofValue; + } }); + Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { + return oneof_1.clearOneofValue; + } }); + Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { + return oneof_1.getSelectedOneofValue; + } }); + var enum_object_1 = require_enum_object(); + Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { + return enum_object_1.listEnumValues; + } }); + Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { + return enum_object_1.listEnumNames; + } }); + Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { + return enum_object_1.listEnumNumbers; + } }); + Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { + return enum_object_1.isEnumObject; + } }); + var lower_camel_case_1 = require_lower_camel_case(); + Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { + return lower_camel_case_1.lowerCamelCase; + } }); var assert_1 = require_assert(); - var ReflectionJsonWriter = class { - constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { + return assert_1.assert; + } }); + Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { + return assert_1.assertNever; + } }); + Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { + return assert_1.assertInt32; + } }); + Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { + return assert_1.assertUInt32; + } }); + Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { + return assert_1.assertFloat32; + } }); + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js +var require_reflection_info2 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + var runtime_1 = require_commonjs11(); + function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + m.serverStreaming = !!m.serverStreaming; + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; + return m; + } + exports2.normalizeMethodInfo = normalizeMethodInfo; + function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readMethodOptions = readMethodOptions; + function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; } - /** - * Converts the message to a JSON object, based on the field descriptors. - */ - write(message, options) { - const json2 = {}, source = message; - for (const field of this.fields) { - if (!field.oneof) { - let jsonValue2 = this.field(field, source[field.localName], options); - if (jsonValue2 !== void 0) - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; - continue; - } - const group = source[field.oneof]; - if (group.oneofKind !== field.localName) - continue; - const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; - let jsonValue = this.field(field, group[field.localName], opt); - assert_1.assert(jsonValue !== void 0); - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; - } - return json2; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - field(field, value, options) { - let jsonValue = void 0; - if (field.kind == "map") { - assert_1.assert(typeof value == "object" && value !== null); - const jsonObj = {}; - switch (field.V.kind) { - case "scalar": - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "message": - const messageType = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.message(messageType, entryValue, field.name, options); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "enum": - const enumInfo = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); - const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - } - if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) - jsonValue = jsonObj; - } else if (field.repeat) { - assert_1.assert(Array.isArray(value)); - const jsonArr = []; - switch (field.kind) { - case "scalar": - for (let i = 0; i < value.length; i++) { - const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "enum": - const enumInfo = field.T(); - for (let i = 0; i < value.length; i++) { - assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); - const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "message": - const messageType = field.T(); - for (let i = 0; i < value.length; i++) { - const val2 = this.message(messageType, value[i], field.name, options); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - } - if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) - jsonValue = jsonArr; - } else { - switch (field.kind) { - case "scalar": - jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); - break; - case "enum": - jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); - break; - case "message": - jsonValue = this.message(field.T(), value, field.name, options); - break; - } - } - return jsonValue; + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMethodOption = readMethodOption; + function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return void 0; } - /** - * Returns `null` as the default for google.protobuf.NullValue. - */ - enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { - if (type2[0] == "google.protobuf.NullValue") - return !emitDefaultValues && !optional ? void 0 : null; - if (value === void 0) { - assert_1.assert(optional); - return void 0; - } - if (value === 0 && !emitDefaultValues && !optional) - return void 0; - assert_1.assert(typeof value == "number"); - assert_1.assert(Number.isInteger(value)); - if (enumAsInteger || !type2[1].hasOwnProperty(value)) - return value; - if (type2[2]) - return type2[2] + type2[1][value]; - return type2[1][value]; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - message(type2, value, fieldName, options) { - if (value === void 0) - return options.emitDefaultValues ? null : void 0; - return type2.internalJsonWrite(value, options); + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readServiceOption = readServiceOption; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js +var require_service_type = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServiceType = void 0; + var reflection_info_1 = require_reflection_info2(); + var ServiceType = class { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; } - scalar(type2, value, fieldName, optional, emitDefaultValues) { - if (value === void 0) { - assert_1.assert(optional); - return void 0; + }; + exports2.ServiceType = ServiceType; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js +var require_rpc_error = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcError = void 0; + var RpcError = class extends Error { + constructor(message, code = "UNKNOWN", meta) { + super(message); + this.name = "RpcError"; + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; + } + toString() { + const l = [this.name + ": " + this.message]; + if (this.code) { + l.push(""); + l.push("Code: " + this.code); } - const ed = emitDefaultValues || optional; - switch (type2) { - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertInt32(value); - return value; - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertUInt32(value); - return value; - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.FLOAT: - assert_1.assertFloat32(value); - case reflection_info_1.ScalarType.DOUBLE: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assert(typeof value == "number"); - if (Number.isNaN(value)) - return "NaN"; - if (value === Number.POSITIVE_INFINITY) - return "Infinity"; - if (value === Number.NEGATIVE_INFINITY) - return "-Infinity"; - return value; - // string: - case reflection_info_1.ScalarType.STRING: - if (value === "") - return ed ? "" : void 0; - assert_1.assert(typeof value == "string"); - return value; - // bool: - case reflection_info_1.ScalarType.BOOL: - if (value === false) - return ed ? false : void 0; - assert_1.assert(typeof value == "boolean"); - return value; - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let ulong = pb_long_1.PbULong.from(value); - if (ulong.isZero() && !ed) - return void 0; - return ulong.toString(); - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let long = pb_long_1.PbLong.from(value); - if (long.isZero() && !ed) - return void 0; - return long.toString(); - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - assert_1.assert(value instanceof Uint8Array); - if (!value.byteLength) - return ed ? "" : void 0; - return base64_1.base64encode(value); + if (this.serviceName && this.methodName) { + l.push("Method: " + this.serviceName + "/" + this.methodName); + } + let m = Object.entries(this.meta); + if (m.length) { + l.push(""); + l.push("Meta:"); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); + } } + return l.join("\n"); } }; - exports2.ReflectionJsonWriter = ReflectionJsonWriter; + exports2.RpcError = RpcError; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js -var require_reflection_scalar_default = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js +var require_rpc_options = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionScalarDefault = void 0; - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var pb_long_1 = require_pb_long(); - function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { - switch (type2) { - case reflection_info_1.ScalarType.BOOL: - return false; - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return 0; - case reflection_info_1.ScalarType.BYTES: - return new Uint8Array(0); - case reflection_info_1.ScalarType.STRING: - return ""; - default: - return 0; + exports2.mergeRpcOptions = void 0; + var runtime_1 = require_commonjs11(); + function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val2 = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); + break; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); + break; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); + break; + } + } + return o; + } + exports2.mergeRpcOptions = mergeRpcOptions; + function copy(a, into) { + if (!a) + return; + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; } } - exports2.reflectionScalarDefault = reflectionScalarDefault; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js -var require_reflection_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js +var require_deferred = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryReader = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var ReflectionBinaryReader = class { - constructor(info6) { - this.info = info6; - } - prepare() { - var _a; - if (!this.fieldNoToField) { - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + exports2.Deferred = exports2.DeferredState = void 0; + var DeferredState; + (function(DeferredState2) { + DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; + DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; + DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; + })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); + var Deferred = class { + /** + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. + */ + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve5, reject) => { + this._resolve = resolve5; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch((_) => { + }); } } /** - * Reads a message from binary format into the target message. + * Get the current state of the promise. + */ + get state() { + return this._state; + } + /** + * Get the deferred promise. + */ + get promise() { + return this._promise; + } + /** + * Resolve the promise. Throws if the promise is already resolved or rejected. + */ + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; + } + /** + * Reject the promise. Throws if the promise is already resolved or rejected. + */ + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; + } + /** + * Resolve the promise. Ignore if not pending. + */ + resolvePending(val2) { + if (this._state === DeferredState.PENDING) + this.resolve(val2); + } + /** + * Reject the promise. Ignore if not pending. + */ + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); + } + }; + exports2.Deferred = Deferred; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js +var require_rpc_output_stream = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcOutputStreamController = void 0; + var deferred_1 = require_deferred(); + var runtime_1 = require_commonjs11(); + var RpcOutputStreamController = class { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [] + }; + this._closed = false; + this._itState = { q: [] }; + } + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); + } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); + } + // --- Controller API + /** + * Is this stream already closed by a completion or error? + */ + get closed() { + return this._closed !== false; + } + /** + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. + */ + notifyNext(message, error4, complete) { + runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); + if (message) + this.notifyMessage(message); + if (error4) + this.notifyError(error4); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, "stream is closed"); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach((l) => l(message)); + this._lis.nxt.forEach((l) => l(message, void 0, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. * - * If a message field is already present, it will be merged with the - * new data. + * Triggers onNext and onError callbacks. */ - read(reader, message, options, length) { - this.prepare(); - const end = length === void 0 ? reader.len : reader.pos + length; - while (reader.pos < end) { - const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); - if (!field) { - let u = options.readUnknownField; - if (u == "throw") - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); - continue; - } - let target = message, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - target = target[field.oneof]; - if (target.oneofKind !== localName) - target = message[field.oneof] = { - oneofKind: localName - }; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - let L = field.kind == "scalar" ? field.L : void 0; - if (repeated) { - let arr = target[localName]; - if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { - let e = reader.uint32() + reader.pos; - while (reader.pos < e) - arr.push(this.scalar(reader, T, L)); - } else - arr.push(this.scalar(reader, T, L)); - } else - target[localName] = this.scalar(reader, T, L); - break; - case "message": - if (repeated) { - let arr = target[localName]; - let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); - arr.push(msg); - } else - target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); - break; - case "map": - let [mapKey, mapVal] = this.mapEntry(field, reader, options); - target[localName][mapKey] = mapVal; - break; - } - } + notifyError(error4) { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = error4; + this.pushIt(error4); + this._lis.err.forEach((l) => l(error4)); + this._lis.nxt.forEach((l) => l(void 0, error4, false)); + this.clearLis(); } /** - * Read a map field, expecting key field = 1, value field = 2 + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. */ - mapEntry(field, reader, options) { - let length = reader.uint32(); - let end = reader.pos + length; - let key = void 0; - let val2 = void 0; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case 1: - if (field.K == reflection_info_1.ScalarType.BOOL) - key = reader.bool().toString(); - else - key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); - break; - case 2: - switch (field.V.kind) { - case "scalar": - val2 = this.scalar(reader, field.V.T, field.V.L); - break; - case "enum": - val2 = reader.int32(); - break; - case "message": - val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); - break; - } - break; - default: - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + notifyComplete() { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach((l) => l()); + this._lis.nxt.forEach((l) => l(void 0, void 0, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); + runtime_1.assert(!state.p, "iterator contract broken"); + let first = state.q.shift(); + if (first) + return "value" in first ? Promise.resolve(first) : Promise.reject(first); + state.p = new deferred_1.Deferred(); + return state.p.promise; } + }; + } + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (state.p) { + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + "value" in result ? p.resolve(result) : p.reject(result); + delete state.p; + } else { + state.q.push(result); } - if (key === void 0) { - let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); - key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + }; + exports2.RpcOutputStreamController = RpcOutputStreamController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js +var require_unary_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - if (val2 === void 0) - switch (field.V.kind) { - case "scalar": - val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); - break; - case "enum": - val2 = 0; - break; - case "message": - val2 = field.V.T().create(); - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return [key, val2]; - } - scalar(reader, type2, longType) { - switch (type2) { - case reflection_info_1.ScalarType.INT32: - return reader.int32(); - case reflection_info_1.ScalarType.STRING: - return reader.string(); - case reflection_info_1.ScalarType.BOOL: - return reader.bool(); - case reflection_info_1.ScalarType.DOUBLE: - return reader.double(); - case reflection_info_1.ScalarType.FLOAT: - return reader.float(); - case reflection_info_1.ScalarType.INT64: - return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); - case reflection_info_1.ScalarType.UINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); - case reflection_info_1.ScalarType.FIXED32: - return reader.fixed32(); - case reflection_info_1.ScalarType.BYTES: - return reader.bytes(); - case reflection_info_1.ScalarType.UINT32: - return reader.uint32(); - case reflection_info_1.ScalarType.SFIXED32: - return reader.sfixed32(); - case reflection_info_1.ScalarType.SFIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); - case reflection_info_1.ScalarType.SINT32: - return reader.sint32(); - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UnaryCall = void 0; + var UnaryCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryReader = ReflectionBinaryReader; + exports2.UnaryCall = UnaryCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js -var require_reflection_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js +var require_server_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryWriter = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var pb_long_1 = require_pb_long(); - var ReflectionBinaryWriter = class { - constructor(info6) { - this.info = info6; - } - prepare() { - if (!this.fields) { - const fieldsInput = this.info.fields ? this.info.fields.concat() : []; - this.fields = fieldsInput.sort((a, b) => a.no - b.no); - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - /** - * Writes the message to binary format. - */ - write(message, writer, options) { - this.prepare(); - for (const field of this.fields) { - let value, emitDefault, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - const group = message[field.oneof]; - if (group.oneofKind !== localName) - continue; - value = group[localName]; - emitDefault = true; - } else { - value = message[localName]; - emitDefault = false; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (repeated) { - assert_1.assert(Array.isArray(value)); - if (repeated == reflection_info_1.RepeatType.PACKED) - this.packed(writer, T, field.no, value); - else - for (const item of value) - this.scalar(writer, T, field.no, item, true); - } else if (value === void 0) - assert_1.assert(field.opt); - else - this.scalar(writer, T, field.no, value, emitDefault || field.opt); - break; - case "message": - if (repeated) { - assert_1.assert(Array.isArray(value)); - for (const item of value) - this.message(writer, options, field.T(), field.no, item); - } else { - this.message(writer, options, field.T(), field.no, value); - } - break; - case "map": - assert_1.assert(typeof value == "object" && value !== null); - for (const [key, val2] of Object.entries(value)) - this.mapEntry(writer, options, field, key, val2); - break; + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - let u = options.writeUnknownFields; - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); - } - mapEntry(writer, options, field, key, value) { - writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let keyValue = key; - switch (field.K) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - keyValue = Number.parseInt(key); - break; - case reflection_info_1.ScalarType.BOOL: - assert_1.assert(key == "true" || key == "false"); - keyValue = key == "true"; - break; - } - this.scalar(writer, field.K, 1, keyValue, true); - switch (field.V.kind) { - case "scalar": - this.scalar(writer, field.V.T, 2, value, true); - break; - case "enum": - this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); - break; - case "message": - this.message(writer, options, field.V.T(), 2, value); - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - writer.join(); - } - message(writer, options, handler, fieldNo, value) { - if (value === void 0) - return; - handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); - writer.join(); - } - /** - * Write a single scalar value. - */ - scalar(writer, type2, fieldNo, value, emitDefault) { - let [wireType, method, isDefault] = this.scalarInfo(type2, value); - if (!isDefault || emitDefault) { - writer.tag(fieldNo, wireType); - writer[method](value); + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerStreamingCall = void 0; + var ServerStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } /** - * Write an array of scalar values in packed format. + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. */ - packed(writer, type2, fieldNo, value) { - if (!value.length) - return; - assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); - writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let [, method] = this.scalarInfo(type2); - for (let i = 0; i < value.length; i++) - writer[method](value[i]); - writer.join(); + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } - /** - * Get information for writing a scalar value. - * - * Returns tuple: - * [0]: appropriate WireType - * [1]: name of the appropriate method of IBinaryWriter - * [2]: whether the given value is a default value - * - * If argument `value` is omitted, [2] is always false. - */ - scalarInfo(type2, value) { - let t = binary_format_contract_1.WireType.Varint; - let m; - let i = value === void 0; - let d = value === 0; - switch (type2) { - case reflection_info_1.ScalarType.INT32: - m = "int32"; - break; - case reflection_info_1.ScalarType.STRING: - d = i || !value.length; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "string"; - break; - case reflection_info_1.ScalarType.BOOL: - d = value === false; - m = "bool"; - break; - case reflection_info_1.ScalarType.UINT32: - m = "uint32"; - break; - case reflection_info_1.ScalarType.DOUBLE: - t = binary_format_contract_1.WireType.Bit64; - m = "double"; - break; - case reflection_info_1.ScalarType.FLOAT: - t = binary_format_contract_1.WireType.Bit32; - m = "float"; - break; - case reflection_info_1.ScalarType.INT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "int64"; - break; - case reflection_info_1.ScalarType.UINT64: - d = i || pb_long_1.PbULong.from(value).isZero(); - m = "uint64"; - break; - case reflection_info_1.ScalarType.FIXED64: - d = i || pb_long_1.PbULong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "fixed64"; - break; - case reflection_info_1.ScalarType.BYTES: - d = i || !value.byteLength; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "bytes"; - break; - case reflection_info_1.ScalarType.FIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "fixed32"; - break; - case reflection_info_1.ScalarType.SFIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "sfixed32"; - break; - case reflection_info_1.ScalarType.SFIXED64: - d = i || pb_long_1.PbLong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "sfixed64"; - break; - case reflection_info_1.ScalarType.SINT32: - m = "sint32"; - break; - case reflection_info_1.ScalarType.SINT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "sint64"; - break; - } - return [t, m, i || d]; + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + exports2.ServerStreamingCall = ServerStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js -var require_reflection_create = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js +var require_client_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionCreate = void 0; - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var message_type_contract_1 = require_message_type_contract(); - function reflectionCreate(type2) { - const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); - for (let field of type2.fields) { - let name = field.localName; - if (field.opt) - continue; - if (field.oneof) - msg[field.oneof] = { oneofKind: void 0 }; - else if (field.repeat) - msg[name] = []; - else - switch (field.kind) { - case "scalar": - msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); - break; - case "enum": - msg[name] = 0; - break; - case "map": - msg[name] = {}; - break; - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - return msg; - } - exports2.reflectionCreate = reflectionCreate; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js -var require_reflection_merge_partial = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionMergePartial = void 0; - function reflectionMergePartial(info6, target, source) { - let fieldValue, input = source, output; - for (let field of info6.fields) { - let name = field.localName; - if (field.oneof) { - const group = input[field.oneof]; - if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { - continue; - } - fieldValue = group[name]; - output = target[field.oneof]; - output.oneofKind = group.oneofKind; - if (fieldValue == void 0) { - delete output[name]; - continue; + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - } else { - fieldValue = input[name]; - output = target; - if (fieldValue == void 0) { - continue; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - if (field.repeat) - output[name].length = fieldValue.length; - switch (field.kind) { - case "scalar": - case "enum": - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = fieldValue[i]; - else - output[name] = fieldValue; - break; - case "message": - let T = field.T(); - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = T.create(fieldValue[i]); - else if (output[name] === void 0) - output[name] = T.create(fieldValue); - else - T.mergePartial(output[name], fieldValue); - break; - case "map": - switch (field.V.kind) { - case "scalar": - case "enum": - Object.assign(output[name], fieldValue); - break; - case "message": - let T2 = field.V.T(); - for (let k of Object.keys(fieldValue)) - output[name][k] = T2.create(fieldValue[k]); - break; - } - break; + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ClientStreamingCall = void 0; + var ClientStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; } - } - exports2.reflectionMergePartial = reflectionMergePartial; + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.ClientStreamingCall = ClientStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js -var require_reflection_equals = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js +var require_duplex_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionEquals = void 0; - var reflection_info_1 = require_reflection_info(); - function reflectionEquals(info6, a, b) { - if (a === b) - return true; - if (!a || !b) - return false; - for (let field of info6.fields) { - let localName = field.localName; - let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; - let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; - switch (field.kind) { - case "enum": - case "scalar": - let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) - return false; - break; - case "map": - if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) - return false; - break; - case "message": - let T = field.T(); - if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) - return false; - break; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DuplexStreamingCall = void 0; + var DuplexStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers + }; + }); } - return true; - } - exports2.reflectionEquals = reflectionEquals; - var objectValues = Object.values; - function primitiveEq(type2, a, b) { - if (a === b) - return true; - if (type2 !== reflection_info_1.ScalarType.BYTES) - return false; - let ba = a; - let bb = b; - if (ba.length !== bb.length) - return false; - for (let i = 0; i < ba.length; i++) - if (ba[i] != bb[i]) - return false; - return true; - } - function repeatedPrimitiveEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!primitiveEq(type2, a[i], b[i])) - return false; - return true; - } - function repeatedMsgEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!type2.equals(a[i], b[i])) - return false; - return true; - } + }; + exports2.DuplexStreamingCall = DuplexStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js -var require_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js +var require_test_transport = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_type_check_1 = require_reflection_type_check(); - var reflection_json_reader_1 = require_reflection_json_reader(); - var reflection_json_writer_1 = require_reflection_json_writer(); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - var reflection_create_1 = require_reflection_create(); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - var json_typings_1 = require_json_typings(); - var json_format_contract_1 = require_json_format_contract(); - var reflection_equals_1 = require_reflection_equals(); - var binary_writer_1 = require_binary_writer(); - var binary_reader_1 = require_binary_reader(); - var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); - var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; - var MessageType = class { - constructor(name, fields, options) { - this.defaultCheckDepth = 16; - this.typeName = name; - this.fields = fields.map(reflection_info_1.normalizeFieldInfo); - this.options = options !== null && options !== void 0 ? options : {}; - messageTypeDescriptor.value = this; - this.messagePrototype = Object.create(null, baseDescriptors); - this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); - this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); - this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); - this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); - this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - create(value) { - let message = reflection_create_1.reflectionCreate(this); - if (value !== void 0) { - reflection_merge_partial_1.reflectionMergePartial(this, message, value); + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - return message; - } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TestTransport = void 0; + var rpc_error_1 = require_rpc_error(); + var runtime_1 = require_commonjs11(); + var rpc_output_stream_1 = require_rpc_output_stream(); + var rpc_options_1 = require_rpc_options(); + var unary_call_1 = require_unary_call(); + var server_streaming_call_1 = require_server_streaming_call(); + var client_streaming_call_1 = require_client_streaming_call(); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + var TestTransport = class _TestTransport { /** - * Clone the message. - * - * Unknown fields are discarded. + * Initialize with mock data. Omitted fields have default value. */ - clone(message) { - let copy = this.create(); - reflection_merge_partial_1.reflectionMergePartial(this, copy, message); - return copy; + constructor(data) { + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; } /** - * Determines whether two message of the same type have the same field values. - * Checks for deep equality, traversing repeated fields, oneof groups, maps - * and messages recursively. - * Will also return true if both messages are `undefined`. + * Sent message(s) during the last operation. */ - equals(a, b) { - return reflection_equals_1.reflectionEquals(this, a, b); + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; + } else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; } /** - * Is the given value assignable to our message type - * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + * Sending message(s) completed? */ - is(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, false); + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } else if (typeof this.lastInput == "object") { + return true; + } + return false; } - /** - * Is the given value assignable to our message type, - * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? - */ - isAssignable(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, true); + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); } - /** - * Copy partial data into the target message. - */ - mergePartial(target, source) { - reflection_merge_partial_1.reflectionMergePartial(this, target, source); + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } else if (this.data.response !== void 0) { + r = this.data.response; + } else { + r = method.O.create(); + } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); } /** - * Create a new message from binary format. + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. */ - fromBinary(data, options) { - let opt = binary_reader_1.binaryReadOptions(options); - return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + streamResponses(method, stream, abort) { + return __awaiter4(this, void 0, void 0, function* () { + const messages = []; + if (this.data.response === void 0) { + messages.push(method.O.create()); + } else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + try { + yield delay(this.responseDelay, abort)(void 0); + } catch (error4) { + stream.notifyError(error4); + return; + } + if (this.data.response instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.response); + return; + } + for (let msg of messages) { + stream.notifyMessage(msg); + try { + yield delay(this.betweenResponseDelay, abort)(void 0); + } catch (error4) { + stream.notifyError(error4); + return; + } + } + if (this.data.status instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.status); + return; + } + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.trailers); + return; + } + stream.notifyComplete(); + }); } - /** - * Read a new message from a JSON value. - */ - fromJson(json2, options) { - return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); } - /** - * Read a new message from a JSON string. - * This is equivalent to `T.fromJson(JSON.parse(json))`. - */ - fromJsonString(json2, options) { - let value = JSON.parse(json2); - return this.fromJson(value, options); + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); } - /** - * Write the message to canonical JSON value. - */ - toJson(message, options) { - return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } } - /** - * Convert the message to canonical JSON string. - * This is equivalent to `JSON.stringify(T.toJson(t))` - */ - toJsonString(message, options) { + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); + } + unary(method, input, options) { var _a; - let value = this.toJson(message, options); - return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); } - /** - * Write the message to binary format. - */ - toBinary(message, options) { - let opt = binary_writer_1.binaryWriteOptions(options); - return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); } - /** - * This is an internal method. If you just want to read a message from - * JSON, use `fromJson()` or `fromJsonString()`. - * - * Reads JSON value and merges the fields into the target - * according to protobuf rules. If the target is omitted, - * a new instance is created first. - */ - internalJsonRead(json2, options, target) { - if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refJsonReader.read(json2, message, options); - return message; + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + } + }; + exports2.TestTransport = TestTransport; + TestTransport.defaultHeaders = { + responseHeader: "test" + }; + TestTransport.defaultStatus = { + code: "OK", + detail: "all good" + }; + TestTransport.defaultTrailers = { + responseTrailer: "test" + }; + function delay(ms, abort) { + return (v) => new Promise((resolve5, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } else { + const id = setTimeout(() => resolve5(v), ms); + if (abort) { + abort.addEventListener("abort", (ev) => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } } - throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); + }); + } + var TestInputStream = class { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; } - /** - * This is an internal method. If you just want to write a message - * to JSON, use `toJson()` or `toJsonString(). - * - * Writes JSON value and returns it. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.write(message, options); + get sent() { + return this._sent; } - /** - * This is an internal method. If you just want to write a message - * in binary format, use `toBinary()`. - * - * Serializes the message in binary format and appends it to the given - * writer. Returns passed writer. - */ - internalBinaryWrite(message, writer, options) { - this.refBinWriter.write(message, writer, options); - return writer; + get completed() { + return this._completed; } - /** - * This is an internal method. If you just want to read a message from - * binary data, use `fromBinary()`. - * - * Reads data from binary format and merges the fields into - * the target according to protobuf rules. If the target is - * omitted, a new instance is created first. - */ - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refBinReader.read(reader, message, options, length); - return message; + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); + } + const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; + return Promise.resolve(void 0).then(() => { + this._sent.push(message); + }).then(delay(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); + } + const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; + return Promise.resolve(void 0).then(() => { + this._completed = true; + }).then(delay(delayMs, this.abort)); } }; - exports2.MessageType = MessageType; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js -var require_reflection_contains_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.containsMessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - function containsMessageType(msg) { - return msg[message_type_contract_1.MESSAGE_TYPE] != null; - } - exports2.containsMessageType = containsMessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js -var require_enum_object = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js +var require_rpc_interceptor = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; - function isEnumObject(arg) { - if (typeof arg != "object" || arg === null) { - return false; + exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; + var runtime_1 = require_commonjs11(); + function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + } + return tail(method, input, options); } - if (!arg.hasOwnProperty(0)) { - return false; + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); } - for (let k of Object.keys(arg)) { - let num = parseInt(k); - if (!Number.isNaN(num)) { - let nam = arg[num]; - if (nam === void 0) - return false; - if (arg[nam] !== num) - return false; - } else { - let num2 = arg[k]; - if (num2 === void 0) - return false; - if (typeof num2 !== "number") - return false; - if (arg[num2] === void 0) - return false; + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); } + return tail(method, options); } - return true; + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); + } + runtime_1.assertNever(kind); } - exports2.isEnumObject = isEnumObject; - function listEnumValues(enumObject) { - if (!isEnumObject(enumObject)) - throw new Error("not a typescript enum object"); - let values = []; - for (let [name, number] of Object.entries(enumObject)) - if (typeof number == "number") - values.push({ name, number }); - return values; + exports2.stackIntercept = stackIntercept; + function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); } - exports2.listEnumValues = listEnumValues; - function listEnumNames(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.name); + exports2.stackUnaryInterceptors = stackUnaryInterceptors; + function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); } - exports2.listEnumNames = listEnumNames; - function listEnumNumbers(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; + function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); } - exports2.listEnumNumbers = listEnumNumbers; + exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; + function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); + } + exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/index.js -var require_commonjs11 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js +var require_server_call_context = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var json_typings_1 = require_json_typings(); - Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { - return json_typings_1.typeofJsonValue; - } }); - Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { - return json_typings_1.isJsonObject; - } }); - var base64_1 = require_base642(); - Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { - return base64_1.base64decode; - } }); - Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { - return base64_1.base64encode; - } }); - var protobufjs_utf8_1 = require_protobufjs_utf8(); - Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { - return protobufjs_utf8_1.utf8read; - } }); - var binary_format_contract_1 = require_binary_format_contract(); - Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { - return binary_format_contract_1.WireType; - } }); - Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { - return binary_format_contract_1.mergeBinaryOptions; - } }); - Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { - return binary_format_contract_1.UnknownFieldHandler; - } }); - var binary_reader_1 = require_binary_reader(); - Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { - return binary_reader_1.BinaryReader; - } }); - Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { - return binary_reader_1.binaryReadOptions; - } }); - var binary_writer_1 = require_binary_writer(); - Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { - return binary_writer_1.BinaryWriter; - } }); - Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { - return binary_writer_1.binaryWriteOptions; - } }); - var pb_long_1 = require_pb_long(); - Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { - return pb_long_1.PbLong; - } }); - Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { - return pb_long_1.PbULong; - } }); - var json_format_contract_1 = require_json_format_contract(); - Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonReadOptions; - } }); - Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonWriteOptions; - } }); - Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { - return json_format_contract_1.mergeJsonOptions; - } }); - var message_type_contract_1 = require_message_type_contract(); - Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { - return message_type_contract_1.MESSAGE_TYPE; - } }); - var message_type_1 = require_message_type(); - Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { - return message_type_1.MessageType; - } }); - var reflection_info_1 = require_reflection_info(); - Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { - return reflection_info_1.ScalarType; - } }); - Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { - return reflection_info_1.LongType; - } }); - Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { - return reflection_info_1.RepeatType; - } }); - Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { - return reflection_info_1.normalizeFieldInfo; - } }); - Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { - return reflection_info_1.readFieldOptions; - } }); - Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { - return reflection_info_1.readFieldOption; - } }); - Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { - return reflection_info_1.readMessageOption; - } }); - var reflection_type_check_1 = require_reflection_type_check(); - Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { - return reflection_type_check_1.ReflectionTypeCheck; - } }); - var reflection_create_1 = require_reflection_create(); - Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { - return reflection_create_1.reflectionCreate; - } }); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { - return reflection_scalar_default_1.reflectionScalarDefault; - } }); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { - return reflection_merge_partial_1.reflectionMergePartial; - } }); - var reflection_equals_1 = require_reflection_equals(); - Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { - return reflection_equals_1.reflectionEquals; - } }); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { - return reflection_binary_reader_1.ReflectionBinaryReader; + exports2.ServerCallContextController = void 0; + var ServerCallContextController = class { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; + } + /** + * Set the call cancelled. + * + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. + */ + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } + } + } + /** + * Send response headers. + */ + sendResponseHeaders(data) { + this._sendRH(data); + } + /** + * Is the call cancelled? + * + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. + */ + get cancelled() { + return this._cancelled; + } + /** + * Add a callback for cancellation. + */ + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; + } + }; + exports2.ServerCallContextController = ServerCallContextController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var service_type_1 = require_service_type(); + Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { + return service_type_1.ServiceType; } }); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { - return reflection_binary_writer_1.ReflectionBinaryWriter; + var reflection_info_1 = require_reflection_info2(); + Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { + return reflection_info_1.readMethodOptions; } }); - var reflection_json_reader_1 = require_reflection_json_reader(); - Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { - return reflection_json_reader_1.ReflectionJsonReader; + Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { + return reflection_info_1.readMethodOption; } }); - var reflection_json_writer_1 = require_reflection_json_writer(); - Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { - return reflection_json_writer_1.ReflectionJsonWriter; + Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { + return reflection_info_1.readServiceOption; } }); - var reflection_contains_message_type_1 = require_reflection_contains_message_type(); - Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { - return reflection_contains_message_type_1.containsMessageType; + var rpc_error_1 = require_rpc_error(); + Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { + return rpc_error_1.RpcError; } }); - var oneof_1 = require_oneof(); - Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { - return oneof_1.isOneofGroup; + var rpc_options_1 = require_rpc_options(); + Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { + return rpc_options_1.mergeRpcOptions; } }); - Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { - return oneof_1.setOneofValue; + var rpc_output_stream_1 = require_rpc_output_stream(); + Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { + return rpc_output_stream_1.RpcOutputStreamController; } }); - Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { - return oneof_1.getOneofValue; + var test_transport_1 = require_test_transport(); + Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { + return test_transport_1.TestTransport; } }); - Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { - return oneof_1.clearOneofValue; + var deferred_1 = require_deferred(); + Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { + return deferred_1.Deferred; } }); - Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { - return oneof_1.getSelectedOneofValue; + Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { + return deferred_1.DeferredState; } }); - var enum_object_1 = require_enum_object(); - Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { - return enum_object_1.listEnumValues; + var duplex_streaming_call_1 = require_duplex_streaming_call(); + Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { + return duplex_streaming_call_1.DuplexStreamingCall; } }); - Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { - return enum_object_1.listEnumNames; + var client_streaming_call_1 = require_client_streaming_call(); + Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { + return client_streaming_call_1.ClientStreamingCall; } }); - Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { - return enum_object_1.listEnumNumbers; + var server_streaming_call_1 = require_server_streaming_call(); + Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { + return server_streaming_call_1.ServerStreamingCall; } }); - Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { - return enum_object_1.isEnumObject; + var unary_call_1 = require_unary_call(); + Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { + return unary_call_1.UnaryCall; } }); - var lower_camel_case_1 = require_lower_camel_case(); - Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { - return lower_camel_case_1.lowerCamelCase; + var rpc_interceptor_1 = require_rpc_interceptor(); + Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { + return rpc_interceptor_1.stackIntercept; } }); - var assert_1 = require_assert(); - Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { - return assert_1.assert; + Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackDuplexStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { - return assert_1.assertNever; + Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackClientStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { - return assert_1.assertInt32; + Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackServerStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { - return assert_1.assertUInt32; + Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackUnaryInterceptors; } }); - Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { - return assert_1.assertFloat32; + var server_call_context_1 = require_server_call_context(); + Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { + return server_call_context_1.ServerCallContextController; } }); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js -var require_reflection_info2 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js +var require_cachescope = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + exports2.CacheScope = void 0; var runtime_1 = require_commonjs11(); - function normalizeMethodInfo(method, service) { - var _a, _b, _c; - let m = method; - m.service = service; - m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); - m.serverStreaming = !!m.serverStreaming; - m.clientStreaming = !!m.clientStreaming; - m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; - m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; - return m; - } - exports2.normalizeMethodInfo = normalizeMethodInfo; - function readMethodOptions(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readMethodOptions = readMethodOptions; - function readMethodOption(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var CacheScope$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheScope", [ + { + no: 1, + name: "scope", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "permission", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + create(value) { + const message = { scope: "", permission: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string scope */ + 1: + message.scope = reader.string(); + break; + case /* int64 permission */ + 2: + message.permission = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.scope !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); + if (message.permission !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheScope = new CacheScope$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js +var require_cachemetadata = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheMetadata = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachescope_1 = require_cachescope(); + var CacheMetadata$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheMetadata", [ + { + no: 1, + name: "repository_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } + ]); + } + create(value) { + const message = { repositoryId: "0", scope: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 repository_id */ + 1: + message.repositoryId = reader.int64().toString(); + break; + case /* repeated github.actions.results.entities.v1.CacheScope scope */ + 2: + message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.repositoryId !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); + for (let i = 0; i < message.scope.length; i++) + cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheMetadata = new CacheMetadata$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js +var require_cache2 = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachemetadata_1 = require_cachemetadata(); + var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* string version */ + 3: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readMethodOption = readMethodOption; - function readServiceOption(service, extensionName, extensionType) { - const options = service.options; - if (!options) { - return void 0; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.version !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + }; + exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); + var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readServiceOption = readServiceOption; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js -var require_service_type = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceType = void 0; - var reflection_info_1 = require_reflection_info2(); - var ServiceType = class { - constructor(typeName, methods, options) { - this.typeName = typeName; - this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); - this.options = options !== null && options !== void 0 ? options : {}; + create(value) { + const message = { ok: false, signedUploadUrl: "", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.ServiceType = ServiceType; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js -var require_rpc_error = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcError = void 0; - var RpcError = class extends Error { - constructor(message, code = "UNKNOWN", meta) { - super(message); - this.name = "RpcError"; - Object.setPrototypeOf(this, new.target.prototype); - this.code = code; - this.meta = meta !== null && meta !== void 0 ? meta : {}; + exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); + var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size_bytes", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - toString() { - const l = [this.name + ": " + this.message]; - if (this.code) { - l.push(""); - l.push("Code: " + this.code); - } - if (this.serviceName && this.methodName) { - l.push("Method: " + this.serviceName + "/" + this.methodName); + create(value) { + const message = { key: "", sizeBytes: "0", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* int64 size_bytes */ + 3: + message.sizeBytes = reader.int64().toString(); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } - let m = Object.entries(this.meta); - if (m.length) { - l.push(""); - l.push("Meta:"); - for (let [k, v] of m) { - l.push(` ${k}: ${v}`); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.sizeBytes !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); + var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "entry_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, entryId: "0", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* int64 entry_id */ + 2: + message.entryId = reader.int64().toString(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - return l.join("\n"); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.entryId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.RpcError = RpcError; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js -var require_rpc_options = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeRpcOptions = void 0; - var runtime_1 = require_commonjs11(); - function mergeRpcOptions(defaults, options) { - if (!options) - return defaults; - let o = {}; - copy(defaults, o); - copy(options, o); - for (let key of Object.keys(options)) { - let val2 = options[key]; - switch (key) { - case "jsonOptions": - o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); - break; - case "binaryOptions": - o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); - break; - case "meta": - o.meta = {}; - copy(defaults.meta, o.meta); - copy(options.meta, o.meta); - break; - case "interceptors": - o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); - break; + exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); + var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "restore_keys", + kind: "scalar", + repeat: 2, + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", restoreKeys: [], version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* repeated string restore_keys */ + 3: + message.restoreKeys.push(reader.string()); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } + return message; } - return o; - } - exports2.mergeRpcOptions = mergeRpcOptions; - function copy(a, into) { - if (!a) - return; - let c = into; - for (let [k, v] of Object.entries(a)) { - if (v instanceof Date) - c[k] = new Date(v.getTime()); - else if (Array.isArray(v)) - c[k] = v.concat(); - else - c[k] = v; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + for (let i = 0; i < message.restoreKeys.length; i++) + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); + var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_download_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "matched_key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_download_url */ + 2: + message.signedDownloadUrl = reader.string(); + break; + case /* string matched_key */ + 3: + message.matchedKey = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedDownloadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); + if (message.matchedKey !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); + exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ + { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, + { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, + { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } + ]); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js -var require_deferred = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js +var require_cache_twirp_client = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Deferred = exports2.DeferredState = void 0; - var DeferredState; - (function(DeferredState2) { - DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; - DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; - DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; - })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); - var Deferred = class { - /** - * @param preventUnhandledRejectionWarning - prevents the warning - * "Unhandled Promise rejection" by adding a noop rejection handler. - * Working with calls returned from the runtime-rpc package in an - * async function usually means awaiting one call property after - * the other. This means that the "status" is not being awaited when - * an earlier await for the "headers" is rejected. This causes the - * "unhandled promise reject" warning. A more correct behaviour for - * calls might be to become aware whether at least one of the - * promises is handled and swallow the rejection warning for the - * others. - */ - constructor(preventUnhandledRejectionWarning = true) { - this._state = DeferredState.PENDING; - this._promise = new Promise((resolve5, reject) => { - this._resolve = resolve5; - this._reject = reject; + exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; + var cache_1 = require_cache2(); + var CacheServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); + } + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false }); - if (preventUnhandledRejectionWarning) { - this._promise.catch((_) => { - }); - } + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Get the current state of the promise. - */ - get state() { - return this._state; + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Get the deferred promise. - */ - get promise() { - return this._promise; + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Resolve the promise. Throws if the promise is already resolved or rejected. - */ - resolve(value) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); - this._resolve(value); - this._state = DeferredState.RESOLVED; + }; + exports2.CacheServiceClientJSON = CacheServiceClientJSON; + var CacheServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - /** - * Reject the promise. Throws if the promise is already resolved or rejected. - */ - reject(reason) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); - this._reject(reason); - this._state = DeferredState.REJECTED; + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); } - /** - * Resolve the promise. Ignore if not pending. - */ - resolvePending(val2) { - if (this._state === DeferredState.PENDING) - this.resolve(val2); + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); } - /** - * Reject the promise. Ignore if not pending. - */ - rejectPending(reason) { - if (this._state === DeferredState.PENDING) - this.reject(reason); + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.Deferred = Deferred; + exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js -var require_rpc_output_stream = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/util.js +var require_util10 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcOutputStreamController = void 0; - var deferred_1 = require_deferred(); - var runtime_1 = require_commonjs11(); - var RpcOutputStreamController = class { - constructor() { - this._lis = { - nxt: [], - msg: [], - err: [], - cmp: [] - }; - this._closed = false; - this._itState = { q: [] }; + exports2.maskSecretUrls = exports2.maskSigUrl = void 0; + var core_1 = require_core(); + function maskSigUrl(url) { + if (!url) + return; + try { + const parsedUrl = new URL(url); + const signature = parsedUrl.searchParams.get("sig"); + if (signature) { + (0, core_1.setSecret)(signature); + (0, core_1.setSecret)(encodeURIComponent(signature)); + } + } catch (error4) { + (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); } - // --- RpcOutputStream callback API - onNext(callback) { - return this.addLis(callback, this._lis.nxt); + } + exports2.maskSigUrl = maskSigUrl; + function maskSecretUrls(body) { + if (typeof body !== "object" || body === null) { + (0, core_1.debug)("body is not an object or is null"); + return; } - onMessage(callback) { - return this.addLis(callback, this._lis.msg); + if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { + maskSigUrl(body.signed_upload_url); } - onError(callback) { - return this.addLis(callback, this._lis.err); + if ("signed_download_url" in body && typeof body.signed_download_url === "string") { + maskSigUrl(body.signed_download_url); } - onComplete(callback) { - return this.addLis(callback, this._lis.cmp); + } + exports2.maskSecretUrls = maskSecretUrls; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js +var require_cacheTwirpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); } - addLis(callback, list) { - list.push(callback); - return () => { - let i = list.indexOf(callback); - if (i >= 0) - list.splice(i, 1); - }; + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.internalCacheTwirpClient = void 0; + var core_1 = require_core(); + var user_agent_1 = require_user_agent(); + var errors_1 = require_errors2(); + var config_1 = require_config(); + var cacheUtils_1 = require_cacheUtils(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib4(); + var cache_twirp_client_1 = require_cache_twirp_client(); + var util_1 = require_util10(); + var CacheServiceClient = class { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3e3; + this.retryMultiplier = 1.5; + const token = (0, cacheUtils_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getCacheServiceURL)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; + } + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) + ]); } - // remove all listeners - clearLis() { - for (let l of Object.values(this._lis)) - l.splice(0, l.length); + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { + return __awaiter4(this, void 0, void 0, function* () { + const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url}`); + const headers = { + "Content-Type": contentType + }; + try { + const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { + return this.httpClient.post(url, JSON.stringify(data), headers); + })); + return body; + } catch (error4) { + throw new Error(`Failed to ${method}: ${error4.message}`); + } + }); } - // --- Controller API - /** - * Is this stream already closed by a completion or error? - */ - get closed() { - return this._closed !== false; + retryableRequest(operation) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ""; + let rawBody = ""; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, util_1.maskSecretUrls)(body); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } catch (error4) { + if (error4 instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + } + if (error4 instanceof errors_1.UsageError) { + throw error4; + } + if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { + throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + } + isRetryable = true; + errorMessage = error4.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; + } + throw new Error(`Request failed`); + }); } - /** - * Emit message, close with error, or close successfully, but only one - * at a time. - * Can be used to wrap a stream by using the other stream's `onNext`. - */ - notifyNext(message, error4, complete) { - runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); - if (message) - this.notifyMessage(message); - if (error4) - this.notifyError(error4); - if (complete) - this.notifyComplete(); + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; } - /** - * Emits a new message. Throws if stream is closed. - * - * Triggers onNext and onMessage callbacks. - */ - notifyMessage(message) { - runtime_1.assert(!this.closed, "stream is closed"); - this.pushIt({ value: message, done: false }); - this._lis.msg.forEach((l) => l(message)); - this._lis.nxt.forEach((l) => l(message, void 0, false)); + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); } - /** - * Closes the stream with an error. Throws if stream is closed. - * - * Triggers onNext and onError callbacks. - */ - notifyError(error4) { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = error4; - this.pushIt(error4); - this._lis.err.forEach((l) => l(error4)); - this._lis.nxt.forEach((l) => l(void 0, error4, false)); - this.clearLis(); + sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => setTimeout(resolve5, milliseconds)); + }); } - /** - * Closes the stream successfully. Throws if stream is closed. - * - * Triggers onNext and onComplete callbacks. - */ - notifyComplete() { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = true; - this.pushIt({ value: null, done: true }); - this._lis.cmp.forEach((l) => l()); - this._lis.nxt.forEach((l) => l(void 0, void 0, true)); - this.clearLis(); + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error("attempt should be a positive integer"); + } + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } - /** - * Creates an async iterator (that can be used with `for await {...}`) - * to consume the stream. - * - * Some things to note: - * - If an error occurs, the `for await` will throw it. - * - If an error occurred before the `for await` was started, `for await` - * will re-throw it. - * - If the stream is already complete, the `for await` will be empty. - * - If your `for await` consumes slower than the stream produces, - * for example because you are relaying messages in a slow operation, - * messages are queued. - */ - [Symbol.asyncIterator]() { - if (this._closed === true) - this.pushIt({ value: null, done: true }); - else if (this._closed !== false) - this.pushIt(this._closed); - return { - next: () => { - let state = this._itState; - runtime_1.assert(state, "bad state"); - runtime_1.assert(!state.p, "iterator contract broken"); - let first = state.q.shift(); - if (first) - return "value" in first ? Promise.resolve(first) : Promise.reject(first); - state.p = new deferred_1.Deferred(); - return state.p.promise; - } - }; + }; + function internalCacheTwirpClient(options) { + const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new cache_twirp_client_1.CacheServiceClientJSON(client); + } + exports2.internalCacheTwirpClient = internalCacheTwirpClient; + } +}); + +// node_modules/@actions/cache/lib/internal/tar.js +var require_tar = __commonJS({ + "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - // "push" a new iterator result. - // this either resolves a pending promise, or enqueues the result. - pushIt(result) { - let state = this._itState; - if (state.p) { - const p = state.p; - runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); - "value" in result ? p.resolve(result) : p.reject(result); - delete state.p; - } else { - state.q.push(result); - } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.RpcOutputStreamController = RpcOutputStreamController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js -var require_unary_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve5) { @@ -72396,47 +75602,221 @@ var require_unary_call = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UnaryCall = void 0; - var UnaryCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * If you are only interested in the final outcome of this call, - * you can await it to receive a `FinishedUnaryCall`. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - response, - status, - trailers - }; - }); - } - }; - exports2.UnaryCall = UnaryCall; + exports2.createTar = exports2.extractTar = exports2.listTar = void 0; + var exec_1 = require_exec(); + var io5 = __importStar4(require_io()); + var fs_1 = require("fs"); + var path7 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var IS_WINDOWS = process.platform === "win32"; + function getTarPath() { + return __awaiter4(this, void 0, void 0, function* () { + switch (process.platform) { + case "win32": { + const gnuTar = yield utils.getGnuTarPathOnWindows(); + const systemTar = constants_1.SystemTarPathOnWindows; + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else if ((0, fs_1.existsSync)(systemTar)) { + return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; + } + break; + } + case "darwin": { + const gnuTar = yield io5.which("gtar", false); + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else { + return { + path: yield io5.which("tar", true), + type: constants_1.ArchiveToolType.BSD + }; + } + } + default: + break; + } + return { + path: yield io5.which("tar", true), + type: constants_1.ArchiveToolType.GNU + }; + }); + } + function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + const args = [`"${tarPath.path}"`]; + const cacheFileName = utils.getCacheFileName(compressionMethod); + const tarFile = "cache.tar"; + const workingDirectory = getWorkingDirectory(); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (type2) { + case "create": + args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); + break; + case "extract": + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path7.sep}`, "g"), "/")); + break; + case "list": + args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "-P"); + break; + } + if (tarPath.type === constants_1.ArchiveToolType.GNU) { + switch (process.platform) { + case "win32": + args.push("--force-local"); + break; + case "darwin": + args.push("--delay-directory-restore"); + break; + } + } + return args; + }); + } + function getCommands(compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + let args; + const tarPath = yield getTarPath(); + const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); + const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + if (BSD_TAR_ZSTD && type2 !== "create") { + args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; + } else { + args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; + } + if (BSD_TAR_ZSTD) { + return args; + } + return [args.join(" ")]; + }); + } + function getWorkingDirectory() { + var _a; + return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); + } + function getDecompressionProgram(tarPath, compressionMethod, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -d --long=30 --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path7.sep}`, "g"), "/") + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -d --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path7.sep}`, "g"), "/") + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; + default: + return ["-z"]; + } + }); + } + function getCompressionProgram(tarPath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheFileName = utils.getCacheFileName(compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --long=30 --force -o", + cacheFileName.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), + constants_1.TarFilename + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --force -o", + cacheFileName.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), + constants_1.TarFilename + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; + default: + return ["-z"]; + } + }); + } + function execCommands(commands, cwd) { + return __awaiter4(this, void 0, void 0, function* () { + for (const command of commands) { + try { + yield (0, exec_1.exec)(command, void 0, { + cwd, + env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) + }); + } catch (error4) { + throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + } + } + }); + } + function listTar(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const commands = yield getCommands(compressionMethod, "list", archivePath); + yield execCommands(commands); + }); + } + exports2.listTar = listTar; + function extractTar2(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const workingDirectory = getWorkingDirectory(); + yield io5.mkdirP(workingDirectory); + const commands = yield getCommands(compressionMethod, "extract", archivePath); + yield execCommands(commands); + }); + } + exports2.extractTar = extractTar2; + function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + (0, fs_1.writeFileSync)(path7.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); + const commands = yield getCommands(compressionMethod, "create"); + yield execCommands(commands, archiveFolder); + }); + } + exports2.createTar = createTar; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js -var require_server_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { +// node_modules/@actions/cache/lib/cache.js +var require_cache3 = __commonJS({ + "node_modules/@actions/cache/lib/cache.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve5) { @@ -72450,200 +75830,421 @@ var require_server_streaming_call = __commonJS({ } catch (e) { reject(e); } - } - function rejected(value) { + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + var core14 = __importStar4(require_core()); + var path7 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var cacheHttpClient = __importStar4(require_cacheHttpClient()); + var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); + var config_1 = require_config(); + var tar_1 = require_tar(); + var http_client_1 = require_lib4(); + var ValidationError = class _ValidationError extends Error { + constructor(message) { + super(message); + this.name = "ValidationError"; + Object.setPrototypeOf(this, _ValidationError.prototype); + } + }; + exports2.ValidationError = ValidationError; + var ReserveCacheError = class _ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = "ReserveCacheError"; + Object.setPrototypeOf(this, _ReserveCacheError.prototype); + } + }; + exports2.ReserveCacheError = ReserveCacheError; + var FinalizeCacheError = class _FinalizeCacheError extends Error { + constructor(message) { + super(message); + this.name = "FinalizeCacheError"; + Object.setPrototypeOf(this, _FinalizeCacheError.prototype); + } + }; + exports2.FinalizeCacheError = FinalizeCacheError; + function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); + } + } + function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } + } + function isFeatureAvailable() { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + switch (cacheServiceVersion) { + case "v2": + return !!process.env["ACTIONS_RESULTS_URL"]; + case "v1": + default: + return !!process.env["ACTIONS_CACHE_URL"]; + } + } + exports2.isFeatureAvailable = isFeatureAvailable; + function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core14.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + switch (cacheServiceVersion) { + case "v2": + return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + case "v1": + default: + return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + } + }); + } + exports2.restoreCache = restoreCache3; + function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core14.debug("Resolved Keys:"); + core14.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + let archivePath = ""; + try { + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod, + enableCrossOsArchive + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + return void 0; + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core14.info("Lookup only - skipping download"); + return cacheEntry.cacheKey; + } + archivePath = path7.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core14.debug(`Archive Path: ${archivePath}`); + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core14.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core14.info("Cache restored successfully"); + return cacheEntry.cacheKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core14.error(`Failed to restore: ${error4.message}`); + } else { + core14.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core14.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core14.debug("Resolved Keys:"); + core14.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + let archivePath = ""; + try { + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + const compressionMethod = yield utils.getCompressionMethod(); + const request = { + key: primaryKey, + restoreKeys, + version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) + }; + const response = yield twirpClient.GetCacheEntryDownloadURL(request); + if (!response.ok) { + core14.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); + return void 0; + } + const isRestoreKeyMatch = request.key !== response.matchedKey; + if (isRestoreKeyMatch) { + core14.info(`Cache hit for restore-key: ${response.matchedKey}`); + } else { + core14.info(`Cache hit for: ${response.matchedKey}`); + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core14.info("Lookup only - skipping download"); + return response.matchedKey; + } + archivePath = path7.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core14.debug(`Archive path: ${archivePath}`); + core14.debug(`Starting download of archive to: ${archivePath}`); + yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + if (core14.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core14.info("Cache restored successfully"); + return response.matchedKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core14.error(`Failed to restore: ${error4.message}`); + } else { + core14.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + if (archivePath) { + yield utils.unlinkFile(archivePath); + } + } catch (error4) { + core14.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function saveCache3(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core14.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + checkKey(key); + switch (cacheServiceVersion) { + case "v2": + return yield saveCacheV2(paths, key, options, enableCrossOsArchive); + case "v1": + default: + return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + } + }); + } + exports2.saveCache = saveCache3; + function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { + var _a, _b, _c, _d, _e; + return __awaiter4(this, void 0, void 0, function* () { + const compressionMethod = yield utils.getCompressionMethod(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core14.debug("Cache Paths:"); + core14.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path7.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core14.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core14.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const fileSizeLimit = 10 * 1024 * 1024 * 1024; + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core14.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core14.debug("Reserving Cache"); + const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod, + enableCrossOsArchive, + cacheSize: archiveFileSize + }); + if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { + cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { + throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); + } else { + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); + } + core14.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError.name) { + core14.info(`Failed to save: ${typedError.message}`); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core14.error(`Failed to save: ${typedError.message}`); + } else { + core14.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + yield utils.unlinkFile(archivePath); + } catch (error4) { + core14.debug(`Failed to delete archive: ${error4}`); } } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return cacheId; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerStreamingCall = void 0; - var ServerStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * You should first setup some listeners to the `request` to - * see the actual messages the server replied with. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - status, - trailers + } + function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); + const compressionMethod = yield utils.getCompressionMethod(); + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core14.debug("Cache Paths:"); + core14.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path7.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core14.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core14.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core14.debug(`File Size: ${archiveFileSize}`); + options.archiveSizeBytes = archiveFileSize; + core14.debug("Reserving Cache"); + const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); + const request = { + key, + version }; - }); - } - }; - exports2.ServerStreamingCall = ServerStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js -var require_client_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { + let signedUploadUrl; try { - step(generator.next(value)); - } catch (e) { - reject(e); + const response = yield twirpClient.CreateCacheEntry(request); + if (!response.ok) { + if (response.message) { + core14.warning(`Cache reservation failed: ${response.message}`); + } + throw new Error(response.message || "Response was not ok"); + } + signedUploadUrl = response.signedUploadUrl; + } catch (error4) { + core14.debug(`Failed to reserve cache: ${error4}`); + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); } - } - function rejected(value) { + core14.debug(`Attempting to upload cache located at: ${archivePath}`); + yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); + const finalizeRequest = { + key, + version, + sizeBytes: `${archiveFileSize}` + }; + const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); + core14.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); + if (!finalizeResponse.ok) { + if (finalizeResponse.message) { + throw new FinalizeCacheError(finalizeResponse.message); + } + throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); + } + cacheId = parseInt(finalizeResponse.entryId); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError.name) { + core14.info(`Failed to save: ${typedError.message}`); + } else if (typedError.name === FinalizeCacheError.name) { + core14.warning(typedError.message); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core14.error(`Failed to save: ${typedError.message}`); + } else { + core14.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + yield utils.unlinkFile(archivePath); + } catch (error4) { + core14.debug(`Failed to delete archive: ${error4}`); } } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return cacheId; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ClientStreamingCall = void 0; - var ClientStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - response, - status, - trailers - }; - }); - } - }; - exports2.ClientStreamingCall = ClientStreamingCall; + } } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js -var require_duplex_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { +// node_modules/@actions/tool-cache/lib/manifest.js +var require_manifest = __commonJS({ + "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DuplexStreamingCall = void 0; - var DuplexStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - status, - trailers - }; - }); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.DuplexStreamingCall = DuplexStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js -var require_test_transport = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve5) { @@ -72666,1204 +76267,824 @@ var require_test_transport = __commonJS({ } } function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TestTransport = void 0; - var rpc_error_1 = require_rpc_error(); - var runtime_1 = require_commonjs11(); - var rpc_output_stream_1 = require_rpc_output_stream(); - var rpc_options_1 = require_rpc_options(); - var unary_call_1 = require_unary_call(); - var server_streaming_call_1 = require_server_streaming_call(); - var client_streaming_call_1 = require_client_streaming_call(); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - var TestTransport = class _TestTransport { - /** - * Initialize with mock data. Omitted fields have default value. - */ - constructor(data) { - this.suppressUncaughtRejections = true; - this.headerDelay = 10; - this.responseDelay = 50; - this.betweenResponseDelay = 10; - this.afterResponseDelay = 10; - this.data = data !== null && data !== void 0 ? data : {}; - } - /** - * Sent message(s) during the last operation. - */ - get sentMessages() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.sent; - } else if (typeof this.lastInput == "object") { - return [this.lastInput.single]; - } - return []; - } - /** - * Sending message(s) completed? - */ - get sendComplete() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.completed; - } else if (typeof this.lastInput == "object") { - return true; - } - return false; - } - // Creates a promise for response headers from the mock data. - promiseHeaders() { - var _a; - const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; - return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); - } - // Creates a promise for a single, valid, message from the mock data. - promiseSingleResponse(method) { - if (this.data.response instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.response); - } - let r; - if (Array.isArray(this.data.response)) { - runtime_1.assert(this.data.response.length > 0); - r = this.data.response[0]; - } else if (this.data.response !== void 0) { - r = this.data.response; - } else { - r = method.O.create(); - } - runtime_1.assert(method.O.is(r)); - return Promise.resolve(r); - } - /** - * Pushes response messages from the mock data to the output stream. - * If an error response, status or trailers are mocked, the stream is - * closed with the respective error. - * Otherwise, stream is completed successfully. - * - * The returned promise resolves when the stream is closed. It should - * not reject. If it does, code is broken. - */ - streamResponses(method, stream, abort) { - return __awaiter4(this, void 0, void 0, function* () { - const messages = []; - if (this.data.response === void 0) { - messages.push(method.O.create()); - } else if (Array.isArray(this.data.response)) { - for (let msg of this.data.response) { - runtime_1.assert(method.O.is(msg)); - messages.push(msg); - } - } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { - runtime_1.assert(method.O.is(this.data.response)); - messages.push(this.data.response); - } - try { - yield delay(this.responseDelay, abort)(void 0); - } catch (error4) { - stream.notifyError(error4); - return; - } - if (this.data.response instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.response); - return; - } - for (let msg of messages) { - stream.notifyMessage(msg); - try { - yield delay(this.betweenResponseDelay, abort)(void 0); - } catch (error4) { - stream.notifyError(error4); - return; - } - } - if (this.data.status instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.status); - return; - } - if (this.data.trailers instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.trailers); - return; - } - stream.notifyComplete(); - }); - } - // Creates a promise for response status from the mock data. - promiseStatus() { - var _a; - const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; - return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); - } - // Creates a promise for response trailers from the mock data. - promiseTrailers() { - var _a; - const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; - return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); - } - maybeSuppressUncaught(...promise) { - if (this.suppressUncaughtRejections) { - for (let p of promise) { - p.catch(() => { - }); - } - } - } - mergeOptions(options) { - return rpc_options_1.mergeRpcOptions({}, options); - } - unary(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); - } - serverStreaming(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); - } - clientStreaming(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); - } - duplex(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); - } - }; - exports2.TestTransport = TestTransport; - TestTransport.defaultHeaders = { - responseHeader: "test" - }; - TestTransport.defaultStatus = { - code: "OK", - detail: "all good" - }; - TestTransport.defaultTrailers = { - responseTrailer: "test" + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - function delay(ms, abort) { - return (v) => new Promise((resolve5, reject) => { - if (abort === null || abort === void 0 ? void 0 : abort.aborted) { - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - } else { - const id = setTimeout(() => resolve5(v), ms); - if (abort) { - abort.addEventListener("abort", (ev) => { - clearTimeout(id); - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; + var semver8 = __importStar4(require_semver2()); + var core_1 = require_core(); + var os2 = require("os"); + var cp = require("child_process"); + var fs7 = require("fs"); + function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os2.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); + if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + file = candidate.files.find((item) => { + (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module2.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } else { + chk = semver8.satisfies(osVersion, item.platform_version); + } + } + return chk; }); + if (file) { + (0, core_1.debug)(`matched ${candidate.version}`); + match = candidate; + break; + } } } + if (match && file) { + result = Object.assign({}, match); + result.files = [file]; + } + return result; }); } - var TestInputStream = class { - constructor(data, abort) { - this._completed = false; - this._sent = []; - this.data = data; - this.abort = abort; - } - get sent() { - return this._sent; - } - get completed() { - return this._completed; - } - send(message) { - if (this.data.inputMessage instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputMessage); + exports2._findMatch = _findMatch; + function _getOsVersion() { + const plat = os2.platform(); + let version = ""; + if (plat === "darwin") { + version = cp.execSync("sw_vers -productVersion").toString(); + } else if (plat === "linux") { + const lsbContents = module2.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split("\n"); + for (const line of lines) { + const parts = line.split("="); + if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { + version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); + break; + } + } } - const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; - return Promise.resolve(void 0).then(() => { - this._sent.push(message); - }).then(delay(delayMs, this.abort)); } - complete() { - if (this.data.inputComplete instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputComplete); - } - const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; - return Promise.resolve(void 0).then(() => { - this._completed = true; - }).then(delay(delayMs, this.abort)); + return version; + } + exports2._getOsVersion = _getOsVersion; + function _readLinuxVersionFile() { + const lsbReleaseFile = "/etc/lsb-release"; + const osReleaseFile = "/etc/os-release"; + let contents = ""; + if (fs7.existsSync(lsbReleaseFile)) { + contents = fs7.readFileSync(lsbReleaseFile).toString(); + } else if (fs7.existsSync(osReleaseFile)) { + contents = fs7.readFileSync(osReleaseFile).toString(); } - }; + return contents; + } + exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js -var require_rpc_interceptor = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; - var runtime_1 = require_commonjs11(); - function stackIntercept(kind, transport, method, options, input) { - var _a, _b, _c, _d; - if (kind == "unary") { - let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); - for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); - } - return tail(method, input, options); - } - if (kind == "serverStreaming") { - let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); - for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); - } - return tail(method, input, options); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - if (kind == "clientStreaming") { - let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); - for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - return tail(method, options); - } - if (kind == "duplex") { - let tail = (mtd, opt) => transport.duplex(mtd, opt); - for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - return tail(method, options); + } else { + return void 0; } - runtime_1.assertNever(kind); - } - exports2.stackIntercept = stackIntercept; - function stackUnaryInterceptors(transport, method, input, options) { - return stackIntercept("unary", transport, method, options, input); - } - exports2.stackUnaryInterceptors = stackUnaryInterceptors; - function stackServerStreamingInterceptors(transport, method, input, options) { - return stackIntercept("serverStreaming", transport, method, options, input); } - exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; - function stackClientStreamingInterceptors(transport, method, options) { - return stackIntercept("clientStreaming", transport, method, options); - } - exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; - function stackDuplexStreamingInterceptors(transport, method, options) { - return stackIntercept("duplex", transport, method, options); - } - exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js -var require_server_call_context = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerCallContextController = void 0; - var ServerCallContextController = class { - constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { - this._cancelled = false; - this._listeners = []; - this.method = method; - this.headers = headers; - this.deadline = deadline; - this.trailers = {}; - this._sendRH = sendResponseHeadersFn; - this.status = defaultStatus; + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - /** - * Set the call cancelled. - * - * Invokes all callbacks registered with onCancel() and - * sets `cancelled = true`. - */ - notifyCancelled() { - if (!this._cancelled) { - this._cancelled = true; - for (let l of this._listeners) { - l(); - } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - /** - * Send response headers. - */ - sendResponseHeaders(data) { - this._sendRH(data); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - /** - * Is the call cancelled? - * - * When the client closes the connection before the server - * is done, the call is cancelled. - * - * If you want to cancel a request on the server, throw a - * RpcError with the CANCELLED status code. - */ - get cancelled() { - return this._cancelled; + get username() { + return this._decodedUsername; } - /** - * Add a callback for cancellation. - */ - onCancel(callback) { - const l = this._listeners; - l.push(callback); - return () => { - let i = l.indexOf(callback); - if (i >= 0) - l.splice(i, 1); - }; + get password() { + return this._decodedPassword; } }; - exports2.ServerCallContextController = ServerCallContextController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js -var require_commonjs12 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var service_type_1 = require_service_type(); - Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { - return service_type_1.ServiceType; - } }); - var reflection_info_1 = require_reflection_info2(); - Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { - return reflection_info_1.readMethodOptions; - } }); - Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { - return reflection_info_1.readMethodOption; - } }); - Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { - return reflection_info_1.readServiceOption; - } }); - var rpc_error_1 = require_rpc_error(); - Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { - return rpc_error_1.RpcError; - } }); - var rpc_options_1 = require_rpc_options(); - Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { - return rpc_options_1.mergeRpcOptions; - } }); - var rpc_output_stream_1 = require_rpc_output_stream(); - Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { - return rpc_output_stream_1.RpcOutputStreamController; - } }); - var test_transport_1 = require_test_transport(); - Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { - return test_transport_1.TestTransport; - } }); - var deferred_1 = require_deferred(); - Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { - return deferred_1.Deferred; - } }); - Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { - return deferred_1.DeferredState; - } }); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { - return duplex_streaming_call_1.DuplexStreamingCall; - } }); - var client_streaming_call_1 = require_client_streaming_call(); - Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { - return client_streaming_call_1.ClientStreamingCall; - } }); - var server_streaming_call_1 = require_server_streaming_call(); - Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { - return server_streaming_call_1.ServerStreamingCall; - } }); - var unary_call_1 = require_unary_call(); - Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { - return unary_call_1.UnaryCall; - } }); - var rpc_interceptor_1 = require_rpc_interceptor(); - Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { - return rpc_interceptor_1.stackIntercept; - } }); - Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackDuplexStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackClientStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackServerStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackUnaryInterceptors; - } }); - var server_call_context_1 = require_server_call_context(); - Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { - return server_call_context_1.ServerCallContextController; - } }); } }); -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js -var require_cachescope = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheScope = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var CacheScope$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheScope", [ - { - no: 1, - name: "scope", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "permission", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve5) { + resolve5(value); + }); + } + return new (P || (P = Promise))(function(resolve5, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - ]); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - create(value) { - const message = { scope: "", permission: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string scope */ - 1: - message.scope = reader.string(); - break; - case /* int64 permission */ - 2: - message.permission = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); + }); } - internalBinaryWrite(message, writer, options) { - if (message.scope !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); - if (message.permission !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); + }); } }; - exports2.CacheScope = new CacheScope$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js -var require_cachemetadata = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheMetadata = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachescope_1 = require_cachescope(); - var CacheMetadata$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheMetadata", [ - { - no: 1, - name: "repository_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } - ]); - } - create(value) { - const message = { repositoryId: "0", scope: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int64 repository_id */ - 1: - message.repositoryId = reader.int64().toString(); - break; - case /* repeated github.actions.results.entities.v1.CacheScope scope */ - 2: - message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.repositoryId !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); - for (let i = 0; i < message.scope.length; i++) - cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.CacheMetadata = new CacheMetadata$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js -var require_cache2 = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachemetadata_1 = require_cachemetadata(); - var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - create(value) { - const message = { key: "", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* string version */ - 3: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.version !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - }; - exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); - var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_upload_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - create(value) { - const message = { ok: false, signedUploadUrl: "", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_upload_url */ - 2: - message.signedUploadUrl = reader.string(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - }; - exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); - var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "size_bytes", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - create(value) { - const message = { key: "", sizeBytes: "0", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* int64 size_bytes */ - 3: - message.sizeBytes = reader.int64().toString(); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - return message; + this._disposed = true; } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.sizeBytes !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); } - }; - exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); - var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "entry_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } - ]); - } - create(value) { - const message = { ok: false, entryId: "0", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 entry_id */ - 2: - message.entryId = reader.int64().toString(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.entryId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } - }; - exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); - var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "restore_keys", - kind: "scalar", - repeat: 2, - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } - ]); + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } - create(value) { - const message = { key: "", restoreKeys: [], version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* repeated string restore_keys */ - 3: - message.restoreKeys.push(reader.string()); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - for (let i = 0; i < message.restoreKeys.length; i++) - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - }; - exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); - var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_download_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "matched_key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - ]); - } - create(value) { - const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + } + return info6; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_download_url */ - 2: - message.signedDownloadUrl = reader.string(); - break; - case /* string matched_key */ - 3: - message.matchedKey = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - return message; + return lowercaseKeys(headers || {}); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedDownloadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); - if (message.matchedKey !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - }; - exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); - exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ - { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, - { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, - { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } - ]); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js -var require_cache_twirp_client = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; - var cache_1 = require_cache2(); - var CacheServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false - }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { - ignoreUnknownFields: true + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); + } + })); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); - } - }; - exports2.CacheServiceClientJSON = CacheServiceClientJSON; - var CacheServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); - } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); - } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); - } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/cache/lib/internal/shared/util.js -var require_util10 = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.maskSecretUrls = exports2.maskSigUrl = void 0; - var core_1 = require_core(); - function maskSigUrl(url) { - if (!url) - return; - try { - const parsedUrl = new URL(url); - const signature = parsedUrl.searchParams.get("sig"); - if (signature) { - (0, core_1.setSecret)(signature); - (0, core_1.setSecret)(encodeURIComponent(signature)); - } - } catch (error4) { - (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); - } - } - exports2.maskSigUrl = maskSigUrl; - function maskSecretUrls(body) { - if (typeof body !== "object" || body === null) { - (0, core_1.debug)("body is not an object or is null"); - return; - } - if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { - maskSigUrl(body.signed_upload_url); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - if ("signed_download_url" in body && typeof body.signed_download_url === "string") { - maskSigUrl(body.signed_download_url); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - } - exports2.maskSecretUrls = maskSecretUrls; - } -}); - -// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js -var require_cacheTwirpClient = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { - "use strict"; + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve5) { @@ -73892,154 +77113,56 @@ var require_cacheTwirpClient = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.internalCacheTwirpClient = void 0; - var core_1 = require_core(); - var user_agent_1 = require_user_agent(); - var errors_1 = require_errors2(); - var config_1 = require_config(); - var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); - var cache_twirp_client_1 = require_cache_twirp_client(); - var util_1 = require_util10(); - var CacheServiceClient = class { - constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { - this.maxAttempts = 5; - this.baseRetryIntervalMilliseconds = 3e3; - this.retryMultiplier = 1.5; - const token = (0, cacheUtils_1.getRuntimeToken)(); - this.baseUrl = (0, config_1.getCacheServiceURL)(); - if (maxAttempts) { - this.maxAttempts = maxAttempts; - } - if (baseRetryIntervalMilliseconds) { - this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + exports2.RetryHelper = void 0; + var core14 = __importStar4(require_core()); + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); } - if (retryMultiplier) { - this.retryMultiplier = retryMultiplier; + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); } - this.httpClient = new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(token) - ]); - } - // This function satisfies the Rpc interface. It is compatible with the JSON - // JSON generated client. - request(service, method, contentType, data) { - return __awaiter4(this, void 0, void 0, function* () { - const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; - (0, core_1.debug)(`[Request] ${method} ${url}`); - const headers = { - "Content-Type": contentType - }; - try { - const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { - return this.httpClient.post(url, JSON.stringify(data), headers); - })); - return body; - } catch (error4) { - throw new Error(`Failed to ${method}: ${error4.message}`); - } - }); } - retryableRequest(operation) { + execute(action, isRetryable) { return __awaiter4(this, void 0, void 0, function* () { - let attempt = 0; - let errorMessage = ""; - let rawBody = ""; + let attempt = 1; while (attempt < this.maxAttempts) { - let isRetryable = false; try { - const response = yield operation(); - const statusCode = response.message.statusCode; - rawBody = yield response.readBody(); - (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); - (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); - const body = JSON.parse(rawBody); - (0, util_1.maskSecretUrls)(body); - (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); - if (this.isSuccessStatusCode(statusCode)) { - return { response, body }; - } - isRetryable = this.isRetryableHttpStatusCode(statusCode); - errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; - if (body.msg) { - if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { - throw new errors_1.UsageError(); - } - errorMessage = `${errorMessage}: ${body.msg}`; - } - } catch (error4) { - if (error4 instanceof SyntaxError) { - (0, core_1.debug)(`Raw Body: ${rawBody}`); - } - if (error4 instanceof errors_1.UsageError) { - throw error4; - } - if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { - throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; } - isRetryable = true; - errorMessage = error4.message; - } - if (!isRetryable) { - throw new Error(`Received non-retryable error: ${errorMessage}`); - } - if (attempt + 1 === this.maxAttempts) { - throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + core14.info(err.message); } - const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); - (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); - yield this.sleep(retryTimeMilliseconds); + const seconds = this.getSleepAmount(); + core14.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); attempt++; } - throw new Error(`Request failed`); + return yield action(); }); } - isSuccessStatusCode(statusCode) { - if (!statusCode) - return false; - return statusCode >= 200 && statusCode < 300; - } - isRetryableHttpStatusCode(statusCode) { - if (!statusCode) - return false; - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.GatewayTimeout, - http_client_1.HttpCodes.InternalServerError, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.TooManyRequests - ]; - return retryableStatusCodes.includes(statusCode); + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; } - sleep(milliseconds) { + sleep(seconds) { return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve5) => setTimeout(resolve5, milliseconds)); + return new Promise((resolve5) => setTimeout(resolve5, seconds * 1e3)); }); } - getExponentialRetryTimeMilliseconds(attempt) { - if (attempt < 0) { - throw new Error("attempt should be a positive integer"); - } - if (attempt === 0) { - return this.baseRetryIntervalMilliseconds; - } - const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); - const maxTime = minTime * this.retryMultiplier; - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); - } }; - function internalCacheTwirpClient(options) { - const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); - return new cache_twirp_client_1.CacheServiceClientJSON(client); - } - exports2.internalCacheTwirpClient = internalCacheTwirpClient; + exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/cache/lib/internal/tar.js -var require_tar = __commonJS({ - "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74096,866 +77219,610 @@ var require_tar = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTar = exports2.extractTar = exports2.listTar = void 0; - var exec_1 = require_exec(); + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; + var core14 = __importStar4(require_core()); var io5 = __importStar4(require_io()); - var fs_1 = require("fs"); + var crypto = __importStar4(require("crypto")); + var fs7 = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os2 = __importStar4(require("os")); var path7 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var constants_1 = require_constants7(); + var httpm = __importStar4(require_lib5()); + var semver8 = __importStar4(require_semver2()); + var stream = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError2 = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + exports2.HTTPError = HTTPError2; var IS_WINDOWS = process.platform === "win32"; - function getTarPath() { + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - switch (process.platform) { - case "win32": { - const gnuTar = yield utils.getGnuTarPathOnWindows(); - const systemTar = constants_1.SystemTarPathOnWindows; - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else if ((0, fs_1.existsSync)(systemTar)) { - return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; - } - break; - } - case "darwin": { - const gnuTar = yield io5.which("gtar", false); - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else { - return { - path: yield io5.which("tar", true), - type: constants_1.ArchiveToolType.BSD - }; + dest = dest || path7.join(_getTempDirectory(), crypto.randomUUID()); + yield io5.mkdirP(path7.dirname(dest)); + core14.debug(`Downloading ${url}`); + core14.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError2 && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; } } - default: - break; - } - return { - path: yield io5.which("tar", true), - type: constants_1.ArchiveToolType.GNU - }; + return true; + }); }); } - function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - const args = [`"${tarPath.path}"`]; - const cacheFileName = utils.getCacheFileName(compressionMethod); - const tarFile = "cache.tar"; - const workingDirectory = getWorkingDirectory(); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (type2) { - case "create": - args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); - break; - case "extract": - args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path7.sep}`, "g"), "/")); - break; - case "list": - args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), "-P"); - break; + if (fs7.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); } - if (tarPath.type === constants_1.ArchiveToolType.GNU) { - switch (process.platform) { - case "win32": - args.push("--force-local"); - break; - case "darwin": - args.push("--delay-directory-restore"); - break; + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core14.debug("set auth"); + if (headers === void 0) { + headers = {}; } + headers.authorization = auth; } - return args; - }); - } - function getCommands(compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - let args; - const tarPath = yield getTarPath(); - const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); - const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - if (BSD_TAR_ZSTD && type2 !== "create") { - args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; - } else { - args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; - } - if (BSD_TAR_ZSTD) { - return args; + const response = yield http.get(url, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError2(response.message.statusCode); + core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; } - return [args.join(" ")]; - }); - } - function getWorkingDirectory() { - var _a; - return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); - } - function getDecompressionProgram(tarPath, compressionMethod, archivePath) { - return __awaiter4(this, void 0, void 0, function* () { - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -d --long=30 --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path7.sep}`, "g"), "/") - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -d --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path7.sep}`, "g"), "/") - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; - default: - return ["-z"]; + const pipeline = util.promisify(stream.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; + try { + yield pipeline(readStream, fs7.createWriteStream(dest)); + core14.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core14.debug("download failed"); + try { + yield io5.rmRF(dest); + } catch (err) { + core14.debug(`Failed to delete '${dest}'. ${err.message}`); + } + } } }); } - function getCompressionProgram(tarPath, compressionMethod) { + function extract7z(file, dest, _7zPath) { return __awaiter4(this, void 0, void 0, function* () { - const cacheFileName = utils.getCacheFileName(compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --long=30 --force -o", - cacheFileName.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), - constants_1.TarFilename - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { + try { + const logLevel = core14.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --force -o", - cacheFileName.replace(new RegExp(`\\${path7.sep}`, "g"), "/"), - constants_1.TarFilename - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; - default: - return ["-z"]; - } - }); - } - function execCommands(commands, cwd) { - return __awaiter4(this, void 0, void 0, function* () { - for (const command of commands) { + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } else { + const escapedScript = path7.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true + }; try { - yield (0, exec_1.exec)(command, void 0, { - cwd, - env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) - }); - } catch (error4) { - throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + const powershellPath = yield io5.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); } } + return dest; }); } - function listTar(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const commands = yield getCommands(compressionMethod, "list", archivePath); - yield execCommands(commands); - }); - } - exports2.listTar = listTar; - function extractTar2(archivePath, compressionMethod) { + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { return __awaiter4(this, void 0, void 0, function* () { - const workingDirectory = getWorkingDirectory(); - yield io5.mkdirP(workingDirectory); - const commands = yield getCommands(compressionMethod, "extract", archivePath); - yield execCommands(commands); + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + core14.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + core14.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + if (core14.isDebug() && !flags.includes("v")) { + args.push("-v"); + } + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); + } + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); + } + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; }); } exports2.extractTar = extractTar2; - function createTar(archiveFolder, sourceDirectories, compressionMethod) { + function extractXar(file, dest, flags = []) { return __awaiter4(this, void 0, void 0, function* () { - (0, fs_1.writeFileSync)(path7.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); - const commands = yield getCommands(compressionMethod, "create"); - yield execCommands(commands, archiveFolder); + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + args.push("-x", "-C", dest, "-f", file); + if (core14.isDebug()) { + args.push("-v"); + } + const xarPath = yield io5.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; }); } - exports2.createTar = createTar; - } -}); - -// node_modules/@actions/cache/lib/cache.js -var require_cache3 = __commonJS({ - "node_modules/@actions/cache/lib/cache.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } else { + yield extractZipNix(file, dest); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return dest; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; - var core14 = __importStar4(require_core()); - var path7 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var cacheHttpClient = __importStar4(require_cacheHttpClient()); - var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); - var config_1 = require_config(); - var tar_1 = require_tar(); - var http_client_1 = require_lib(); - var ValidationError = class _ValidationError extends Error { - constructor(message) { - super(message); - this.name = "ValidationError"; - Object.setPrototypeOf(this, _ValidationError.prototype); - } - }; - exports2.ValidationError = ValidationError; - var ReserveCacheError = class _ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = "ReserveCacheError"; - Object.setPrototypeOf(this, _ReserveCacheError.prototype); - } - }; - exports2.ReserveCacheError = ReserveCacheError; - var FinalizeCacheError = class _FinalizeCacheError extends Error { - constructor(message) { - super(message); - this.name = "FinalizeCacheError"; - Object.setPrototypeOf(this, _FinalizeCacheError.prototype); - } - }; - exports2.FinalizeCacheError = FinalizeCacheError; - function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } - } - function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); - } - } - function isFeatureAvailable() { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - switch (cacheServiceVersion) { - case "v2": - return !!process.env["ACTIONS_RESULTS_URL"]; - case "v1": - default: - return !!process.env["ACTIONS_CACHE_URL"]; - } } - exports2.isFeatureAvailable = isFeatureAvailable; - function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core14.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - switch (cacheServiceVersion) { - case "v2": - return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - case "v1": - default: - return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io5.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core14.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io5.which("powershell", true); + core14.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); } }); } - exports2.restoreCache = restoreCache3; - function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + function extractZipNix(file, dest) { return __awaiter4(this, void 0, void 0, function* () { - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core14.debug("Resolved Keys:"); - core14.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); - } - const compressionMethod = yield utils.getCompressionMethod(); - let archivePath = ""; - try { - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod, - enableCrossOsArchive - }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - return void 0; - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core14.info("Lookup only - skipping download"); - return cacheEntry.cacheKey; - } - archivePath = path7.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core14.debug(`Archive Path: ${archivePath}`); - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core14.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core14.info("Cache restored successfully"); - return cacheEntry.cacheKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core14.error(`Failed to restore: ${error4.message}`); - } else { - core14.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core14.debug(`Failed to delete archive: ${error4}`); - } + const unzipPath = yield io5.which("unzip", true); + const args = [file]; + if (!core14.isDebug()) { + args.unshift("-q"); } - return void 0; + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); }); } - function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + function cacheDir(sourceDir, tool, version, arch) { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core14.debug("Resolved Keys:"); - core14.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); + version = semver8.clean(version) || version; + arch = arch || os2.arch(); + core14.debug(`Caching tool ${tool} ${version} ${arch}`); + core14.debug(`source dir: ${sourceDir}`); + if (!fs7.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); } - let archivePath = ""; - try { - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - const compressionMethod = yield utils.getCompressionMethod(); - const request = { - key: primaryKey, - restoreKeys, - version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) - }; - const response = yield twirpClient.GetCacheEntryDownloadURL(request); - if (!response.ok) { - core14.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); - return void 0; - } - const isRestoreKeyMatch = request.key !== response.matchedKey; - if (isRestoreKeyMatch) { - core14.info(`Cache hit for restore-key: ${response.matchedKey}`); - } else { - core14.info(`Cache hit for: ${response.matchedKey}`); - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core14.info("Lookup only - skipping download"); - return response.matchedKey; - } - archivePath = path7.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core14.debug(`Archive path: ${archivePath}`); - core14.debug(`Starting download of archive to: ${archivePath}`); - yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - if (core14.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core14.info("Cache restored successfully"); - return response.matchedKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core14.error(`Failed to restore: ${error4.message}`); - } else { - core14.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - if (archivePath) { - yield utils.unlinkFile(archivePath); - } - } catch (error4) { - core14.debug(`Failed to delete archive: ${error4}`); - } + const destPath = yield _createToolPath(tool, version, arch); + for (const itemName of fs7.readdirSync(sourceDir)) { + const s = path7.join(sourceDir, itemName); + yield io5.cp(s, destPath, { recursive: true }); } - return void 0; + _completeToolPath(tool, version, arch); + return destPath; }); } - function saveCache3(paths, key, options, enableCrossOsArchive = false) { + exports2.cacheDir = cacheDir; + function cacheFile(sourceFile, targetFile, tool, version, arch) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core14.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - checkKey(key); - switch (cacheServiceVersion) { - case "v2": - return yield saveCacheV2(paths, key, options, enableCrossOsArchive); - case "v1": - default: - return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + version = semver8.clean(version) || version; + arch = arch || os2.arch(); + core14.debug(`Caching tool ${tool} ${version} ${arch}`); + core14.debug(`source file: ${sourceFile}`); + if (!fs7.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); } + const destFolder = yield _createToolPath(tool, version, arch); + const destPath = path7.join(destFolder, targetFile); + core14.debug(`destination file ${destPath}`); + yield io5.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch); + return destFolder; }); } - exports2.saveCache = saveCache3; - function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { - var _a, _b, _c, _d, _e; - return __awaiter4(this, void 0, void 0, function* () { - const compressionMethod = yield utils.getCompressionMethod(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core14.debug("Cache Paths:"); - core14.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch) { + if (!toolName) { + throw new Error("toolName parameter is required"); + } + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); + } + arch = arch || os2.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions2(toolName, arch); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; + } + let toolPath = ""; + if (versionSpec) { + versionSpec = semver8.clean(versionSpec) || ""; + const cachePath = path7.join(_getCacheDirectory(), toolName, versionSpec, arch); + core14.debug(`checking cache: ${cachePath}`); + if (fs7.existsSync(cachePath) && fs7.existsSync(`${cachePath}.complete`)) { + core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); + toolPath = cachePath; + } else { + core14.debug("not found"); } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path7.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core14.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core14.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const fileSizeLimit = 10 * 1024 * 1024 * 1024; - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core14.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); - } - core14.debug("Reserving Cache"); - const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod, - enableCrossOsArchive, - cacheSize: archiveFileSize - }); - if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { - cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; - } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { - throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); - } else { - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); - } - core14.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError.name) { - core14.info(`Failed to save: ${typedError.message}`); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core14.error(`Failed to save: ${typedError.message}`); - } else { - core14.warning(`Failed to save: ${typedError.message}`); + } + return toolPath; + } + exports2.find = find2; + function findAllVersions2(toolName, arch) { + const versions = []; + arch = arch || os2.arch(); + const toolPath = path7.join(_getCacheDirectory(), toolName); + if (fs7.existsSync(toolPath)) { + const children = fs7.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path7.join(toolPath, child, arch || ""); + if (fs7.existsSync(fullPath) && fs7.existsSync(`${fullPath}.complete`)) { + versions.push(child); } } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core14.debug(`Failed to delete archive: ${error4}`); - } } - return cacheId; - }); + } + return versions; } - function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + exports2.findAllVersions = findAllVersions2; + function getManifestFromRepo(owner, repo, auth, branch = "master") { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); - const compressionMethod = yield utils.getCompressionMethod(); - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core14.debug("Cache Paths:"); - core14.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core14.debug("set auth"); + headers.authorization = auth; } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path7.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core14.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core14.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core14.debug(`File Size: ${archiveFileSize}`); - options.archiveSizeBytes = archiveFileSize; - core14.debug("Reserving Cache"); - const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); - const request = { - key, - version - }; - let signedUploadUrl; - try { - const response = yield twirpClient.CreateCacheEntry(request); - if (!response.ok) { - if (response.message) { - core14.warning(`Cache reservation failed: ${response.message}`); - } - throw new Error(response.message || "Response was not ok"); - } - signedUploadUrl = response.signedUploadUrl; - } catch (error4) { - core14.debug(`Failed to reserve cache: ${error4}`); - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); - } - core14.debug(`Attempting to upload cache located at: ${archivePath}`); - yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); - const finalizeRequest = { - key, - version, - sizeBytes: `${archiveFileSize}` - }; - const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); - core14.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); - if (!finalizeResponse.ok) { - if (finalizeResponse.message) { - throw new FinalizeCacheError(finalizeResponse.message); - } - throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); - } - cacheId = parseInt(finalizeResponse.entryId); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError.name) { - core14.info(`Failed to save: ${typedError.message}`); - } else if (typedError.name === FinalizeCacheError.name) { - core14.warning(typedError.message); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core14.error(`Failed to save: ${typedError.message}`); - } else { - core14.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core14.debug(`Failed to delete archive: ${error4}`); - } + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; } - return cacheId; - }); - } - } -}); - -// node_modules/@actions/tool-cache/lib/manifest.js -var require_manifest = __commonJS({ - "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; } } - function rejected(value) { + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + releases = JSON.parse(versionsRaw); + } catch (_a) { + core14.debug("Invalid json"); } } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return releases; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver8 = __importStar4(require_semver2()); - var core_1 = require_core(); - var os2 = require("os"); - var cp = require("child_process"); - var fs7 = require("fs"); - function _findMatch(versionSpec, stable, candidates, archFilter) { + } + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os2.arch()) { return __awaiter4(this, void 0, void 0, function* () { - const platFilter = os2.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { - file = candidate.files.find((item) => { - (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module2.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } else { - chk = semver8.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - (0, core_1.debug)(`matched ${candidate.version}`); - match = candidate; - break; - } - } - } - if (match && file) { - result = Object.assign({}, match); - result.files = [file]; + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; + }); + } + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!dest) { + dest = path7.join(_getTempDirectory(), crypto.randomUUID()); } - return result; + yield io5.mkdirP(dest); + return dest; }); } - exports2._findMatch = _findMatch; - function _getOsVersion() { - const plat = os2.platform(); + function _createToolPath(tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + const folderPath = path7.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); + core14.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io5.rmRF(folderPath); + yield io5.rmRF(markerPath); + yield io5.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch) { + const folderPath = path7.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); + const markerPath = `${folderPath}.complete`; + fs7.writeFileSync(markerPath, ""); + core14.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver8.clean(versionSpec) || ""; + core14.debug(`isExplicit: ${c}`); + const valid3 = semver8.valid(c) != null; + core14.debug(`explicit? ${valid3}`); + return valid3; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { let version = ""; - if (plat === "darwin") { - version = cp.execSync("sw_vers -productVersion").toString(); - } else if (plat === "linux") { - const lsbContents = module2.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split("\n"); - for (const line of lines) { - const parts = line.split("="); - if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { - version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); - break; - } - } + core14.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver8.gt(a, b)) { + return 1; + } + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver8.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; } } + if (version) { + core14.debug(`matched: ${version}`); + } else { + core14.debug("match not found"); + } return version; } - exports2._getOsVersion = _getOsVersion; - function _readLinuxVersionFile() { - const lsbReleaseFile = "/etc/lsb-release"; - const osReleaseFile = "/etc/os-release"; - let contents = ""; - if (fs7.existsSync(lsbReleaseFile)) { - contents = fs7.readFileSync(lsbReleaseFile).toString(); - } else if (fs7.existsSync(osReleaseFile)) { - contents = fs7.readFileSync(osReleaseFile).toString(); - } - return contents; + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); } - exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve5) { - resolve5(value); - }); - } - return new (P || (P = Promise))(function(resolve5, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + module2.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; } - function step(result) { - result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return true; + } + return a !== a && b !== b; }; + } +}); + +// node_modules/@actions/http-client/lib/proxy.js +var require_proxy5 = __commonJS({ + "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core14 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); + exports2.getProxyUrl = getProxyUrl; + exports2.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - execute(action, isRetryable) { - return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core14.info(err.message); - } - const seconds = this.getSleepAmount(); - core14.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - return yield action(); - }); + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + get username() { + return this._decodedUsername; } - sleep(seconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve5) => setTimeout(resolve5, seconds * 1e3)); - }); + get password() { + return this._decodedPassword; } }; - exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib6 = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74975,15 +77842,25 @@ var require_tool_cache = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve5) { @@ -75012,523 +77889,616 @@ var require_tool_cache = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core14 = __importStar4(require_core()); - var io5 = __importStar4(require_io()); - var crypto = __importStar4(require("crypto")); - var fs7 = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os2 = __importStar4(require("os")); - var path7 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver8 = __importStar4(require_semver2()); - var stream = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError2 = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy5()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.HTTPError = HTTPError2; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path7.join(_getTempDirectory(), crypto.randomUUID()); - yield io5.mkdirP(path7.dirname(dest)); - core14.debug(`Downloading ${url}`); - core14.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError2 && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve5(output.toString()); + }); + })); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs7.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve5(Buffer.concat(chunks)); + }); + })); }); - if (auth) { - core14.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - headers.authorization = auth; - } - const response = yield http.get(url, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError2(response.message.statusCode); - core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; - } - const pipeline = util.promisify(stream.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs7.createWriteStream(dest)); - core14.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core14.debug("download failed"); - try { - yield io5.rmRF(dest); - } catch (err) { - core14.debug(`Failed to delete '${dest}'. ${err.message}`); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core14.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } else { - const escapedScript = path7.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io5.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core14.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - core14.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core14.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - args.push("-x", "-C", dest, "-f", file); - if (core14.isDebug()) { - args.push("-v"); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve5(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - const xarPath = yield io5.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io5.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core14.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io5.which("powershell", true); - core14.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); - } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io5.which("unzip", true); - const args = [file]; - if (!core14.isDebug()) { - args.unshift("-q"); + req.end(); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir(sourceDir, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch = arch || os2.arch(); - core14.debug(`Caching tool ${tool} ${version} ${arch}`); - core14.debug(`source dir: ${sourceDir}`); - if (!fs7.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const destPath = yield _createToolPath(tool, version, arch); - for (const itemName of fs7.readdirSync(sourceDir)) { - const s = path7.join(sourceDir, itemName); - yield io5.cp(s, destPath, { recursive: true }); + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - _completeToolPath(tool, version, arch); - return destPath; - }); - } - exports2.cacheDir = cacheDir; - function cacheFile(sourceFile, targetFile, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch = arch || os2.arch(); - core14.debug(`Caching tool ${tool} ${version} ${arch}`); - core14.debug(`source file: ${sourceFile}`); - if (!fs7.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } } - const destFolder = yield _createToolPath(tool, version, arch); - const destPath = path7.join(destFolder, targetFile); - core14.debug(`destination file ${destPath}`); - yield io5.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); + return info6; } - arch = arch || os2.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions2(toolName, arch); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver8.clean(versionSpec) || ""; - const cachePath = path7.join(_getCacheDirectory(), toolName, versionSpec, arch); - core14.debug(`checking cache: ${cachePath}`); - if (fs7.existsSync(cachePath) && fs7.existsSync(`${cachePath}.complete`)) { - core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); - toolPath = cachePath; - } else { - core14.debug("not found"); + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return toolPath; - } - exports2.find = find2; - function findAllVersions2(toolName, arch) { - const versions = []; - arch = arch || os2.arch(); - const toolPath = path7.join(_getCacheDirectory(), toolName); - if (fs7.existsSync(toolPath)) { - const children = fs7.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path7.join(toolPath, child, arch || ""); - if (fs7.existsSync(fullPath) && fs7.existsSync(`${fullPath}.complete`)) { - versions.push(child); + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; } } } + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; + } + } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return versions; - } - exports2.findAllVersions = findAllVersions2; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core14.debug("set auth"); - headers.authorization = auth; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + if (!useProxy) { + agent = this._agent; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; - } + if (agent) { + return agent; } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core14.debug("Invalid json"); - } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os2.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path7.join(_getTempDirectory(), crypto.randomUUID()); + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - yield io5.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path7.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); - core14.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io5.rmRF(folderPath); - yield io5.rmRF(markerPath); - yield io5.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch) { - const folderPath = path7.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); - const markerPath = `${folderPath}.complete`; - fs7.writeFileSync(markerPath, ""); - core14.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver8.clean(versionSpec) || ""; - core14.debug(`isExplicit: ${c}`); - const valid3 = semver8.valid(c) != null; - core14.debug(`explicit? ${valid3}`); - return valid3; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core14.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver8.gt(a, b)) { - return 1; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver8.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } + return agent; } - if (version) { - core14.debug(`matched: ${version}`); - } else { - core14.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; + if (proxyAgent) { + return proxyAgent; } - return true; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve5) => setTimeout(() => resolve5(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve5, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve5(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve5(response); + } + })); + }); } - return a !== a && b !== b; }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -79414,7 +82384,7 @@ var supportedAnalysisKinds = new Set(Object.values(AnalysisKind)); var core6 = __toESM(require_core()); // src/config/db-config.ts -var jsonschema = __toESM(require_lib2()); +var jsonschema = __toESM(require_lib3()); var semver2 = __toESM(require_semver2()); var PACK_IDENTIFIER_PATTERN = (function() { const alphaNumeric = "[a-z0-9]"; @@ -80223,7 +83193,7 @@ var semver5 = __toESM(require_semver2()); // src/tools-download.ts var core9 = __toESM(require_core()); -var import_http_client = __toESM(require_lib()); +var import_http_client = __toESM(require_lib6()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); var semver6 = __toESM(require_semver2()); diff --git a/lib/init-action-post.js b/lib/init-action-post.js index b6f466f9a0..459d0daf80 100644 --- a/lib/init-action-post.js +++ b/lib/init-action-post.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -19875,9 +19875,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -19934,737 +20016,826 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url2, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url2, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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 (isPlainObject(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, url2] = route.split(" "); - options = Object.assign(url2 ? { method, url: url2 } : { 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(url2, parameters) { - const separator = /\?/.test(url2) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url2; - } - return url2 + 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+)|(?:(? a.concat(b), []); - } - function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - } - function encodeReserved(str2) { - return str2.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(str2) { - return encodeURIComponent(str2).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; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - function isDefined2(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context3, operator, key, modifier) { - var value = context3[key], result = []; - if (isDefined2(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)); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - result.push(encodeValue(operator, value[k], k)); + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; } - }); + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } } - }); + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - } else { - if (operator === ";") { - if (isDefined2(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; - } - function expand(template, context3) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_2, 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(context3, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); } - } else { - return encodeReserved(literal); + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } - } - function parse(options) { - let method = options.method.toUpperCase(); - let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url2); - url2 = parseUrl(url2).expand(parameters); - if (!/^http/.test(url2)) { - url2 = options.baseUrl + url2; - } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(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(","); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (url2.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - } - if (["GET", "HEAD"].includes(method)) { - url2 = addQueryParameters(url2, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + req.end(); } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return Object.assign( - { method, url: url2, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); - } - function endpointWithDefaults(defaults, route, options) { - return parse(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 - }); - } - var endpoint = withDefaults(null, DEFAULTS); - } -}); - -// node_modules/deprecation/dist-node/index.js -var require_dist_node3 = __commonJS({ - "node_modules/deprecation/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var Deprecation = class extends Error { - constructor(message) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; } - this.name = "Deprecation"; + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; } - }; - exports2.Deprecation = Deprecation; - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - return ret; + return additionalHeaders[header] || clientHeader || _default2; } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; + var httpClient = __importStar4(require_lib2()); + var undici_1 = require_undici(); + function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error("Parameter token or opts.auth is required"); + } else if (token && options.auth) { + throw new Error("Parameters token and opts.auth may not both be specified"); + } + return typeof options.auth === "string" ? options.auth : `token ${token}`; + } + exports2.getAuthString = getAuthString; + function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + exports2.getProxyAgent = getProxyAgent; + function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); + } + exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; + function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url2, opts) => __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url2, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; + return proxyFetch; } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; } + exports2.getApiBaseUrl = getApiBaseUrl; } }); -// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node4 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { "use strict"; - var __create2 = Object.create; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - RequestError: () => RequestError - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_deprecation = require_dist_node3(); - var import_once = __toESM2(require_once()); - var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - request: () => request - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node2(); - var import_universal_user_agent = require_dist_node(); - var VERSION = "8.4.1"; - function isPlainObject(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); - } - var import_request_error = require_dist_node4(); - function getBufferResponse(response) { - return response.arrayBuffer(); - } - function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url2; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - 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" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } - }).then(async (response) => { - url2 = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url: url2, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url: url2, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url: url2, - status, - headers, - data - }, - request: requestOptions - }); - throw error4; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url: url2, - headers, - data - }; - }).catch((error4) => { - if (error4 instanceof import_request_error.RequestError) - throw error4; - else if (error4.name === "AbortError") - throw error4; - let message = error4.message; - if (error4.name === "TypeError" && "cause" in error4) { - if (error4.cause instanceof Error) { - message = error4.cause.message; - } else if (typeof error4.cause === "string") { - message = error4.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); - } - 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 getBufferResponse(response); - } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; - } - function withDefaults(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: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - } - var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } - }); - } -}); - -// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node6 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint + endpoint: () => endpoint }); module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); @@ -21218,9 +21179,101 @@ var require_dist_node6 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node7 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/deprecation/dist-node/index.js +var require_dist_node3 = __commonJS({ + "node_modules/deprecation/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var Deprecation = class extends Error { + constructor(message) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "Deprecation"; + } + }; + exports2.Deprecation = Deprecation; + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node4 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; var __create2 = Object.create; var __defProp2 = Object.defineProperty; @@ -21310,9 +21363,9 @@ var require_dist_node7 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js -var require_dist_node8 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js +var require_dist_node5 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21336,7 +21389,7 @@ var require_dist_node8 = __commonJS({ request: () => request }); module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node6(); + var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; function isPlainObject(value) { @@ -21350,7 +21403,7 @@ var require_dist_node8 = __commonJS({ 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); } - var import_request_error = require_dist_node7(); + var import_request_error = require_dist_node4(); function getBufferResponse(response) { return response.arrayBuffer(); } @@ -21520,9 +21573,9 @@ var require_dist_node8 = __commonJS({ } }); -// node_modules/@octokit/graphql/dist-node/index.js -var require_dist_node9 = __commonJS({ - "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node6 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21541,129 +21594,340 @@ var require_dist_node9 = __commonJS({ return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export2(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint }); - module2.exports = __toCommonJS2(index_exports); - var import_request3 = require_dist_node8(); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); - var VERSION = "7.1.1"; - var import_request2 = require_dist_node8(); - var import_request = require_dist_node8(); - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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; + }, {}); } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + function isPlainObject(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 (isPlainObject(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]; } } - }; - 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`) - ); + return obj; + } + function merge2(defaults, route, options) { + if (typeof route === "string") { + let [method, url2] = route.split(" "); + options = Object.assign(url2 ? { method, url: url2 } : { 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); } - 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` - ) - ); + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; + } + function addQueryParameters(url2, parameters) { + const separator = /\?/.test(url2) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url2; + } + return url2 + 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+)|(?:(? { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } + function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; } - if (!result.variables) { - result.variables = {}; + } + return result; + } + function encodeReserved(str2) { + return str2.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, "]"); } - 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 part; + }).join(""); + } + function encodeUnreserved(str2) { + return encodeURIComponent(str2).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; } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; + } + function isDefined2(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context3, operator, key, modifier) { + var value = context3[key], result = []; + if (isDefined2(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)); } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(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(",")); + } + } } - return response.data.data; - }); + } else { + if (operator === ";") { + if (isDefined2(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; } - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); + function parseUrl(template) { + return { + expand: expand.bind(null, template) }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); } - var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" - }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" + function expand(template, context3) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_2, 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(context3, 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 parse(options) { + let method = options.method.toUpperCase(); + let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url2); + url2 = parseUrl(url2).expand(parameters); + if (!/^http/.test(url2)) { + url2 = options.baseUrl + url2; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(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 (url2.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url2 = addQueryParameters(url2, 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: url2, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); + } + function endpointWithDefaults(defaults, route, options) { + return parse(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 }); } + var endpoint = withDefaults(null, DEFAULTS); } }); -// node_modules/@octokit/auth-token/dist-node/index.js -var require_dist_node10 = __commonJS({ - "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node7 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; + var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) @@ -21677,53 +21941,490 @@ var require_dist_node10 = __commonJS({ } return to; }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - createTokenAuth: () => createTokenAuth + RequestError: () => RequestError }); module2.exports = __toCommonJS2(dist_src_exports); - 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, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); - } - 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" - ); + var import_deprecation = require_dist_node3(); + var import_once = __toESM2(require_once()); + var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + request: () => request + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_endpoint = require_dist_node6(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "8.4.1"; + function isPlainObject(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); + } + var import_request_error = require_dist_node7(); + function getBufferResponse(response) { + return response.arrayBuffer(); + } + function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url2; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + 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" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url2 = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url: url2, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url: url2, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url: url2, + status, + headers, + data + }, + request: requestOptions + }); + throw error4; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url: url2, + headers, + data + }; + }).catch((error4) => { + if (error4 instanceof import_request_error.RequestError) + throw error4; + else if (error4.name === "AbortError") + throw error4; + let message = error4.message; + if (error4.name === "TypeError" && "cause" in error4) { + if (error4.cause instanceof Error) { + message = error4.cause.message; + } else if (typeof error4.cause === "string") { + message = error4.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); + } + 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 getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; + } + function withDefaults(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: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + } + var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }); + } +}); + +// node_modules/@octokit/graphql/dist-node/index.js +var require_dist_node9 = __commonJS({ + "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export2(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest + }); + module2.exports = __toCommonJS2(index_exports); + var import_request3 = require_dist_node8(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "7.1.1"; + var import_request2 = require_dist_node8(); + var import_request = require_dist_node8(); + 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.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + }; + 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 withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); + } + } +}); + +// node_modules/@octokit/auth-token/dist-node/index.js +var require_dist_node10 = __commonJS({ + "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + createTokenAuth: () => createTokenAuth + }); + module2.exports = __toCommonJS2(dist_src_exports); + 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, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + 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) + }); }; } }); @@ -26499,7 +27200,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -29372,7 +30073,7 @@ var require_validator = __commonJS({ }); // node_modules/jsonschema/lib/index.js -var require_lib2 = __commonJS({ +var require_lib3 = __commonJS({ "node_modules/jsonschema/lib/index.js"(exports2, module2) { "use strict"; var Validator3 = module2.exports.Validator = require_validator(); @@ -32511,5019 +33212,5824 @@ var require_cacheUtils = __commonJS({ } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); - var HttpPipeline = class _HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = void 0; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - this._policies.push({ - policy, - options - }); - this._orderedPolicies = void 0; + } else { + return void 0; } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { - removedPolicies.push(policyDescriptor.policy); - return false; - } else { - return true; - } - }); - this._orderedPolicies = void 0; - return removedPolicies; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - clone() { - return new _HttpPipeline(this._policies); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - static create() { - return new _HttpPipeline(); + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - orderPolicies() { - const result = []; - const policyMap = /* @__PURE__ */ new Map(); - function createPhase(name) { - return { - name, - policies: /* @__PURE__ */ new Set(), - hasRun: false, - hasAfterPolicies: false - }; - } - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } else if (phase === "Serialize") { - return serializePhase; - } else if (phase === "Deserialize") { - return deserializePhase; - } else if (phase === "Sign") { - return signPhase; - } else { - return noPhase; - } - } - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: /* @__PURE__ */ new Set(), - dependants: /* @__PURE__ */ new Set() - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); - } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); - } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); - } - } - } - } - function walkPhase(phase) { - phase.hasRun = true; - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - continue; - } - if (node.dependsOn.size === 0) { - result.push(node.policy); - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); - } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - walkPhase(noPhase); - } - return; - } - if (phase.hasAfterPolicies) { - walkPhase(noPhase); - } - } - } - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - walkPhases(); - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return result; } - }; - function createEmptyPipeline() { - return HttpPipeline.create(); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@azure/logger/dist/index.js -var require_dist = __commonJS({ - "node_modules/@azure/logger/dist/index.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var os3 = require("os"); - var util = require("util"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); - function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os3.EOL}`); - } - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; - var enabledString; - var enabledNamespaces = []; - var skippedNamespaces = []; - var debuggers = []; - if (debugEnvVariable) { - enable(debugEnvVariable); - } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log - }); - function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); - } else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); - } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - } - function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - } - return false; - } - function disable() { - const result = enabledString || ""; - enable(""); - return result; - } - function createDebugger(namespace) { - const newDebugger = Object.assign(debug6, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend: extend3 - }); - function debug6(...args) { - if (!newDebugger.enabled) { - return; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } - newDebugger.log(...args); - } - debuggers.push(newDebugger); - return newDebugger; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return false; - } - function extend3(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; - } - var debug5 = debugObj; - var registeredLoggers = /* @__PURE__ */ new Set(); - var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; - var azureLogLevel; - var AzureLogger = debug5("azure"); - AzureLogger.log = (...args) => { - debug5.log(...args); }; - var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; - if (logLevelFromEnv) { - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); - } else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - } - function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); + }); } - azureLogLevel = level; - const enabledNamespaces2 = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces2.push(logger.namespace); - } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); + }); } - debug5.enable(enabledNamespaces2.join(",")); - } - function getLogLevel() { - return azureLogLevel; - } - var levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 }; - function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") - }; - } - function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); - }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces2 = debug5.disable(); - debug5.enable(enabledNamespaces2 + "," + logger.namespace); + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - registeredLoggers.add(logger); - return logger; - } - function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); - } - function isAzureLogLevel(logLevel) { - return AZURE_LOG_LEVELS.includes(logLevel); - } - exports2.AzureLogger = AzureLogger; - exports2.createClientLogger = createClientLogger; - exports2.getLogLevel = getLogLevel; - exports2.setLogLevel = setLogLevel; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js -var require_log = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_dist(); - exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - } -}); - -// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js -var require_createAbortablePromise = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createAbortablePromise = createAbortablePromise; - var abort_controller_1 = require_commonjs(); - function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve8, reject) => { - function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - function removeListeners() { - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - function onAbort() { - cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); - removeListeners(); - rejectOnAbort(); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { - return rejectOnAbort(); + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - try { - buildPromise((x) => { - removeListeners(); - resolve8(x); - }, (x) => { - removeListeners(); - reject(x); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); }); - } catch (err) { - reject(err); + data.pipe(req); + } else { + req.end(); } - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); - }); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/random.js -var require_random = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - function getRandomIntegerInclusive(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - const offset = Math.floor(Math.random() * (max - min + 1)); - return offset + min; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/delay.js -var require_delay = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay2; - exports2.calculateRetryDelay = calculateRetryDelay; - var createAbortablePromise_js_1 = require_createAbortablePromise(); - var random_js_1 = require_random(); - var StandardAbortMessage = "The delay was aborted."; - function delay2(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve8) => { - token = setTimeout(resolve8, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage - }); - } - function calculateRetryDelay(retryAttempt, config) { - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); - return { retryAfterInMs }; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js -var require_aborterUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cancelablePromiseRace = cancelablePromiseRace; - async function cancelablePromiseRace(abortablePromiseBuilders, options) { - var _a, _b; - const aborter = new AbortController(); - function abortHandler() { - aborter.abort(); } - (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); - try { - return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); - } finally { - aborter.abort(); - (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/object.js -var require_object = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isObject = isObject2; - function isObject2(input) { - return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/error.js -var require_error = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isError = isError; - exports2.getErrorMessage = getErrorMessage2; - var object_js_1 = require_object(); - function isError(e) { - if ((0, object_js_1.isObject)(e)) { - const hasName = typeof e.name === "string"; - const hasMessage = typeof e.message === "string"; - return hasName && hasMessage; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return false; - } - function getErrorMessage2(e) { - if (isError(e)) { - return e.message; - } else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } else { - stringified = String(e); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); } - } catch (err) { - stringified = "[unable to stringify input]"; } - return `Unknown error ${stringified}`; + return info7; } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.computeSha256Hash = computeSha256Hash; - var crypto_1 = require("crypto"); - async function computeSha256Hmac(key, stringToSign, encoding) { - const decodedKey = Buffer.from(key, "base64"); - return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); - } - async function computeSha256Hash(content, encoding) { - return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/typeGuards.js -var require_typeGuards = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isDefined = isDefined2; - exports2.isObjectWithProperties = isObjectWithProperties; - exports2.objectHasProperty = objectHasProperty; - function isDefined2(thing) { - return typeof thing !== "undefined" && thing !== null; - } - function isObjectWithProperties(thing, properties) { - if (!isDefined2(thing) || typeof thing !== "object") { - return false; - } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - return true; - } - function objectHasProperty(thing, property) { - return isDefined2(thing) && typeof thing === "object" && property in thing; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js -var require_uuidUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomUUID = randomUUID2; - var crypto_1 = require("crypto"); - var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; - function randomUUID2() { - return uuidFunction(); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js -var require_checkEnvironment = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { - "use strict"; - var _a; - var _b; - var _c; - var _d; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; - exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; - exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); - exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; - exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; - exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); - exports2.isNode = exports2.isNodeLike; - exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; - exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; - } -}); - -// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js -var require_bytesEncoding = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - function uint8ArrayToString(bytes, format) { - return Buffer.from(bytes).toString(format); - } - function stringToUint8Array(value, format) { - return Buffer.from(value, format); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/index.js -var require_commonjs2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; - var delay_js_1 = require_delay(); - Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { - return delay_js_1.delay; - } }); - Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { - return delay_js_1.calculateRetryDelay; - } }); - var aborterUtils_js_1 = require_aborterUtils(); - Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { - return aborterUtils_js_1.cancelablePromiseRace; - } }); - var createAbortablePromise_js_1 = require_createAbortablePromise(); - Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { - return createAbortablePromise_js_1.createAbortablePromise; - } }); - var random_js_1 = require_random(); - Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { - return random_js_1.getRandomIntegerInclusive; - } }); - var object_js_1 = require_object(); - Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { - return object_js_1.isObject; - } }); - var error_js_1 = require_error(); - Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { - return error_js_1.isError; - } }); - Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { - return error_js_1.getErrorMessage; - } }); - var sha256_js_1 = require_sha256(); - Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hash; - } }); - Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hmac; - } }); - var typeGuards_js_1 = require_typeGuards(); - Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { - return typeGuards_js_1.isDefined; - } }); - Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { - return typeGuards_js_1.isObjectWithProperties; - } }); - Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { - return typeGuards_js_1.objectHasProperty; - } }); - var uuidUtils_js_1 = require_uuidUtils(); - Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { - return uuidUtils_js_1.randomUUID; - } }); - var checkEnvironment_js_1 = require_checkEnvironment(); - Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBrowser; - } }); - Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBun; - } }); - Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNode; - } }); - Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeLike; - } }); - Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeRuntime; - } }); - Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { - return checkEnvironment_js_1.isDeno; - } }); - Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { - return checkEnvironment_js_1.isReactNative; - } }); - Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { - return checkEnvironment_js_1.isWebWorker; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js -var require_sanitizer = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = void 0; - var core_util_1 = require_commonjs2(); - var RedactedString = "REDACTED"; - var defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate" - ]; - var defaultAllowedQueryParameters = ["api-version"]; - var Sanitizer = class { - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { - allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); - allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); - } - sanitize(obj) { - const seen = /* @__PURE__ */ new Set(); - return JSON.stringify(obj, (key, value) => { - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); - } - if (key === "headers") { - return this.sanitizeHeaders(value); - } else if (key === "url") { - return this.sanitizeUrl(value); - } else if (key === "query") { - return this.sanitizeQuery(value); - } else if (key === "body") { - return void 0; - } else if (key === "response") { - return void 0; - } else if (key === "operationSpec") { - return void 0; - } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - } - return value; - }, 2); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - sanitizeUrl(value) { - if (typeof value !== "string" || value === null || value === "") { - return value; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const url2 = new URL(value); - if (!url2.search) { - return value; + if (!useProxy) { + agent = this._agent; } - for (const [key] of url2.searchParams) { - if (!this.allowedQueryParameters.has(key.toLowerCase())) { - url2.searchParams.set(key, RedactedString); - } + if (agent) { + return agent; } - return url2.toString(); - } - sanitizeHeaders(obj) { - const sanitized = {}; - for (const key of Object.keys(obj)) { - if (this.allowedHeaderNames.has(key.toLowerCase())) { - sanitized[key] = obj[key]; + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - sanitized[key] = RedactedString; + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - return sanitized; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - sanitizeQuery(value) { - if (typeof value !== "object" || value === null) { - return value; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (this.allowedQueryParameters.has(k.toLowerCase())) { - sanitized[k] = value[k]; - } else { - sanitized[k] = RedactedString; - } + if (proxyAgent) { + return proxyAgent; } - return sanitized; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); + } + })); + }); } }; - exports2.Sanitizer = Sanitizer; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js -var require_logPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log(); - var sanitizer_js_1 = require_sanitizer(); - exports2.logPolicyName = "logPolicy"; - function logPolicy(options = {}) { - var _a; - const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - return { - name: exports2.logPolicyName, - async sendRequest(request, next) { - if (!logger.enabled) { - return next(request); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - logger(`Request: ${sanitizer.sanitize(request)}`); - const response = await next(request); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); - return response; } - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js -var require_redirectPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - exports2.redirectPolicyName = "redirectPolicy"; - var allowedRedirect = ["GET", "HEAD"]; - function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: exports2.redirectPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return handleRedirect(next, response, maxRetries); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - }; - } - async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { - const url2 = new URL(locationHeader, request.url); - request.url = url2.toString(); - if (status === 303) { - request.method = "GET"; - request.headers.delete("Content-Length"); - delete request.body; + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } - request.headers.delete("Authorization"); - const res = await next(request); - return handleRedirect(next, res, maxRetries, currentRetries + 1); - } - return response; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs -var tslib_es6_exports = {}; -__export(tslib_es6_exports, { - __addDisposableResource: () => __addDisposableResource, - __assign: () => __assign, - __asyncDelegator: () => __asyncDelegator, - __asyncGenerator: () => __asyncGenerator, - __asyncValues: () => __asyncValues, - __await: () => __await, - __awaiter: () => __awaiter, - __classPrivateFieldGet: () => __classPrivateFieldGet, - __classPrivateFieldIn: () => __classPrivateFieldIn, - __classPrivateFieldSet: () => __classPrivateFieldSet, - __createBinding: () => __createBinding, - __decorate: () => __decorate, - __disposeResources: () => __disposeResources, - __esDecorate: () => __esDecorate, - __exportStar: () => __exportStar, - __extends: () => __extends, - __generator: () => __generator, - __importDefault: () => __importDefault, - __importStar: () => __importStar, - __makeTemplateObject: () => __makeTemplateObject, - __metadata: () => __metadata, - __param: () => __param, - __propKey: () => __propKey, - __read: () => __read, - __rest: () => __rest, - __runInitializers: () => __runInitializers, - __setFunctionName: () => __setFunctionName, - __spread: () => __spread, - __spreadArray: () => __spreadArray, - __spreadArrays: () => __spreadArrays, - __values: () => __values2, - default: () => tslib_es6_default -}); -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _2, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context3 = {}; - for (var p in contextIn) context3[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context3.access[p] = contextIn.access[p]; - context3.addInitializer = function(f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context3); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_2 = accept(result.get)) descriptor.get = _2; - if (_2 = accept(result.set)) descriptor.set = _2; - if (_2 = accept(result.init)) initializers.unshift(_2); - } else if (_2 = accept(result)) { - if (kind === "field") initializers.unshift(_2); - else descriptor[key] = _2; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} -function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -} -function __propKey(x) { - return typeof x === "symbol" ? x : "".concat(x); -} -function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); -} -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _2 = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_2 = 0)), _2) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _2.label++; - return { value: op[1], done: false }; - case 5: - _2.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _2.ops.pop(); - _2.trys.pop(); - continue; - default: - if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _2 = 0; - continue; +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _2.label = op[1]; - break; + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; } - if (op[0] === 6 && _2.label < t[1]) { - _2.label = t[1]; - t = op; - break; + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); } - if (t && _2.label < t[2]) { - _2.label = t[2]; - _2.ops.push(op); - break; + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; } - if (t[2]) _2.ops.pop(); - _2.trys.pop(); - continue; + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; } - op = body.call(thisArg, _2); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; + }; + function createEmptyPipeline() { + return HttpPipeline.create(); } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; } -} -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} -function __values2(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function() { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; +}); + +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os3 = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error4) { - e = { error: error4 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os3.EOL}`); } - } - return ar; -} -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - if (f) i[n] = f(i[n]); + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log + }); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function(e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function() { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function(v) { - return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; - } : f; - } -} -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve8, reject) { - v = o[n](v), settle(resolve8, reject, v.done, v.value); - }); - }; - } - function settle(resolve8, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve8({ value: v2, done: d }); - }, reject); - } -} -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - } - __setModuleDefault(result, mod); - return result; -} -function __importDefault(mod) { - return mod && mod.__esModule ? mod : { default: mod }; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldIn(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} -function __addDisposableResource(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; + function disable() { + const result = enabledString || ""; + enable(""); + return result; } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; + function createDebugger(namespace) { + const newDebugger = Object.assign(debug6, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug6(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { - try { - inner.call(this); - } catch (e) { - return Promise.reject(e); + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; } + return false; + } + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; + } + var debug5 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug5("azure"); + AzureLogger.log = (...args) => { + debug5.log(...args); }; - env.stack.push({ value, dispose, async }); - } else if (async) { - env.stack.push({ async: true }); - } - return value; -} -function __disposeResources(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { - fail(e); - return next(); - }); - } else s |= 1; - } catch (e) { - fail(e); + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); } } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; - } - return next(); -} -var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; -var init_tslib_es6 = __esm({ - "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() { - extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics(d, b); - }; - __assign = function() { - __assign = Object.assign || function __assign4(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); } - return t; - }; - return __assign.apply(this, arguments); - }; - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - }); - __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; - }; - tslib_es6_default = { - __extends, - __assign, - __rest, - __decorate, - __param, - __metadata, - __awaiter, - __generator, - __createBinding, - __exportStar, - __values: __values2, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn, - __addDisposableResource, - __disposeResources + debug5.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 }; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js -var require_userAgentPlatform = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getHeaderName = getHeaderName; - exports2.setPlatformSpecificData = setPlatformSpecificData; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var os3 = tslib_1.__importStar(require("node:os")); - var process2 = tslib_1.__importStar(require("node:process")); - function getHeaderName() { - return "User-Agent"; + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; } - async function setPlatformSpecificData(map2) { - if (process2 && process2.versions) { - const versions = process2.versions; - if (versions.bun) { - map2.set("Bun", versions.bun); - } else if (versions.deno) { - map2.set("Deno", versions.deno); - } else if (versions.node) { - map2.set("Node", versions.node); - } + function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; + } + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces2 = debug5.disable(); + debug5.enable(enabledNamespaces2 + "," + logger.namespace); } - map2.set("OS", `(${os3.arch()}-${os3.type()}-${os3.release()})`); + registeredLoggers.add(logger); + return logger; + } + function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + } + function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); } + exports2.AzureLogger = AzureLogger; + exports2.createClientLogger = createClientLogger; + exports2.getLogLevel = getLogLevel; + exports2.setLogLevel = setLogLevel; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js -var require_constants8 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js +var require_log = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; - exports2.SDK_VERSION = "1.17.0"; - exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js -var require_userAgent = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUserAgentHeaderName = getUserAgentHeaderName; - exports2.getUserAgentValue = getUserAgentValue; - var userAgentPlatform_js_1 = require_userAgentPlatform(); - var constants_js_1 = require_constants8(); - function getUserAgentString(telemetryInfo) { - const parts = []; - for (const [key, value] of telemetryInfo) { - const token = value ? `${key}/${value}` : key; - parts.push(token); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } - return parts.join(" "); - } - function getUserAgentHeaderName() { - return (0, userAgentPlatform_js_1.getHeaderName)(); - } - async function getUserAgentValue(prefix) { - const runtimeInfo = /* @__PURE__ */ new Map(); - runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); - await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); - const defaultAgent = getUserAgentString(runtimeInfo); - const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; - return userAgentValue; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js -var require_userAgentPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.userAgentPolicyName = void 0; - exports2.userAgentPolicy = userAgentPolicy; - var userAgent_js_1 = require_userAgent(); - var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); - exports2.userAgentPolicyName = "userAgentPolicy"; - function userAgentPolicy(options = {}) { - const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); - return { - name: exports2.userAgentPolicyName, - async sendRequest(request, next) { - if (!request.headers.has(UserAgentHeaderName)) { - request.headers.set(UserAgentHeaderName, await userAgentValue); - } - return next(request); - } - }; - } + }; + exports2.AbortError = AbortError; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js -var require_typeGuards2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) { +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isNodeReadableStream = isNodeReadableStream; - exports2.isWebReadableStream = isWebReadableStream; - exports2.isReadableStream = isReadableStream; - exports2.isBlob = isBlob; - function isNodeReadableStream(x) { - return Boolean(x && typeof x["pipe"] === "function"); - } - function isWebReadableStream(x) { - return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); - } - function isReadableStream(x) { - return isNodeReadableStream(x) || isWebReadableStream(x); - } - function isBlob(x) { - return typeof x.stream === "function"; - } + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js -var require_file2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRawContent = getRawContent; - exports2.createFileFromStream = createFileFromStream; - exports2.createFile = createFile; - var core_util_1 = require_commonjs2(); - var typeGuards_js_1 = require_typeGuards2(); - var unimplementedMethods = { - arrayBuffer: () => { - throw new Error("Not implemented"); - }, - slice: () => { - throw new Error("Not implemented"); - }, - text: () => { - throw new Error("Not implemented"); - } - }; - var rawContent = Symbol("rawContent"); - function hasRawContent(x) { - return typeof x[rawContent] === "function"; - } - function getRawContent(blob) { - if (hasRawContent(blob)) { - return blob[rawContent](); - } else { - return blob.stream(); - } - } - function createFileFromStream(stream2, name, options = {}) { - var _a, _b, _c, _d; - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { - const s = stream2(); - if ((0, typeGuards_js_1.isNodeReadableStream)(s)) { - throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve8, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); } - return s; - }, [rawContent]: stream2 }); + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve8(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); } - function createFile(content, name, options = {}) { - var _a, _b, _c; - if (core_util_1.isNodeLike) { - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); - } else { - return new File([content], name, options); - } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/random.js +var require_random = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; + function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js -var require_concat = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.concat = concat; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var node_stream_1 = require("node:stream"); - var typeGuards_js_1 = require_typeGuards2(); - var file_js_1 = require_file2(); - function streamAsyncIterator() { - return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { - const reader = this.getReader(); - try { - while (true) { - const { done, value } = yield tslib_1.__await(reader.read()); - if (done) { - return yield tslib_1.__await(void 0); - } - yield yield tslib_1.__await(value); - } - } finally { - reader.releaseLock(); - } + exports2.delay = delay2; + exports2.calculateRetryDelay = calculateRetryDelay; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var random_js_1 = require_random(); + var StandardAbortMessage = "The delay was aborted."; + function delay2(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve8) => { + token = setTimeout(resolve8, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage }); } - function makeAsyncIterable(webStream) { - if (!webStream[Symbol.asyncIterator]) { - webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); - } - if (!webStream.values) { - webStream.values = streamAsyncIterator.bind(webStream); - } + function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; } - function ensureNodeStream(stream2) { - if (stream2 instanceof ReadableStream) { - makeAsyncIterable(stream2); - return node_stream_1.Readable.fromWeb(stream2); - } else { - return stream2; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); } - } - function toStream(source) { - if (source instanceof Uint8Array) { - return node_stream_1.Readable.from(Buffer.from(source)); - } else if ((0, typeGuards_js_1.isBlob)(source)) { - return toStream((0, file_js_1.getRawContent)(source)); - } else { - return ensureNodeStream(source); + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); } } - async function concat(sources) { - return function() { - const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); - return node_stream_1.Readable.from((function() { - return tslib_1.__asyncGenerator(this, arguments, function* () { - var _a, e_1, _b, _c; - for (const stream2 of streams) { - try { - for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream2)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { - _c = stream_1_1.value; - _d = false; - const chunk = _c; - yield yield tslib_1.__await(chunk); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1)); - } finally { - if (e_1) throw e_1.error; - } - } - } - }); - })()); - }; - } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js -var require_multipartPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/object.js +var require_object = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.multipartPolicyName = void 0; - exports2.multipartPolicy = multipartPolicy; - var core_util_1 = require_commonjs2(); - var concat_js_1 = require_concat(); - var typeGuards_js_1 = require_typeGuards2(); - function generateBoundary() { - return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; + exports2.isObject = isObject2; + function isObject2(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); } - function encodeHeaders(headers) { - let result = ""; - for (const [key, value] of headers) { - result += `${key}: ${value}\r -`; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isError = isError; + exports2.getErrorMessage = getErrorMessage2; + var object_js_1 = require_object(); + function isError(e) { + if ((0, object_js_1.isObject)(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; } - return result; + return false; } - function getLength(source) { - if (source instanceof Uint8Array) { - return source.byteLength; - } else if ((0, typeGuards_js_1.isBlob)(source)) { - return source.size === -1 ? void 0 : source.size; + function getErrorMessage2(e) { + if (isError(e)) { + return e.message; } else { - return void 0; - } - } - function getTotalLength(sources) { - let total = 0; - for (const source of sources) { - const partLength = getLength(source); - if (partLength === void 0) { - return void 0; - } else { - total += partLength; + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } else { + stringified = String(e); + } + } catch (err) { + stringified = "[unable to stringify input]"; } + return `Unknown error ${stringified}`; } - return total; - } - async function buildRequestBody(request, parts, boundary) { - const sources = [ - (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"), - ...parts.flatMap((part) => [ - (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), - (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), - (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), - part.body, - (0, core_util_1.stringToUint8Array)(`\r ---${boundary}`, "utf-8") - ]), - (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8") - ]; - const contentLength = getTotalLength(sources); - if (contentLength) { - request.headers.set("Content-Length", contentLength); - } - request.body = await (0, concat_js_1.concat)(sources); } - exports2.multipartPolicyName = "multipartPolicy"; - var maxBoundaryLength = 70; - var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); - function assertValidBoundary(boundary) { - if (boundary.length > maxBoundaryLength) { - throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); - } - if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { - throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); - } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.computeSha256Hmac = computeSha256Hmac; + exports2.computeSha256Hash = computeSha256Hash; + var crypto_1 = require("crypto"); + async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); } - function multipartPolicy() { - return { - name: exports2.multipartPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.multipartBody) { - return next(request); - } - if (request.body) { - throw new Error("multipartBody and regular body cannot be set at the same time"); - } - let boundary = request.multipartBody.boundary; - const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; - const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); - if (!parsedHeader) { - throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); - } - const [, contentType, parsedBoundary] = parsedHeader; - if (parsedBoundary && boundary && parsedBoundary !== boundary) { - throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); - } - boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary; - if (boundary) { - assertValidBoundary(boundary); - } else { - boundary = generateBoundary(); - } - request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); - await buildRequestBody(request, request.multipartBody.parts, boundary); - request.multipartBody = void 0; - return next(request); - } - }; + async function computeSha256Hash(content, encoding) { + return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js -var require_decompressResponsePolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decompressResponsePolicyName = void 0; - exports2.decompressResponsePolicy = decompressResponsePolicy; - exports2.decompressResponsePolicyName = "decompressResponsePolicy"; - function decompressResponsePolicy() { - return { - name: exports2.decompressResponsePolicyName, - async sendRequest(request, next) { - if (request.method !== "HEAD") { - request.headers.set("Accept-Encoding", "gzip,deflate"); - } - return next(request); + exports2.isDefined = isDefined2; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined2(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined2(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; } - }; + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined2(thing) && typeof thing === "object" && property in thing; } } }); -// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js +var require_uuidUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { "use strict"; + var _a; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; - } - }; - exports2.AbortError = AbortError; + exports2.randomUUID = randomUUID2; + var crypto_1 = require("crypto"); + var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; + function randomUUID2() { + return uuidFunction(); + } } }); -// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs3 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js +var require_checkEnvironment = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { "use strict"; + var _a; + var _b; + var _c; + var _d; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError2(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); + exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; + exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; + exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); + exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; + exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; + exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); + exports2.isNode = exports2.isNodeLike; + exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; + exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js -var require_helpers2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js +var require_bytesEncoding = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay2; - exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; - var abort_controller_1 = require_commonjs3(); - var StandardAbortMessage = "The operation was aborted."; - function delay2(delayInMs, value, options) { - return new Promise((resolve8, reject) => { - let timer = void 0; - let onAborted = void 0; - const rejectOnAbort = () => { - return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); - }; - const removeListeners = () => { - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { - options.abortSignal.removeEventListener("abort", onAborted); - } - }; - onAborted = () => { - if (timer) { - clearTimeout(timer); - } - removeListeners(); - return rejectOnAbort(); - }; - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { - return rejectOnAbort(); - } - timer = setTimeout(() => { - removeListeners(); - resolve8(value); - }, delayInMs); - if (options === null || options === void 0 ? void 0 : options.abortSignal) { - options.abortSignal.addEventListener("abort", onAborted); - } - }); + exports2.uint8ArrayToString = uint8ArrayToString; + exports2.stringToUint8Array = stringToUint8Array; + function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); } - function parseHeaderValueAsNumber(response, headerName) { - const value = response.headers.get(headerName); - if (!value) - return; - const valueAsNum = Number(value); - if (Number.isNaN(valueAsNum)) - return; - return valueAsNum; + function stringToUint8Array(value, format) { + return Buffer.from(value, format); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js -var require_throttlingRetryStrategy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; - exports2.throttlingRetryStrategy = throttlingRetryStrategy; - var helpers_js_1 = require_helpers2(); - var RetryAfterHeader = "Retry-After"; - var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; - function getRetryAfterInMs(response) { - if (!(response && [429, 503].includes(response.status))) - return void 0; - try { - for (const header of AllRetryAfterHeaders) { - const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); - if (retryAfterValue === 0 || retryAfterValue) { - const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; - return retryAfterValue * multiplyingFactor; - } - } - const retryAfterHeader = response.headers.get(RetryAfterHeader); - if (!retryAfterHeader) - return; - const date = Date.parse(retryAfterHeader); - const diff = date - Date.now(); - return Number.isFinite(diff) ? Math.max(0, diff) : void 0; - } catch (_a) { - return void 0; - } - } - function isThrottlingRetryResponse(response) { - return Number.isFinite(getRetryAfterInMs(response)); - } - function throttlingRetryStrategy() { - return { - name: "throttlingRetryStrategy", - retry({ response }) { - const retryAfterInMs = getRetryAfterInMs(response); - if (!Number.isFinite(retryAfterInMs)) { - return { skipStrategy: true }; - } - return { - retryAfterInMs - }; - } - }; - } + exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; + var delay_js_1 = require_delay(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { + return delay_js_1.calculateRetryDelay; + } }); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var random_js_1 = require_random(); + Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { + return random_js_1.getRandomIntegerInclusive; + } }); + var object_js_1 = require_object(); + Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { + return object_js_1.isObject; + } }); + var error_js_1 = require_error(); + Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { + return error_js_1.isError; + } }); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var sha256_js_1 = require_sha256(); + Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hash; + } }); + Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hmac; + } }); + var typeGuards_js_1 = require_typeGuards(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + var uuidUtils_js_1 = require_uuidUtils(); + Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { + return uuidUtils_js_1.randomUUID; + } }); + var checkEnvironment_js_1 = require_checkEnvironment(); + Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBrowser; + } }); + Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBun; + } }); + Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNode; + } }); + Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeLike; + } }); + Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeRuntime; + } }); + Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { + return checkEnvironment_js_1.isDeno; + } }); + Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { + return checkEnvironment_js_1.isReactNative; + } }); + Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { + return checkEnvironment_js_1.isWebWorker; + } }); + var bytesEncoding_js_1 = require_bytesEncoding(); + Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { + return bytesEncoding_js_1.uint8ArrayToString; + } }); + Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { + return bytesEncoding_js_1.stringToUint8Array; + } }); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js -var require_exponentialRetryStrategy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js +var require_sanitizer = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryStrategy = exponentialRetryStrategy; - exports2.isExponentialRetryResponse = isExponentialRetryResponse; - exports2.isSystemError = isSystemError; + exports2.Sanitizer = void 0; var core_util_1 = require_commonjs2(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; - var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; - function exponentialRetryStrategy(options = {}) { - var _a, _b; - const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; - const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - let retryAfterInMs = retryInterval; - return { - name: "exponentialRetryStrategy", - retry({ retryCount, response, responseError }) { - const matchedSystemError = isSystemError(responseError); - const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; - const isExponential = isExponentialRetryResponse(response); - const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; - const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); - if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { - return { skipStrategy: true }; + var RedactedString = "REDACTED"; + var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" + ]; + var defaultAllowedQueryParameters = ["api-version"]; + var Sanitizer = class { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); } - if (responseError && !matchedSystemError && !isExponential) { - return { errorToThrow: responseError }; + if (key === "headers") { + return this.sanitizeHeaders(value); + } else if (key === "url") { + return this.sanitizeUrl(value); + } else if (key === "query") { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); } - const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); - const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); - retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2); - return { retryAfterInMs }; + return value; + }, 2); + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; } - }; - } - function isExponentialRetryResponse(response) { - return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); - } - function isSystemError(err) { - if (!err) { - return false; + const url2 = new URL(value); + if (!url2.search) { + return value; + } + for (const [key] of url2.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url2.searchParams.set(key, RedactedString); + } + } + return url2.toString(); } - return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; - } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } + }; + exports2.Sanitizer = Sanitizer; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js -var require_retryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js +var require_logPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.retryPolicy = retryPolicy; - var helpers_js_1 = require_helpers2(); - var logger_1 = require_dist(); - var abort_controller_1 = require_commonjs3(); - var constants_js_1 = require_constants8(); - var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); - var retryPolicyName = "retryPolicy"; - function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { - const logger = options.logger || retryPolicyLogger; + exports2.logPolicyName = void 0; + exports2.logPolicy = logPolicy; + var log_js_1 = require_log(); + var sanitizer_js_1 = require_sanitizer(); + exports2.logPolicyName = "logPolicy"; + function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); return { - name: retryPolicyName, + name: exports2.logPolicyName, async sendRequest(request, next) { - var _a, _b; - let response; - let responseError; - let retryCount = -1; - retryRequest: while (true) { - retryCount += 1; - response = void 0; - responseError = void 0; - try { - logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); - response = await next(request); - logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); - } catch (e) { - logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); - responseError = e; - if (!e || responseError.name !== "RestError") { - throw e; - } - response = responseError.response; - } - if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - logger.error(`Retry ${retryCount}: Request aborted.`); - const abortError = new abort_controller_1.AbortError(); - throw abortError; - } - if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { - logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); - if (responseError) { - throw responseError; - } else if (response) { - return response; - } else { - throw new Error("Maximum retries reached with no response or error to throw"); - } - } - logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); - strategiesLoop: for (const strategy of strategies) { - const strategyLogger = strategy.logger || retryPolicyLogger; - strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); - const modifiers = strategy.retry({ - retryCount, - response, - responseError - }); - if (modifiers.skipStrategy) { - strategyLogger.info(`Retry ${retryCount}: Skipped.`); - continue strategiesLoop; - } - const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; - if (errorToThrow) { - strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); - throw errorToThrow; - } - if (retryAfterInMs || retryAfterInMs === 0) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); - await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); - continue retryRequest; - } - if (redirectTo) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); - request.url = redirectTo; - continue retryRequest; - } - } - if (responseError) { - logger.info(`None of the retry strategies could work with the received error. Throwing it.`); - throw responseError; - } - if (response) { - logger.info(`None of the retry strategies could work with the received response. Returning it.`); - return response; - } + if (!logger.enabled) { + return next(request); } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; } }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js -var require_defaultRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.defaultRetryPolicyName = void 0; - exports2.defaultRetryPolicy = defaultRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.defaultRetryPolicyName = "defaultRetryPolicy"; - function defaultRetryPolicy(options = {}) { - var _a; + exports2.redirectPolicyName = void 0; + exports2.redirectPolicy = redirectPolicy; + exports2.redirectPolicyName = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; return { - name: exports2.defaultRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest + name: exports2.redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + } }; } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js -var require_httpHeaders = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createHttpHeaders = createHttpHeaders; - function normalizeName(name) { - return name.toLowerCase(); - } - function* headerIterator(map2) { - for (const entry of map2.values()) { - yield [entry.name, entry.value]; - } - } - var HttpHeadersImpl = class { - constructor(rawHeaders) { - this._headersMap = /* @__PURE__ */ new Map(); - if (rawHeaders) { - for (const headerName of Object.keys(rawHeaders)) { - this.set(headerName, rawHeaders[headerName]); - } - } - } - /** - * Set a header in this collection with the provided name and value. The name is - * case-insensitive. - * @param name - The name of the header to set. This value is case-insensitive. - * @param value - The value of the header to set. - */ - set(name, value) { - this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); - } - /** - * Get the header value for the provided header name, or undefined if no header exists in this - * collection with the provided name. - * @param name - The name of the header. This value is case-insensitive. - */ - get(name) { - var _a; - return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; - } - /** - * Get whether or not this header collection contains a header entry for the provided header name. - * @param name - The name of the header to set. This value is case-insensitive. - */ - has(name) { - return this._headersMap.has(normalizeName(name)); - } - /** - * Remove the header with the provided headerName. - * @param name - The name of the header to remove. - */ - delete(name) { - this._headersMap.delete(normalizeName(name)); - } - /** - * Get the JSON object representation of this HTTP header collection. - */ - toJSON(options = {}) { - const result = {}; - if (options.preserveCase) { - for (const entry of this._headersMap.values()) { - result[entry.name] = entry.value; - } - } else { - for (const [normalizedName, entry] of this._headersMap) { - result[normalizedName] = entry.value; - } + async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url2 = new URL(locationHeader, request.url); + request.url = url2.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; } - return result; - } - /** - * Get the string representation of this HTTP header collection. - */ - toString() { - return JSON.stringify(this.toJSON({ preserveCase: true })); - } - /** - * Iterate over tuples of header [name, value] pairs. - */ - [Symbol.iterator]() { - return headerIterator(this._headersMap); + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); } - }; - function createHttpHeaders(rawHeaders) { - return new HttpHeadersImpl(rawHeaders); + return response; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js -var require_formDataPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.formDataPolicyName = void 0; - exports2.formDataPolicy = formDataPolicy; - var core_util_1 = require_commonjs2(); - var httpHeaders_js_1 = require_httpHeaders(); - exports2.formDataPolicyName = "formDataPolicy"; - function formDataToFormDataMap(formData) { - var _a; - const formDataMap = {}; - for (const [key, value] of formData.entries()) { - (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = []; - formDataMap[key].push(value); - } - return formDataMap; - } - function formDataPolicy() { - return { - name: exports2.formDataPolicyName, - async sendRequest(request, next) { - if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { - request.formData = formDataToFormDataMap(request.body); - request.body = void 0; - } - if (request.formData) { - const contentType = request.headers.get("Content-Type"); - if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { - request.body = wwwFormUrlEncode(request.formData); - } else { - await prepareFormData(request.formData, request); - } - request.formData = void 0; - } - return next(request); - } - }; - } - function wwwFormUrlEncode(formData) { - const urlSearchParams = new URLSearchParams(); - for (const [key, value] of Object.entries(formData)) { - if (Array.isArray(value)) { - for (const subValue of value) { - urlSearchParams.append(key, subValue.toString()); - } - } else { - urlSearchParams.append(key, value.toString()); - } - } - return urlSearchParams.toString(); - } - async function prepareFormData(formData, request) { - const contentType = request.headers.get("Content-Type"); - if (contentType && !contentType.startsWith("multipart/form-data")) { - return; - } - request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); - const parts = []; - for (const [fieldName, values] of Object.entries(formData)) { - for (const value of Array.isArray(values) ? values : [values]) { - if (typeof value === "string") { - parts.push({ - headers: (0, httpHeaders_js_1.createHttpHeaders)({ - "Content-Disposition": `form-data; name="${fieldName}"` - }), - body: (0, core_util_1.stringToUint8Array)(value, "utf-8") - }); - } else if (value === void 0 || value === null || typeof value !== "object") { - throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); - } else { - const fileName = value.name || "blob"; - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); - headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); - headers.set("Content-Type", value.type || "application/octet-stream"); - parts.push({ - headers, - body: value - }); - } - } - } - request.multipartBody = { parts }; +// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __addDisposableResource: () => __addDisposableResource, + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __disposeResources: () => __disposeResources, + __esDecorate: () => __esDecorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __propKey: () => __propKey, + __read: () => __read, + __rest: () => __rest, + __runInitializers: () => __runInitializers, + __setFunctionName: () => __setFunctionName, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values2, + default: () => tslib_es6_default +}); +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; } + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; } -}); - -// node_modules/ms/index.js -var require_ms = __commonJS({ - "node_modules/ms/index.js"(exports2, module2) { - var s = 1e3; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - module2.exports = function(val2, options) { - options = options || {}; - var type2 = typeof val2; - if (type2 === "string" && val2.length > 0) { - return parse(val2); - } else if (type2 === "number" && isFinite(val2)) { - return options.long ? fmtLong(val2) : fmtShort(val2); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2) - ); + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _2, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context3 = {}; + for (var p in contextIn) context3[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context3.access[p] = contextIn.access[p]; + context3.addInitializer = function(f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); }; - function parse(str2) { - str2 = String(str2); - if (str2.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str2 - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type2 = (match[2] || "ms").toLowerCase(); - switch (type2) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "weeks": - case "week": - case "w": - return n * w; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return void 0; - } + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context3); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_2 = accept(result.get)) descriptor.get = _2; + if (_2 = accept(result.set)) descriptor.set = _2; + if (_2 = accept(result.init)) initializers.unshift(_2); + } else if (_2 = accept(result)) { + if (kind === "field") initializers.unshift(_2); + else descriptor[key] = _2; } - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; - } - if (msAbs >= m) { - return Math.round(ms / m) + "m"; - } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - return ms + "ms"; } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, "minute"); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return ms + " ms"; } - function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _2 = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n) { + return function(v) { + return step([n, v]); + }; } -}); - -// node_modules/debug/src/common.js -var require_common = __commonJS({ - "node_modules/debug/src/common.js"(exports2, module2) { - function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce3; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require_ms(); - createDebug.destroy = destroy; - Object.keys(env).forEach((key) => { - createDebug[key] = env[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash2 = 0; - for (let i = 0; i < namespace.length; i++) { - hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); - hash2 |= 0; - } - return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug5(...args) { - if (!debug5.enabled) { - return; - } - const self2 = debug5; - const curr = Number(/* @__PURE__ */ new Date()); - const ms = curr - (prevTime || curr); - self2.diff = ms; - self2.prev = prevTime; - self2.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_2 = 0)), _2) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _2.label++; + return { value: op[1], done: false }; + case 5: + _2.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; + continue; } - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - if (match === "%%") { - return "%"; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === "function") { - const val2 = args[index]; - match = formatter.call(self2, val2); - args.splice(index, 1); - index--; - } - return match; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); - } - debug5.namespace = namespace; - debug5.useColors = createDebug.useColors(); - debug5.color = createDebug.selectColor(namespace); - debug5.extend = extend3; - debug5.destroy = createDebug.destroy; - Object.defineProperty(debug5, "enabled", { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, - set: (v) => { - enableOverride = v; + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _2.label = op[1]; + break; } - }); - if (typeof createDebug.init === "function") { - createDebug.init(debug5); - } - return debug5; - } - function extend3(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns of split) { - if (ns[0] === "-") { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); + if (op[0] === 6 && _2.label < t[1]) { + _2.label = t[1]; + t = op; + break; } - } - } - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { - if (template[templateIndex] === "*") { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; + if (t && _2.label < t[2]) { + _2.label = t[2]; + _2.ops.push(op); + break; } - } - while (templateIndex < template.length && template[templateIndex] === "*") { - templateIndex++; - } - return templateIndex === template.length; - } - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; + if (t[2]) _2.ops.pop(); + _2.trys.pop(); + continue; } - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; - } - } - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; - } - } - return false; - } - function coerce3(val2) { - if (val2 instanceof Error) { - return val2.stack || val2.message; - } - return val2; - } - function destroy() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - createDebug.enable(createDebug.load()); - return createDebug; + op = body.call(thisArg, _2); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; } - module2.exports = setup; + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; } -}); - -// node_modules/debug/src/browser.js -var require_browser = __commonJS({ - "node_modules/debug/src/browser.js"(exports2, module2) { - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load2; - exports2.useColors = useColors; - exports2.storage = localstorage(); - exports2.destroy = /* @__PURE__ */ (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } +} +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} +function __values2(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function() { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error4) { + e = { error: error4 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); }; - })(); - exports2.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - let m; - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 - typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker - typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + if (f) i[n] = f(i[n]); } - function formatArgs(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; - } - index++; - if (match === "%c") { - lastC = index; - } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function(e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function() { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function(v) { + return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; + } : f; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve8, reject) { + v = o[n](v), settle(resolve8, reject, v.done, v.value); }); - args.splice(lastC, 0, c); + }; + } + function settle(resolve8, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve8({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; } - exports2.log = console.debug || console.log || (() => { - }); - function save(namespaces) { - try { - if (namespaces) { - exports2.storage.setItem("debug", namespaces); - } else { - exports2.storage.removeItem("debug"); - } - } catch (error4) { - } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; } - function load2() { - let r; + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { - r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); - } catch (error4) { - } - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; + inner.call(this); + } catch (e) { + return Promise.reject(e); } - return r; - } - function localstorage() { + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { try { - return localStorage; - } catch (error4) { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); } } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error4) { - return "[UnexpectedJSONParseError]: " + error4.message; + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; +var init_tslib_es6 = __esm({ + "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() { + extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + __assign = function() { + __assign = Object.assign || function __assign4(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; + }; + tslib_es6_default = { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values: __values2, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources }; } }); -// node_modules/has-flag/index.js -var require_has_flag = __commonJS({ - "node_modules/has-flag/index.js"(exports2, module2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js +var require_userAgentPlatform = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { "use strict"; - module2.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf("--"); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); - }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getHeaderName = getHeaderName; + exports2.setPlatformSpecificData = setPlatformSpecificData; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var os3 = tslib_1.__importStar(require("node:os")); + var process2 = tslib_1.__importStar(require("node:process")); + function getHeaderName() { + return "User-Agent"; + } + async function setPlatformSpecificData(map2) { + if (process2 && process2.versions) { + const versions = process2.versions; + if (versions.bun) { + map2.set("Bun", versions.bun); + } else if (versions.deno) { + map2.set("Deno", versions.deno); + } else if (versions.node) { + map2.set("Node", versions.node); + } + } + map2.set("OS", `(${os3.arch()}-${os3.type()}-${os3.release()})`); + } } }); -// node_modules/supports-color/index.js -var require_supports_color = __commonJS({ - "node_modules/supports-color/index.js"(exports2, module2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js +var require_constants8 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { "use strict"; - var os3 = require("os"); - var tty = require("tty"); - var hasFlag = require_has_flag(); - var { env } = process; - var forceColor; - if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { - forceColor = 0; - } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { - forceColor = 1; - } - if ("FORCE_COLOR" in env) { - if (env.FORCE_COLOR === "true") { - forceColor = 1; - } else if (env.FORCE_COLOR === "false") { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; + exports2.SDK_VERSION = "1.17.0"; + exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js +var require_userAgent = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getUserAgentHeaderName = getUserAgentHeaderName; + exports2.getUserAgentValue = getUserAgentValue; + var userAgentPlatform_js_1 = require_userAgentPlatform(); + var constants_js_1 = require_constants8(); + function getUserAgentString(telemetryInfo) { + const parts = []; + for (const [key, value] of telemetryInfo) { + const token = value ? `${key}/${value}` : key; + parts.push(token); } + return parts.join(" "); } - function translateLevel(level) { - if (level === 0) { - return false; - } + function getUserAgentHeaderName() { + return (0, userAgentPlatform_js_1.getHeaderName)(); + } + async function getUserAgentValue(prefix) { + const runtimeInfo = /* @__PURE__ */ new Map(); + runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); + await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); + const defaultAgent = getUserAgentString(runtimeInfo); + const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; + return userAgentValue; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js +var require_userAgentPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.userAgentPolicyName = void 0; + exports2.userAgentPolicy = userAgentPolicy; + var userAgent_js_1 = require_userAgent(); + var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); + exports2.userAgentPolicyName = "userAgentPolicy"; + function userAgentPolicy(options = {}) { + const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 + name: exports2.userAgentPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(UserAgentHeaderName)) { + request.headers.set(UserAgentHeaderName, await userAgentValue); + } + return next(request); + } }; } - function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } - if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { - return 3; - } - if (hasFlag("color=256")) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === void 0) { - return 0; - } - const min = forceColor || 0; - if (env.TERM === "dumb") { - return min; - } - if (process.platform === "win32") { - const osRelease = os3.release().split("."); - if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - return 1; - } - if ("CI" in env) { - if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { - return 1; - } - return min; - } - if ("TEAMCITY_VERSION" in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - if (env.COLORTERM === "truecolor") { - return 3; - } - if ("TERM_PROGRAM" in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (env.TERM_PROGRAM) { - case "iTerm.app": - return version >= 3 ? 3 : 2; - case "Apple_Terminal": - return 2; - } - } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - if ("COLORTERM" in env) { - return 1; - } - return min; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js +var require_typeGuards2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isNodeReadableStream = isNodeReadableStream; + exports2.isWebReadableStream = isWebReadableStream; + exports2.isReadableStream = isReadableStream; + exports2.isBlob = isBlob; + function isNodeReadableStream(x) { + return Boolean(x && typeof x["pipe"] === "function"); } - function getSupportLevel(stream2) { - const level = supportsColor(stream2, stream2 && stream2.isTTY); - return translateLevel(level); + function isWebReadableStream(x) { + return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); + } + function isReadableStream(x) { + return isNodeReadableStream(x) || isWebReadableStream(x); + } + function isBlob(x) { + return typeof x.stream === "function"; } - module2.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) - }; } }); -// node_modules/debug/src/node.js -var require_node = __commonJS({ - "node_modules/debug/src/node.js"(exports2, module2) { - var tty = require("tty"); - var util = require("util"); - exports2.init = init; - exports2.log = log; - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load2; - exports2.useColors = useColors; - exports2.destroy = util.deprecate( - () => { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js +var require_file2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRawContent = getRawContent; + exports2.createFileFromStream = createFileFromStream; + exports2.createFile = createFile; + var core_util_1 = require_commonjs2(); + var typeGuards_js_1 = require_typeGuards2(); + var unimplementedMethods = { + arrayBuffer: () => { + throw new Error("Not implemented"); }, - "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." - ); - exports2.colors = [6, 2, 3, 4, 5, 1]; - try { - const supportsColor = require_supports_color(); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports2.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; + slice: () => { + throw new Error("Not implemented"); + }, + text: () => { + throw new Error("Not implemented"); } - } catch (error4) { + }; + var rawContent = Symbol("rawContent"); + function hasRawContent(x) { + return typeof x[rawContent] === "function"; } - exports2.inspectOpts = Object.keys(process.env).filter((key) => { - return /^debug_/i.test(key); - }).reduce((obj, key) => { - const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_2, k) => { - return k.toUpperCase(); - }); - let val2 = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val2)) { - val2 = true; - } else if (/^(no|off|false|disabled)$/i.test(val2)) { - val2 = false; - } else if (val2 === "null") { - val2 = null; + function getRawContent(blob) { + if (hasRawContent(blob)) { + return blob[rawContent](); } else { - val2 = Number(val2); + return blob.stream(); } - obj[prop] = val2; - return obj; - }, {}); - function useColors() { - return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); } - function formatArgs(args) { - const { namespace: name, useColors: useColors2 } = this; - if (useColors2) { - const c = this.color; - const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); - const prefix = ` ${colorCode};1m${name} \x1B[0m`; - args[0] = prefix + args[0].split("\n").join("\n" + prefix); - args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + function createFileFromStream(stream2, name, options = {}) { + var _a, _b, _c, _d; + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { + const s = stream2(); + if ((0, typeGuards_js_1.isNodeReadableStream)(s)) { + throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); + } + return s; + }, [rawContent]: stream2 }); + } + function createFile(content, name, options = {}) { + var _a, _b, _c; + if (core_util_1.isNodeLike) { + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); } else { - args[0] = getDate() + name + " " + args[0]; + return new File([content], name, options); } } - function getDate() { - if (exports2.inspectOpts.hideDate) { - return ""; - } - return (/* @__PURE__ */ new Date()).toISOString() + " "; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js +var require_concat = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.concat = concat; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var node_stream_1 = require("node:stream"); + var typeGuards_js_1 = require_typeGuards2(); + var file_js_1 = require_file2(); + function streamAsyncIterator() { + return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { + const reader = this.getReader(); + try { + while (true) { + const { done, value } = yield tslib_1.__await(reader.read()); + if (done) { + return yield tslib_1.__await(void 0); + } + yield yield tslib_1.__await(value); + } + } finally { + reader.releaseLock(); + } + }); } - function log(...args) { - return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + function makeAsyncIterable(webStream) { + if (!webStream[Symbol.asyncIterator]) { + webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); + } + if (!webStream.values) { + webStream.values = streamAsyncIterator.bind(webStream); + } } - function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; + function ensureNodeStream(stream2) { + if (stream2 instanceof ReadableStream) { + makeAsyncIterable(stream2); + return node_stream_1.Readable.fromWeb(stream2); } else { - delete process.env.DEBUG; + return stream2; } } - function load2() { - return process.env.DEBUG; - } - function init(debug5) { - debug5.inspectOpts = {}; - const keys = Object.keys(exports2.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug5.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + function toStream(source) { + if (source instanceof Uint8Array) { + return node_stream_1.Readable.from(Buffer.from(source)); + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return toStream((0, file_js_1.getRawContent)(source)); + } else { + return ensureNodeStream(source); } } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" "); - }; - formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); - }; - } -}); - -// node_modules/debug/src/index.js -var require_src = __commonJS({ - "node_modules/debug/src/index.js"(exports2, module2) { - if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { - module2.exports = require_browser(); - } else { - module2.exports = require_node(); + async function concat(sources) { + return function() { + const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); + return node_stream_1.Readable.from((function() { + return tslib_1.__asyncGenerator(this, arguments, function* () { + var _a, e_1, _b, _c; + for (const stream2 of streams) { + try { + for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream2)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { + _c = stream_1_1.value; + _d = false; + const chunk = _c; + yield yield tslib_1.__await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1)); + } finally { + if (e_1) throw e_1.error; + } + } + } + }); + })()); + }; } } }); -// node_modules/agent-base/dist/helpers.js -var require_helpers3 = __commonJS({ - "node_modules/agent-base/dist/helpers.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js +var require_multipartPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.req = exports2.json = exports2.toBuffer = void 0; - var http = __importStar4(require("http")); - var https2 = __importStar4(require("https")); - async function toBuffer(stream2) { - let length = 0; - const chunks = []; - for await (const chunk of stream2) { - length += chunk.length; - chunks.push(chunk); + exports2.multipartPolicyName = void 0; + exports2.multipartPolicy = multipartPolicy; + var core_util_1 = require_commonjs2(); + var concat_js_1 = require_concat(); + var typeGuards_js_1 = require_typeGuards2(); + function generateBoundary() { + return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; + } + function encodeHeaders(headers) { + let result = ""; + for (const [key, value] of headers) { + result += `${key}: ${value}\r +`; } - return Buffer.concat(chunks, length); + return result; } - exports2.toBuffer = toBuffer; - async function json2(stream2) { - const buf = await toBuffer(stream2); - const str2 = buf.toString("utf8"); - try { - return JSON.parse(str2); - } catch (_err) { - const err = _err; - err.message += ` (input: ${str2})`; - throw err; + function getLength(source) { + if (source instanceof Uint8Array) { + return source.byteLength; + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return source.size === -1 ? void 0 : source.size; + } else { + return void 0; } } - exports2.json = json2; - function req(url2, opts = {}) { - const href = typeof url2 === "string" ? url2 : url2.href; - const req2 = (href.startsWith("https:") ? https2 : http).request(url2, opts); - const promise = new Promise((resolve8, reject) => { - req2.once("response", resolve8).once("error", reject).end(); - }); - req2.then = promise.then.bind(promise); - return req2; + function getTotalLength(sources) { + let total = 0; + for (const source of sources) { + const partLength = getLength(source); + if (partLength === void 0) { + return void 0; + } else { + total += partLength; + } + } + return total; } - exports2.req = req; - } -}); - -// node_modules/agent-base/dist/index.js -var require_dist2 = __commonJS({ - "node_modules/agent-base/dist/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + async function buildRequestBody(request, parts, boundary) { + const sources = [ + (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"), + ...parts.flatMap((part) => [ + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + part.body, + (0, core_util_1.stringToUint8Array)(`\r +--${boundary}`, "utf-8") + ]), + (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8") + ]; + const contentLength = getTotalLength(sources); + if (contentLength) { + request.headers.set("Content-Length", contentLength); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + request.body = await (0, concat_js_1.concat)(sources); + } + exports2.multipartPolicyName = "multipartPolicy"; + var maxBoundaryLength = 70; + var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); + function assertValidBoundary(boundary) { + if (boundary.length > maxBoundaryLength) { + throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); } - __setModuleDefault4(result, mod); - return result; - }; - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Agent = void 0; - var net = __importStar4(require("net")); - var http = __importStar4(require("http")); - var https_1 = require("https"); - __exportStar4(require_helpers3(), exports2); - var INTERNAL = Symbol("AgentBaseInternalState"); - var Agent = class extends http.Agent { - constructor(opts) { - super(opts); - this[INTERNAL] = {}; + if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { + throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); } - /** - * Determine whether this is an `http` or `https` request. - */ - isSecureEndpoint(options) { - if (options) { - if (typeof options.secureEndpoint === "boolean") { - return options.secureEndpoint; + } + function multipartPolicy() { + return { + name: exports2.multipartPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.multipartBody) { + return next(request); } - if (typeof options.protocol === "string") { - return options.protocol === "https:"; + if (request.body) { + throw new Error("multipartBody and regular body cannot be set at the same time"); } - } - const { stack } = new Error(); - if (typeof stack !== "string") - return false; - return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); - } - // In order to support async signatures in `connect()` and Node's native - // connection pooling in `http.Agent`, the array of sockets for each origin - // has to be updated synchronously. This is so the length of the array is - // accurate when `addRequest()` is next called. We achieve this by creating a - // fake socket and adding it to `sockets[origin]` and incrementing - // `totalSocketCount`. - incrementSockets(name) { - if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { - return null; - } - if (!this.sockets[name]) { - this.sockets[name] = []; - } - const fakeSocket = new net.Socket({ writable: false }); - this.sockets[name].push(fakeSocket); - this.totalSocketCount++; - return fakeSocket; - } - decrementSockets(name, socket) { - if (!this.sockets[name] || socket === null) { - return; - } - const sockets = this.sockets[name]; - const index = sockets.indexOf(socket); - if (index !== -1) { - sockets.splice(index, 1); - this.totalSocketCount--; - if (sockets.length === 0) { - delete this.sockets[name]; + let boundary = request.multipartBody.boundary; + const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; + const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); + if (!parsedHeader) { + throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); } - } - } - // In order to properly update the socket pool, we need to call `getName()` on - // the core `https.Agent` if it is a secureEndpoint. - getName(options) { - const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options); - if (secureEndpoint) { - return https_1.Agent.prototype.getName.call(this, options); - } - return super.getName(options); - } - createSocket(req, options, cb) { - const connectOpts = { - ...options, - secureEndpoint: this.isSecureEndpoint(options) - }; - const name = this.getName(connectOpts); - const fakeSocket = this.incrementSockets(name); - Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { - this.decrementSockets(name, fakeSocket); - if (socket instanceof http.Agent) { - try { - return socket.addRequest(req, connectOpts); - } catch (err) { - return cb(err); - } + const [, contentType, parsedBoundary] = parsedHeader; + if (parsedBoundary && boundary && parsedBoundary !== boundary) { + throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); } - this[INTERNAL].currentSocket = socket; - super.createSocket(req, options, cb); - }, (err) => { - this.decrementSockets(name, fakeSocket); - cb(err); - }); - } - createConnection() { - const socket = this[INTERNAL].currentSocket; - this[INTERNAL].currentSocket = void 0; - if (!socket) { - throw new Error("No socket was returned in the `connect()` function"); - } - return socket; - } - get defaultPort() { - return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); - } - set defaultPort(v) { - if (this[INTERNAL]) { - this[INTERNAL].defaultPort = v; + boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary; + if (boundary) { + assertValidBoundary(boundary); + } else { + boundary = generateBoundary(); + } + request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); + await buildRequestBody(request, request.multipartBody.parts, boundary); + request.multipartBody = void 0; + return next(request); } - } - get protocol() { - return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); - } - set protocol(v) { - if (this[INTERNAL]) { - this[INTERNAL].protocol = v; + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js +var require_decompressResponsePolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.decompressResponsePolicyName = void 0; + exports2.decompressResponsePolicy = decompressResponsePolicy; + exports2.decompressResponsePolicyName = "decompressResponsePolicy"; + function decompressResponsePolicy() { + return { + name: exports2.decompressResponsePolicyName, + async sendRequest(request, next) { + if (request.method !== "HEAD") { + request.headers.set("Accept-Encoding", "gzip,deflate"); + } + return next(request); } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } }; - exports2.Agent = Agent; + exports2.AbortError = AbortError; } }); -// node_modules/https-proxy-agent/dist/parse-proxy-response.js -var require_parse_proxy_response = __commonJS({ - "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs3 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { "use strict"; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.parseProxyResponse = void 0; - var debug_1 = __importDefault4(require_src()); - var debug5 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); - function parseProxyResponse(socket) { + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError2(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js +var require_helpers2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay2; + exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; + var abort_controller_1 = require_commonjs3(); + var StandardAbortMessage = "The operation was aborted."; + function delay2(delayInMs, value, options) { return new Promise((resolve8, reject) => { - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once("readable", read); - } - function cleanup() { - socket.removeListener("end", onend); - socket.removeListener("error", onerror); - socket.removeListener("readable", read); - } - function onend() { - cleanup(); - debug5("onend"); - reject(new Error("Proxy connection ended before receiving CONNECT response")); - } - function onerror(err) { - cleanup(); - debug5("onerror %o", err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf("\r\n\r\n"); - if (endOfHeaders === -1) { - debug5("have not received end of HTTP headers yet..."); - read(); - return; - } - const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); - const firstLine = headerParts.shift(); - if (!firstLine) { - socket.destroy(); - return reject(new Error("No header received from proxy CONNECT response")); + let timer = void 0; + let onAborted = void 0; + const rejectOnAbort = () => { + return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); } - const firstLineParts = firstLine.split(" "); - const statusCode = +firstLineParts[1]; - const statusText = firstLineParts.slice(2).join(" "); - const headers = {}; - for (const header of headerParts) { - if (!header) - continue; - const firstColon = header.indexOf(":"); - if (firstColon === -1) { - socket.destroy(); - return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); - } - const key = header.slice(0, firstColon).toLowerCase(); - const value = header.slice(firstColon + 1).trimStart(); - const current = headers[key]; - if (typeof current === "string") { - headers[key] = [current, value]; - } else if (Array.isArray(current)) { - current.push(value); - } else { - headers[key] = value; - } + }; + onAborted = () => { + if (timer) { + clearTimeout(timer); } - debug5("got proxy server response: %o %o", firstLine, headers); - cleanup(); - resolve8({ - connect: { - statusCode, - statusText, - headers - }, - buffered - }); + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve8(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); } - socket.on("error", onerror); - socket.on("end", onend); - read(); }); } - exports2.parseProxyResponse = parseProxyResponse; + function parseHeaderValueAsNumber(response, headerName) { + const value = response.headers.get(headerName); + if (!value) + return; + const valueAsNum = Number(value); + if (Number.isNaN(valueAsNum)) + return; + return valueAsNum; + } } }); -// node_modules/https-proxy-agent/dist/index.js -var require_dist3 = __commonJS({ - "node_modules/https-proxy-agent/dist/index.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js +var require_throttlingRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpsProxyAgent = void 0; - var net = __importStar4(require("net")); - var tls = __importStar4(require("tls")); - var assert_1 = __importDefault4(require("assert")); - var debug_1 = __importDefault4(require_src()); - var agent_base_1 = require_dist2(); - var url_1 = require("url"); - var parse_proxy_response_1 = require_parse_proxy_response(); - var debug5 = (0, debug_1.default)("https-proxy-agent"); - var setServernameFromNonIpHost = (options) => { - if (options.servername === void 0 && options.host && !net.isIP(options.host)) { - return { - ...options, - servername: options.host - }; - } - return options; - }; - var HttpsProxyAgent = class extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.options = { path: void 0 }; - this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug5("Creating new HttpsProxyAgent instance: %o", this.proxy.href); - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); - const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; - this.connectOpts = { - // Attempt to negotiate http/1.1 for proxy servers that support http/2 - ALPNProtocols: ["http/1.1"], - ...opts ? omit(opts, "headers") : null, - host, - port - }; + exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; + exports2.throttlingRetryStrategy = throttlingRetryStrategy; + var helpers_js_1 = require_helpers2(); + var RetryAfterHeader = "Retry-After"; + var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; + function getRetryAfterInMs(response) { + if (!(response && [429, 503].includes(response.status))) + return void 0; + try { + for (const header of AllRetryAfterHeaders) { + const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); + if (retryAfterValue === 0 || retryAfterValue) { + const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; + return retryAfterValue * multiplyingFactor; + } + } + const retryAfterHeader = response.headers.get(RetryAfterHeader); + if (!retryAfterHeader) + return; + const date = Date.parse(retryAfterHeader); + const diff = date - Date.now(); + return Number.isFinite(diff) ? Math.max(0, diff) : void 0; + } catch (_a) { + return void 0; } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - */ - async connect(req, opts) { - const { proxy } = this; - if (!opts.host) { - throw new TypeError('No "host" provided'); + } + function isThrottlingRetryResponse(response) { + return Number.isFinite(getRetryAfterInMs(response)); + } + function throttlingRetryStrategy() { + return { + name: "throttlingRetryStrategy", + retry({ response }) { + const retryAfterInMs = getRetryAfterInMs(response); + if (!Number.isFinite(retryAfterInMs)) { + return { skipStrategy: true }; + } + return { + retryAfterInMs + }; } - let socket; - if (proxy.protocol === "https:") { - debug5("Creating `tls.Socket`: %o", this.connectOpts); - socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); - } else { - debug5("Creating `net.Socket`: %o", this.connectOpts); - socket = net.connect(this.connectOpts); - } - const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; - const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; - let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r -`; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; - } - headers.Host = `${host}:${opts.port}`; - if (!headers["Proxy-Connection"]) { - headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; - } - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r -`; - } - const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); - socket.write(`${payload}\r -`); - const { connect, buffered } = await proxyResponsePromise; - req.emit("proxyConnect", connect); - this.emit("proxyConnect", connect, req); - if (connect.statusCode === 200) { - req.once("socket", resume); - if (opts.secureEndpoint) { - debug5("Upgrading socket connection to TLS"); - return tls.connect({ - ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), - socket - }); - } - return socket; - } - socket.destroy(); - const fakeSocket = new net.Socket({ writable: false }); - fakeSocket.readable = true; - req.once("socket", (s) => { - debug5("Replaying proxy buffer for failed request"); - (0, assert_1.default)(s.listenerCount("data") > 0); - s.push(buffered); - s.push(null); - }); - return fakeSocket; - } - }; - HttpsProxyAgent.protocols = ["http", "https"]; - exports2.HttpsProxyAgent = HttpsProxyAgent; - function resume(socket) { - socket.resume(); - } - function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - } -}); - -// node_modules/http-proxy-agent/dist/index.js -var require_dist4 = __commonJS({ - "node_modules/http-proxy-agent/dist/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpProxyAgent = void 0; - var net = __importStar4(require("net")); - var tls = __importStar4(require("tls")); - var debug_1 = __importDefault4(require_src()); - var events_1 = require("events"); - var agent_base_1 = require_dist2(); - var url_1 = require("url"); - var debug5 = (0, debug_1.default)("http-proxy-agent"); - var HttpProxyAgent = class extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug5("Creating new HttpProxyAgent instance: %o", this.proxy.href); - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); - const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; - this.connectOpts = { - ...opts ? omit(opts, "headers") : null, - host, - port - }; - } - addRequest(req, opts) { - req._header = null; - this.setRequestProps(req, opts); - super.addRequest(req, opts); - } - setRequestProps(req, opts) { - const { proxy } = this; - const protocol = opts.secureEndpoint ? "https:" : "http:"; - const hostname = req.getHeader("host") || "localhost"; - const base = `${protocol}//${hostname}`; - const url2 = new url_1.URL(req.path, base); - if (opts.port !== 80) { - url2.port = String(opts.port); - } - req.path = String(url2); - const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; - } - if (!headers["Proxy-Connection"]) { - headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; - } - for (const name of Object.keys(headers)) { - const value = headers[name]; - if (value) { - req.setHeader(name, value); - } - } - } - async connect(req, opts) { - req._header = null; - if (!req.path.includes("://")) { - this.setRequestProps(req, opts); - } - let first; - let endOfHeaders; - debug5("Regenerating stored HTTP header string for request"); - req._implicitHeader(); - if (req.outputData && req.outputData.length > 0) { - debug5("Patching connection write() output buffer with updated header"); - first = req.outputData[0].data; - endOfHeaders = first.indexOf("\r\n\r\n") + 4; - req.outputData[0].data = req._header + first.substring(endOfHeaders); - debug5("Output buffer: %o", req.outputData[0].data); - } - let socket; - if (this.proxy.protocol === "https:") { - debug5("Creating `tls.Socket`: %o", this.connectOpts); - socket = tls.connect(this.connectOpts); - } else { - debug5("Creating `net.Socket`: %o", this.connectOpts); - socket = net.connect(this.connectOpts); - } - await (0, events_1.once)(socket, "connect"); - return socket; - } - }; - HttpProxyAgent.protocols = ["http", "https"]; - exports2.HttpProxyAgent = HttpProxyAgent; - function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; + }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js -var require_proxyPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js +var require_exponentialRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; - exports2.loadNoProxy = loadNoProxy; - exports2.getDefaultProxySettings = getDefaultProxySettings; - exports2.proxyPolicy = proxyPolicy; - var https_proxy_agent_1 = require_dist3(); - var http_proxy_agent_1 = require_dist4(); - var log_js_1 = require_log(); - var HTTPS_PROXY = "HTTPS_PROXY"; - var HTTP_PROXY = "HTTP_PROXY"; - var ALL_PROXY = "ALL_PROXY"; - var NO_PROXY = "NO_PROXY"; - exports2.proxyPolicyName = "proxyPolicy"; - exports2.globalNoProxyList = []; - var noProxyListLoaded = false; - var globalBypassedMap = /* @__PURE__ */ new Map(); - function getEnvironmentValue(name) { - if (process.env[name]) { - return process.env[name]; - } else if (process.env[name.toLowerCase()]) { - return process.env[name.toLowerCase()]; - } - return void 0; - } - function loadEnvironmentProxyValue() { - if (!process) { - return void 0; - } - const httpsProxy = getEnvironmentValue(HTTPS_PROXY); - const allProxy = getEnvironmentValue(ALL_PROXY); - const httpProxy = getEnvironmentValue(HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; - } - function isBypassed(uri, noProxyList, bypassedMap) { - if (noProxyList.length === 0) { - return false; - } - const host = new URL(uri).hostname; - if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { - return bypassedMap.get(host); - } - let isBypassedFlag = false; - for (const pattern of noProxyList) { - if (pattern[0] === ".") { - if (host.endsWith(pattern)) { - isBypassedFlag = true; - } else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } + exports2.exponentialRetryStrategy = exponentialRetryStrategy; + exports2.isExponentialRetryResponse = isExponentialRetryResponse; + exports2.isSystemError = isSystemError; + var core_util_1 = require_commonjs2(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; + var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; + function exponentialRetryStrategy(options = {}) { + var _a, _b; + const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; + const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + let retryAfterInMs = retryInterval; + return { + name: "exponentialRetryStrategy", + retry({ retryCount, response, responseError }) { + const matchedSystemError = isSystemError(responseError); + const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; + const isExponential = isExponentialRetryResponse(response); + const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; + const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); + if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { + return { skipStrategy: true }; } - } else { - if (host === pattern) { - isBypassedFlag = true; + if (responseError && !matchedSystemError && !isExponential) { + return { errorToThrow: responseError }; } + const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); + const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); + retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2); + return { retryAfterInMs }; } - } - bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); - return isBypassedFlag; - } - function loadNoProxy() { - const noProxy = getEnvironmentValue(NO_PROXY); - noProxyListLoaded = true; - if (noProxy) { - return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); - } - return []; - } - function getDefaultProxySettings(proxyUrl) { - if (!proxyUrl) { - proxyUrl = loadEnvironmentProxyValue(); - if (!proxyUrl) { - return void 0; - } - } - const parsedUrl = new URL(proxyUrl); - const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; - return { - host: schema2 + parsedUrl.hostname, - port: Number.parseInt(parsedUrl.port || "80"), - username: parsedUrl.username, - password: parsedUrl.password }; } - function getDefaultProxySettingsInternal() { - const envProxy = loadEnvironmentProxyValue(); - return envProxy ? new URL(envProxy) : void 0; - } - function getUrlFromProxySettings(settings) { - let parsedProxyUrl; - try { - parsedProxyUrl = new URL(settings.host); - } catch (_a) { - throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); - } - parsedProxyUrl.port = String(settings.port); - if (settings.username) { - parsedProxyUrl.username = settings.username; - } - if (settings.password) { - parsedProxyUrl.password = settings.password; - } - return parsedProxyUrl; - } - function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { - if (request.agent) { - return; - } - const url2 = new URL(request.url); - const isInsecure = url2.protocol !== "https:"; - if (request.tlsSettings) { - log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); - } - const headers = request.headers.toJSON(); - if (isInsecure) { - if (!cachedAgents.httpProxyAgent) { - cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpProxyAgent; - } else { - if (!cachedAgents.httpsProxyAgent) { - cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpsProxyAgent; - } + function isExponentialRetryResponse(response) { + return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); } - function proxyPolicy(proxySettings, options) { - if (!noProxyListLoaded) { - exports2.globalNoProxyList.push(...loadNoProxy()); + function isSystemError(err) { + if (!err) { + return false; } - const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); - const cachedAgents = {}; - return { - name: exports2.proxyPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) { - setProxyAgentOnRequest(request, cachedAgents, defaultProxy); - } else if (request.proxySettings) { - setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); - } - return next(request); - } - }; + return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js -var require_setClientRequestIdPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js +var require_retryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.setClientRequestIdPolicyName = void 0; - exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; - exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; - function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + exports2.retryPolicy = retryPolicy; + var helpers_js_1 = require_helpers2(); + var logger_1 = require_dist(); + var abort_controller_1 = require_commonjs3(); + var constants_js_1 = require_constants8(); + var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); + var retryPolicyName = "retryPolicy"; + function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { + const logger = options.logger || retryPolicyLogger; return { - name: exports2.setClientRequestIdPolicyName, + name: retryPolicyName, async sendRequest(request, next) { - if (!request.headers.has(requestIdHeaderName)) { - request.headers.set(requestIdHeaderName, request.requestId); + var _a, _b; + let response; + let responseError; + let retryCount = -1; + retryRequest: while (true) { + retryCount += 1; + response = void 0; + responseError = void 0; + try { + logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); + response = await next(request); + logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); + } catch (e) { + logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); + responseError = e; + if (!e || responseError.name !== "RestError") { + throw e; + } + response = responseError.response; + } + if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + logger.error(`Retry ${retryCount}: Request aborted.`); + const abortError = new abort_controller_1.AbortError(); + throw abortError; + } + if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { + logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + if (responseError) { + throw responseError; + } else if (response) { + return response; + } else { + throw new Error("Maximum retries reached with no response or error to throw"); + } + } + logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + strategiesLoop: for (const strategy of strategies) { + const strategyLogger = strategy.logger || retryPolicyLogger; + strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); + const modifiers = strategy.retry({ + retryCount, + response, + responseError + }); + if (modifiers.skipStrategy) { + strategyLogger.info(`Retry ${retryCount}: Skipped.`); + continue strategiesLoop; + } + const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; + if (errorToThrow) { + strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); + throw errorToThrow; + } + if (retryAfterInMs || retryAfterInMs === 0) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); + await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); + continue retryRequest; + } + if (redirectTo) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); + request.url = redirectTo; + continue retryRequest; + } + } + if (responseError) { + logger.info(`None of the retry strategies could work with the received error. Throwing it.`); + throw responseError; + } + if (response) { + logger.info(`None of the retry strategies could work with the received response. Returning it.`); + return response; + } } - return next(request); } }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js -var require_tlsPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js +var require_defaultRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tlsPolicyName = void 0; - exports2.tlsPolicy = tlsPolicy; - exports2.tlsPolicyName = "tlsPolicy"; - function tlsPolicy(tlsSettings) { + exports2.defaultRetryPolicyName = void 0; + exports2.defaultRetryPolicy = defaultRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.defaultRetryPolicyName = "defaultRetryPolicy"; + function defaultRetryPolicy(options = {}) { + var _a; return { - name: exports2.tlsPolicyName, - sendRequest: async (req, next) => { - if (!req.tlsSettings) { - req.tlsSettings = tlsSettings; - } - return next(req); - } + name: exports2.defaultRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest }; } } }); -// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js -var require_tracingContext = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js +var require_httpHeaders = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0; - exports2.knownContextKeys = { - span: Symbol.for("@azure/core-tracing span"), - namespace: Symbol.for("@azure/core-tracing namespace") - }; - function createTracingContext(options = {}) { - let context3 = new TracingContextImpl(options.parentContext); - if (options.span) { - context3 = context3.setValue(exports2.knownContextKeys.span, options.span); - } - if (options.namespace) { - context3 = context3.setValue(exports2.knownContextKeys.namespace, options.namespace); - } - return context3; + exports2.createHttpHeaders = createHttpHeaders; + function normalizeName(name) { + return name.toLowerCase(); } - exports2.createTracingContext = createTracingContext; - var TracingContextImpl = class _TracingContextImpl { - constructor(initialContext) { - this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); - } - setValue(key, value) { - const newContext = new _TracingContextImpl(this); - newContext._contextMap.set(key, value); - return newContext; - } - getValue(key) { - return this._contextMap.get(key); - } - deleteValue(key) { - const newContext = new _TracingContextImpl(this); - newContext._contextMap.delete(key); - return newContext; + function* headerIterator(map2) { + for (const entry of map2.values()) { + yield [entry.name, entry.value]; } - }; - exports2.TracingContextImpl = TracingContextImpl; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/state.js -var require_state = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.state = void 0; - exports2.state = { - instrumenterImplementation: void 0 - }; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js -var require_instrumenter = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0; - var tracingContext_js_1 = require_tracingContext(); - var state_js_1 = require_state(); - function createDefaultTracingSpan() { - return { - end: () => { - }, - isRecording: () => false, - recordException: () => { - }, - setAttribute: () => { - }, - setStatus: () => { - } - }; } - exports2.createDefaultTracingSpan = createDefaultTracingSpan; - function createDefaultInstrumenter() { - return { - createRequestHeaders: () => { - return {}; - }, - parseTraceparentHeader: () => { - return void 0; - }, - startSpan: (_name, spanOptions) => { - return { - span: createDefaultTracingSpan(), - tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }) - }; - }, - withContext(_context, callback, ...callbackArgs) { - return callback(...callbackArgs); + var HttpHeadersImpl = class { + constructor(rawHeaders) { + this._headersMap = /* @__PURE__ */ new Map(); + if (rawHeaders) { + for (const headerName of Object.keys(rawHeaders)) { + this.set(headerName, rawHeaders[headerName]); + } } - }; - } - exports2.createDefaultInstrumenter = createDefaultInstrumenter; - function useInstrumenter(instrumenter) { - state_js_1.state.instrumenterImplementation = instrumenter; - } - exports2.useInstrumenter = useInstrumenter; - function getInstrumenter() { - if (!state_js_1.state.instrumenterImplementation) { - state_js_1.state.instrumenterImplementation = createDefaultInstrumenter(); } - return state_js_1.state.instrumenterImplementation; - } - exports2.getInstrumenter = getInstrumenter; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js -var require_tracingClient = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTracingClient = void 0; - var instrumenter_js_1 = require_instrumenter(); - var tracingContext_js_1 = require_tracingContext(); - function createTracingClient(options) { - const { namespace, packageName, packageVersion } = options; - function startSpan(name, operationOptions, spanOptions) { - var _a; - const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); - let tracingContext = startSpanResult.tracingContext; - const span = startSpanResult.span; - if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { - tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace); - } - span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); - const updatedOptions = Object.assign({}, operationOptions, { - tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }) - }); - return { - span, - updatedOptions - }; + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param name - The name of the header to set. This value is case-insensitive. + * @param value - The value of the header to set. + */ + set(name, value) { + this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); } - async function withSpan(name, operationOptions, callback, spanOptions) { - const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); - try { - const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); - span.setStatus({ status: "success" }); - return result; - } catch (err) { - span.setStatus({ status: "error", error: err }); - throw err; - } finally { - span.end(); - } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param name - The name of the header. This value is case-insensitive. + */ + get(name) { + var _a; + return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; } - function withContext(context3, callback, ...callbackArgs) { - return (0, instrumenter_js_1.getInstrumenter)().withContext(context3, callback, ...callbackArgs); + /** + * Get whether or not this header collection contains a header entry for the provided header name. + * @param name - The name of the header to set. This value is case-insensitive. + */ + has(name) { + return this._headersMap.has(normalizeName(name)); } - function parseTraceparentHeader(traceparentHeader) { - return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader); + /** + * Remove the header with the provided headerName. + * @param name - The name of the header to remove. + */ + delete(name) { + this._headersMap.delete(normalizeName(name)); } - function createRequestHeaders(tracingContext) { - return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext); + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJSON(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const entry of this._headersMap.values()) { + result[entry.name] = entry.value; + } + } else { + for (const [normalizedName, entry] of this._headersMap) { + result[normalizedName] = entry.value; + } + } + return result; } - return { - startSpan, - withSpan, - withContext, - parseTraceparentHeader, - createRequestHeaders - }; - } - exports2.createTracingClient = createTracingClient; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/index.js -var require_commonjs4 = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTracingClient = exports2.useInstrumenter = void 0; - var instrumenter_js_1 = require_instrumenter(); - Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() { - return instrumenter_js_1.useInstrumenter; - } }); - var tracingClient_js_1 = require_tracingClient(); - Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() { - return tracingClient_js_1.createTracingClient; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js -var require_inspect = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.custom = void 0; - var node_util_1 = require("node:util"); - exports2.custom = node_util_1.inspect.custom; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js -var require_restError = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RestError = void 0; - exports2.isRestError = isRestError; - var core_util_1 = require_commonjs2(); - var inspect_js_1 = require_inspect(); - var sanitizer_js_1 = require_sanitizer(); - var errorSanitizer = new sanitizer_js_1.Sanitizer(); - var RestError = class _RestError extends Error { - constructor(message, options = {}) { - super(message); - this.name = "RestError"; - this.code = options.code; - this.statusCode = options.statusCode; - Object.defineProperty(this, "request", { value: options.request, enumerable: false }); - Object.defineProperty(this, "response", { value: options.response, enumerable: false }); - Object.setPrototypeOf(this, _RestError.prototype); + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJSON({ preserveCase: true })); } /** - * Logging method for util.inspect in Node + * Iterate over tuples of header [name, value] pairs. */ - [inspect_js_1.custom]() { - return `RestError: ${this.message} - ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; + [Symbol.iterator]() { + return headerIterator(this._headersMap); } }; - exports2.RestError = RestError; - RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; - RestError.PARSE_ERROR = "PARSE_ERROR"; - function isRestError(e) { - if (e instanceof RestError) { - return true; - } - return (0, core_util_1.isError)(e) && e.name === "RestError"; + function createHttpHeaders(rawHeaders) { + return new HttpHeadersImpl(rawHeaders); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js -var require_tracingPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js +var require_formDataPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tracingPolicyName = void 0; - exports2.tracingPolicy = tracingPolicy; - var core_tracing_1 = require_commonjs4(); - var constants_js_1 = require_constants8(); - var userAgent_js_1 = require_userAgent(); - var log_js_1 = require_log(); + exports2.formDataPolicyName = void 0; + exports2.formDataPolicy = formDataPolicy; var core_util_1 = require_commonjs2(); - var restError_js_1 = require_restError(); - var sanitizer_js_1 = require_sanitizer(); - exports2.tracingPolicyName = "tracingPolicy"; - function tracingPolicy(options = {}) { - const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - const tracingClient = tryCreateTracingClient(); + var httpHeaders_js_1 = require_httpHeaders(); + exports2.formDataPolicyName = "formDataPolicy"; + function formDataToFormDataMap(formData) { + var _a; + const formDataMap = {}; + for (const [key, value] of formData.entries()) { + (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = []; + formDataMap[key].push(value); + } + return formDataMap; + } + function formDataPolicy() { return { - name: exports2.tracingPolicyName, + name: exports2.formDataPolicyName, async sendRequest(request, next) { - var _a; - if (!tracingClient) { - return next(request); - } - const userAgent = await userAgentPromise; - const spanAttributes = { - "http.url": sanitizer.sanitizeUrl(request.url), - "http.method": request.method, - "http.user_agent": userAgent, - requestId: request.requestId - }; - if (userAgent) { - spanAttributes["http.user_agent"] = userAgent; - } - const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; - if (!span || !tracingContext) { - return next(request); + if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { + request.formData = formDataToFormDataMap(request.body); + request.body = void 0; } - try { - const response = await tracingClient.withContext(tracingContext, next, request); - tryProcessResponse(span, response); - return response; - } catch (err) { - tryProcessError(span, err); - throw err; + if (request.formData) { + const contentType = request.headers.get("Content-Type"); + if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { + request.body = wwwFormUrlEncode(request.formData); + } else { + await prepareFormData(request.formData, request); + } + request.formData = void 0; } + return next(request); } }; } - function tryCreateTracingClient() { - try { - return (0, core_tracing_1.createTracingClient)({ - namespace: "", - packageName: "@azure/core-rest-pipeline", - packageVersion: constants_js_1.SDK_VERSION - }); - } catch (e) { - log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); - return void 0; - } - } - function tryCreateSpan(tracingClient, request, spanAttributes) { - try { - const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { - spanKind: "client", - spanAttributes - }); - if (!span.isRecording()) { - span.end(); - return void 0; - } - const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); - for (const [key, value] of Object.entries(headers)) { - request.headers.set(key, value); + function wwwFormUrlEncode(formData) { + const urlSearchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(formData)) { + if (Array.isArray(value)) { + for (const subValue of value) { + urlSearchParams.append(key, subValue.toString()); + } + } else { + urlSearchParams.append(key, value.toString()); } - return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; - } catch (e) { - log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); - return void 0; } + return urlSearchParams.toString(); } - function tryProcessError(span, error4) { - try { - span.setStatus({ - status: "error", - error: (0, core_util_1.isError)(error4) ? error4 : void 0 - }); - if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) { - span.setAttribute("http.status_code", error4.statusCode); - } - span.end(); - } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + async function prepareFormData(formData, request) { + const contentType = request.headers.get("Content-Type"); + if (contentType && !contentType.startsWith("multipart/form-data")) { + return; } - } - function tryProcessResponse(span, response) { - try { - span.setAttribute("http.status_code", response.status); - const serviceRequestId = response.headers.get("x-ms-request-id"); - if (serviceRequestId) { - span.setAttribute("serviceRequestId", serviceRequestId); + request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); + const parts = []; + for (const [fieldName, values] of Object.entries(formData)) { + for (const value of Array.isArray(values) ? values : [values]) { + if (typeof value === "string") { + parts.push({ + headers: (0, httpHeaders_js_1.createHttpHeaders)({ + "Content-Disposition": `form-data; name="${fieldName}"` + }), + body: (0, core_util_1.stringToUint8Array)(value, "utf-8") + }); + } else if (value === void 0 || value === null || typeof value !== "object") { + throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); + } else { + const fileName = value.name || "blob"; + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); + headers.set("Content-Type", value.type || "application/octet-stream"); + parts.push({ + headers, + body: value + }); + } } - span.setStatus({ - status: "success" - }); - span.end(); - } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); } + request.multipartBody = { parts }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js -var require_createPipelineFromOptions = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineFromOptions = createPipelineFromOptions; - var logPolicy_js_1 = require_logPolicy(); - var pipeline_js_1 = require_pipeline(); - var redirectPolicy_js_1 = require_redirectPolicy(); - var userAgentPolicy_js_1 = require_userAgentPolicy(); - var multipartPolicy_js_1 = require_multipartPolicy(); - var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); - var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); - var formDataPolicy_js_1 = require_formDataPolicy(); - var core_util_1 = require_commonjs2(); - var proxyPolicy_js_1 = require_proxyPolicy(); - var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); - var tlsPolicy_js_1 = require_tlsPolicy(); - var tracingPolicy_js_1 = require_tracingPolicy(); - function createPipelineFromOptions(options) { - var _a; - const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); - if (core_util_1.isNodeLike) { - if (options.tlsOptions) { - pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); - } - pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); - pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); +// node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/ms/index.js"(exports2, module2) { + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module2.exports = function(val2, options) { + options = options || {}; + var type2 = typeof val2; + if (type2 === "string" && val2.length > 0) { + return parse(val2); + } else if (type2 === "number" && isFinite(val2)) { + return options.long ? fmtLong(val2) : fmtShort(val2); } - pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); - pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); - pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); - pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); - pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); - pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { - afterPhase: "Retry" - }); - if (core_util_1.isNodeLike) { - pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2) + ); + }; + function parse(str2) { + str2 = String(str2); + if (str2.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str2 + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type2 = (match[2] || "ms").toLowerCase(); + switch (type2) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; } - pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); - return pipeline; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js -var require_nodeHttpClient = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getBodyLength = getBodyLength; - exports2.createNodeHttpClient = createNodeHttpClient; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var http = tslib_1.__importStar(require("node:http")); - var https2 = tslib_1.__importStar(require("node:https")); - var zlib3 = tslib_1.__importStar(require("node:zlib")); - var node_stream_1 = require("node:stream"); - var abort_controller_1 = require_commonjs3(); - var httpHeaders_js_1 = require_httpHeaders(); - var restError_js_1 = require_restError(); - var log_js_1 = require_log(); - var DEFAULT_TLS_SETTINGS = {}; - function isReadableStream(body) { - return body && typeof body.pipe === "function"; - } - function isStreamComplete(stream2) { - return new Promise((resolve8) => { - const handler = () => { - resolve8(); - stream2.removeListener("close", handler); - stream2.removeListener("end", handler); - stream2.removeListener("error", handler); - }; - stream2.on("close", handler); - stream2.on("end", handler); - stream2.on("error", handler); - }); } - function isArrayBuffer(body) { - return body && typeof body.byteLength === "number"; + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; } - var ReportTransform = class extends node_stream_1.Transform { - // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type - _transform(chunk, _encoding, callback) { - this.push(chunk); - this.loadedBytes += chunk.length; - try { - this.progressCallback({ loadedBytes: this.loadedBytes }); - callback(); - } catch (e) { - callback(e); - } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); } - constructor(progressCallback) { - super(); - this.loadedBytes = 0; - this.progressCallback = progressCallback; + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); } - }; - var NodeHttpClient = class { - constructor() { - this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); } - /** - * Makes a request over an underlying transport layer and returns the response. - * @param request - The request to be made. - */ - async sendRequest(request) { - var _a, _b, _c; - const abortController = new AbortController(); - let abortListener; - if (request.abortSignal) { - if (request.abortSignal.aborted) { - throw new abort_controller_1.AbortError("The operation was aborted."); - } - abortListener = (event) => { - if (event.type === "abort") { - abortController.abort(); - } - }; - request.abortSignal.addEventListener("abort", abortListener); - } - if (request.timeout > 0) { - setTimeout(() => { - abortController.abort(); - }, request.timeout); - } - const acceptEncoding = request.headers.get("Accept-Encoding"); - const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); - let body = typeof request.body === "function" ? request.body() : request.body; - if (body && !request.headers.has("Content-Length")) { - const bodyLength = getBodyLength(body); - if (bodyLength !== null) { - request.headers.set("Content-Length", bodyLength); - } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/debug/src/common.js +var require_common = __commonJS({ + "node_modules/debug/src/common.js"(exports2, module2) { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce3; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash2 = 0; + for (let i = 0; i < namespace.length; i++) { + hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); + hash2 |= 0; } - let responseStream; - try { - if (body && request.onUploadProgress) { - const onUploadProgress = request.onUploadProgress; - const uploadReportStream = new ReportTransform(onUploadProgress); - uploadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in upload progress", e); - }); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } else { - uploadReportStream.end(body); - } - body = uploadReportStream; - } - const res = await this.makeRequest(request, abortController, body); - const headers = getResponseHeaders(res); - const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; - const response = { - status, - headers, - request - }; - if (request.method === "HEAD") { - res.resume(); - return response; - } - responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; - const onDownloadProgress = request.onDownloadProgress; - if (onDownloadProgress) { - const downloadReportStream = new ReportTransform(onDownloadProgress); - downloadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in download progress", e); - }); - responseStream.pipe(downloadReportStream); - responseStream = downloadReportStream; + return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug5(...args) { + if (!debug5.enabled) { + return; } - if ( - // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code - ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status)) - ) { - response.readableStreamBody = responseStream; - } else { - response.bodyAsText = await streamToText(responseStream); + const self2 = debug5; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); } - return response; - } finally { - if (request.abortSignal && abortListener) { - let uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; } - let downloadStreamDone = Promise.resolve(); - if (isReadableStream(responseStream)) { - downloadStreamDone = isStreamComplete(responseStream); + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val2 = args[index]; + match = formatter.call(self2, val2); + args.splice(index, 1); + index--; } - Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { - var _a2; - if (abortListener) { - (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener); - } - }).catch((e) => { - log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); - }); + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug5.namespace = namespace; + debug5.useColors = createDebug.useColors(); + debug5.color = createDebug.selectColor(namespace); + debug5.extend = extend3; + debug5.destroy = createDebug.destroy; + Object.defineProperty(debug5, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug5); } + return debug5; } - makeRequest(request, abortController, body) { - var _a; - const url2 = new URL(request.url); - const isInsecure = url2.protocol !== "https:"; - if (isInsecure && !request.allowInsecureConnection) { - throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + function extend3(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } } - const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); - const options = { - agent, - hostname: url2.hostname, - path: `${url2.pathname}${url2.search}`, - port: url2.port, - method: request.method, - headers: request.headers.toJSON({ preserveCase: true }) - }; - return new Promise((resolve8, reject) => { - const req = isInsecure ? http.request(options, resolve8) : https2.request(options, resolve8); - req.once("error", (err) => { - var _a2; - reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); - }); - abortController.signal.addEventListener("abort", () => { - const abortError = new abort_controller_1.AbortError("The operation was aborted."); - req.destroy(abortError); - reject(abortError); - }); - if (body && isReadableStream(body)) { - body.pipe(req); - } else if (body) { - if (typeof body === "string" || Buffer.isBuffer(body)) { - req.end(body); - } else if (isArrayBuffer(body)) { - req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; } else { - log_js_1.logger.error("Unrecognized body type", body); - reject(new restError_js_1.RestError("Unrecognized body type")); + searchIndex++; + templateIndex++; } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; } else { - req.end(); + return false; } - }); + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; } - getOrCreateAgent(request, isInsecure) { - var _a; - const disableKeepAlive = request.disableKeepAlive; - if (isInsecure) { - if (disableKeepAlive) { - return http.globalAgent; - } - if (!this.cachedHttpAgent) { - this.cachedHttpAgent = new http.Agent({ keepAlive: true }); - } - return this.cachedHttpAgent; - } else { - if (disableKeepAlive && !request.tlsSettings) { - return https2.globalAgent; - } - const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; - let agent = this.cachedHttpsAgents.get(tlsSettings); - if (agent && agent.options.keepAlive === !disableKeepAlive) { - return agent; + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; } - log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); - agent = new https2.Agent(Object.assign({ - // keepAlive is true if disableKeepAlive is false. - keepAlive: !disableKeepAlive - }, tlsSettings)); - this.cachedHttpsAgents.set(tlsSettings, agent); - return agent; } - } - }; - function getResponseHeaders(res) { - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); - for (const header of Object.keys(res.headers)) { - const value = res.headers[header]; - if (Array.isArray(value)) { - if (value.length > 0) { - headers.set(header, value[0]); + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; } - } else if (value) { - headers.set(header, value); } + return false; } - return headers; - } - function getDecodedResponseStream(stream2, headers) { - const contentEncoding = headers.get("Content-Encoding"); - if (contentEncoding === "gzip") { - const unzip = zlib3.createGunzip(); - stream2.pipe(unzip); - return unzip; - } else if (contentEncoding === "deflate") { - const inflate = zlib3.createInflate(); - stream2.pipe(inflate); - return inflate; + function coerce3(val2) { + if (val2 instanceof Error) { + return val2.stack || val2.message; + } + return val2; } - return stream2; - } - function streamToText(stream2) { - return new Promise((resolve8, reject) => { - const buffer = []; - stream2.on("data", (chunk) => { - if (Buffer.isBuffer(chunk)) { - buffer.push(chunk); - } else { - buffer.push(Buffer.from(chunk)); - } - }); - stream2.on("end", () => { - resolve8(Buffer.concat(buffer).toString("utf8")); - }); - stream2.on("error", (e) => { - if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { - reject(e); - } else { - reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { - code: restError_js_1.RestError.PARSE_ERROR - })); - } - }); - }); - } - function getBodyLength(body) { - if (!body) { - return 0; - } else if (Buffer.isBuffer(body)) { - return body.length; - } else if (isReadableStream(body)) { - return null; - } else if (isArrayBuffer(body)) { - return body.byteLength; - } else if (typeof body === "string") { - return Buffer.from(body).length; - } else { - return null; + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } + createDebug.enable(createDebug.load()); + return createDebug; } - function createNodeHttpClient() { - return new NodeHttpClient(); - } + module2.exports = setup; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js -var require_defaultHttpClient = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createDefaultHttpClient = createDefaultHttpClient; - var nodeHttpClient_js_1 = require_nodeHttpClient(); - function createDefaultHttpClient() { - return (0, nodeHttpClient_js_1.createNodeHttpClient)(); - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js -var require_pipelineRequest = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineRequest = createPipelineRequest; - var httpHeaders_js_1 = require_httpHeaders(); - var core_util_1 = require_commonjs2(); - var PipelineRequestImpl = class { - constructor(options) { - var _a, _b, _c, _d, _e, _f, _g; - this.url = options.url; - this.body = options.body; - this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); - this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; - this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; - this.multipartBody = options.multipartBody; - this.formData = options.formData; - this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; - this.proxySettings = options.proxySettings; - this.streamResponseStatusCodes = options.streamResponseStatusCodes; - this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; - this.abortSignal = options.abortSignal; - this.tracingOptions = options.tracingOptions; - this.onUploadProgress = options.onUploadProgress; - this.onDownloadProgress = options.onDownloadProgress; - this.requestId = options.requestId || (0, core_util_1.randomUUID)(); - this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; - this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; +// node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/debug/src/browser.js"(exports2, module2) { + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.storage = localstorage(); + exports2.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports2.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; } - }; - function createPipelineRequest(options) { - return new PipelineRequestImpl(options); + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js -var require_exponentialRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryPolicyName = void 0; - exports2.exponentialRetryPolicy = exponentialRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; - function exponentialRetryPolicy(options = {}) { - var _a; - return (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })) - ], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index++; + if (match === "%c") { + lastC = index; + } }); + args.splice(lastC, 0, c); + } + exports2.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports2.storage.setItem("debug", namespaces); + } else { + exports2.storage.removeItem("debug"); + } + } catch (error4) { + } + } + function load2() { + let r; + try { + r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); + } catch (error4) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error4) { + } } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error4) { + return "[UnexpectedJSONParseError]: " + error4.message; + } + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js -var require_systemErrorRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { +// node_modules/has-flag/index.js +var require_has_flag = __commonJS({ + "node_modules/has-flag/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.systemErrorRetryPolicyName = void 0; - exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; - function systemErrorRetryPolicy(options = {}) { - var _a; - return { - name: exports2.systemErrorRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })) - ], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest - }; - } + module2.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js -var require_throttlingRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { +// node_modules/supports-color/index.js +var require_supports_color = __commonJS({ + "node_modules/supports-color/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.throttlingRetryPolicyName = void 0; - exports2.throttlingRetryPolicy = throttlingRetryPolicy; - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; - function throttlingRetryPolicy(options = {}) { - var _a; + var os3 = require("os"); + var tty = require("tty"); + var hasFlag = require_has_flag(); + var { env } = process; + var forceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { + forceColor = 0; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = 1; + } + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + forceColor = 1; + } else if (env.FORCE_COLOR === "false") { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } return { - name: exports2.throttlingRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 }; } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js -var require_tokenCycler = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_CYCLER_OPTIONS = void 0; - exports2.createTokenCycler = createTokenCycler; - var helpers_js_1 = require_helpers2(); - exports2.DEFAULT_CYCLER_OPTIONS = { - forcedRefreshWindowInMs: 1e3, - // Force waiting for a refresh 1s before the token expires - retryIntervalInMs: 3e3, - // Allow refresh attempts every 3s - refreshWindowInMs: 1e3 * 60 * 2 - // Start refreshing 2m before expiry - }; - async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { - async function tryGetAccessToken() { - if (Date.now() < refreshTimeout) { - try { - return await getAccessToken(); - } catch (_a) { - return null; - } - } else { - const finalToken = await getAccessToken(); - if (finalToken === null) { - throw new Error("Failed to refresh access token."); - } - return finalToken; - } + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; } - let token = await tryGetAccessToken(); - while (token === null) { - await (0, helpers_js_1.delay)(retryIntervalInMs); - token = await tryGetAccessToken(); + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; } - return token; - } - function createTokenCycler(credential, tokenCyclerOptions) { - let refreshWorker = null; - let token = null; - let tenantId; - const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); - const cycler = { - /** - * Produces true if a refresh job is currently in progress. - */ - get isRefreshing() { - return refreshWorker !== null; - }, - /** - * Produces true if the cycler SHOULD refresh (we are within the refresh - * window and not already refreshing) - */ - get shouldRefresh() { - var _a; - if (cycler.isRefreshing) { - return false; - } - if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { - return true; - } - return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); - }, - /** - * Produces true if the cycler MUST refresh (null or nearly-expired - * token). - */ - get mustRefresh() { - return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); - } - }; - function refresh(scopes, getTokenOptions) { - var _a; - if (!cycler.isRefreshing) { - const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); - refreshWorker = beginRefresh( - tryGetAccessToken, - options.retryIntervalInMs, - // If we don't have a token, then we should timeout immediately - (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now() - ).then((_token) => { - refreshWorker = null; - token = _token; - tenantId = getTokenOptions.tenantId; - return token; - }).catch((reason) => { - refreshWorker = null; - token = null; - tenantId = void 0; - throw reason; - }); - } - return refreshWorker; + if (hasFlag("color=256")) { + return 2; } - return async (scopes, tokenOptions) => { - const hasClaimChallenge = Boolean(tokenOptions.claims); - const tenantIdChanged = tenantId !== tokenOptions.tenantId; - if (hasClaimChallenge) { - token = null; + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (process.platform === "win32") { + const osRelease = os3.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; } - const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; - if (mustRefresh) { - return refresh(scopes, tokenOptions); + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { + return 1; } - if (cycler.shouldRefresh) { - refresh(scopes, tokenOptions); + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; } - return token; - }; + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; + } + function getSupportLevel(stream2) { + const level = supportsColor(stream2, stream2 && stream2.isTTY); + return translateLevel(level); } + module2.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js -var require_bearerTokenAuthenticationPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bearerTokenAuthenticationPolicyName = void 0; - exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log(); - exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; - async function defaultAuthorizeRequest(options) { - const { scopes, getAccessToken, request } = options; - const getTokenOptions = { - abortSignal: request.abortSignal, - tracingOptions: request.tracingOptions - }; - const accessToken = await getAccessToken(scopes, getTokenOptions); - if (accessToken) { - options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); - } - } - function getChallenge(response) { - const challenge = response.headers.get("WWW-Authenticate"); - if (response.status === 401 && challenge) { - return challenge; - } - return; - } - function bearerTokenAuthenticationPolicy(options) { - var _a; - const { credential, scopes, challengeCallbacks } = options; - const logger = options.logger || log_js_1.logger; - const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); - const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( - credential - /* , options */ - ) : () => Promise.resolve(null); - return { - name: exports2.bearerTokenAuthenticationPolicyName, - /** - * If there's no challenge parameter: - * - It will try to retrieve the token using the cache, or the credential's getToken. - * - Then it will try the next policy with or without the retrieved token. - * - * It uses the challenge parameters to: - * - Skip a first attempt to get the token from the credential if there's no cached token, - * since it expects the token to be retrievable only after the challenge. - * - Prepare the outgoing request if the `prepareRequest` method has been provided. - * - Send an initial request to receive the challenge if it fails. - * - Process a challenge if the response contains it. - * - Retrieve a token with the challenge information, then re-send the request. - */ - async sendRequest(request, next) { - if (!request.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); - } - await callbacks.authorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - getAccessToken, - logger - }); - let response; - let error4; - try { - response = await next(request); - } catch (err) { - error4 = err; - response = err.response; - } - if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) { - const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - response, - getAccessToken, - logger - }); - if (shouldSendRequest) { - return next(request); - } - } - if (error4) { - throw error4; - } else { - return response; - } - } - }; +// node_modules/debug/src/node.js +var require_node = __commonJS({ + "node_modules/debug/src/node.js"(exports2, module2) { + var tty = require("tty"); + var util = require("util"); + exports2.init = init; + exports2.log = log; + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.destroy = util.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports2.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports2.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error4) { + } + exports2.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_2, k) => { + return k.toUpperCase(); + }); + let val2 = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val2)) { + val2 = true; + } else if (/^(no|off|false|disabled)$/i.test(val2)) { + val2 = false; + } else if (val2 === "null") { + val2 = null; + } else { + val2 = Number(val2); + } + obj[prop] = val2; + return obj; + }, {}); + function useColors() { + return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + " " + args[0]; + } + } + function getDate() { + if (exports2.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + function log(...args) { + return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load2() { + return process.env.DEBUG; + } + function init(debug5) { + debug5.inspectOpts = {}; + const keys = Object.keys(exports2.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug5.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + } } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js -var require_ndJsonPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { +// node_modules/debug/src/index.js +var require_src = __commonJS({ + "node_modules/debug/src/index.js"(exports2, module2) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module2.exports = require_browser(); + } else { + module2.exports = require_node(); + } + } +}); + +// node_modules/agent-base/dist/helpers.js +var require_helpers3 = __commonJS({ + "node_modules/agent-base/dist/helpers.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ndJsonPolicyName = void 0; - exports2.ndJsonPolicy = ndJsonPolicy; - exports2.ndJsonPolicyName = "ndJsonPolicy"; - function ndJsonPolicy() { - return { - name: exports2.ndJsonPolicyName, - async sendRequest(request, next) { - if (typeof request.body === "string" && request.body.startsWith("[")) { - const body = JSON.parse(request.body); - if (Array.isArray(body)) { - request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); - } - } - return next(request); - } - }; + exports2.req = exports2.json = exports2.toBuffer = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + async function toBuffer(stream2) { + let length = 0; + const chunks = []; + for await (const chunk of stream2) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); + } + exports2.toBuffer = toBuffer; + async function json2(stream2) { + const buf = await toBuffer(stream2); + const str2 = buf.toString("utf8"); + try { + return JSON.parse(str2); + } catch (_err) { + const err = _err; + err.message += ` (input: ${str2})`; + throw err; + } + } + exports2.json = json2; + function req(url2, opts = {}) { + const href = typeof url2 === "string" ? url2 : url2.href; + const req2 = (href.startsWith("https:") ? https2 : http).request(url2, opts); + const promise = new Promise((resolve8, reject) => { + req2.once("response", resolve8).once("error", reject).end(); + }); + req2.then = promise.then.bind(promise); + return req2; } + exports2.req = req; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js -var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { +// node_modules/agent-base/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/agent-base/dist/index.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; - exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log(); - exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; - var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; - async function sendAuthorizeRequest(options) { - var _a, _b; - const { scopes, getAccessToken, request } = options; - const getTokenOptions = { - abortSignal: request.abortSignal, - tracingOptions: request.tracingOptions - }; - return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; - } - function auxiliaryAuthenticationHeaderPolicy(options) { - const { credentials, scopes } = options; - const logger = options.logger || log_js_1.logger; - const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); - return { - name: exports2.auxiliaryAuthenticationHeaderPolicyName, - async sendRequest(request, next) { - if (!request.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); + exports2.Agent = void 0; + var net = __importStar4(require("net")); + var http = __importStar4(require("http")); + var https_1 = require("https"); + __exportStar4(require_helpers3(), exports2); + var INTERNAL = Symbol("AgentBaseInternalState"); + var Agent = class extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + if (typeof options.secureEndpoint === "boolean") { + return options.secureEndpoint; } - if (!credentials || credentials.length === 0) { - logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); - return next(request); + if (typeof options.protocol === "string") { + return options.protocol === "https:"; } - const tokenPromises = []; - for (const credential of credentials) { - let getAccessToken = tokenCyclerMap.get(credential); - if (!getAccessToken) { - getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); - tokenCyclerMap.set(credential, getAccessToken); - } - tokenPromises.push(sendAuthorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - getAccessToken, - logger - })); + } + const { stack } = new Error(); + if (typeof stack !== "string") + return false; + return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + if (!this.sockets[name]) { + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + this.totalSocketCount--; + if (sockets.length === 0) { + delete this.sockets[name]; } - const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); - if (auxiliaryTokens.length === 0) { - logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); - return next(request); + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options); + if (secureEndpoint) { + return https_1.Agent.prototype.getName.call(this, options); + } + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options) + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + try { + return socket.addRequest(req, connectOpts); + } catch (err) { + return cb(err); + } } - request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); - return next(request); + this[INTERNAL].currentSocket = socket; + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = void 0; + if (!socket) { + throw new Error("No socket was returned in the `connect()` function"); } - }; - } + return socket; + } + get defaultPort() { + return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } + }; + exports2.Agent = Agent; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js -var require_commonjs5 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { +// node_modules/https-proxy-agent/dist/parse-proxy-response.js +var require_parse_proxy_response = __commonJS({ + "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.parseProxyResponse = void 0; + var debug_1 = __importDefault4(require_src()); + var debug5 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); + function parseProxyResponse(socket) { + return new Promise((resolve8, reject) => { + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once("readable", read); + } + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("readable", read); + } + function onend() { + cleanup(); + debug5("onend"); + reject(new Error("Proxy connection ended before receiving CONNECT response")); + } + function onerror(err) { + cleanup(); + debug5("onerror %o", err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf("\r\n\r\n"); + if (endOfHeaders === -1) { + debug5("have not received end of HTTP headers yet..."); + read(); + return; + } + const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error("No header received from proxy CONNECT response")); + } + const firstLineParts = firstLine.split(" "); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(" "); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(":"); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === "string") { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } + } + debug5("got proxy server response: %o %o", firstLine, headers); + cleanup(); + resolve8({ + connect: { + statusCode, + statusText, + headers + }, + buffered + }); + } + socket.on("error", onerror); + socket.on("end", onend); + read(); + }); + } + exports2.parseProxyResponse = parseProxyResponse; + } +}); + +// node_modules/https-proxy-agent/dist/index.js +var require_dist3 = __commonJS({ + "node_modules/https-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpsProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var assert_1 = __importDefault4(require("assert")); + var debug_1 = __importDefault4(require_src()); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var parse_proxy_response_1 = require_parse_proxy_response(); + var debug5 = (0, debug_1.default)("https-proxy-agent"); + var setServernameFromNonIpHost = (options) => { + if (options.servername === void 0 && options.host && !net.isIP(options.host)) { + return { + ...options, + servername: options.host + }; + } + return options; + }; + var HttpsProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: void 0 }; + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug5("Creating new HttpsProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ["http/1.1"], + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + let socket; + if (proxy.protocol === "https:") { + debug5("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } else { + debug5("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r +`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r +`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r +`); + const { connect, buffered } = await proxyResponsePromise; + req.emit("proxyConnect", connect); + this.emit("proxyConnect", connect, req); + if (connect.statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debug5("Upgrading socket connection to TLS"); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), + socket + }); + } + return socket; + } + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debug5("Replaying proxy buffer for failed request"); + (0, assert_1.default)(s.listenerCount("data") > 0); + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } + }; + HttpsProxyAgent.protocols = ["http", "https"]; + exports2.HttpsProxyAgent = HttpsProxyAgent; + function resume(socket) { + socket.resume(); + } + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + } +}); + +// node_modules/http-proxy-agent/dist/index.js +var require_dist4 = __commonJS({ + "node_modules/http-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var debug_1 = __importDefault4(require_src()); + var events_1 = require("events"); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var debug5 = (0, debug_1.default)("http-proxy-agent"); + var HttpProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug5("Creating new HttpProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + addRequest(req, opts) { + req._header = null; + this.setRequestProps(req, opts); + super.addRequest(req, opts); + } + setRequestProps(req, opts) { + const { proxy } = this; + const protocol = opts.secureEndpoint ? "https:" : "http:"; + const hostname = req.getHeader("host") || "localhost"; + const base = `${protocol}//${hostname}`; + const url2 = new url_1.URL(req.path, base); + if (opts.port !== 80) { + url2.port = String(opts.port); + } + req.path = String(url2); + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + const value = headers[name]; + if (value) { + req.setHeader(name, value); + } + } + } + async connect(req, opts) { + req._header = null; + if (!req.path.includes("://")) { + this.setRequestProps(req, opts); + } + let first; + let endOfHeaders; + debug5("Regenerating stored HTTP header string for request"); + req._implicitHeader(); + if (req.outputData && req.outputData.length > 0) { + debug5("Patching connection write() output buffer with updated header"); + first = req.outputData[0].data; + endOfHeaders = first.indexOf("\r\n\r\n") + 4; + req.outputData[0].data = req._header + first.substring(endOfHeaders); + debug5("Output buffer: %o", req.outputData[0].data); + } + let socket; + if (this.proxy.protocol === "https:") { + debug5("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(this.connectOpts); + } else { + debug5("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + await (0, events_1.once)(socket, "connect"); + return socket; + } + }; + HttpProxyAgent.protocols = ["http", "https"]; + exports2.HttpProxyAgent = HttpProxyAgent; + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js +var require_proxyPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; + exports2.loadNoProxy = loadNoProxy; + exports2.getDefaultProxySettings = getDefaultProxySettings; + exports2.proxyPolicy = proxyPolicy; + var https_proxy_agent_1 = require_dist3(); + var http_proxy_agent_1 = require_dist4(); + var log_js_1 = require_log(); + var HTTPS_PROXY = "HTTPS_PROXY"; + var HTTP_PROXY = "HTTP_PROXY"; + var ALL_PROXY = "ALL_PROXY"; + var NO_PROXY = "NO_PROXY"; + exports2.proxyPolicyName = "proxyPolicy"; + exports2.globalNoProxyList = []; + var noProxyListLoaded = false; + var globalBypassedMap = /* @__PURE__ */ new Map(); + function getEnvironmentValue(name) { + if (process.env[name]) { + return process.env[name]; + } else if (process.env[name.toLowerCase()]) { + return process.env[name.toLowerCase()]; + } + return void 0; + } + function loadEnvironmentProxyValue() { + if (!process) { + return void 0; + } + const httpsProxy = getEnvironmentValue(HTTPS_PROXY); + const allProxy = getEnvironmentValue(ALL_PROXY); + const httpProxy = getEnvironmentValue(HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; + } + function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = new URL(uri).hostname; + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } + } else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; + } + function loadNoProxy() { + const noProxy = getEnvironmentValue(NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); + } + return []; + } + function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return void 0; + } + } + const parsedUrl = new URL(proxyUrl); + const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; + return { + host: schema2 + parsedUrl.hostname, + port: Number.parseInt(parsedUrl.port || "80"), + username: parsedUrl.username, + password: parsedUrl.password + }; + } + function getDefaultProxySettingsInternal() { + const envProxy = loadEnvironmentProxyValue(); + return envProxy ? new URL(envProxy) : void 0; + } + function getUrlFromProxySettings(settings) { + let parsedProxyUrl; + try { + parsedProxyUrl = new URL(settings.host); + } catch (_a) { + throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); + } + parsedProxyUrl.port = String(settings.port); + if (settings.username) { + parsedProxyUrl.username = settings.username; + } + if (settings.password) { + parsedProxyUrl.password = settings.password; + } + return parsedProxyUrl; + } + function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { + if (request.agent) { + return; + } + const url2 = new URL(request.url); + const isInsecure = url2.protocol !== "https:"; + if (request.tlsSettings) { + log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); + } + const headers = request.headers.toJSON(); + if (isInsecure) { + if (!cachedAgents.httpProxyAgent) { + cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpProxyAgent; + } else { + if (!cachedAgents.httpsProxyAgent) { + cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpsProxyAgent; + } + } + function proxyPolicy(proxySettings, options) { + if (!noProxyListLoaded) { + exports2.globalNoProxyList.push(...loadNoProxy()); + } + const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); + const cachedAgents = {}; + return { + name: exports2.proxyPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) { + setProxyAgentOnRequest(request, cachedAgents, defaultProxy); + } else if (request.proxySettings) { + setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js +var require_setClientRequestIdPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.setClientRequestIdPolicyName = void 0; + exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; + exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; + function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + return { + name: exports2.setClientRequestIdPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(requestIdHeaderName)) { + request.headers.set(requestIdHeaderName, request.requestId); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js +var require_tlsPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.tlsPolicyName = void 0; + exports2.tlsPolicy = tlsPolicy; + exports2.tlsPolicyName = "tlsPolicy"; + function tlsPolicy(tlsSettings) { + return { + name: exports2.tlsPolicyName, + sendRequest: async (req, next) => { + if (!req.tlsSettings) { + req.tlsSettings = tlsSettings; + } + return next(req); + } + }; + } + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js +var require_tracingContext = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0; + exports2.knownContextKeys = { + span: Symbol.for("@azure/core-tracing span"), + namespace: Symbol.for("@azure/core-tracing namespace") + }; + function createTracingContext(options = {}) { + let context3 = new TracingContextImpl(options.parentContext); + if (options.span) { + context3 = context3.setValue(exports2.knownContextKeys.span, options.span); + } + if (options.namespace) { + context3 = context3.setValue(exports2.knownContextKeys.namespace, options.namespace); + } + return context3; + } + exports2.createTracingContext = createTracingContext; + var TracingContextImpl = class _TracingContextImpl { + constructor(initialContext) { + this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); + } + setValue(key, value) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.set(key, value); + return newContext; + } + getValue(key) { + return this._contextMap.get(key); + } + deleteValue(key) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.delete(key); + return newContext; + } + }; + exports2.TracingContextImpl = TracingContextImpl; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/state.js +var require_state = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.state = void 0; + exports2.state = { + instrumenterImplementation: void 0 + }; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js +var require_instrumenter = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0; + var tracingContext_js_1 = require_tracingContext(); + var state_js_1 = require_state(); + function createDefaultTracingSpan() { + return { + end: () => { + }, + isRecording: () => false, + recordException: () => { + }, + setAttribute: () => { + }, + setStatus: () => { + } + }; + } + exports2.createDefaultTracingSpan = createDefaultTracingSpan; + function createDefaultInstrumenter() { + return { + createRequestHeaders: () => { + return {}; + }, + parseTraceparentHeader: () => { + return void 0; + }, + startSpan: (_name, spanOptions) => { + return { + span: createDefaultTracingSpan(), + tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }) + }; + }, + withContext(_context, callback, ...callbackArgs) { + return callback(...callbackArgs); + } + }; + } + exports2.createDefaultInstrumenter = createDefaultInstrumenter; + function useInstrumenter(instrumenter) { + state_js_1.state.instrumenterImplementation = instrumenter; + } + exports2.useInstrumenter = useInstrumenter; + function getInstrumenter() { + if (!state_js_1.state.instrumenterImplementation) { + state_js_1.state.instrumenterImplementation = createDefaultInstrumenter(); + } + return state_js_1.state.instrumenterImplementation; + } + exports2.getInstrumenter = getInstrumenter; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js +var require_tracingClient = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTracingClient = void 0; + var instrumenter_js_1 = require_instrumenter(); + var tracingContext_js_1 = require_tracingContext(); + function createTracingClient(options) { + const { namespace, packageName, packageVersion } = options; + function startSpan(name, operationOptions, spanOptions) { + var _a; + const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); + let tracingContext = startSpanResult.tracingContext; + const span = startSpanResult.span; + if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { + tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace); + } + span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); + const updatedOptions = Object.assign({}, operationOptions, { + tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }) + }); + return { + span, + updatedOptions + }; + } + async function withSpan(name, operationOptions, callback, spanOptions) { + const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); + try { + const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); + span.setStatus({ status: "success" }); + return result; + } catch (err) { + span.setStatus({ status: "error", error: err }); + throw err; + } finally { + span.end(); + } + } + function withContext(context3, callback, ...callbackArgs) { + return (0, instrumenter_js_1.getInstrumenter)().withContext(context3, callback, ...callbackArgs); + } + function parseTraceparentHeader(traceparentHeader) { + return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader); + } + function createRequestHeaders(tracingContext) { + return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext); + } + return { + startSpan, + withSpan, + withContext, + parseTraceparentHeader, + createRequestHeaders + }; + } + exports2.createTracingClient = createTracingClient; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/index.js +var require_commonjs4 = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTracingClient = exports2.useInstrumenter = void 0; + var instrumenter_js_1 = require_instrumenter(); + Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() { + return instrumenter_js_1.useInstrumenter; + } }); + var tracingClient_js_1 = require_tracingClient(); + Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() { + return tracingClient_js_1.createTracingClient; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js +var require_inspect = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.custom = void 0; + var node_util_1 = require("node:util"); + exports2.custom = node_util_1.inspect.custom; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js +var require_restError = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RestError = void 0; + exports2.isRestError = isRestError; + var core_util_1 = require_commonjs2(); + var inspect_js_1 = require_inspect(); + var sanitizer_js_1 = require_sanitizer(); + var errorSanitizer = new sanitizer_js_1.Sanitizer(); + var RestError = class _RestError extends Error { + constructor(message, options = {}) { + super(message); + this.name = "RestError"; + this.code = options.code; + this.statusCode = options.statusCode; + Object.defineProperty(this, "request", { value: options.request, enumerable: false }); + Object.defineProperty(this, "response", { value: options.response, enumerable: false }); + Object.setPrototypeOf(this, _RestError.prototype); + } + /** + * Logging method for util.inspect in Node + */ + [inspect_js_1.custom]() { + return `RestError: ${this.message} + ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; + } + }; + exports2.RestError = RestError; + RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; + RestError.PARSE_ERROR = "PARSE_ERROR"; + function isRestError(e) { + if (e instanceof RestError) { + return true; + } + return (0, core_util_1.isError)(e) && e.name === "RestError"; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js +var require_tracingPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.tracingPolicyName = void 0; + exports2.tracingPolicy = tracingPolicy; + var core_tracing_1 = require_commonjs4(); + var constants_js_1 = require_constants8(); + var userAgent_js_1 = require_userAgent(); + var log_js_1 = require_log(); + var core_util_1 = require_commonjs2(); + var restError_js_1 = require_restError(); + var sanitizer_js_1 = require_sanitizer(); + exports2.tracingPolicyName = "tracingPolicy"; + function tracingPolicy(options = {}) { + const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + const tracingClient = tryCreateTracingClient(); + return { + name: exports2.tracingPolicyName, + async sendRequest(request, next) { + var _a; + if (!tracingClient) { + return next(request); + } + const userAgent = await userAgentPromise; + const spanAttributes = { + "http.url": sanitizer.sanitizeUrl(request.url), + "http.method": request.method, + "http.user_agent": userAgent, + requestId: request.requestId + }; + if (userAgent) { + spanAttributes["http.user_agent"] = userAgent; + } + const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; + if (!span || !tracingContext) { + return next(request); + } + try { + const response = await tracingClient.withContext(tracingContext, next, request); + tryProcessResponse(span, response); + return response; + } catch (err) { + tryProcessError(span, err); + throw err; + } + } + }; + } + function tryCreateTracingClient() { + try { + return (0, core_tracing_1.createTracingClient)({ + namespace: "", + packageName: "@azure/core-rest-pipeline", + packageVersion: constants_js_1.SDK_VERSION + }); + } catch (e) { + log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); + return void 0; + } + } + function tryCreateSpan(tracingClient, request, spanAttributes) { + try { + const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { + spanKind: "client", + spanAttributes + }); + if (!span.isRecording()) { + span.end(); + return void 0; + } + const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); + for (const [key, value] of Object.entries(headers)) { + request.headers.set(key, value); + } + return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; + } catch (e) { + log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + return void 0; + } + } + function tryProcessError(span, error4) { + try { + span.setStatus({ + status: "error", + error: (0, core_util_1.isError)(error4) ? error4 : void 0 + }); + if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) { + span.setAttribute("http.status_code", error4.statusCode); + } + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + } + } + function tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); + } + span.setStatus({ + status: "success" + }); + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + } + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js +var require_createPipelineFromOptions = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createPipelineFromOptions = createPipelineFromOptions; + var logPolicy_js_1 = require_logPolicy(); + var pipeline_js_1 = require_pipeline(); + var redirectPolicy_js_1 = require_redirectPolicy(); + var userAgentPolicy_js_1 = require_userAgentPolicy(); + var multipartPolicy_js_1 = require_multipartPolicy(); + var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); + var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); + var formDataPolicy_js_1 = require_formDataPolicy(); + var core_util_1 = require_commonjs2(); + var proxyPolicy_js_1 = require_proxyPolicy(); + var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); + var tlsPolicy_js_1 = require_tlsPolicy(); + var tracingPolicy_js_1 = require_tracingPolicy(); + function createPipelineFromOptions(options) { + var _a; + const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); + if (core_util_1.isNodeLike) { + if (options.tlsOptions) { + pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); + } + pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); + pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); + } + pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); + pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); + pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); + pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); + pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); + pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { + afterPhase: "Retry" + }); + if (core_util_1.isNodeLike) { + pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + } + pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); + return pipeline; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js +var require_nodeHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getBodyLength = getBodyLength; + exports2.createNodeHttpClient = createNodeHttpClient; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var http = tslib_1.__importStar(require("node:http")); + var https2 = tslib_1.__importStar(require("node:https")); + var zlib3 = tslib_1.__importStar(require("node:zlib")); + var node_stream_1 = require("node:stream"); + var abort_controller_1 = require_commonjs3(); + var httpHeaders_js_1 = require_httpHeaders(); + var restError_js_1 = require_restError(); + var log_js_1 = require_log(); + var DEFAULT_TLS_SETTINGS = {}; + function isReadableStream(body) { + return body && typeof body.pipe === "function"; + } + function isStreamComplete(stream2) { + return new Promise((resolve8) => { + const handler = () => { + resolve8(); + stream2.removeListener("close", handler); + stream2.removeListener("end", handler); + stream2.removeListener("error", handler); + }; + stream2.on("close", handler); + stream2.on("end", handler); + stream2.on("error", handler); + }); + } + function isArrayBuffer(body) { + return body && typeof body.byteLength === "number"; + } + var ReportTransform = class extends node_stream_1.Transform { + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + _transform(chunk, _encoding, callback) { + this.push(chunk); + this.loadedBytes += chunk.length; + try { + this.progressCallback({ loadedBytes: this.loadedBytes }); + callback(); + } catch (e) { + callback(e); + } + } + constructor(progressCallback) { + super(); + this.loadedBytes = 0; + this.progressCallback = progressCallback; + } + }; + var NodeHttpClient = class { + constructor() { + this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); + } + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + var _a, _b, _c; + const abortController = new AbortController(); + let abortListener; + if (request.abortSignal) { + if (request.abortSignal.aborted) { + throw new abort_controller_1.AbortError("The operation was aborted."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController.abort(); + } + }; + request.abortSignal.addEventListener("abort", abortListener); + } + if (request.timeout > 0) { + setTimeout(() => { + abortController.abort(); + }, request.timeout); + } + const acceptEncoding = request.headers.get("Accept-Encoding"); + const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); + let body = typeof request.body === "function" ? request.body() : request.body; + if (body && !request.headers.has("Content-Length")) { + const bodyLength = getBodyLength(body); + if (bodyLength !== null) { + request.headers.set("Content-Length", bodyLength); + } + } + let responseStream; + try { + if (body && request.onUploadProgress) { + const onUploadProgress = request.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + uploadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in upload progress", e); + }); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); + } else { + uploadReportStream.end(body); + } + body = uploadReportStream; + } + const res = await this.makeRequest(request, abortController, body); + const headers = getResponseHeaders(res); + const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; + const response = { + status, + headers, + request + }; + if (request.method === "HEAD") { + res.resume(); + return response; + } + responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; + const onDownloadProgress = request.onDownloadProgress; + if (onDownloadProgress) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + downloadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in download progress", e); + }); + responseStream.pipe(downloadReportStream); + responseStream = downloadReportStream; + } + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status)) + ) { + response.readableStreamBody = responseStream; + } else { + response.bodyAsText = await streamToText(responseStream); + } + return response; + } finally { + if (request.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(responseStream)) { + downloadStreamDone = isStreamComplete(responseStream); + } + Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { + var _a2; + if (abortListener) { + (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener); + } + }).catch((e) => { + log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } + makeRequest(request, abortController, body) { + var _a; + const url2 = new URL(request.url); + const isInsecure = url2.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + } + const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); + const options = { + agent, + hostname: url2.hostname, + path: `${url2.pathname}${url2.search}`, + port: url2.port, + method: request.method, + headers: request.headers.toJSON({ preserveCase: true }) + }; + return new Promise((resolve8, reject) => { + const req = isInsecure ? http.request(options, resolve8) : https2.request(options, resolve8); + req.once("error", (err) => { + var _a2; + reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); + }); + abortController.signal.addEventListener("abort", () => { + const abortError = new abort_controller_1.AbortError("The operation was aborted."); + req.destroy(abortError); + reject(abortError); + }); + if (body && isReadableStream(body)) { + body.pipe(req); + } else if (body) { + if (typeof body === "string" || Buffer.isBuffer(body)) { + req.end(body); + } else if (isArrayBuffer(body)) { + req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } else { + log_js_1.logger.error("Unrecognized body type", body); + reject(new restError_js_1.RestError("Unrecognized body type")); + } + } else { + req.end(); + } + }); + } + getOrCreateAgent(request, isInsecure) { + var _a; + const disableKeepAlive = request.disableKeepAlive; + if (isInsecure) { + if (disableKeepAlive) { + return http.globalAgent; + } + if (!this.cachedHttpAgent) { + this.cachedHttpAgent = new http.Agent({ keepAlive: true }); + } + return this.cachedHttpAgent; + } else { + if (disableKeepAlive && !request.tlsSettings) { + return https2.globalAgent; + } + const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; + let agent = this.cachedHttpsAgents.get(tlsSettings); + if (agent && agent.options.keepAlive === !disableKeepAlive) { + return agent; + } + log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); + agent = new https2.Agent(Object.assign({ + // keepAlive is true if disableKeepAlive is false. + keepAlive: !disableKeepAlive + }, tlsSettings)); + this.cachedHttpsAgents.set(tlsSettings, agent); + return agent; + } + } + }; + function getResponseHeaders(res) { + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + for (const header of Object.keys(res.headers)) { + const value = res.headers[header]; + if (Array.isArray(value)) { + if (value.length > 0) { + headers.set(header, value[0]); + } + } else if (value) { + headers.set(header, value); + } + } + return headers; + } + function getDecodedResponseStream(stream2, headers) { + const contentEncoding = headers.get("Content-Encoding"); + if (contentEncoding === "gzip") { + const unzip = zlib3.createGunzip(); + stream2.pipe(unzip); + return unzip; + } else if (contentEncoding === "deflate") { + const inflate = zlib3.createInflate(); + stream2.pipe(inflate); + return inflate; + } + return stream2; + } + function streamToText(stream2) { + return new Promise((resolve8, reject) => { + const buffer = []; + stream2.on("data", (chunk) => { + if (Buffer.isBuffer(chunk)) { + buffer.push(chunk); + } else { + buffer.push(Buffer.from(chunk)); + } + }); + stream2.on("end", () => { + resolve8(Buffer.concat(buffer).toString("utf8")); + }); + stream2.on("error", (e) => { + if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { + reject(e); + } else { + reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { + code: restError_js_1.RestError.PARSE_ERROR + })); + } + }); + }); + } + function getBodyLength(body) { + if (!body) { + return 0; + } else if (Buffer.isBuffer(body)) { + return body.length; + } else if (isReadableStream(body)) { + return null; + } else if (isArrayBuffer(body)) { + return body.byteLength; + } else if (typeof body === "string") { + return Buffer.from(body).length; + } else { + return null; + } + } + function createNodeHttpClient() { + return new NodeHttpClient(); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js +var require_defaultHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createDefaultHttpClient = createDefaultHttpClient; + var nodeHttpClient_js_1 = require_nodeHttpClient(); + function createDefaultHttpClient() { + return (0, nodeHttpClient_js_1.createNodeHttpClient)(); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js +var require_pipelineRequest = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createPipelineRequest = createPipelineRequest; + var httpHeaders_js_1 = require_httpHeaders(); + var core_util_1 = require_commonjs2(); + var PipelineRequestImpl = class { + constructor(options) { + var _a, _b, _c, _d, _e, _f, _g; + this.url = options.url; + this.body = options.body; + this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); + this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; + this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; + this.multipartBody = options.multipartBody; + this.formData = options.formData; + this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; + this.proxySettings = options.proxySettings; + this.streamResponseStatusCodes = options.streamResponseStatusCodes; + this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; + this.abortSignal = options.abortSignal; + this.tracingOptions = options.tracingOptions; + this.onUploadProgress = options.onUploadProgress; + this.onDownloadProgress = options.onDownloadProgress; + this.requestId = options.requestId || (0, core_util_1.randomUUID)(); + this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; + this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; + } + }; + function createPipelineRequest(options) { + return new PipelineRequestImpl(options); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js +var require_exponentialRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.exponentialRetryPolicyName = void 0; + exports2.exponentialRetryPolicy = exponentialRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; + function exponentialRetryPolicy(options = {}) { + var _a; + return (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js +var require_systemErrorRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.systemErrorRetryPolicyName = void 0; + exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; + function systemErrorRetryPolicy(options = {}) { + var _a; + return { + name: exports2.systemErrorRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js +var require_throttlingRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.throttlingRetryPolicyName = void 0; + exports2.throttlingRetryPolicy = throttlingRetryPolicy; + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; + function throttlingRetryPolicy(options = {}) { + var _a; + return { + name: exports2.throttlingRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js +var require_tokenCycler = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_CYCLER_OPTIONS = void 0; + exports2.createTokenCycler = createTokenCycler; + var helpers_js_1 = require_helpers2(); + exports2.DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1e3, + // Force waiting for a refresh 1s before the token expires + retryIntervalInMs: 3e3, + // Allow refresh attempts every 3s + refreshWindowInMs: 1e3 * 60 * 2 + // Start refreshing 2m before expiry + }; + async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { + async function tryGetAccessToken() { + if (Date.now() < refreshTimeout) { + try { + return await getAccessToken(); + } catch (_a) { + return null; + } + } else { + const finalToken = await getAccessToken(); + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + let token = await tryGetAccessToken(); + while (token === null) { + await (0, helpers_js_1.delay)(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; + } + function createTokenCycler(credential, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + let tenantId; + const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + const cycler = { + /** + * Produces true if a refresh job is currently in progress. + */ + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) + */ + get shouldRefresh() { + var _a; + if (cycler.isRefreshing) { + return false; + } + if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { + return true; + } + return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); + } + }; + function refresh(scopes, getTokenOptions) { + var _a; + if (!cycler.isRefreshing) { + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); + refreshWorker = beginRefresh( + tryGetAccessToken, + options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now() + ).then((_token) => { + refreshWorker = null; + token = _token; + tenantId = getTokenOptions.tenantId; + return token; + }).catch((reason) => { + refreshWorker = null; + token = null; + tenantId = void 0; + throw reason; + }); + } + return refreshWorker; + } + return async (scopes, tokenOptions) => { + const hasClaimChallenge = Boolean(tokenOptions.claims); + const tenantIdChanged = tenantId !== tokenOptions.tenantId; + if (hasClaimChallenge) { + token = null; + } + const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; + if (mustRefresh) { + return refresh(scopes, tokenOptions); + } + if (cycler.shouldRefresh) { + refresh(scopes, tokenOptions); + } + return token; + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js +var require_bearerTokenAuthenticationPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.bearerTokenAuthenticationPolicyName = void 0; + exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log(); + exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; + async function defaultAuthorizeRequest(options) { + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions + }; + const accessToken = await getAccessToken(scopes, getTokenOptions); + if (accessToken) { + options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); + } + } + function getChallenge(response) { + const challenge = response.headers.get("WWW-Authenticate"); + if (response.status === 401 && challenge) { + return challenge; + } + return; + } + function bearerTokenAuthenticationPolicy(options) { + var _a; + const { credential, scopes, challengeCallbacks } = options; + const logger = options.logger || log_js_1.logger; + const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); + const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( + credential + /* , options */ + ) : () => Promise.resolve(null); + return { + name: exports2.bearerTokenAuthenticationPolicyName, + /** + * If there's no challenge parameter: + * - It will try to retrieve the token using the cache, or the credential's getToken. + * - Then it will try the next policy with or without the retrieved token. + * + * It uses the challenge parameters to: + * - Skip a first attempt to get the token from the credential if there's no cached token, + * since it expects the token to be retrievable only after the challenge. + * - Prepare the outgoing request if the `prepareRequest` method has been provided. + * - Send an initial request to receive the challenge if it fails. + * - Process a challenge if the response contains it. + * - Retrieve a token with the challenge information, then re-send the request. + */ + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + await callbacks.authorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + }); + let response; + let error4; + try { + response = await next(request); + } catch (err) { + error4 = err; + response = err.response; + } + if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) { + const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + response, + getAccessToken, + logger + }); + if (shouldSendRequest) { + return next(request); + } + } + if (error4) { + throw error4; + } else { + return response; + } + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js +var require_ndJsonPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ndJsonPolicyName = void 0; + exports2.ndJsonPolicy = ndJsonPolicy; + exports2.ndJsonPolicyName = "ndJsonPolicy"; + function ndJsonPolicy() { + return { + name: exports2.ndJsonPolicyName, + async sendRequest(request, next) { + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js +var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; + exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log(); + exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; + var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; + async function sendAuthorizeRequest(options) { + var _a, _b; + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions + }; + return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; + } + function auxiliaryAuthenticationHeaderPolicy(options) { + const { credentials, scopes } = options; + const logger = options.logger || log_js_1.logger; + const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); + return { + name: exports2.auxiliaryAuthenticationHeaderPolicyName, + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); + } + if (!credentials || credentials.length === 0) { + logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); + return next(request); + } + const tokenPromises = []; + for (const credential of credentials) { + let getAccessToken = tokenCyclerMap.get(credential); + if (!getAccessToken) { + getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); + tokenCyclerMap.set(credential, getAccessToken); + } + tokenPromises.push(sendAuthorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + })); + } + const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); + if (auxiliaryTokens.length === 0) { + logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); + return next(request); + } + request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js +var require_commonjs5 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; var pipeline_js_1 = require_pipeline(); Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() { return pipeline_js_1.createEmptyPipeline; @@ -64347,1936 +65853,2782 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * of the existing blob will remain unchanged. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * - * @param size - size of the page blob. - * @param options - + * @param size - size of the page blob. + * @param options - + */ + async createIfNotExists(size, options = {}) { + return tracingClient.withSpan("PageBlobClient-createIfNotExists", options, async (updatedOptions) => { + var _a, _b; + try { + const conditions = { ifNoneMatch: ETagAny }; + const res = assertResponse(await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions }))); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + throw e; + } + }); + } + /** + * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * + * @param body - Data to upload + * @param offset - Offset of destination page blob + * @param count - Content length of the body, also number of bytes to be uploaded + * @param options - Options to the Page Blob Upload Pages operation. + * @returns Response data for the Page Blob Upload Pages operation. + */ + async uploadPages(body2, offset, count, options = {}) { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("PageBlobClient-uploadPages", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.uploadPages(count, body2, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + requestOptions: { + onUploadProgress: options.onProgress + }, + range: rangeToString({ offset, count }), + sequenceNumberAccessConditions: options.conditions, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * The Upload Pages operation writes a range of pages to a page blob where the + * contents are read from a URL. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url + * + * @param sourceURL - Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication + * @param sourceOffset - The source offset to copy from. Pass 0 to copy from the beginning of source page blob + * @param destOffset - Offset of destination page blob + * @param count - Number of bytes to be uploaded from source page blob + * @param options - + */ + async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return tracingClient.withSpan("PageBlobClient-uploadPagesFromURL", options, async (updatedOptions) => { + var _a, _b, _c, _d, _e; + return assertResponse(await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), { + abortSignal: options.abortSignal, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + sequenceNumberAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, + sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, + sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, + sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Frees the specified pages from the page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * + * @param offset - Starting byte position of the pages to clear. + * @param count - Number of bytes to clear. + * @param options - Options to the Page Blob Clear Pages operation. + * @returns Response data for the Page Blob Clear Pages operation. + */ + async clearPages(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-clearPages", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.clearPages(0, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset, count }), + sequenceNumberAccessConditions: options.conditions, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns the list of valid page ranges for a page blob or snapshot of a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param options - Options to the Page Blob Get Ranges operation. + * @returns Response data for the Page Blob Get Ranges operation. + */ + async getPageRanges(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-getPageRanges", options, async (updatedOptions) => { + var _a; + const response = assertResponse(await this.pageBlobContext.getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + })); + return rangeResponseFromModel(response); + }); + } + /** + * getPageRangesSegment returns a single segment of page ranges starting from the + * specified Marker. Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call getPageRangesSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to PageBlob Get Page Ranges Segment operation. + */ + async listPageRangesSegment(offset = 0, count, marker2, options = {}) { + return tracingClient.withSpan("PageBlobClient-getPageRangesSegment", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset, count }), + marker: marker2, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesResponseModel} + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param marker - A string value that identifies the portion of + * the get of page ranges to be returned with the next getting operation. The + * operation returns the ContinuationToken value within the response body if the + * getting operation did not return all page ranges remaining within the current page. + * The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of get + * items. The marker value is opaque to the client. + * @param options - Options to List Page Ranges operation. + */ + listPageRangeItemSegments() { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeItemSegments_1(offset = 0, count, marker2, options = {}) { + let getPageRangeItemSegmentsResponse; + if (!!marker2 || marker2 === void 0) { + do { + getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesSegment(offset, count, marker2, options)); + marker2 = getPageRangeItemSegmentsResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param options - Options to List Page Ranges operation. + */ + listPageRangeItems() { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeItems_1(offset = 0, count, options = {}) { + var _a, e_1, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeItemSegments(offset, count, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const getPageRangesSegment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_1) throw e_1.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list of page ranges for a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * .byPage() returns an async iterable iterator to list of page ranges for a page blob. + * + * Example using `for await` syntax: + * + * ```js + * // Get the pageBlobClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` + * let i = 1; + * for await (const pageRange of pageBlobClient.listPageRanges()) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = pageBlobClient.listPageRanges(); + * let pageRangeItem = await iter.next(); + * while (!pageRangeItem.done) { + * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); + * pageRangeItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of pageBlobClient.listPageRanges().byPage({ maxPageSize: 20 })) { + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = pageBlobClient.listPageRanges().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 page ranges + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = pageBlobClient.listPageRanges().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 page ranges + * for (const blob of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param options - Options to the Page Blob Get Ranges operation. + * @returns An asyncIterableIterator that supports paging. + */ + listPageRanges(offset = 0, count, options = {}) { + options.conditions = options.conditions || {}; + const iter = this.listPageRangeItems(offset, count, options); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listPageRangeItemSegments(offset, count, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); + } + }; + } + /** + * Gets the collection of page ranges that differ between a specified snapshot and this page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page blob + * @param count - Number of bytes to get ranges diff. + * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @returns Response data for the Page Blob Get Page Range Diff operation. + */ + async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("PageBlobClient-getPageRangesDiff", options, async (updatedOptions) => { + var _a; + const result = assertResponse(await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevsnapshot: prevSnapshot, + range: rangeToString({ offset, count }), + tracingOptions: updatedOptions.tracingOptions + })); + return rangeResponseFromModel(result); + }); + } + /** + * getPageRangesDiffSegment returns a single segment of page ranges starting from the + * specified Marker for difference between previous snapshot and the target page blob. + * Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call getPageRangesDiffSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. + * @param marker - A string value that identifies the portion of the get to be returned with the next get operation. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + */ + async listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options = {}) { + return tracingClient.withSpan("PageBlobClient-getPageRangesDiffSegment", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.getPageRangesDiff({ + abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, + leaseAccessConditions: options === null || options === void 0 ? void 0 : options.conditions, + modifiedAccessConditions: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.conditions), { ifTags: (_a = options === null || options === void 0 ? void 0 : options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevsnapshot: prevSnapshotOrUrl, + range: rangeToString({ + offset, + count + }), + marker: marker2, + maxPageSize: options === null || options === void 0 ? void 0 : options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + }); + } + /** + * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesDiffResponseModel} + * + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. + * @param marker - A string value that identifies the portion of + * the get of page ranges to be returned with the next getting operation. The + * operation returns the ContinuationToken value within the response body if the + * getting operation did not return all page ranges remaining within the current page. + * The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of get + * items. The marker value is opaque to the client. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + */ + listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options) { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItemSegments_1() { + let getPageRangeItemSegmentsResponse; + if (!!marker2 || marker2 === void 0) { + do { + getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options)); + marker2 = getPageRangeItemSegmentsResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects + * + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + */ + listPageRangeDiffItems(offset, count, prevSnapshotOrUrl, options) { + return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItems_1() { + var _a, e_2, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const getPageRangesSegment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * .byPage() returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. + * + * Example using `for await` syntax: + * + * ```js + * // Get the pageBlobClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` + * let i = 1; + * for await (const pageRange of pageBlobClient.listPageRangesDiff()) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = pageBlobClient.listPageRangesDiff(); + * let pageRangeItem = await iter.next(); + * while (!pageRangeItem.done) { + * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); + * pageRangeItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 20 })) { + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 page ranges + * for (const pageRange of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = pageBlobClient.listPageRangesDiff().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 page ranges + * for (const blob of response) { + * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); + * } + * ``` + * @param offset - Starting byte position of the page ranges. + * @param count - Number of bytes to get. + * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Ranges operation. + * @returns An asyncIterableIterator that supports paging. */ - async createIfNotExists(size, options = {}) { - return tracingClient.withSpan("PageBlobClient-createIfNotExists", options, async (updatedOptions) => { - var _a, _b; - try { - const conditions = { ifNoneMatch: ETagAny }; - const res = assertResponse(await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions }))); - return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); - } catch (e) { - if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { - return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); - } - throw e; + listPageRangesDiff(offset, count, prevSnapshot, options = {}) { + options.conditions = options.conditions || {}; + const iter = this.listPageRangeDiffItems(offset, count, prevSnapshot, Object.assign({}, options)); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listPageRangeDiffItemSegments(offset, count, prevSnapshot, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); } - }); + }; } /** - * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. - * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * - * @param body - Data to upload - * @param offset - Offset of destination page blob - * @param count - Content length of the body, also number of bytes to be uploaded - * @param options - Options to the Page Blob Upload Pages operation. - * @returns Response data for the Page Blob Upload Pages operation. + * @param offset - Starting byte position of the page blob + * @param count - Number of bytes to get ranges diff. + * @param prevSnapshotUrl - URL of snapshot to retrieve the difference. + * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @returns Response data for the Page Blob Get Page Range Diff operation. */ - async uploadPages(body2, offset, count, options = {}) { + async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl2, options = {}) { options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return tracingClient.withSpan("PageBlobClient-uploadPages", options, async (updatedOptions) => { + return tracingClient.withSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options, async (updatedOptions) => { var _a; - return assertResponse(await this.pageBlobContext.uploadPages(count, body2, { + const response = assertResponse(await this.pageBlobContext.getPageRangesDiff({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - requestOptions: { - onUploadProgress: options.onProgress - }, + prevSnapshotUrl: prevSnapshotUrl2, range: rangeToString({ offset, count }), - sequenceNumberAccessConditions: options.conditions, - transactionalContentMD5: options.transactionalContentMD5, - transactionalContentCrc64: options.transactionalContentCrc64, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions })); + return rangeResponseFromModel(response); }); } /** - * The Upload Pages operation writes a range of pages to a page blob where the - * contents are read from a URL. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url + * Resizes the page blob to the specified size (which must be a multiple of 512). + * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties * - * @param sourceURL - Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication - * @param sourceOffset - The source offset to copy from. Pass 0 to copy from the beginning of source page blob - * @param destOffset - Offset of destination page blob - * @param count - Number of bytes to be uploaded from source page blob - * @param options - + * @param size - Target size + * @param options - Options to the Page Blob Resize operation. + * @returns Response data for the Page Blob Resize operation. */ - async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { + async resize(size, options = {}) { options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return tracingClient.withSpan("PageBlobClient-uploadPagesFromURL", options, async (updatedOptions) => { - var _a, _b, _c, _d, _e; - return assertResponse(await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), { + return tracingClient.withSpan("PageBlobClient-resize", options, async (updatedOptions) => { + var _a; + return assertResponse(await this.pageBlobContext.resize(size, { abortSignal: options.abortSignal, - sourceContentMD5: options.sourceContentMD5, - sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, - sequenceNumberAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - sourceModifiedAccessConditions: { - sourceIfMatch: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifMatch, - sourceIfModifiedSince: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifModifiedSince, - sourceIfNoneMatch: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch, - sourceIfUnmodifiedSince: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.ifUnmodifiedSince - }, - cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, - copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tracingOptions: updatedOptions.tracingOptions })); }); } /** - * Frees the specified pages from the page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * Sets a page blob's sequence number. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * - * @param offset - Starting byte position of the pages to clear. - * @param count - Number of bytes to clear. - * @param options - Options to the Page Blob Clear Pages operation. - * @returns Response data for the Page Blob Clear Pages operation. + * @param sequenceNumberAction - Indicates how the service should modify the blob's sequence number. + * @param sequenceNumber - Required if sequenceNumberAction is max or update + * @param options - Options to the Page Blob Update Sequence Number operation. + * @returns Response data for the Page Blob Update Sequence Number operation. */ - async clearPages(offset = 0, count, options = {}) { + async updateSequenceNumber(sequenceNumberAction2, sequenceNumber, options = {}) { options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-clearPages", options, async (updatedOptions) => { + return tracingClient.withSpan("PageBlobClient-updateSequenceNumber", options, async (updatedOptions) => { var _a; - return assertResponse(await this.pageBlobContext.clearPages(0, { + return assertResponse(await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction2, { abortSignal: options.abortSignal, + blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset, count }), - sequenceNumberAccessConditions: options.conditions, - cpkInfo: options.customerProvidedKey, - encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions })); }); } /** - * Returns the list of valid page ranges for a page blob or snapshot of a page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. + * The snapshot is copied such that only the differential changes between the previously + * copied snapshot are transferred to the destination. + * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. + * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob + * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param options - Options to the Page Blob Get Ranges operation. - * @returns Response data for the Page Blob Get Ranges operation. + * @param copySource - Specifies the name of the source page blob snapshot. For example, + * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param options - Options to the Page Blob Copy Incremental operation. + * @returns Response data for the Page Blob Copy Incremental operation. */ - async getPageRanges(offset = 0, count, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-getPageRanges", options, async (updatedOptions) => { + async startCopyIncremental(copySource2, options = {}) { + return tracingClient.withSpan("PageBlobClient-startCopyIncremental", options, async (updatedOptions) => { var _a; - const response = assertResponse(await this.pageBlobContext.getPageRanges({ + return assertResponse(await this.pageBlobContext.copyIncremental(copySource2, { abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset, count }), tracingOptions: updatedOptions.tracingOptions })); - return rangeResponseFromModel(response); }); } - /** - * getPageRangesSegment returns a single segment of page ranges starting from the - * specified Marker. Use an empty Marker to start enumeration from the beginning. - * After getting a segment, process it, and then call getPageRangesSegment again - * (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges - * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. - * @param options - Options to PageBlob Get Page Ranges Segment operation. - */ - async listPageRangesSegment(offset = 0, count, marker2, options = {}) { - return tracingClient.withSpan("PageBlobClient-getPageRangesSegment", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.getPageRanges({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - range: rangeToString({ offset, count }), - marker: marker2, - maxPageSize: options.maxPageSize, - tracingOptions: updatedOptions.tracingOptions - })); - }); + }; + async function getBodyAsText(batchResponse) { + let buffer2 = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); + const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer2); + buffer2 = buffer2.slice(0, responseLength); + return buffer2.toString(); + } + function utf8ByteLength(str2) { + return Buffer.byteLength(str2); + } + var HTTP_HEADER_DELIMITER = ": "; + var SPACE_DELIMITER = " "; + var NOT_FOUND = -1; + var BatchResponseParser = class { + constructor(batchResponse, subRequests) { + if (!batchResponse || !batchResponse.contentType) { + throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); + } + if (!subRequests || subRequests.size === 0) { + throw new RangeError("Invalid state: subRequests is not provided or size is 0."); + } + this.batchResponse = batchResponse; + this.subRequests = subRequests; + this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; + this.perResponsePrefix = `--${this.responseBatchBoundary}${HTTP_LINE_ENDING}`; + this.batchResponseEnding = `--${this.responseBatchBoundary}--`; + } + // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response + async parseBatchResponse() { + if (this.batchResponse._response.status !== HTTPURLConnection.HTTP_ACCEPTED) { + throw new Error(`Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.`); + } + const responseBodyAsText = await getBodyAsText(this.batchResponse); + const subResponses = responseBodyAsText.split(this.batchResponseEnding)[0].split(this.perResponsePrefix).slice(1); + const subResponseCount = subResponses.length; + if (subResponseCount !== this.subRequests.size && subResponseCount !== 1) { + throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); + } + const deserializedSubResponses = new Array(subResponseCount); + let subResponsesSucceededCount = 0; + let subResponsesFailedCount = 0; + for (let index = 0; index < subResponseCount; index++) { + const subResponse = subResponses[index]; + const deserializedSubResponse = {}; + deserializedSubResponse.headers = coreHttpCompat.toHttpHeadersLike(coreRestPipeline.createHttpHeaders()); + const responseLines = subResponse.split(`${HTTP_LINE_ENDING}`); + let subRespHeaderStartFound = false; + let subRespHeaderEndFound = false; + let subRespFailed = false; + let contentId = NOT_FOUND; + for (const responseLine of responseLines) { + if (!subRespHeaderStartFound) { + if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { + contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); + } + if (responseLine.startsWith(HTTP_VERSION_1_1)) { + subRespHeaderStartFound = true; + const tokens = responseLine.split(SPACE_DELIMITER); + deserializedSubResponse.status = parseInt(tokens[1]); + deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); + } + continue; + } + if (responseLine.trim() === "") { + if (!subRespHeaderEndFound) { + subRespHeaderEndFound = true; + } + continue; + } + if (!subRespHeaderEndFound) { + if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { + throw new Error(`Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.`); + } + const tokens = responseLine.split(HTTP_HEADER_DELIMITER); + deserializedSubResponse.headers.set(tokens[0], tokens[1]); + if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { + deserializedSubResponse.errorCode = tokens[1]; + subRespFailed = true; + } + } else { + if (!deserializedSubResponse.bodyAsText) { + deserializedSubResponse.bodyAsText = ""; + } + deserializedSubResponse.bodyAsText += responseLine; + } + } + if (contentId !== NOT_FOUND && Number.isInteger(contentId) && contentId >= 0 && contentId < this.subRequests.size && deserializedSubResponses[contentId] === void 0) { + deserializedSubResponse._request = this.subRequests.get(contentId); + deserializedSubResponses[contentId] = deserializedSubResponse; + } else { + logger.error(`subResponses[${index}] is dropped as the Content-ID is not found or invalid, Content-ID: ${contentId}`); + } + if (subRespFailed) { + subResponsesFailedCount++; + } else { + subResponsesSucceededCount++; + } + } + return { + subResponses: deserializedSubResponses, + subResponsesSucceededCount, + subResponsesFailedCount + }; + } + }; + var MutexLockStatus; + (function(MutexLockStatus2) { + MutexLockStatus2[MutexLockStatus2["LOCKED"] = 0] = "LOCKED"; + MutexLockStatus2[MutexLockStatus2["UNLOCKED"] = 1] = "UNLOCKED"; + })(MutexLockStatus || (MutexLockStatus = {})); + var Mutex = class { + /** + * Lock for a specific key. If the lock has been acquired by another customer, then + * will wait until getting the lock. + * + * @param key - lock key + */ + static async lock(key) { + return new Promise((resolve8) => { + if (this.keys[key] === void 0 || this.keys[key] === MutexLockStatus.UNLOCKED) { + this.keys[key] = MutexLockStatus.LOCKED; + resolve8(); + } else { + this.onUnlockEvent(key, () => { + this.keys[key] = MutexLockStatus.LOCKED; + resolve8(); + }); + } + }); + } + /** + * Unlock a key. + * + * @param key - + */ + static async unlock(key) { + return new Promise((resolve8) => { + if (this.keys[key] === MutexLockStatus.LOCKED) { + this.emitUnlockEvent(key); + } + delete this.keys[key]; + resolve8(); + }); + } + static onUnlockEvent(key, handler) { + if (this.listeners[key] === void 0) { + this.listeners[key] = [handler]; + } else { + this.listeners[key].push(handler); + } + } + static emitUnlockEvent(key) { + if (this.listeners[key] !== void 0 && this.listeners[key].length > 0) { + const handler = this.listeners[key].shift(); + setImmediate(() => { + handler.call(this); + }); + } + } + }; + Mutex.keys = {}; + Mutex.listeners = {}; + var BlobBatch = class { + constructor() { + this.batch = "batch"; + this.batchRequest = new InnerBatchRequest(); + } + /** + * Get the value of Content-Type for a batch request. + * The value must be multipart/mixed with a batch boundary. + * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 + */ + getMultiPartContentType() { + return this.batchRequest.getMultipartContentType(); + } + /** + * Get assembled HTTP request body for sub requests. + */ + getHttpRequestBody() { + return this.batchRequest.getHttpRequestBody(); + } + /** + * Get sub requests that are added into the batch request. + */ + getSubRequests() { + return this.batchRequest.getSubRequests(); + } + async addSubRequestInternal(subRequest, assembleSubRequestFunc) { + await Mutex.lock(this.batch); + try { + this.batchRequest.preAddSubRequest(subRequest); + await assembleSubRequestFunc(); + this.batchRequest.postAddSubRequest(subRequest); + } finally { + await Mutex.unlock(this.batch); + } + } + setBatchType(batchType) { + if (!this.batchType) { + this.batchType = batchType; + } + if (this.batchType !== batchType) { + throw new RangeError(`BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.`); + } + } + async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { + let url3; + let credential; + if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrOptions instanceof StorageSharedKeyCredential || credentialOrOptions instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrOptions))) { + url3 = urlOrBlobClient; + credential = credentialOrOptions; + } else if (urlOrBlobClient instanceof BlobClient) { + url3 = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + options = credentialOrOptions; + } else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + return tracingClient.withSpan("BatchDeleteRequest-addSubRequest", options, async (updatedOptions) => { + this.setBatchType("delete"); + await this.addSubRequestInternal({ + url: url3, + credential + }, async () => { + await new BlobClient(url3, this.batchRequest.createPipeline(credential)).delete(updatedOptions); + }); + }); + } + async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { + let url3; + let credential; + let tier2; + if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrTier instanceof StorageSharedKeyCredential || credentialOrTier instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrTier))) { + url3 = urlOrBlobClient; + credential = credentialOrTier; + tier2 = tierOrOptions; + } else if (urlOrBlobClient instanceof BlobClient) { + url3 = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + tier2 = credentialOrTier; + options = tierOrOptions; + } else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + return tracingClient.withSpan("BatchSetTierRequest-addSubRequest", options, async (updatedOptions) => { + this.setBatchType("setAccessTier"); + await this.addSubRequestInternal({ + url: url3, + credential + }, async () => { + await new BlobClient(url3, this.batchRequest.createPipeline(credential)).setAccessTier(tier2, updatedOptions); + }); + }); + } + }; + var InnerBatchRequest = class { + constructor() { + this.operationCount = 0; + this.body = ""; + const tempGuid = coreUtil.randomUUID(); + this.boundary = `batch_${tempGuid}`; + this.subRequestPrefix = `--${this.boundary}${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TYPE}: application/http${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; + this.multipartContentType = `multipart/mixed; boundary=${this.boundary}`; + this.batchRequestEnding = `--${this.boundary}--`; + this.subRequests = /* @__PURE__ */ new Map(); + } + /** + * Create pipeline to assemble sub requests. The idea here is to use existing + * credential and serialization/deserialization components, with additional policies to + * filter unnecessary headers, assemble sub requests into request's body + * and intercept request from going to wire. + * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. + */ + createPipeline(credential) { + const corePipeline = coreRestPipeline.createEmptyPipeline(); + corePipeline.addPolicy(coreClient.serializationPolicy({ + stringifyXML: coreXml.stringifyXML, + serializerOptions: { + xml: { + xmlCharKey: "#" + } + } + }), { phase: "Serialize" }); + corePipeline.addPolicy(batchHeaderFilterPolicy()); + corePipeline.addPolicy(batchRequestAssemblePolicy(this), { afterPhase: "Sign" }); + if (coreAuth.isTokenCredential(credential)) { + corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ + credential, + scopes: StorageOAuthScopes, + challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge } + }), { phase: "Sign" }); + } else if (credential instanceof StorageSharedKeyCredential) { + corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ + accountName: credential.accountName, + accountKey: credential.accountKey + }), { phase: "Sign" }); + } + const pipeline = new Pipeline([]); + pipeline._credential = credential; + pipeline._corePipeline = corePipeline; + return pipeline; + } + appendSubRequestToBody(request) { + this.body += [ + this.subRequestPrefix, + // sub request constant prefix + `${HeaderConstants.CONTENT_ID}: ${this.operationCount}`, + // sub request's content ID + "", + // empty line after sub request's content ID + `${request.method.toString()} ${getURLPathAndQuery(request.url)} ${HTTP_VERSION_1_1}${HTTP_LINE_ENDING}` + // sub request start line with method + ].join(HTTP_LINE_ENDING); + for (const [name, value] of request.headers) { + this.body += `${name}: ${value}${HTTP_LINE_ENDING}`; + } + this.body += HTTP_LINE_ENDING; + } + preAddSubRequest(subRequest) { + if (this.operationCount >= BATCH_MAX_REQUEST) { + throw new RangeError(`Cannot exceed ${BATCH_MAX_REQUEST} sub requests in a single batch`); + } + const path15 = getURLPath(subRequest.url); + if (!path15 || path15 === "") { + throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); + } + } + postAddSubRequest(subRequest) { + this.subRequests.set(this.operationCount, subRequest); + this.operationCount++; + } + // Return the http request body with assembling the ending line to the sub request body. + getHttpRequestBody() { + return `${this.body}${this.batchRequestEnding}${HTTP_LINE_ENDING}`; } - /** - * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesResponseModel} - * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param marker - A string value that identifies the portion of - * the get of page ranges to be returned with the next getting operation. The - * operation returns the ContinuationToken value within the response body if the - * getting operation did not return all page ranges remaining within the current page. - * The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of get - * items. The marker value is opaque to the client. - * @param options - Options to List Page Ranges operation. - */ - listPageRangeItemSegments() { - return tslib.__asyncGenerator(this, arguments, function* listPageRangeItemSegments_1(offset = 0, count, marker2, options = {}) { - let getPageRangeItemSegmentsResponse; - if (!!marker2 || marker2 === void 0) { - do { - getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesSegment(offset, count, marker2, options)); - marker2 = getPageRangeItemSegmentsResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); - } while (marker2); + getMultipartContentType() { + return this.multipartContentType; + } + getSubRequests() { + return this.subRequests; + } + }; + function batchRequestAssemblePolicy(batchRequest) { + return { + name: "batchRequestAssemblePolicy", + async sendRequest(request) { + batchRequest.appendSubRequestToBody(request); + return { + request, + status: 200, + headers: coreRestPipeline.createHttpHeaders() + }; + } + }; + } + function batchHeaderFilterPolicy() { + return { + name: "batchHeaderFilterPolicy", + async sendRequest(request, next) { + let xMsHeaderName = ""; + for (const [name] of request.headers) { + if (iEqual(name, HeaderConstants.X_MS_VERSION)) { + xMsHeaderName = name; + } } - }); + if (xMsHeaderName !== "") { + request.headers.delete(xMsHeaderName); + } + return next(request); + } + }; + } + var BlobBatchClient = class { + constructor(url3, credentialOrPipeline, options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { + pipeline = credentialOrPipeline; + } else if (!credentialOrPipeline) { + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + pipeline = newPipeline(credentialOrPipeline, options); + } + const storageClientContext = new StorageContextClient(url3, getCoreClientOptions(pipeline)); + const path15 = getURLPath(url3); + if (path15 && path15 !== "/") { + this.serviceOrContainerContext = storageClientContext.container; + } else { + this.serviceOrContainerContext = storageClientContext.service; + } } /** - * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects - * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param options - Options to List Page Ranges operation. + * Creates a {@link BlobBatch}. + * A BlobBatch represents an aggregated set of operations on blobs. */ - listPageRangeItems() { - return tslib.__asyncGenerator(this, arguments, function* listPageRangeItems_1(offset = 0, count, options = {}) { - var _a, e_1, _b, _c; - let marker2; - try { - for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeItemSegments(offset, count, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const getPageRangesSegment = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_1) throw e_1.error; - } + createBatch() { + return new BlobBatch(); + } + async deleteBlobs(urlsOrBlobClients, credentialOrOptions, options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); + } else { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions); } - }); + } + return this.submitBatch(batch); + } + async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); + } else { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); + } + } + return this.submitBatch(batch); } /** - * Returns an async iterable iterator to list of page ranges for a page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges - * - * .byPage() returns an async iterable iterator to list of page ranges for a page blob. - * - * Example using `for await` syntax: + * Submit batch request which consists of multiple subrequests. * - * ```js - * // Get the pageBlobClient before you run these snippets, - * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` - * let i = 1; - * for await (const pageRange of pageBlobClient.listPageRanges()) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * ``` + * Get `blobBatchClient` and other details before running the snippets. + * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` * - * Example using `iter.next()`: + * Example usage: * * ```js - * let i = 1; - * let iter = pageBlobClient.listPageRanges(); - * let pageRangeItem = await iter.next(); - * while (!pageRangeItem.done) { - * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); - * pageRangeItem = await iter.next(); - * } + * let batchRequest = new BlobBatch(); + * await batchRequest.deleteBlob(urlInString0, credential0); + * await batchRequest.deleteBlob(urlInString1, credential1, { + * deleteSnapshots: "include" + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); * ``` * - * Example using `byPage()`: + * Example using a lease: * * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of pageBlobClient.listPageRanges().byPage({ maxPageSize: 20 })) { - * for (const pageRange of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * } + * let batchRequest = new BlobBatch(); + * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); + * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { + * conditions: { leaseId: leaseId } + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); * ``` * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = pageBlobClient.listPageRanges().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 page ranges - * for (const pageRange of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * - * // Passing next marker as continuationToken - * - * iterator = pageBlobClient.listPageRanges().byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * - * // Prints 10 page ranges - * for (const blob of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * ``` - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param options - Options to the Page Blob Get Ranges operation. - * @returns An asyncIterableIterator that supports paging. + * @param batchRequest - A set of Delete or SetTier operations. + * @param options - */ - listPageRanges(offset = 0, count, options = {}) { - options.conditions = options.conditions || {}; - const iter = this.listPageRangeItems(offset, count, options); - return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listPageRangeItemSegments(offset, count, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); - } - }; + async submitBatch(batchRequest, options = {}) { + if (!batchRequest || batchRequest.getSubRequests().size === 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + return tracingClient.withSpan("BlobBatchClient-submitBatch", options, async (updatedOptions) => { + const batchRequestBody = batchRequest.getHttpRequestBody(); + const rawBatchResponse = assertResponse(await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, Object.assign({}, updatedOptions))); + const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + const responseSummary = await batchResponseParser.parseBatchResponse(); + const res = { + _response: rawBatchResponse._response, + contentType: rawBatchResponse.contentType, + errorCode: rawBatchResponse.errorCode, + requestId: rawBatchResponse.requestId, + clientRequestId: rawBatchResponse.clientRequestId, + version: rawBatchResponse.version, + subResponses: responseSummary.subResponses, + subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, + subResponsesFailedCount: responseSummary.subResponsesFailedCount + }; + return res; + }); } + }; + var ContainerClient = class extends StorageClient { /** - * Gets the collection of page ranges that differ between a specified snapshot and this page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges - * - * @param offset - Starting byte position of the page blob - * @param count - Number of bytes to get ranges diff. - * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. - * @returns Response data for the Page Blob Get Page Range Diff operation. + * The name of the container. */ - async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-getPageRangesDiff", options, async (updatedOptions) => { - var _a; - const result = assertResponse(await this.pageBlobContext.getPageRangesDiff({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevsnapshot: prevSnapshot, - range: rangeToString({ offset, count }), - tracingOptions: updatedOptions.tracingOptions - })); - return rangeResponseFromModel(result); - }); + get containerName() { + return this._containerName; + } + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { + let pipeline; + let url3; + options = options || {}; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { + url3 = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } else if (coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipelineOrContainerName)) { + url3 = urlOrConnectionString; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { + url3 = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { + const containerName = credentialOrPipelineOrContainerName; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url3 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + pipeline = newPipeline(sharedKeyCredential, options); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + url3 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + "?" + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } else { + throw new Error("Expecting non-empty strings for containerName parameter"); + } + super(url3, pipeline); + this._containerName = this.getContainerNameFromUrl(); + this.containerContext = this.storageClientContext.container; } /** - * getPageRangesDiffSegment returns a single segment of page ranges starting from the - * specified Marker for difference between previous snapshot and the target page blob. - * Use an empty Marker to start enumeration from the beginning. - * After getting a segment, process it, and then call getPageRangesDiffSegment again - * (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * Creates a new container under the specified account. If the container with + * the same name already exists, the operation fails. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. - * @param marker - A string value that identifies the portion of the get to be returned with the next get operation. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @param options - Options to Container Create operation. + * + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * const createContainerResponse = await containerClient.create(); + * console.log("Container was created successfully", createContainerResponse.requestId); + * ``` */ - async listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options = {}) { - return tracingClient.withSpan("PageBlobClient-getPageRangesDiffSegment", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.getPageRangesDiff({ - abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, - leaseAccessConditions: options === null || options === void 0 ? void 0 : options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.conditions), { ifTags: (_a = options === null || options === void 0 ? void 0 : options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevsnapshot: prevSnapshotOrUrl, - range: rangeToString({ - offset, - count - }), - marker: marker2, - maxPageSize: options === null || options === void 0 ? void 0 : options.maxPageSize, - tracingOptions: updatedOptions.tracingOptions - })); + async create(options = {}) { + return tracingClient.withSpan("ContainerClient-create", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.create(updatedOptions)); }); } /** - * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesDiffResponseModel} - * + * Creates a new container under the specified account. If the container with + * the same name already exists, it is not changed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. - * @param marker - A string value that identifies the portion of - * the get of page ranges to be returned with the next getting operation. The - * operation returns the ContinuationToken value within the response body if the - * getting operation did not return all page ranges remaining within the current page. - * The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of get - * items. The marker value is opaque to the client. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * @param options - */ - listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options) { - return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItemSegments_1() { - let getPageRangeItemSegmentsResponse; - if (!!marker2 || marker2 === void 0) { - do { - getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker2, options)); - marker2 = getPageRangeItemSegmentsResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); - } while (marker2); + async createIfNotExists(options = {}) { + return tracingClient.withSpan("ContainerClient-createIfNotExists", options, async (updatedOptions) => { + var _a, _b; + try { + const res = await this.create(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } else { + throw e; + } } }); } /** - * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects + * Returns true if the Azure container resource represented by this client exists; false otherwise. * - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. + * NOTE: use this function with care since an existing container might be deleted by other clients or + * applications. Vice versa new containers with the same name might be added by other clients or + * applications after this function completes. + * + * @param options - */ - listPageRangeDiffItems(offset, count, prevSnapshotOrUrl, options) { - return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItems_1() { - var _a, e_2, _b, _c; - let marker2; + async exists(options = {}) { + return tracingClient.withSpan("ContainerClient-exists", options, async (updatedOptions) => { try { - for (var _d = true, _e = tslib.__asyncValues(this.listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const getPageRangesSegment = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); - } - } catch (e_2_1) { - e_2 = { error: e_2_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_2) throw e_2.error; + await this.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + }); + return true; + } catch (e) { + if (e.statusCode === 404) { + return false; } + throw e; } }); } /** - * Returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges - * - * .byPage() returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. - * - * Example using `for await` syntax: - * - * ```js - * // Get the pageBlobClient before you run these snippets, - * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` - * let i = 1; - * for await (const pageRange of pageBlobClient.listPageRangesDiff()) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * ``` + * Creates a {@link BlobClient} * - * Example using `iter.next()`: + * @param blobName - A blob name + * @returns A new BlobClient object for the given blob name. + */ + getBlobClient(blobName) { + return new BlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Creates an {@link AppendBlobClient} * - * ```js - * let i = 1; - * let iter = pageBlobClient.listPageRangesDiff(); - * let pageRangeItem = await iter.next(); - * while (!pageRangeItem.done) { - * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); - * pageRangeItem = await iter.next(); - * } - * ``` + * @param blobName - An append blob name + */ + getAppendBlobClient(blobName) { + return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Creates a {@link BlockBlobClient} * - * Example using `byPage()`: + * @param blobName - A block blob name * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 20 })) { - * for (const pageRange of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * } - * ``` * - * Example using paging with a marker: + * Example usage: * * ```js - * let i = 1; - * let iterator = pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 page ranges - * for (const pageRange of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } + * const content = "Hello world!"; * - * // Gets next marker - * let marker = response.continuationToken; + * const blockBlobClient = containerClient.getBlockBlobClient(""); + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); + * ``` + */ + getBlockBlobClient(blobName) { + return new BlockBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Creates a {@link PageBlobClient} * - * // Passing next marker as continuationToken + * @param blobName - A page blob name + */ + getPageBlobClient(blobName) { + return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + /** + * Returns all user-defined metadata and system properties for the specified + * container. The data returned does not include the container's list of blobs. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties * - * iterator = pageBlobClient.listPageRangesDiff().byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which + * will retain their original casing. * - * // Prints 10 page ranges - * for (const blob of response) { - * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); - * } - * ``` - * @param offset - Starting byte position of the page ranges. - * @param count - Number of bytes to get. - * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. - * @param options - Options to the Page Blob Get Ranges operation. - * @returns An asyncIterableIterator that supports paging. + * @param options - Options to Container Get Properties operation. */ - listPageRangesDiff(offset, count, prevSnapshot, options = {}) { - options.conditions = options.conditions || {}; - const iter = this.listPageRangeDiffItems(offset, count, prevSnapshot, Object.assign({}, options)); - return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listPageRangeDiffItemSegments(offset, count, prevSnapshot, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); - } - }; + async getProperties(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("ContainerClient-getProperties", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), { tracingOptions: updatedOptions.tracingOptions }))); + }); } /** - * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. - * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * Marks the specified container for deletion. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * - * @param offset - Starting byte position of the page blob - * @param count - Number of bytes to get ranges diff. - * @param prevSnapshotUrl - URL of snapshot to retrieve the difference. - * @param options - Options to the Page Blob Get Page Ranges Diff operation. - * @returns Response data for the Page Blob Get Page Range Diff operation. + * @param options - Options to Container Delete operation. */ - async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl2, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options, async (updatedOptions) => { - var _a; - const response = assertResponse(await this.pageBlobContext.getPageRangesDiff({ + async delete(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("ContainerClient-delete", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.delete({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - prevSnapshotUrl: prevSnapshotUrl2, - range: rangeToString({ offset, count }), + modifiedAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions })); - return rangeResponseFromModel(response); }); } /** - * Resizes the page blob to the specified size (which must be a multiple of 512). - * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties + * Marks the specified container for deletion if it exists. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * - * @param size - Target size - * @param options - Options to the Page Blob Resize operation. - * @returns Response data for the Page Blob Resize operation. + * @param options - Options to Container Delete operation. */ - async resize(size, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-resize", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.resize(size, { + async deleteIfExists(options = {}) { + return tracingClient.withSpan("ContainerClient-deleteIfExists", options, async (updatedOptions) => { + var _a, _b; + try { + const res = await this.delete(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); + } catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + throw e; + } + }); + } + /** + * Sets one or more user-defined name-value pairs for the specified container. + * + * If no option provided, or no metadata defined in the parameter, the container + * metadata will be removed. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * + * @param metadata - Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param options - Options to Container Set Metadata operation. + */ + async setMetadata(metadata2, options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + if (options.conditions.ifUnmodifiedSince) { + throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + } + return tracingClient.withSpan("ContainerClient-setMetadata", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.setMetadata({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - encryptionScope: options.encryptionScope, + metadata: metadata2, + modifiedAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions })); }); } /** - * Sets a page blob's sequence number. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * Gets the permissions for the specified container. The permissions indicate + * whether container data may be accessed publicly. * - * @param sequenceNumberAction - Indicates how the service should modify the blob's sequence number. - * @param sequenceNumber - Required if sequenceNumberAction is max or update - * @param options - Options to the Page Blob Update Sequence Number operation. - * @returns Response data for the Page Blob Update Sequence Number operation. + * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. + * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl + * + * @param options - Options to Container Get Access Policy operation. */ - async updateSequenceNumber(sequenceNumberAction2, sequenceNumber, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("PageBlobClient-updateSequenceNumber", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction2, { + async getAccessPolicy(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + return tracingClient.withSpan("ContainerClient-getAccessPolicy", options, async (updatedOptions) => { + const response = assertResponse(await this.containerContext.getAccessPolicy({ abortSignal: options.abortSignal, - blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), tracingOptions: updatedOptions.tracingOptions })); + const res = { + _response: response._response, + blobPublicAccess: response.blobPublicAccess, + date: response.date, + etag: response.etag, + errorCode: response.errorCode, + lastModified: response.lastModified, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + signedIdentifiers: [], + version: response.version + }; + for (const identifier of response) { + let accessPolicy = void 0; + if (identifier.accessPolicy) { + accessPolicy = { + permissions: identifier.accessPolicy.permissions + }; + if (identifier.accessPolicy.expiresOn) { + accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); + } + if (identifier.accessPolicy.startsOn) { + accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); + } + } + res.signedIdentifiers.push({ + accessPolicy, + id: identifier.id + }); + } + return res; }); } /** - * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. - * The snapshot is copied such that only the differential changes between the previously - * copied snapshot are transferred to the destination. - * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. - * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob - * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots + * Sets the permissions for the specified container. The permissions indicate + * whether blobs in a container may be accessed publicly. * - * @param copySource - Specifies the name of the source page blob snapshot. For example, - * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= - * @param options - Options to the Page Blob Copy Incremental operation. - * @returns Response data for the Page Blob Copy Incremental operation. + * When you set permissions for a container, the existing permissions are replaced. + * If no access or containerAcl provided, the existing container ACL will be + * removed. + * + * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. + * During this interval, a shared access signature that is associated with the stored access policy will + * fail with status code 403 (Forbidden), until the access policy becomes active. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl + * + * @param access - The level of public access to data in the container. + * @param containerAcl - Array of elements each having a unique Id and details of the access policy. + * @param options - Options to Container Set Access Policy operation. */ - async startCopyIncremental(copySource2, options = {}) { - return tracingClient.withSpan("PageBlobClient-startCopyIncremental", options, async (updatedOptions) => { - var _a; - return assertResponse(await this.pageBlobContext.copyIncremental(copySource2, { + async setAccessPolicy(access2, containerAcl2, options = {}) { + options.conditions = options.conditions || {}; + return tracingClient.withSpan("ContainerClient-setAccessPolicy", options, async (updatedOptions) => { + const acl = []; + for (const identifier of containerAcl2 || []) { + acl.push({ + accessPolicy: { + expiresOn: identifier.accessPolicy.expiresOn ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) : "", + permissions: identifier.accessPolicy.permissions, + startsOn: identifier.accessPolicy.startsOn ? truncatedISO8061Date(identifier.accessPolicy.startsOn) : "" + }, + id: identifier.id + }); + } + return assertResponse(await this.containerContext.setAccessPolicy({ abortSignal: options.abortSignal, - modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + access: access2, + containerAcl: acl, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, tracingOptions: updatedOptions.tracingOptions })); }); } - }; - async function getBodyAsText(batchResponse) { - let buffer2 = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); - const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer2); - buffer2 = buffer2.slice(0, responseLength); - return buffer2.toString(); - } - function utf8ByteLength(str2) { - return Buffer.byteLength(str2); - } - var HTTP_HEADER_DELIMITER = ": "; - var SPACE_DELIMITER = " "; - var NOT_FOUND = -1; - var BatchResponseParser = class { - constructor(batchResponse, subRequests) { - if (!batchResponse || !batchResponse.contentType) { - throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); - } - if (!subRequests || subRequests.size === 0) { - throw new RangeError("Invalid state: subRequests is not provided or size is 0."); - } - this.batchResponse = batchResponse; - this.subRequests = subRequests; - this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; - this.perResponsePrefix = `--${this.responseBatchBoundary}${HTTP_LINE_ENDING}`; - this.batchResponseEnding = `--${this.responseBatchBoundary}--`; + /** + * Get a {@link BlobLeaseClient} that manages leases on the container. + * + * @param proposeLeaseId - Initial proposed lease Id. + * @returns A new BlobLeaseClient object for managing leases on the container. + */ + getBlobLeaseClient(proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); } - // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response - async parseBatchResponse() { - if (this.batchResponse._response.status !== HTTPURLConnection.HTTP_ACCEPTED) { - throw new Error(`Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.`); - } - const responseBodyAsText = await getBodyAsText(this.batchResponse); - const subResponses = responseBodyAsText.split(this.batchResponseEnding)[0].split(this.perResponsePrefix).slice(1); - const subResponseCount = subResponses.length; - if (subResponseCount !== this.subRequests.size && subResponseCount !== 1) { - throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); - } - const deserializedSubResponses = new Array(subResponseCount); - let subResponsesSucceededCount = 0; - let subResponsesFailedCount = 0; - for (let index = 0; index < subResponseCount; index++) { - const subResponse = subResponses[index]; - const deserializedSubResponse = {}; - deserializedSubResponse.headers = coreHttpCompat.toHttpHeadersLike(coreRestPipeline.createHttpHeaders()); - const responseLines = subResponse.split(`${HTTP_LINE_ENDING}`); - let subRespHeaderStartFound = false; - let subRespHeaderEndFound = false; - let subRespFailed = false; - let contentId = NOT_FOUND; - for (const responseLine of responseLines) { - if (!subRespHeaderStartFound) { - if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { - contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); - } - if (responseLine.startsWith(HTTP_VERSION_1_1)) { - subRespHeaderStartFound = true; - const tokens = responseLine.split(SPACE_DELIMITER); - deserializedSubResponse.status = parseInt(tokens[1]); - deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); - } - continue; - } - if (responseLine.trim() === "") { - if (!subRespHeaderEndFound) { - subRespHeaderEndFound = true; - } - continue; - } - if (!subRespHeaderEndFound) { - if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { - throw new Error(`Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.`); - } - const tokens = responseLine.split(HTTP_HEADER_DELIMITER); - deserializedSubResponse.headers.set(tokens[0], tokens[1]); - if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { - deserializedSubResponse.errorCode = tokens[1]; - subRespFailed = true; - } - } else { - if (!deserializedSubResponse.bodyAsText) { - deserializedSubResponse.bodyAsText = ""; - } - deserializedSubResponse.bodyAsText += responseLine; - } - } - if (contentId !== NOT_FOUND && Number.isInteger(contentId) && contentId >= 0 && contentId < this.subRequests.size && deserializedSubResponses[contentId] === void 0) { - deserializedSubResponse._request = this.subRequests.get(contentId); - deserializedSubResponses[contentId] = deserializedSubResponse; - } else { - logger.error(`subResponses[${index}] is dropped as the Content-ID is not found or invalid, Content-ID: ${contentId}`); - } - if (subRespFailed) { - subResponsesFailedCount++; - } else { - subResponsesSucceededCount++; + /** + * Creates a new block blob, or updates the content of an existing block blob. + * + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. + * + * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, + * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better + * performance with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param blobName - Name of the block blob to create or update. + * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param options - Options to configure the Block Blob Upload operation. + * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. + */ + async uploadBlockBlob(blobName, body2, contentLength2, options = {}) { + return tracingClient.withSpan("ContainerClient-uploadBlockBlob", options, async (updatedOptions) => { + const blockBlobClient = this.getBlockBlobClient(blobName); + const response = await blockBlobClient.upload(body2, contentLength2, updatedOptions); + return { + blockBlobClient, + response + }; + }); + } + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param blobName - + * @param options - Options to Blob Delete operation. + * @returns Block blob deletion response data. + */ + async deleteBlob(blobName, options = {}) { + return tracingClient.withSpan("ContainerClient-deleteBlob", options, async (updatedOptions) => { + let blobClient = this.getBlobClient(blobName); + if (options.versionId) { + blobClient = blobClient.withVersion(options.versionId); } - } - return { - subResponses: deserializedSubResponses, - subResponsesSucceededCount, - subResponsesFailedCount - }; + return blobClient.delete(updatedOptions); + }); } - }; - var MutexLockStatus; - (function(MutexLockStatus2) { - MutexLockStatus2[MutexLockStatus2["LOCKED"] = 0] = "LOCKED"; - MutexLockStatus2[MutexLockStatus2["UNLOCKED"] = 1] = "UNLOCKED"; - })(MutexLockStatus || (MutexLockStatus = {})); - var Mutex = class { /** - * Lock for a specific key. If the lock has been acquired by another customer, then - * will wait until getting the lock. + * listBlobFlatSegment returns a single segment of blobs starting from the + * specified Marker. Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call listBlobsFlatSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs * - * @param key - lock key + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to Container List Blob Flat Segment operation. */ - static async lock(key) { - return new Promise((resolve8) => { - if (this.keys[key] === void 0 || this.keys[key] === MutexLockStatus.UNLOCKED) { - this.keys[key] = MutexLockStatus.LOCKED; - resolve8(); - } else { - this.onUnlockEvent(key, () => { - this.keys[key] = MutexLockStatus.LOCKED; - resolve8(); - }); + async listBlobFlatSegment(marker2, options = {}) { + return tracingClient.withSpan("ContainerClient-listBlobFlatSegment", options, async (updatedOptions) => { + const response = assertResponse(await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobFlat(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { + const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return wrappedResponse; + }); + } + /** + * listBlobHierarchySegment returns a single segment of blobs starting from + * the specified Marker. Use an empty Marker to start enumeration from the + * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment + * again (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. + * @param options - Options to Container List Blob Hierarchy Segment operation. + */ + async listBlobHierarchySegment(delimiter2, marker2, options = {}) { + return tracingClient.withSpan("ContainerClient-listBlobHierarchySegment", options, async (updatedOptions) => { + var _a; + const response = assertResponse(await this.containerContext.listBlobHierarchySegment(delimiter2, Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobHierarchy(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { + const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); + return blobItem; + }), blobPrefixes: (_a = response.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { + const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); + return blobPrefix; + }) }) }); + return wrappedResponse; + }); + } + /** + * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to list blobs operation. + */ + listSegments(marker_1) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { + let listBlobsFlatSegmentResponse; + if (!!marker2 || marker2 === void 0) { + do { + listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker2, options)); + marker2 = listBlobsFlatSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); + } while (marker2); } }); } /** - * Unlock a key. + * Returns an AsyncIterableIterator of {@link BlobItem} objects * - * @param key - + * @param options - Options to list blobs operation. */ - static async unlock(key) { - return new Promise((resolve8) => { - if (this.keys[key] === MutexLockStatus.LOCKED) { - this.emitUnlockEvent(key); + listItems() { + return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { + var _a, e_1, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const listBlobsFlatSegmentResponse = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_1) throw e_1.error; + } } - delete this.keys[key]; - resolve8(); }); } - static onUnlockEvent(key, handler) { - if (this.listeners[key] === void 0) { - this.listeners[key] = [handler]; - } else { - this.listeners[key].push(handler); - } - } - static emitUnlockEvent(key) { - if (this.listeners[key] !== void 0 && this.listeners[key].length > 0) { - const handler = this.listeners[key].shift(); - setImmediate(() => { - handler.call(this); - }); - } - } - }; - Mutex.keys = {}; - Mutex.listeners = {}; - var BlobBatch = class { - constructor() { - this.batch = "batch"; - this.batchRequest = new InnerBatchRequest(); - } - /** - * Get the value of Content-Type for a batch request. - * The value must be multipart/mixed with a batch boundary. - * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 - */ - getMultiPartContentType() { - return this.batchRequest.getMultipartContentType(); - } - /** - * Get assembled HTTP request body for sub requests. - */ - getHttpRequestBody() { - return this.batchRequest.getHttpRequestBody(); - } /** - * Get sub requests that are added into the batch request. + * Returns an async iterable iterator to list all the blobs + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * Example using `for await` syntax: + * + * ```js + * // Get the containerClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("");` + * let i = 1; + * for await (const blob of containerClient.listBlobsFlat()) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = containerClient.listBlobsFlat(); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * @param options - Options to list blobs. + * @returns An asyncIterableIterator that supports paging. */ - getSubRequests() { - return this.batchRequest.getSubRequests(); - } - async addSubRequestInternal(subRequest, assembleSubRequestFunc) { - await Mutex.lock(this.batch); - try { - this.batchRequest.preAddSubRequest(subRequest); - await assembleSubRequestFunc(); - this.batchRequest.postAddSubRequest(subRequest); - } finally { - await Mutex.unlock(this.batch); + listBlobsFlat(options = {}) { + const include2 = []; + if (options.includeCopy) { + include2.push("copy"); } - } - setBatchType(batchType) { - if (!this.batchType) { - this.batchType = batchType; + if (options.includeDeleted) { + include2.push("deleted"); } - if (this.batchType !== batchType) { - throw new RangeError(`BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.`); + if (options.includeMetadata) { + include2.push("metadata"); } - } - async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { - let url3; - let credential; - if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrOptions instanceof StorageSharedKeyCredential || credentialOrOptions instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrOptions))) { - url3 = urlOrBlobClient; - credential = credentialOrOptions; - } else if (urlOrBlobClient instanceof BlobClient) { - url3 = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - options = credentialOrOptions; - } else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + if (options.includeSnapshots) { + include2.push("snapshots"); } - if (!options) { - options = {}; + if (options.includeVersions) { + include2.push("versions"); } - return tracingClient.withSpan("BatchDeleteRequest-addSubRequest", options, async (updatedOptions) => { - this.setBatchType("delete"); - await this.addSubRequestInternal({ - url: url3, - credential - }, async () => { - await new BlobClient(url3, this.batchRequest.createPipeline(credential)).delete(updatedOptions); - }); - }); - } - async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { - let url3; - let credential; - let tier2; - if (typeof urlOrBlobClient === "string" && (coreUtil.isNode && credentialOrTier instanceof StorageSharedKeyCredential || credentialOrTier instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrTier))) { - url3 = urlOrBlobClient; - credential = credentialOrTier; - tier2 = tierOrOptions; - } else if (urlOrBlobClient instanceof BlobClient) { - url3 = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - tier2 = credentialOrTier; - options = tierOrOptions; - } else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + if (options.includeUncommitedBlobs) { + include2.push("uncommittedblobs"); } - if (!options) { - options = {}; + if (options.includeTags) { + include2.push("tags"); } - return tracingClient.withSpan("BatchSetTierRequest-addSubRequest", options, async (updatedOptions) => { - this.setBatchType("setAccessTier"); - await this.addSubRequestInternal({ - url: url3, - credential - }, async () => { - await new BlobClient(url3, this.batchRequest.createPipeline(credential)).setAccessTier(tier2, updatedOptions); - }); - }); + if (options.includeDeletedWithVersions) { + include2.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include2.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include2.push("legalhold"); + } + if (options.prefix === "") { + options.prefix = void 0; + } + const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); + const iter = this.listItems(updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; } - }; - var InnerBatchRequest = class { - constructor() { - this.operationCount = 0; - this.body = ""; - const tempGuid = coreUtil.randomUUID(); - this.boundary = `batch_${tempGuid}`; - this.subRequestPrefix = `--${this.boundary}${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TYPE}: application/http${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; - this.multipartContentType = `multipart/mixed; boundary=${this.boundary}`; - this.batchRequestEnding = `--${this.boundary}--`; - this.subRequests = /* @__PURE__ */ new Map(); + /** + * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to list blobs operation. + */ + listHierarchySegments(delimiter_1, marker_1) { + return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1(delimiter2, marker2, options = {}) { + let listBlobsHierarchySegmentResponse; + if (!!marker2 || marker2 === void 0) { + do { + listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter2, marker2, options)); + marker2 = listBlobsHierarchySegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); + } while (marker2); + } + }); } /** - * Create pipeline to assemble sub requests. The idea here is to use existing - * credential and serialization/deserialization components, with additional policies to - * filter unnecessary headers, assemble sub requests into request's body - * and intercept request from going to wire. - * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. + * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param options - Options to list blobs operation. */ - createPipeline(credential) { - const corePipeline = coreRestPipeline.createEmptyPipeline(); - corePipeline.addPolicy(coreClient.serializationPolicy({ - stringifyXML: coreXml.stringifyXML, - serializerOptions: { - xml: { - xmlCharKey: "#" + listItemsByHierarchy(delimiter_1) { + return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1(delimiter2, options = {}) { + var _a, e_2, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listHierarchySegments(delimiter2, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const listBlobsHierarchySegmentResponse = _c; + const segment = listBlobsHierarchySegmentResponse.segment; + if (segment.blobPrefixes) { + for (const prefix2 of segment.blobPrefixes) { + yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix2)); + } + } + for (const blob of segment.blobItems) { + yield yield tslib.__await(Object.assign({ kind: "blob" }, blob)); + } + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_2) throw e_2.error; } } - }), { phase: "Serialize" }); - corePipeline.addPolicy(batchHeaderFilterPolicy()); - corePipeline.addPolicy(batchRequestAssemblePolicy(this), { afterPhase: "Sign" }); - if (coreAuth.isTokenCredential(credential)) { - corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ - credential, - scopes: StorageOAuthScopes, - challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge } - }), { phase: "Sign" }); - } else if (credential instanceof StorageSharedKeyCredential) { - corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ - accountName: credential.accountName, - accountKey: credential.accountKey - }), { phase: "Sign" }); - } - const pipeline = new Pipeline([]); - pipeline._credential = credential; - pipeline._corePipeline = corePipeline; - return pipeline; + }); } - appendSubRequestToBody(request) { - this.body += [ - this.subRequestPrefix, - // sub request constant prefix - `${HeaderConstants.CONTENT_ID}: ${this.operationCount}`, - // sub request's content ID - "", - // empty line after sub request's content ID - `${request.method.toString()} ${getURLPathAndQuery(request.url)} ${HTTP_VERSION_1_1}${HTTP_LINE_ENDING}` - // sub request start line with method - ].join(HTTP_LINE_ENDING); - for (const [name, value] of request.headers) { - this.body += `${name}: ${value}${HTTP_LINE_ENDING}`; + /** + * Returns an async iterable iterator to list all the blobs by hierarchy. + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. + * + * Example using `for await` syntax: + * + * ```js + * for await (const item of containerClient.listBlobsByHierarchy("/")) { + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}`); + * } + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); + * let entity = await iter.next(); + * while (!entity.done) { + * let item = entity.value; + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}`); + * } + * entity = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * console.log("Listing blobs by hierarchy by page"); + * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { + * const segment = response.segment; + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}`); + * } + * } + * ``` + * + * Example using paging with a max page size: + * + * ```js + * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); + * + * let i = 1; + * for await (const response of containerClient + * .listBlobsByHierarchy("/", { prefix: "prefix2/sub1/" }) + * .byPage({ maxPageSize: 2 })) { + * console.log(`Page ${i++}`); + * const segment = response.segment; + * + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}`); + * } + * } + * ``` + * + * @param delimiter - The character or string used to define the virtual hierarchy + * @param options - Options to list blobs operation. + */ + listBlobsByHierarchy(delimiter2, options = {}) { + if (delimiter2 === "") { + throw new RangeError("delimiter should contain one or more characters"); } - this.body += HTTP_LINE_ENDING; - } - preAddSubRequest(subRequest) { - if (this.operationCount >= BATCH_MAX_REQUEST) { - throw new RangeError(`Cannot exceed ${BATCH_MAX_REQUEST} sub requests in a single batch`); + const include2 = []; + if (options.includeCopy) { + include2.push("copy"); } - const path15 = getURLPath(subRequest.url); - if (!path15 || path15 === "") { - throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); + if (options.includeDeleted) { + include2.push("deleted"); } - } - postAddSubRequest(subRequest) { - this.subRequests.set(this.operationCount, subRequest); - this.operationCount++; - } - // Return the http request body with assembling the ending line to the sub request body. - getHttpRequestBody() { - return `${this.body}${this.batchRequestEnding}${HTTP_LINE_ENDING}`; - } - getMultipartContentType() { - return this.multipartContentType; - } - getSubRequests() { - return this.subRequests; - } - }; - function batchRequestAssemblePolicy(batchRequest) { - return { - name: "batchRequestAssemblePolicy", - async sendRequest(request) { - batchRequest.appendSubRequestToBody(request); - return { - request, - status: 200, - headers: coreRestPipeline.createHttpHeaders() - }; + if (options.includeMetadata) { + include2.push("metadata"); } - }; - } - function batchHeaderFilterPolicy() { - return { - name: "batchHeaderFilterPolicy", - async sendRequest(request, next) { - let xMsHeaderName = ""; - for (const [name] of request.headers) { - if (iEqual(name, HeaderConstants.X_MS_VERSION)) { - xMsHeaderName = name; - } - } - if (xMsHeaderName !== "") { - request.headers.delete(xMsHeaderName); - } - return next(request); + if (options.includeSnapshots) { + include2.push("snapshots"); + } + if (options.includeVersions) { + include2.push("versions"); + } + if (options.includeUncommitedBlobs) { + include2.push("uncommittedblobs"); } - }; - } - var BlobBatchClient = class { - constructor(url3, credentialOrPipeline, options) { - let pipeline; - if (isPipelineLike(credentialOrPipeline)) { - pipeline = credentialOrPipeline; - } else if (!credentialOrPipeline) { - pipeline = newPipeline(new AnonymousCredential(), options); - } else { - pipeline = newPipeline(credentialOrPipeline, options); + if (options.includeTags) { + include2.push("tags"); } - const storageClientContext = new StorageContextClient(url3, getCoreClientOptions(pipeline)); - const path15 = getURLPath(url3); - if (path15 && path15 !== "/") { - this.serviceOrContainerContext = storageClientContext.container; - } else { - this.serviceOrContainerContext = storageClientContext.service; + if (options.includeDeletedWithVersions) { + include2.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include2.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include2.push("legalhold"); + } + if (options.prefix === "") { + options.prefix = void 0; } + const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); + const iter = this.listItemsByHierarchy(delimiter2, updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + async next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listHierarchySegments(delimiter2, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; } /** - * Creates a {@link BlobBatch}. - * A BlobBatch represents an aggregated set of operations on blobs. + * The Filter Blobs operation enables callers to list blobs in the container whose tags + * match a given search expression. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to find blobs by tags. */ - createBatch() { - return new BlobBatch(); + async findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options = {}) { + return tracingClient.withSpan("ContainerClient-findBlobsByTagsSegment", options, async (updatedOptions) => { + const response = assertResponse(await this.containerContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker: marker2, + maxPageSize: options.maxPageSize, + tracingOptions: updatedOptions.tracingOptions + })); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { + var _a; + let tagValue = ""; + if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); + }) }); + return wrappedResponse; + }); } - async deleteBlobs(urlsOrBlobClients, credentialOrOptions, options) { - const batch = new BlobBatch(); - for (const urlOrBlobClient of urlsOrBlobClients) { - if (typeof urlOrBlobClient === "string") { - await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); - } else { - await batch.deleteBlob(urlOrBlobClient, credentialOrOptions); + /** + * Returns an AsyncIterableIterator for ContainerFindBlobsByTagsSegmentResponse. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param marker - A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to find blobs by tags. + */ + findBlobsByTagsSegments(tagFilterSqlExpression_1, marker_1) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1(tagFilterSqlExpression, marker2, options = {}) { + let response; + if (!!marker2 || marker2 === void 0) { + do { + response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options)); + response.blobs = response.blobs || []; + marker2 = response.continuationToken; + yield yield tslib.__await(response); + } while (marker2); } - } - return this.submitBatch(batch); + }); } - async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { - const batch = new BlobBatch(); - for (const urlOrBlobClient of urlsOrBlobClients) { - if (typeof urlOrBlobClient === "string") { - await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); - } else { - await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); + /** + * Returns an AsyncIterableIterator for blobs. + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param options - Options to findBlobsByTagsItems. + */ + findBlobsByTagsItems(tagFilterSqlExpression_1) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { + var _a, e_3, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const segment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_3) throw e_3.error; + } } - } - return this.submitBatch(batch); + }); } /** - * Submit batch request which consists of multiple subrequests. + * Returns an async iterable iterator to find all blobs with specified tag + * under the specified container. * - * Get `blobBatchClient` and other details before running the snippets. - * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` + * .byPage() returns an async iterable iterator to list the blobs in pages. * - * Example usage: + * Example using `for await` syntax: * * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.deleteBlob(urlInString0, credential0); - * await batchRequest.deleteBlob(urlInString1, credential1, { - * deleteSnapshots: "include" - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); + * let i = 1; + * for await (const blob of containerClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } * ``` * - * Example using a lease: + * Example using `iter.next()`: * * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); - * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { - * conditions: { leaseId: leaseId } - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); + * let i = 1; + * const iter = containerClient.findBlobsByTags("tagkey='tagvalue'"); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } * ``` * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * Example using `byPage()`: * - * @param batchRequest - A set of Delete or SetTier operations. - * @param options - + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = containerClient + * .findBlobsByTags("tagkey='tagvalue'") + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param options - Options to find blobs by tags. */ - async submitBatch(batchRequest, options = {}) { - if (!batchRequest || batchRequest.getSubRequests().size === 0) { - throw new RangeError("Batch request should contain one or more sub requests."); - } - return tracingClient.withSpan("BlobBatchClient-submitBatch", options, async (updatedOptions) => { - const batchRequestBody = batchRequest.getHttpRequestBody(); - const rawBatchResponse = assertResponse(await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, Object.assign({}, updatedOptions))); - const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); - const responseSummary = await batchResponseParser.parseBatchResponse(); - const res = { - _response: rawBatchResponse._response, - contentType: rawBatchResponse.contentType, - errorCode: rawBatchResponse.errorCode, - requestId: rawBatchResponse.requestId, - clientRequestId: rawBatchResponse.clientRequestId, - version: rawBatchResponse.version, - subResponses: responseSummary.subResponses, - subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, - subResponsesFailedCount: responseSummary.subResponsesFailedCount - }; - return res; - }); + findBlobsByTags(tagFilterSqlExpression, options = {}) { + const listSegmentOptions = Object.assign({}, options); + const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; } - }; - var ContainerClient = class extends StorageClient { /** - * The name of the container. + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * + * @param options - Options to the Service Get Account Info operation. + * @returns Response data for the Service Get Account Info operation. */ - get containerName() { - return this._containerName; + async getAccountInfo(options = {}) { + return tracingClient.withSpan("ContainerClient-getAccountInfo", options, async (updatedOptions) => { + return assertResponse(await this.containerContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); } - constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { - let pipeline; - let url3; - options = options || {}; - if (isPipelineLike(credentialOrPipelineOrContainerName)) { - url3 = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } else if (coreUtil.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipelineOrContainerName)) { - url3 = urlOrConnectionString; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { - url3 = urlOrConnectionString; - pipeline = newPipeline(new AnonymousCredential(), options); - } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { - const containerName = credentialOrPipelineOrContainerName; - const extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - if (coreUtil.isNode) { - const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url3 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); - if (!options.proxyOptions) { - options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); - } - pipeline = newPipeline(sharedKeyCredential, options); - } else { - throw new Error("Account connection string is only supported in Node.js environment"); - } - } else if (extractedCreds.kind === "SASConnString") { - url3 = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + "?" + extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); + getContainerNameFromUrl() { + let containerName; + try { + const parsedUrl = new URL(this.url); + if (parsedUrl.hostname.split(".")[1] === "blob") { + containerName = parsedUrl.pathname.split("/")[1]; + } else if (isIpEndpointStyle(parsedUrl)) { + containerName = parsedUrl.pathname.split("/")[2]; } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + containerName = parsedUrl.pathname.split("/")[1]; } - } else { - throw new Error("Expecting non-empty strings for containerName parameter"); + containerName = decodeURIComponent(containerName); + if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return containerName; + } catch (error4) { + throw new Error("Unable to extract containerName with provided information."); } - super(url3, pipeline); - this._containerName = this.getContainerNameFromUrl(); - this.containerContext = this.storageClientContext.container; } /** - * Creates a new container under the specified account. If the container with - * the same name already exists, the operation fails. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container - * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata - * - * @param options - Options to Container Create operation. + * Only available for ContainerClient constructed with a shared key credential. * + * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. * - * Example usage: + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * const createContainerResponse = await containerClient.create(); - * console.log("Container was created successfully", createContainerResponse.requestId); - * ``` + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - async create(options = {}) { - return tracingClient.withSpan("ContainerClient-create", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.create(updatedOptions)); + generateSasUrl(options) { + return new Promise((resolve8) => { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); + resolve8(appendToURLQuery(this.url, sas)); }); } /** - * Creates a new container under the specified account. If the container with - * the same name already exists, it is not changed. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container - * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata + * Only available for ContainerClient constructed with a shared key credential. * - * @param options - + * Generates string to sign for a Blob Container Service Shared Access Signature (SAS) URI + * based on the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - async createIfNotExists(options = {}) { - return tracingClient.withSpan("ContainerClient-createIfNotExists", options, async (updatedOptions) => { - var _a, _b; - try { - const res = await this.create(updatedOptions); - return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); - } catch (e) { - if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { - return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); - } else { - throw e; - } - } - }); + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + generateSasStringToSign(options) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName }, options), this.credential).stringToSign; } /** - * Returns true if the Azure container resource represented by this client exists; false otherwise. + * Creates a BlobBatchClient object to conduct batch operations. * - * NOTE: use this function with care since an existing container might be deleted by other clients or - * applications. Vice versa new containers with the same name might be added by other clients or - * applications after this function completes. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * - * @param options - + * @returns A new BlobBatchClient object for this container. */ - async exists(options = {}) { - return tracingClient.withSpan("ContainerClient-exists", options, async (updatedOptions) => { - try { - await this.getProperties({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - }); - return true; - } catch (e) { - if (e.statusCode === 404) { - return false; - } - throw e; + getBlobBatchClient() { + return new BlobBatchClient(this.url, this.pipeline); + } + }; + var AccountSASPermissions = class _AccountSASPermissions { + constructor() { + this.read = false; + this.write = false; + this.delete = false; + this.deleteVersion = false; + this.list = false; + this.add = false; + this.create = false; + this.update = false; + this.process = false; + this.tag = false; + this.filter = false; + this.setImmutabilityPolicy = false; + this.permanentDelete = false; + } + /** + * Parse initializes the AccountSASPermissions fields from a string. + * + * @param permissions - + */ + static parse(permissions) { + const accountSASPermissions = new _AccountSASPermissions(); + for (const c of permissions) { + switch (c) { + case "r": + accountSASPermissions.read = true; + break; + case "w": + accountSASPermissions.write = true; + break; + case "d": + accountSASPermissions.delete = true; + break; + case "x": + accountSASPermissions.deleteVersion = true; + break; + case "l": + accountSASPermissions.list = true; + break; + case "a": + accountSASPermissions.add = true; + break; + case "c": + accountSASPermissions.create = true; + break; + case "u": + accountSASPermissions.update = true; + break; + case "p": + accountSASPermissions.process = true; + break; + case "t": + accountSASPermissions.tag = true; + break; + case "f": + accountSASPermissions.filter = true; + break; + case "i": + accountSASPermissions.setImmutabilityPolicy = true; + break; + case "y": + accountSASPermissions.permanentDelete = true; + break; + default: + throw new RangeError(`Invalid permission character: ${c}`); } - }); - } - /** - * Creates a {@link BlobClient} - * - * @param blobName - A blob name - * @returns A new BlobClient object for the given blob name. - */ - getBlobClient(blobName) { - return new BlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + } + return accountSASPermissions; } /** - * Creates an {@link AppendBlobClient} + * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it + * and boolean values for them. * - * @param blobName - An append blob name + * @param permissionLike - */ - getAppendBlobClient(blobName) { - return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + static from(permissionLike) { + const accountSASPermissions = new _AccountSASPermissions(); + if (permissionLike.read) { + accountSASPermissions.read = true; + } + if (permissionLike.write) { + accountSASPermissions.write = true; + } + if (permissionLike.delete) { + accountSASPermissions.delete = true; + } + if (permissionLike.deleteVersion) { + accountSASPermissions.deleteVersion = true; + } + if (permissionLike.filter) { + accountSASPermissions.filter = true; + } + if (permissionLike.tag) { + accountSASPermissions.tag = true; + } + if (permissionLike.list) { + accountSASPermissions.list = true; + } + if (permissionLike.add) { + accountSASPermissions.add = true; + } + if (permissionLike.create) { + accountSASPermissions.create = true; + } + if (permissionLike.update) { + accountSASPermissions.update = true; + } + if (permissionLike.process) { + accountSASPermissions.process = true; + } + if (permissionLike.setImmutabilityPolicy) { + accountSASPermissions.setImmutabilityPolicy = true; + } + if (permissionLike.permanentDelete) { + accountSASPermissions.permanentDelete = true; + } + return accountSASPermissions; } /** - * Creates a {@link BlockBlobClient} - * - * @param blobName - A block blob name - * + * Produces the SAS permissions string for an Azure Storage account. + * Call this method to set AccountSASSignatureValues Permissions field. * - * Example usage: + * Using this method will guarantee the resource types are in + * an order accepted by the service. * - * ```js - * const content = "Hello world!"; + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * - * const blockBlobClient = containerClient.getBlockBlobClient(""); - * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); - * ``` */ - getBlockBlobClient(blobName) { - return new BlockBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + toString() { + const permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.filter) { + permissions.push("f"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.list) { + permissions.push("l"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.update) { + permissions.push("u"); + } + if (this.process) { + permissions.push("p"); + } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } + if (this.permanentDelete) { + permissions.push("y"); + } + return permissions.join(""); } - /** - * Creates a {@link PageBlobClient} - * - * @param blobName - A page blob name - */ - getPageBlobClient(blobName) { - return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); + }; + var AccountSASResourceTypes = class _AccountSASResourceTypes { + constructor() { + this.service = false; + this.container = false; + this.object = false; } /** - * Returns all user-defined metadata and system properties for the specified - * container. The data returned does not include the container's list of blobs. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties - * - * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if - * they originally contained uppercase characters. This differs from the metadata keys returned by - * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which - * will retain their original casing. + * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an + * Error if it encounters a character that does not correspond to a valid resource type. * - * @param options - Options to Container Get Properties operation. + * @param resourceTypes - */ - async getProperties(options = {}) { - if (!options.conditions) { - options.conditions = {}; + static parse(resourceTypes) { + const accountSASResourceTypes = new _AccountSASResourceTypes(); + for (const c of resourceTypes) { + switch (c) { + case "s": + accountSASResourceTypes.service = true; + break; + case "c": + accountSASResourceTypes.container = true; + break; + case "o": + accountSASResourceTypes.object = true; + break; + default: + throw new RangeError(`Invalid resource type: ${c}`); + } } - return tracingClient.withSpan("ContainerClient-getProperties", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), { tracingOptions: updatedOptions.tracingOptions }))); - }); + return accountSASResourceTypes; } /** - * Marks the specified container for deletion. The container and any blobs - * contained within it are later deleted during garbage collection. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * Converts the given resource types to a string. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * - * @param options - Options to Container Delete operation. */ - async delete(options = {}) { - if (!options.conditions) { - options.conditions = {}; + toString() { + const resourceTypes = []; + if (this.service) { + resourceTypes.push("s"); } - return tracingClient.withSpan("ContainerClient-delete", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.delete({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); + if (this.container) { + resourceTypes.push("c"); + } + if (this.object) { + resourceTypes.push("o"); + } + return resourceTypes.join(""); + } + }; + var AccountSASServices = class _AccountSASServices { + constructor() { + this.blob = false; + this.file = false; + this.queue = false; + this.table = false; } /** - * Marks the specified container for deletion if it exists. The container and any blobs - * contained within it are later deleted during garbage collection. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * Creates an {@link AccountSASServices} from the specified services string. This method will throw an + * Error if it encounters a character that does not correspond to a valid service. * - * @param options - Options to Container Delete operation. + * @param services - */ - async deleteIfExists(options = {}) { - return tracingClient.withSpan("ContainerClient-deleteIfExists", options, async (updatedOptions) => { - var _a, _b; - try { - const res = await this.delete(updatedOptions); - return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); - } catch (e) { - if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { - return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); - } - throw e; + static parse(services) { + const accountSASServices = new _AccountSASServices(); + for (const c of services) { + switch (c) { + case "b": + accountSASServices.blob = true; + break; + case "f": + accountSASServices.file = true; + break; + case "q": + accountSASServices.queue = true; + break; + case "t": + accountSASServices.table = true; + break; + default: + throw new RangeError(`Invalid service character: ${c}`); } - }); + } + return accountSASServices; } /** - * Sets one or more user-defined name-value pairs for the specified container. - * - * If no option provided, or no metadata defined in the parameter, the container - * metadata will be removed. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * Converts the given services to a string. * - * @param metadata - Replace existing metadata with this value. - * If no value provided the existing metadata will be removed. - * @param options - Options to Container Set Metadata operation. */ - async setMetadata(metadata2, options = {}) { - if (!options.conditions) { - options.conditions = {}; + toString() { + const services = []; + if (this.blob) { + services.push("b"); } - if (options.conditions.ifUnmodifiedSince) { - throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + if (this.table) { + services.push("t"); } - return tracingClient.withSpan("ContainerClient-setMetadata", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.setMetadata({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - metadata: metadata2, - modifiedAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); - } - /** - * Gets the permissions for the specified container. The permissions indicate - * whether container data may be accessed publicly. - * - * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. - * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl - * - * @param options - Options to Container Get Access Policy operation. - */ - async getAccessPolicy(options = {}) { - if (!options.conditions) { - options.conditions = {}; + if (this.queue) { + services.push("q"); } - return tracingClient.withSpan("ContainerClient-getAccessPolicy", options, async (updatedOptions) => { - const response = assertResponse(await this.containerContext.getAccessPolicy({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - const res = { - _response: response._response, - blobPublicAccess: response.blobPublicAccess, - date: response.date, - etag: response.etag, - errorCode: response.errorCode, - lastModified: response.lastModified, - requestId: response.requestId, - clientRequestId: response.clientRequestId, - signedIdentifiers: [], - version: response.version - }; - for (const identifier of response) { - let accessPolicy = void 0; - if (identifier.accessPolicy) { - accessPolicy = { - permissions: identifier.accessPolicy.permissions - }; - if (identifier.accessPolicy.expiresOn) { - accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); - } - if (identifier.accessPolicy.startsOn) { - accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); - } - } - res.signedIdentifiers.push({ - accessPolicy, - id: identifier.id - }); - } - return res; - }); + if (this.file) { + services.push("f"); + } + return services.join(""); } - /** - * Sets the permissions for the specified container. The permissions indicate - * whether blobs in a container may be accessed publicly. - * - * When you set permissions for a container, the existing permissions are replaced. - * If no access or containerAcl provided, the existing container ACL will be - * removed. - * - * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. - * During this interval, a shared access signature that is associated with the stored access policy will - * fail with status code 403 (Forbidden), until the access policy becomes active. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl - * - * @param access - The level of public access to data in the container. - * @param containerAcl - Array of elements each having a unique Id and details of the access policy. - * @param options - Options to Container Set Access Policy operation. - */ - async setAccessPolicy(access2, containerAcl2, options = {}) { - options.conditions = options.conditions || {}; - return tracingClient.withSpan("ContainerClient-setAccessPolicy", options, async (updatedOptions) => { - const acl = []; - for (const identifier of containerAcl2 || []) { - acl.push({ - accessPolicy: { - expiresOn: identifier.accessPolicy.expiresOn ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) : "", - permissions: identifier.accessPolicy.permissions, - startsOn: identifier.accessPolicy.startsOn ? truncatedISO8061Date(identifier.accessPolicy.startsOn) : "" - }, - id: identifier.id - }); - } - return assertResponse(await this.containerContext.setAccessPolicy({ - abortSignal: options.abortSignal, - access: access2, - containerAcl: acl, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: options.conditions, - tracingOptions: updatedOptions.tracingOptions - })); - }); + }; + function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + return generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential).sasQueryParameters; + } + function generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) { + const version2 = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.setImmutabilityPolicy && version2 < "2020-08-04") { + throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); } - /** - * Get a {@link BlobLeaseClient} that manages leases on the container. - * - * @param proposeLeaseId - Initial proposed lease Id. - * @returns A new BlobLeaseClient object for managing leases on the container. - */ - getBlobLeaseClient(proposeLeaseId) { - return new BlobLeaseClient(this, proposeLeaseId); + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.deleteVersion && version2 < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.permanentDelete && version2 < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'y' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.tag && version2 < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.filter && version2 < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); + } + if (accountSASSignatureValues.encryptionScope && version2 < "2020-12-06") { + throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); + } + const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + let stringToSign; + if (version2 >= "2020-12-06") { + stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version2, + accountSASSignatureValues.encryptionScope ? accountSASSignatureValues.encryptionScope : "", + "" + // Account SAS requires an additional newline character + ].join("\n"); + } else { + stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version2, + "" + // Account SAS requires an additional newline character + ].join("\n"); } + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(version2, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, accountSASSignatureValues.encryptionScope), + stringToSign + }; + } + var BlobServiceClient = class _BlobServiceClient extends StorageClient { /** - * Creates a new block blob, or updates the content of an existing block blob. - * - * Updating an existing block blob overwrites any existing metadata on the blob. - * Partial updates are not supported; the content of the existing blob is - * overwritten with the new content. To perform a partial update of a block blob's, - * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. - * - * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, - * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better - * performance with concurrency uploading. * - * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * Creates an instance of BlobServiceClient from connection string. * - * @param blobName - Name of the block blob to create or update. - * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function - * which returns a new Readable stream whose offset is from data source beginning. - * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a - * string including non non-Base64/Hex-encoded characters. - * @param options - Options to configure the Block Blob Upload operation. - * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. + * @param connectionString - Account connection string or a SAS connection string of an Azure storage account. + * [ Note - Account connection string can only be used in NODE.JS runtime. ] + * Account connection string example - + * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` + * SAS connection string example - + * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` + * @param options - Optional. Options to configure the HTTP pipeline. */ - async uploadBlockBlob(blobName, body2, contentLength2, options = {}) { - return tracingClient.withSpan("ContainerClient-uploadBlockBlob", options, async (updatedOptions) => { - const blockBlobClient = this.getBlockBlobClient(blobName); - const response = await blockBlobClient.upload(body2, contentLength2, updatedOptions); - return { - blockBlobClient, - response - }; - }); + static fromConnectionString(connectionString, options) { + options = options || {}; + const extractedCreds = extractConnectionStringParts(connectionString); + if (extractedCreds.kind === "AccountConnString") { + if (coreUtil.isNode) { + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + if (!options.proxyOptions) { + options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); + } + const pipeline = newPipeline(sharedKeyCredential, options); + return new _BlobServiceClient(extractedCreds.url, pipeline); + } else { + throw new Error("Account connection string is only supported in Node.js environment"); + } + } else if (extractedCreds.kind === "SASConnString") { + const pipeline = newPipeline(new AnonymousCredential(), options); + return new _BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + } else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + constructor(url3, credentialOrPipeline, options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { + pipeline = credentialOrPipeline; + } else if (coreUtil.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential || credentialOrPipeline instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipeline)) { + pipeline = newPipeline(credentialOrPipeline, options); + } else { + pipeline = newPipeline(new AnonymousCredential(), options); + } + super(url3, pipeline); + this.serviceContext = this.storageClientContext.service; } /** - * Marks the specified blob or snapshot for deletion. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * Creates a {@link ContainerClient} object * - * @param blobName - - * @param options - Options to Blob Delete operation. - * @returns Block blob deletion response data. + * @param containerName - A container name + * @returns A new ContainerClient object for the given container name. + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * ``` */ - async deleteBlob(blobName, options = {}) { - return tracingClient.withSpan("ContainerClient-deleteBlob", options, async (updatedOptions) => { - let blobClient = this.getBlobClient(blobName); - if (options.versionId) { - blobClient = blobClient.withVersion(options.versionId); - } - return blobClient.delete(updatedOptions); - }); + getContainerClient(containerName) { + return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); } /** - * listBlobFlatSegment returns a single segment of blobs starting from the - * specified Marker. Use an empty Marker to start enumeration from the beginning. - * After getting a segment, process it, and then call listBlobsFlatSegment again - * (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * Create a Blob container. @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container * - * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. - * @param options - Options to Container List Blob Flat Segment operation. + * @param containerName - Name of the container to create. + * @param options - Options to configure Container Create operation. + * @returns Container creation response and the corresponding container client. */ - async listBlobFlatSegment(marker2, options = {}) { - return tracingClient.withSpan("ContainerClient-listBlobFlatSegment", options, async (updatedOptions) => { - const response = assertResponse(await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); - const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobFlat(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { - const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return wrappedResponse; + async createContainer(containerName, options = {}) { + return tracingClient.withSpan("BlobServiceClient-createContainer", options, async (updatedOptions) => { + const containerClient = this.getContainerClient(containerName); + const containerCreateResponse = await containerClient.create(updatedOptions); + return { + containerClient, + containerCreateResponse + }; }); } /** - * listBlobHierarchySegment returns a single segment of blobs starting from - * the specified Marker. Use an empty Marker to start enumeration from the - * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment - * again (passing the the previously-returned Marker) to get the next segment. - * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * Deletes a Blob container. * - * @param delimiter - The character or string used to define the virtual hierarchy - * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. - * @param options - Options to Container List Blob Hierarchy Segment operation. + * @param containerName - Name of the container to delete. + * @param options - Options to configure Container Delete operation. + * @returns Container deletion response. */ - async listBlobHierarchySegment(delimiter2, marker2, options = {}) { - return tracingClient.withSpan("ContainerClient-listBlobHierarchySegment", options, async (updatedOptions) => { - var _a; - const response = assertResponse(await this.containerContext.listBlobHierarchySegment(delimiter2, Object.assign(Object.assign({ marker: marker2 }, options), { tracingOptions: updatedOptions.tracingOptions }))); - const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobHierarchy(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInternal) => { - const blobItem = Object.assign(Object.assign({}, blobItemInternal), { name: BlobNameToString(blobItemInternal.name), tags: toTags(blobItemInternal.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInternal.objectReplicationMetadata) }); - return blobItem; - }), blobPrefixes: (_a = response.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { - const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); - return blobPrefix; - }) }) }); - return wrappedResponse; + async deleteContainer(containerName, options = {}) { + return tracingClient.withSpan("BlobServiceClient-deleteContainer", options, async (updatedOptions) => { + const containerClient = this.getContainerClient(containerName); + return containerClient.delete(updatedOptions); }); } /** - * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * Restore a previously deleted Blob container. + * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. * - * @param marker - A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the ContinuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to list blobs operation. + * @param deletedContainerName - Name of the previously deleted container. + * @param deletedContainerVersion - Version of the previously deleted container, used to uniquely identify the deleted container. + * @param options - Options to configure Container Restore operation. + * @returns Container deletion response. */ - listSegments(marker_1) { - return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { - let listBlobsFlatSegmentResponse; - if (!!marker2 || marker2 === void 0) { - do { - listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker2, options)); - marker2 = listBlobsFlatSegmentResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); - } while (marker2); - } + async undeleteContainer(deletedContainerName2, deletedContainerVersion2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-undeleteContainer", options, async (updatedOptions) => { + const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName2); + const containerContext = containerClient["storageClientContext"].container; + const containerUndeleteResponse = assertResponse(await containerContext.restore({ + deletedContainerName: deletedContainerName2, + deletedContainerVersion: deletedContainerVersion2, + tracingOptions: updatedOptions.tracingOptions + })); + return { containerClient, containerUndeleteResponse }; }); } /** - * Returns an AsyncIterableIterator of {@link BlobItem} objects + * Rename an existing Blob Container. * - * @param options - Options to list blobs operation. + * @param sourceContainerName - The name of the source container. + * @param destinationContainerName - The new name of the container. + * @param options - Options to configure Container Rename operation. */ - listItems() { - return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { - var _a, e_1, _b, _c; - let marker2; - try { - for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const listBlobsFlatSegmentResponse = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_1) throw e_1.error; - } - } + /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ + // @ts-ignore Need to hide this interface for now. Make it public and turn on the live tests for it when the service is ready. + async renameContainer(sourceContainerName2, destinationContainerName, options = {}) { + return tracingClient.withSpan("BlobServiceClient-renameContainer", options, async (updatedOptions) => { + var _a; + const containerClient = this.getContainerClient(destinationContainerName); + const containerContext = containerClient["storageClientContext"].container; + const containerRenameResponse = assertResponse(await containerContext.rename(sourceContainerName2, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId }))); + return { containerClient, containerRenameResponse }; }); } /** - * Returns an async iterable iterator to list all the blobs - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * Example using `for await` syntax: - * - * ```js - * // Get the containerClient before you run these snippets, - * // Can be obtained from `blobServiceClient.getContainerClient("");` - * let i = 1; - * for await (const blob of containerClient.listBlobsFlat()) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * let iter = containerClient.listBlobsFlat(); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * - * // Passing next marker as continuationToken - * - * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints 10 blob names - * for (const blob of response.segment.blobItems) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * ``` + * Gets the properties of a storage account’s Blob service, including properties + * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties * - * @param options - Options to list blobs. - * @returns An asyncIterableIterator that supports paging. + * @param options - Options to the Service Get Properties operation. + * @returns Response data for the Service Get Properties operation. */ - listBlobsFlat(options = {}) { - const include2 = []; - if (options.includeCopy) { - include2.push("copy"); - } - if (options.includeDeleted) { - include2.push("deleted"); - } - if (options.includeMetadata) { - include2.push("metadata"); - } - if (options.includeSnapshots) { - include2.push("snapshots"); - } - if (options.includeVersions) { - include2.push("versions"); - } - if (options.includeUncommitedBlobs) { - include2.push("uncommittedblobs"); - } - if (options.includeTags) { - include2.push("tags"); - } - if (options.includeDeletedWithVersions) { - include2.push("deletedwithversions"); - } - if (options.includeImmutabilityPolicy) { - include2.push("immutabilitypolicy"); - } - if (options.includeLegalHold) { - include2.push("legalhold"); - } - if (options.prefix === "") { - options.prefix = void 0; - } - const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); - const iter = this.listItems(updatedOptions); - return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - } - }; + async getProperties(options = {}) { + return tracingClient.withSpan("BlobServiceClient-getProperties", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); } /** - * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * Sets properties for a storage account’s Blob service endpoint, including properties + * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties * - * @param delimiter - The character or string used to define the virtual hierarchy - * @param marker - A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the ContinuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The ContinuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to list blobs operation. + * @param properties - + * @param options - Options to the Service Set Properties operation. + * @returns Response data for the Service Set Properties operation. */ - listHierarchySegments(delimiter_1, marker_1) { - return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1(delimiter2, marker2, options = {}) { - let listBlobsHierarchySegmentResponse; - if (!!marker2 || marker2 === void 0) { - do { - listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter2, marker2, options)); - marker2 = listBlobsHierarchySegmentResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); - } while (marker2); - } + async setProperties(properties, options = {}) { + return tracingClient.withSpan("BlobServiceClient-setProperties", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.setProperties(properties, { + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); }); } /** - * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * Retrieves statistics related to replication for the Blob service. It is only + * available on the secondary location endpoint when read-access geo-redundant + * replication is enabled for the storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats * - * @param delimiter - The character or string used to define the virtual hierarchy - * @param options - Options to list blobs operation. + * @param options - Options to the Service Get Statistics operation. + * @returns Response data for the Service Get Statistics operation. */ - listItemsByHierarchy(delimiter_1) { - return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1(delimiter2, options = {}) { - var _a, e_2, _b, _c; - let marker2; - try { - for (var _d = true, _e = tslib.__asyncValues(this.listHierarchySegments(delimiter2, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const listBlobsHierarchySegmentResponse = _c; - const segment = listBlobsHierarchySegmentResponse.segment; - if (segment.blobPrefixes) { - for (const prefix2 of segment.blobPrefixes) { - yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix2)); - } - } - for (const blob of segment.blobItems) { - yield yield tslib.__await(Object.assign({ kind: "blob" }, blob)); - } - } - } catch (e_2_1) { - e_2 = { error: e_2_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_2) throw e_2.error; - } - } + async getStatistics(options = {}) { + return tracingClient.withSpan("BlobServiceClient-getStatistics", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.getStatistics({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); }); } /** - * Returns an async iterable iterator to list all the blobs by hierarchy. - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. - * - * Example using `for await` syntax: - * - * ```js - * for await (const item of containerClient.listBlobsByHierarchy("/")) { - * if (item.kind === "prefix") { - * console.log(`\tBlobPrefix: ${item.name}`); - * } else { - * console.log(`\tBlobItem: name - ${item.name}`); - * } - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); - * let entity = await iter.next(); - * while (!entity.done) { - * let item = entity.value; - * if (item.kind === "prefix") { - * console.log(`\tBlobPrefix: ${item.name}`); - * } else { - * console.log(`\tBlobItem: name - ${item.name}`); - * } - * entity = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * console.log("Listing blobs by hierarchy by page"); - * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { - * const segment = response.segment; - * if (segment.blobPrefixes) { - * for (const prefix of segment.blobPrefixes) { - * console.log(`\tBlobPrefix: ${prefix.name}`); - * } - * } - * for (const blob of response.segment.blobItems) { - * console.log(`\tBlobItem: name - ${blob.name}`); - * } - * } - * ``` - * - * Example using paging with a max page size: - * - * ```js - * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); - * - * let i = 1; - * for await (const response of containerClient - * .listBlobsByHierarchy("/", { prefix: "prefix2/sub1/" }) - * .byPage({ maxPageSize: 2 })) { - * console.log(`Page ${i++}`); - * const segment = response.segment; - * - * if (segment.blobPrefixes) { - * for (const prefix of segment.blobPrefixes) { - * console.log(`\tBlobPrefix: ${prefix.name}`); - * } - * } - * - * for (const blob of response.segment.blobItems) { - * console.log(`\tBlobItem: name - ${blob.name}`); - * } - * } - * ``` + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information * - * @param delimiter - The character or string used to define the virtual hierarchy - * @param options - Options to list blobs operation. - */ - listBlobsByHierarchy(delimiter2, options = {}) { - if (delimiter2 === "") { - throw new RangeError("delimiter should contain one or more characters"); - } - const include2 = []; - if (options.includeCopy) { - include2.push("copy"); - } - if (options.includeDeleted) { - include2.push("deleted"); - } - if (options.includeMetadata) { - include2.push("metadata"); - } - if (options.includeSnapshots) { - include2.push("snapshots"); - } - if (options.includeVersions) { - include2.push("versions"); - } - if (options.includeUncommitedBlobs) { - include2.push("uncommittedblobs"); - } - if (options.includeTags) { - include2.push("tags"); - } - if (options.includeDeletedWithVersions) { - include2.push("deletedwithversions"); - } - if (options.includeImmutabilityPolicy) { - include2.push("immutabilitypolicy"); - } - if (options.includeLegalHold) { - include2.push("legalhold"); - } - if (options.prefix === "") { - options.prefix = void 0; - } - const updatedOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); - const iter = this.listItemsByHierarchy(delimiter2, updatedOptions); - return { - /** - * The next method, part of the iteration protocol - */ - async next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listHierarchySegments(delimiter2, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - } - }; + * @param options - Options to the Service Get Account Info operation. + * @returns Response data for the Service Get Account Info operation. + */ + async getAccountInfo(options = {}) { + return tracingClient.withSpan("BlobServiceClient-getAccountInfo", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.getAccountInfo({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions + })); + }); } /** - * The Filter Blobs operation enables callers to list blobs in the container whose tags - * match a given search expression. + * Returns a list of the containers under the specified account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 + * + * @param marker - A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to the Service List Container Segment operation. + * @returns Response data for the Service List Container Segment operation. + */ + async listContainersSegment(marker2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-listContainersSegment", options, async (updatedOptions) => { + return assertResponse(await this.serviceContext.listContainersSegment(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker: marker2 }, options), { include: typeof options.include === "string" ? [options.include] : options.include, tracingOptions: updatedOptions.tracingOptions }))); + }); + } + /** + * The Filter Blobs operation enables callers to list blobs across all containers whose tags + * match a given search expression. Filter blobs searches across all containers within a + * storage account but can be scoped within the expression to a single container. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. @@ -66292,8 +68644,8 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * @param options - Options to find blobs by tags. */ async findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options = {}) { - return tracingClient.withSpan("ContainerClient-findBlobsByTagsSegment", options, async (updatedOptions) => { - const response = assertResponse(await this.containerContext.filterBlobs({ + return tracingClient.withSpan("BlobServiceClient-findBlobsByTagsSegment", options, async (updatedOptions) => { + const response = assertResponse(await this.serviceContext.filterBlobs({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker: marker2, @@ -66312,7 +68664,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; }); } /** - * Returns an AsyncIterableIterator for ContainerFindBlobsByTagsSegmentResponse. + * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. @@ -66351,7 +68703,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; */ findBlobsByTagsItems(tagFilterSqlExpression_1) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { - var _a, e_3, _b, _c; + var _a, e_1, _b, _c; let marker2; try { for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { @@ -66360,29 +68712,31 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; const segment = _c; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); } - } catch (e_3_1) { - e_3 = { error: e_3_1 }; + } catch (e_1_1) { + e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); } finally { - if (e_3) throw e_3.error; + if (e_1) throw e_1.error; } } }); } /** * Returns an async iterable iterator to find all blobs with specified tag - * under the specified container. + * under the specified account. * * .byPage() returns an async iterable iterator to list the blobs in pages. * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * * Example using `for await` syntax: * * ```js * let i = 1; - * for await (const blob of containerClient.findBlobsByTags("tagkey='tagvalue'")) { - * console.log(`Blob ${i++}: ${blob.name}`); + * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${container.name}`); * } * ``` * @@ -66390,7 +68744,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * * ```js * let i = 1; - * const iter = containerClient.findBlobsByTags("tagkey='tagvalue'"); + * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); * let blobItem = await iter.next(); * while (!blobItem.done) { * console.log(`Blob ${i++}: ${blobItem.value.name}`); @@ -66403,7 +68757,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * ```js * // passing optional maxPageSize in the page settings * let i = 1; - * for await (const response of containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); @@ -66416,7 +68770,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * * ```js * let i = 1; - * let iterator = containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 blob names @@ -66429,7 +68783,7 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; * // Gets next marker * let marker = response.continuationToken; * // Passing next marker as continuationToken - * iterator = containerClient + * iterator = blobServiceClient * .findBlobsByTags("tagkey='tagvalue'") * .byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; @@ -66473,5969 +68827,6548 @@ ${key}:${decodeURIComponent(lowercaseQueries[key])}`; }; } /** - * The Get Account Information operation returns the sku name and account kind - * for the specified account. - * The Get Account Information operation is available on service versions beginning - * with version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses * - * @param options - Options to the Service Get Account Info operation. - * @returns Response data for the Service Get Account Info operation. + * @param marker - A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the continuationToken value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The continuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param options - Options to list containers operation. */ - async getAccountInfo(options = {}) { - return tracingClient.withSpan("ContainerClient-getAccountInfo", options, async (updatedOptions) => { - return assertResponse(await this.containerContext.getAccountInfo({ + listSegments(marker_1) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { + let listContainersSegmentResponse; + if (!!marker2 || marker2 === void 0) { + do { + listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker2, options)); + listContainersSegmentResponse.containerItems = listContainersSegmentResponse.containerItems || []; + marker2 = listContainersSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); + } while (marker2); + } + }); + } + /** + * Returns an AsyncIterableIterator for Container Items + * + * @param options - Options to list containers operation. + */ + listItems() { + return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { + var _a, e_2, _b, _c; + let marker2; + try { + for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const segment = _c; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + } + /** + * Returns an async iterable iterator to list all the containers + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the containers in pages. + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const container of blobServiceClient.listContainers()) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.listContainers(); + * let containerItem = await iter.next(); + * while (!containerItem.done) { + * console.log(`Container ${i++}: ${containerItem.value.name}`); + * containerItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .listContainers() + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * ``` + * + * @param options - Options to list containers. + * @returns An asyncIterableIterator that supports paging. + */ + listContainers(options = {}) { + if (options.prefix === "") { + options.prefix = void 0; + } + const include2 = []; + if (options.includeDeleted) { + include2.push("deleted"); + } + if (options.includeMetadata) { + include2.push("metadata"); + } + if (options.includeSystem) { + include2.push("system"); + } + const listSegmentOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); + const iter = this.listItems(listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); + }, + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator]() { + return this; + }, + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; + } + /** + * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). + * + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * + * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time + * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time + */ + async getUserDelegationKey(startsOn, expiresOn2, options = {}) { + return tracingClient.withSpan("BlobServiceClient-getUserDelegationKey", options, async (updatedOptions) => { + const response = assertResponse(await this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn2, false) + }, { abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions })); + const userDelegationKey = { + signedObjectId: response.signedObjectId, + signedTenantId: response.signedTenantId, + signedStartsOn: new Date(response.signedStartsOn), + signedExpiresOn: new Date(response.signedExpiresOn), + signedService: response.signedService, + signedVersion: response.signedVersion, + value: response.value + }; + const res = Object.assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return res; }); } - getContainerNameFromUrl() { - let containerName; - try { - const parsedUrl = new URL(this.url); - if (parsedUrl.hostname.split(".")[1] === "blob") { - containerName = parsedUrl.pathname.split("/")[1]; - } else if (isIpEndpointStyle(parsedUrl)) { - containerName = parsedUrl.pathname.split("/")[2]; - } else { - containerName = parsedUrl.pathname.split("/")[1]; + /** + * Creates a BlobBatchClient object to conduct batch operations. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @returns A new BlobBatchClient object for this service. + */ + getBlobBatchClient() { + return new BlobBatchClient(this.url, this.pipeline); + } + /** + * Only available for BlobServiceClient constructed with a shared key credential. + * + * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties + * and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * + * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. + * @param permissions - Specifies the list of permissions to be associated with the SAS. + * @param resourceTypes - Specifies the resource types associated with the shared access signature. + * @param options - Optional parameters. + * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + generateAccountSasUrl(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + } + if (expiresOn2 === void 0) { + const now = /* @__PURE__ */ new Date(); + expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + } + const sas = generateAccountSASQueryParameters(Object.assign({ + permissions, + expiresOn: expiresOn2, + resourceTypes, + services: AccountSASServices.parse("b").toString() + }, options), this.credential).toString(); + return appendToURLQuery(this.url, sas); + } + /** + * Only available for BlobServiceClient constructed with a shared key credential. + * + * Generates string to sign for a Blob account Shared Access Signature (SAS) URI based on + * the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * + * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. + * @param permissions - Specifies the list of permissions to be associated with the SAS. + * @param resourceTypes - Specifies the resource types associated with the shared access signature. + * @param options - Optional parameters. + * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + generateSasStringToSign(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + } + if (expiresOn2 === void 0) { + const now = /* @__PURE__ */ new Date(); + expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + } + return generateAccountSASQueryParametersInternal(Object.assign({ + permissions, + expiresOn: expiresOn2, + resourceTypes, + services: AccountSASServices.parse("b").toString() + }, options), this.credential).stringToSign; + } + }; + exports2.KnownEncryptionAlgorithmType = void 0; + (function(KnownEncryptionAlgorithmType) { + KnownEncryptionAlgorithmType["AES256"] = "AES256"; + })(exports2.KnownEncryptionAlgorithmType || (exports2.KnownEncryptionAlgorithmType = {})); + Object.defineProperty(exports2, "RestError", { + enumerable: true, + get: function() { + return coreRestPipeline.RestError; + } + }); + exports2.AccountSASPermissions = AccountSASPermissions; + exports2.AccountSASResourceTypes = AccountSASResourceTypes; + exports2.AccountSASServices = AccountSASServices; + exports2.AnonymousCredential = AnonymousCredential; + exports2.AnonymousCredentialPolicy = AnonymousCredentialPolicy; + exports2.AppendBlobClient = AppendBlobClient; + exports2.BaseRequestPolicy = BaseRequestPolicy; + exports2.BlobBatch = BlobBatch; + exports2.BlobBatchClient = BlobBatchClient; + exports2.BlobClient = BlobClient; + exports2.BlobLeaseClient = BlobLeaseClient; + exports2.BlobSASPermissions = BlobSASPermissions; + exports2.BlobServiceClient = BlobServiceClient; + exports2.BlockBlobClient = BlockBlobClient; + exports2.ContainerClient = ContainerClient; + exports2.ContainerSASPermissions = ContainerSASPermissions; + exports2.Credential = Credential; + exports2.CredentialPolicy = CredentialPolicy; + exports2.PageBlobClient = PageBlobClient; + exports2.Pipeline = Pipeline; + exports2.SASQueryParameters = SASQueryParameters; + exports2.StorageBrowserPolicy = StorageBrowserPolicy; + exports2.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; + exports2.StorageOAuthScopes = StorageOAuthScopes; + exports2.StorageRetryPolicy = StorageRetryPolicy; + exports2.StorageRetryPolicyFactory = StorageRetryPolicyFactory; + exports2.StorageSharedKeyCredential = StorageSharedKeyCredential; + exports2.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; + exports2.generateAccountSASQueryParameters = generateAccountSASQueryParameters; + exports2.generateBlobSASQueryParameters = generateBlobSASQueryParameters; + exports2.getBlobServiceAccountAudience = getBlobServiceAccountAudience; + exports2.isPipelineLike = isPipelineLike; + exports2.logger = logger; + exports2.newPipeline = newPipeline; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/errors.js +var require_errors2 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/errors.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UsageError = exports2.NetworkError = exports2.GHESNotSupportedError = exports2.CacheNotFoundError = exports2.InvalidResponseError = exports2.FilesNotFoundError = void 0; + var FilesNotFoundError = class extends Error { + constructor(files = []) { + let message = "No files were found to upload"; + if (files.length > 0) { + message += `: ${files.join(", ")}`; + } + super(message); + this.files = files; + this.name = "FilesNotFoundError"; + } + }; + exports2.FilesNotFoundError = FilesNotFoundError; + var InvalidResponseError = class extends Error { + constructor(message) { + super(message); + this.name = "InvalidResponseError"; + } + }; + exports2.InvalidResponseError = InvalidResponseError; + var CacheNotFoundError = class extends Error { + constructor(message = "Cache not found") { + super(message); + this.name = "CacheNotFoundError"; + } + }; + exports2.CacheNotFoundError = CacheNotFoundError; + var GHESNotSupportedError = class extends Error { + constructor(message = "@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.") { + super(message); + this.name = "GHESNotSupportedError"; + } + }; + exports2.GHESNotSupportedError = GHESNotSupportedError; + var NetworkError = class extends Error { + constructor(code) { + const message = `Unable to make request: ${code} +If you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`; + super(message); + this.code = code; + this.name = "NetworkError"; + } + }; + exports2.NetworkError = NetworkError; + NetworkError.isNetworkErrorCode = (code) => { + if (!code) + return false; + return [ + "ECONNRESET", + "ENOTFOUND", + "ETIMEDOUT", + "ECONNREFUSED", + "EHOSTUNREACH" + ].includes(code); + }; + var UsageError = class extends Error { + constructor() { + const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours. +More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; + super(message); + this.name = "UsageError"; + } + }; + exports2.UsageError = UsageError; + UsageError.isUsageErrorMessage = (msg) => { + if (!msg) + return false; + return msg.includes("insufficient usage"); + }; + } +}); + +// node_modules/@actions/cache/lib/internal/uploadUtils.js +var require_uploadUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/uploadUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - containerName = decodeURIComponent(containerName); - if (!containerName) { - throw new Error("Provided containerName is invalid."); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return containerName; - } catch (error4) { - throw new Error("Unable to extract containerName with provided information."); } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.uploadCacheArchiveSDK = exports2.UploadProgress = void 0; + var core18 = __importStar4(require_core()); + var storage_blob_1 = require_dist7(); + var errors_1 = require_errors2(); + var UploadProgress = class { + constructor(contentLength) { + this.contentLength = contentLength; + this.sentBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); } /** - * Only available for ContainerClient constructed with a shared key credential. - * - * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * Sets the number of bytes sent * - * @param options - Optional parameters. - * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * @param sentBytes the number of bytes sent */ - generateSasUrl(options) { - return new Promise((resolve8) => { - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); - } - const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); - resolve8(appendToURLQuery(this.url, sas)); - }); + setSentBytes(sentBytes) { + this.sentBytes = sentBytes; } /** - * Only available for ContainerClient constructed with a shared key credential. - * - * Generates string to sign for a Blob Container Service Shared Access Signature (SAS) URI - * based on the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas - * - * @param options - Optional parameters. - * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + * Returns the total number of bytes transferred. */ - /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ - generateSasStringToSign(options) { - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); - } - return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName }, options), this.credential).stringToSign; + getTransferredBytes() { + return this.sentBytes; } /** - * Creates a BlobBatchClient object to conduct batch operations. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @returns A new BlobBatchClient object for this container. + * Returns true if the upload is complete. */ - getBlobBatchClient() { - return new BlobBatchClient(this.url, this.pipeline); - } - }; - var AccountSASPermissions = class _AccountSASPermissions { - constructor() { - this.read = false; - this.write = false; - this.delete = false; - this.deleteVersion = false; - this.list = false; - this.add = false; - this.create = false; - this.update = false; - this.process = false; - this.tag = false; - this.filter = false; - this.setImmutabilityPolicy = false; - this.permanentDelete = false; + isDone() { + return this.getTransferredBytes() === this.contentLength; } /** - * Parse initializes the AccountSASPermissions fields from a string. - * - * @param permissions - + * Prints the current upload stats. Once the upload completes, this will print one + * last line and then stop. */ - static parse(permissions) { - const accountSASPermissions = new _AccountSASPermissions(); - for (const c of permissions) { - switch (c) { - case "r": - accountSASPermissions.read = true; - break; - case "w": - accountSASPermissions.write = true; - break; - case "d": - accountSASPermissions.delete = true; - break; - case "x": - accountSASPermissions.deleteVersion = true; - break; - case "l": - accountSASPermissions.list = true; - break; - case "a": - accountSASPermissions.add = true; - break; - case "c": - accountSASPermissions.create = true; - break; - case "u": - accountSASPermissions.update = true; - break; - case "p": - accountSASPermissions.process = true; - break; - case "t": - accountSASPermissions.tag = true; - break; - case "f": - accountSASPermissions.filter = true; - break; - case "i": - accountSASPermissions.setImmutabilityPolicy = true; - break; - case "y": - accountSASPermissions.permanentDelete = true; - break; - default: - throw new RangeError(`Invalid permission character: ${c}`); - } + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.sentBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); + core18.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; } - return accountSASPermissions; } /** - * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it - * and boolean values for them. - * - * @param permissionLike - + * Returns a function used to handle TransferProgressEvents. */ - static from(permissionLike) { - const accountSASPermissions = new _AccountSASPermissions(); - if (permissionLike.read) { - accountSASPermissions.read = true; - } - if (permissionLike.write) { - accountSASPermissions.write = true; - } - if (permissionLike.delete) { - accountSASPermissions.delete = true; - } - if (permissionLike.deleteVersion) { - accountSASPermissions.deleteVersion = true; - } - if (permissionLike.filter) { - accountSASPermissions.filter = true; - } - if (permissionLike.tag) { - accountSASPermissions.tag = true; - } - if (permissionLike.list) { - accountSASPermissions.list = true; - } - if (permissionLike.add) { - accountSASPermissions.add = true; - } - if (permissionLike.create) { - accountSASPermissions.create = true; - } - if (permissionLike.update) { - accountSASPermissions.update = true; - } - if (permissionLike.process) { - accountSASPermissions.process = true; - } - if (permissionLike.setImmutabilityPolicy) { - accountSASPermissions.setImmutabilityPolicy = true; - } - if (permissionLike.permanentDelete) { - accountSASPermissions.permanentDelete = true; - } - return accountSASPermissions; + onProgress() { + return (progress) => { + this.setSentBytes(progress.loadedBytes); + }; } /** - * Produces the SAS permissions string for an Azure Storage account. - * Call this method to set AccountSASSignatureValues Permissions field. - * - * Using this method will guarantee the resource types are in - * an order accepted by the service. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * Starts the timer that displays the stats. * + * @param delayInMs the delay between each write */ - toString() { - const permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.filter) { - permissions.push("f"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.list) { - permissions.push("l"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.update) { - permissions.push("u"); - } - if (this.process) { - permissions.push("p"); - } - if (this.setImmutabilityPolicy) { - permissions.push("i"); + startDisplayTimer(delayInMs = 1e3) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + /** + * Stops the timer that displays the stats. As this typically indicates the upload + * is complete, this will display one last line, unless the last line has already + * been written. + */ + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = void 0; } - if (this.permanentDelete) { - permissions.push("y"); + this.display(); + } + }; + exports2.UploadProgress = UploadProgress; + function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) { + var _a; + return __awaiter4(this, void 0, void 0, function* () { + const blobClient = new storage_blob_1.BlobClient(signedUploadURL); + const blockBlobClient = blobClient.getBlockBlobClient(); + const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0); + const uploadOptions = { + blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize, + concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency, + maxSingleShotSize: 128 * 1024 * 1024, + onProgress: uploadProgress.onProgress() + }; + try { + uploadProgress.startDisplayTimer(); + core18.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`); + const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions); + if (response._response.status >= 400) { + throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`); + } + return response; + } catch (error4) { + core18.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error4.message}`); + throw error4; + } finally { + uploadProgress.stopDisplayTimer(); } - return permissions.join(""); + }); + } + exports2.uploadCacheArchiveSDK = uploadCacheArchiveSDK; + } +}); + +// node_modules/@actions/cache/lib/internal/requestUtils.js +var require_requestUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/requestUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - var AccountSASResourceTypes = class _AccountSASResourceTypes { - constructor() { - this.service = false; - this.container = false; - this.object = false; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - /** - * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an - * Error if it encounters a character that does not correspond to a valid resource type. - * - * @param resourceTypes - - */ - static parse(resourceTypes) { - const accountSASResourceTypes = new _AccountSASResourceTypes(); - for (const c of resourceTypes) { - switch (c) { - case "s": - accountSASResourceTypes.service = true; - break; - case "c": - accountSASResourceTypes.container = true; - break; - case "o": - accountSASResourceTypes.object = true; - break; - default: - throw new RangeError(`Invalid resource type: ${c}`); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return accountSASResourceTypes; - } - /** - * Converts the given resource types to a string. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - */ - toString() { - const resourceTypes = []; - if (this.service) { - resourceTypes.push("s"); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (this.container) { - resourceTypes.push("c"); + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } - if (this.object) { - resourceTypes.push("o"); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; + var core18 = __importStar4(require_core()); + var http_client_1 = require_lib4(); + var constants_1 = require_constants7(); + function isSuccessStatusCode(statusCode) { + if (!statusCode) { + return false; + } + return statusCode >= 200 && statusCode < 300; + } + exports2.isSuccessStatusCode = isSuccessStatusCode; + function isServerErrorStatusCode(statusCode) { + if (!statusCode) { + return true; + } + return statusCode >= 500; + } + exports2.isServerErrorStatusCode = isServerErrorStatusCode; + function isRetryableStatusCode(statusCode) { + if (!statusCode) { + return false; + } + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.GatewayTimeout + ]; + return retryableStatusCodes.includes(statusCode); + } + exports2.isRetryableStatusCode = isRetryableStatusCode; + function sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => setTimeout(resolve8, milliseconds)); + }); + } + function retry3(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay2 = constants_1.DefaultRetryDelay, onError = void 0) { + return __awaiter4(this, void 0, void 0, function* () { + let errorMessage = ""; + let attempt = 1; + while (attempt <= maxAttempts) { + let response = void 0; + let statusCode = void 0; + let isRetryable = false; + try { + response = yield method(); + } catch (error4) { + if (onError) { + response = onError(error4); + } + isRetryable = true; + errorMessage = error4.message; + } + if (response) { + statusCode = getStatusCode(response); + if (!isServerErrorStatusCode(statusCode)) { + return response; + } + } + if (statusCode) { + isRetryable = isRetryableStatusCode(statusCode); + errorMessage = `Cache service responded with ${statusCode}`; + } + core18.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); + if (!isRetryable) { + core18.debug(`${name} - Error is not retryable`); + break; + } + yield sleep(delay2); + attempt++; } - return resourceTypes.join(""); + throw Error(`${name} failed: ${errorMessage}`); + }); + } + exports2.retry = retry3; + function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay2 = constants_1.DefaultRetryDelay) { + return __awaiter4(this, void 0, void 0, function* () { + return yield retry3( + name, + method, + (response) => response.statusCode, + maxAttempts, + delay2, + // If the error object contains the statusCode property, extract it and return + // an TypedResponse so it can be processed by the retry logic. + (error4) => { + if (error4 instanceof http_client_1.HttpClientError) { + return { + statusCode: error4.statusCode, + result: null, + headers: {}, + error: error4 + }; + } else { + return void 0; + } + } + ); + }); + } + exports2.retryTypedResponse = retryTypedResponse; + function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay2 = constants_1.DefaultRetryDelay) { + return __awaiter4(this, void 0, void 0, function* () { + return yield retry3(name, method, (response) => response.message.statusCode, maxAttempts, delay2); + }); + } + exports2.retryHttpClientResponse = retryHttpClientResponse; + } +}); + +// node_modules/@actions/cache/lib/internal/downloadUtils.js +var require_downloadUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/downloadUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - var AccountSASServices = class _AccountSASServices { - constructor() { - this.blob = false; - this.file = false; - this.queue = false; - this.table = false; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - /** - * Creates an {@link AccountSASServices} from the specified services string. This method will throw an - * Error if it encounters a character that does not correspond to a valid service. - * - * @param services - - */ - static parse(services) { - const accountSASServices = new _AccountSASServices(); - for (const c of services) { - switch (c) { - case "b": - accountSASServices.blob = true; - break; - case "f": - accountSASServices.file = true; - break; - case "q": - accountSASServices.queue = true; - break; - case "t": - accountSASServices.table = true; - break; - default: - throw new RangeError(`Invalid service character: ${c}`); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return accountSASServices; - } - /** - * Converts the given services to a string. - * - */ - toString() { - const services = []; - if (this.blob) { - services.push("b"); - } - if (this.table) { - services.push("t"); - } - if (this.queue) { - services.push("q"); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (this.file) { - services.push("f"); + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } - return services.join(""); - } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { - return generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential).sasQueryParameters; - } - function generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) { - const version2 = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.setImmutabilityPolicy && version2 < "2020-08-04") { - throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); - } - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.deleteVersion && version2 < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); - } - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.permanentDelete && version2 < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when provided 'y' permission."); - } - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.tag && version2 < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); - } - if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.filter && version2 < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); - } - if (accountSASSignatureValues.encryptionScope && version2 < "2020-12-06") { - throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); - } - const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); - const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); - const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); - let stringToSign; - if (version2 >= "2020-12-06") { - stringToSign = [ - sharedKeyCredential.accountName, - parsedPermissions, - parsedServices, - parsedResourceTypes, - accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", - truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", - accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", - version2, - accountSASSignatureValues.encryptionScope ? accountSASSignatureValues.encryptionScope : "", - "" - // Account SAS requires an additional newline character - ].join("\n"); - } else { - stringToSign = [ - sharedKeyCredential.accountName, - parsedPermissions, - parsedServices, - parsedResourceTypes, - accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", - truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", - accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", - version2, - "" - // Account SAS requires an additional newline character - ].join("\n"); - } - const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return { - sasQueryParameters: new SASQueryParameters(version2, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, accountSASSignatureValues.encryptionScope), - stringToSign - }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; + var core18 = __importStar4(require_core()); + var http_client_1 = require_lib4(); + var storage_blob_1 = require_dist7(); + var buffer = __importStar4(require("buffer")); + var fs17 = __importStar4(require("fs")); + var stream2 = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var requestUtils_1 = require_requestUtils(); + var abort_controller_1 = require_dist5(); + function pipeResponseToStream(response, output) { + return __awaiter4(this, void 0, void 0, function* () { + const pipeline = util.promisify(stream2.pipeline); + yield pipeline(response.message, output); + }); } - var BlobServiceClient = class _BlobServiceClient extends StorageClient { - /** - * - * Creates an instance of BlobServiceClient from connection string. - * - * @param connectionString - Account connection string or a SAS connection string of an Azure storage account. - * [ Note - Account connection string can only be used in NODE.JS runtime. ] - * Account connection string example - - * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` - * SAS connection string example - - * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` - * @param options - Optional. Options to configure the HTTP pipeline. - */ - static fromConnectionString(connectionString, options) { - options = options || {}; - const extractedCreds = extractConnectionStringParts(connectionString); - if (extractedCreds.kind === "AccountConnString") { - if (coreUtil.isNode) { - const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - if (!options.proxyOptions) { - options.proxyOptions = coreRestPipeline.getDefaultProxySettings(extractedCreds.proxyUri); - } - const pipeline = newPipeline(sharedKeyCredential, options); - return new _BlobServiceClient(extractedCreds.url, pipeline); - } else { - throw new Error("Account connection string is only supported in Node.js environment"); - } - } else if (extractedCreds.kind === "SASConnString") { - const pipeline = newPipeline(new AnonymousCredential(), options); - return new _BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); - } else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - constructor(url3, credentialOrPipeline, options) { - let pipeline; - if (isPipelineLike(credentialOrPipeline)) { - pipeline = credentialOrPipeline; - } else if (coreUtil.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential || credentialOrPipeline instanceof AnonymousCredential || coreAuth.isTokenCredential(credentialOrPipeline)) { - pipeline = newPipeline(credentialOrPipeline, options); - } else { - pipeline = newPipeline(new AnonymousCredential(), options); - } - super(url3, pipeline); - this.serviceContext = this.storageClientContext.service; + var DownloadProgress = class { + constructor(contentLength) { + this.contentLength = contentLength; + this.segmentIndex = 0; + this.segmentSize = 0; + this.segmentOffset = 0; + this.receivedBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); } /** - * Creates a {@link ContainerClient} object - * - * @param containerName - A container name - * @returns A new ContainerClient object for the given container name. - * - * Example usage: + * Progress to the next segment. Only call this method when the previous segment + * is complete. * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * ``` + * @param segmentSize the length of the next segment */ - getContainerClient(containerName) { - return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + nextSegment(segmentSize) { + this.segmentOffset = this.segmentOffset + this.segmentSize; + this.segmentIndex = this.segmentIndex + 1; + this.segmentSize = segmentSize; + this.receivedBytes = 0; + core18.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); } /** - * Create a Blob container. @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Sets the number of bytes received for the current segment. * - * @param containerName - Name of the container to create. - * @param options - Options to configure Container Create operation. - * @returns Container creation response and the corresponding container client. + * @param receivedBytes the number of bytes received */ - async createContainer(containerName, options = {}) { - return tracingClient.withSpan("BlobServiceClient-createContainer", options, async (updatedOptions) => { - const containerClient = this.getContainerClient(containerName); - const containerCreateResponse = await containerClient.create(updatedOptions); - return { - containerClient, - containerCreateResponse - }; - }); + setReceivedBytes(receivedBytes) { + this.receivedBytes = receivedBytes; } /** - * Deletes a Blob container. - * - * @param containerName - Name of the container to delete. - * @param options - Options to configure Container Delete operation. - * @returns Container deletion response. + * Returns the total number of bytes transferred. */ - async deleteContainer(containerName, options = {}) { - return tracingClient.withSpan("BlobServiceClient-deleteContainer", options, async (updatedOptions) => { - const containerClient = this.getContainerClient(containerName); - return containerClient.delete(updatedOptions); - }); + getTransferredBytes() { + return this.segmentOffset + this.receivedBytes; } /** - * Restore a previously deleted Blob container. - * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. - * - * @param deletedContainerName - Name of the previously deleted container. - * @param deletedContainerVersion - Version of the previously deleted container, used to uniquely identify the deleted container. - * @param options - Options to configure Container Restore operation. - * @returns Container deletion response. + * Returns true if the download is complete. */ - async undeleteContainer(deletedContainerName2, deletedContainerVersion2, options = {}) { - return tracingClient.withSpan("BlobServiceClient-undeleteContainer", options, async (updatedOptions) => { - const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName2); - const containerContext = containerClient["storageClientContext"].container; - const containerUndeleteResponse = assertResponse(await containerContext.restore({ - deletedContainerName: deletedContainerName2, - deletedContainerVersion: deletedContainerVersion2, - tracingOptions: updatedOptions.tracingOptions - })); - return { containerClient, containerUndeleteResponse }; - }); + isDone() { + return this.getTransferredBytes() === this.contentLength; } /** - * Rename an existing Blob Container. - * - * @param sourceContainerName - The name of the source container. - * @param destinationContainerName - The new name of the container. - * @param options - Options to configure Container Rename operation. + * Prints the current download stats. Once the download completes, this will print one + * last line and then stop. */ - /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ - // @ts-ignore Need to hide this interface for now. Make it public and turn on the live tests for it when the service is ready. - async renameContainer(sourceContainerName2, destinationContainerName, options = {}) { - return tracingClient.withSpan("BlobServiceClient-renameContainer", options, async (updatedOptions) => { - var _a; - const containerClient = this.getContainerClient(destinationContainerName); - const containerContext = containerClient["storageClientContext"].container; - const containerRenameResponse = assertResponse(await containerContext.rename(sourceContainerName2, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId }))); - return { containerClient, containerRenameResponse }; - }); + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.segmentOffset + this.receivedBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const downloadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); + core18.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; + } } /** - * Gets the properties of a storage account’s Blob service, including properties - * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * @param options - Options to the Service Get Properties operation. - * @returns Response data for the Service Get Properties operation. + * Returns a function used to handle TransferProgressEvents. */ - async getProperties(options = {}) { - return tracingClient.withSpan("BlobServiceClient-getProperties", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.getProperties({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + onProgress() { + return (progress) => { + this.setReceivedBytes(progress.loadedBytes); + }; } /** - * Sets properties for a storage account’s Blob service endpoint, including properties - * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties + * Starts the timer that displays the stats. * - * @param properties - - * @param options - Options to the Service Set Properties operation. - * @returns Response data for the Service Set Properties operation. + * @param delayInMs the delay between each write */ - async setProperties(properties, options = {}) { - return tracingClient.withSpan("BlobServiceClient-setProperties", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.setProperties(properties, { - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + startDisplayTimer(delayInMs = 1e3) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); } /** - * Retrieves statistics related to replication for the Blob service. It is only - * available on the secondary location endpoint when read-access geo-redundant - * replication is enabled for the storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats - * - * @param options - Options to the Service Get Statistics operation. - * @returns Response data for the Service Get Statistics operation. + * Stops the timer that displays the stats. As this typically indicates the download + * is complete, this will display one last line, unless the last line has already + * been written. */ - async getStatistics(options = {}) { - return tracingClient.withSpan("BlobServiceClient-getStatistics", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.getStatistics({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - }); + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = void 0; + } + this.display(); } - /** - * The Get Account Information operation returns the sku name and account kind - * for the specified account. - * The Get Account Information operation is available on service versions beginning - * with version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information - * - * @param options - Options to the Service Get Account Info operation. - * @returns Response data for the Service Get Account Info operation. - */ - async getAccountInfo(options = {}) { - return tracingClient.withSpan("BlobServiceClient-getAccountInfo", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.getAccountInfo({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); + }; + exports2.DownloadProgress = DownloadProgress; + function downloadCacheHttpClient(archiveLocation, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const writeStream = fs17.createWriteStream(archivePath); + const httpClient = new http_client_1.HttpClient("actions/cache"); + const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.get(archiveLocation); + })); + downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { + downloadResponse.message.destroy(); + core18.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); }); - } - /** - * Returns a list of the containers under the specified account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 - * - * @param marker - A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to the Service List Container Segment operation. - * @returns Response data for the Service List Container Segment operation. - */ - async listContainersSegment(marker2, options = {}) { - return tracingClient.withSpan("BlobServiceClient-listContainersSegment", options, async (updatedOptions) => { - return assertResponse(await this.serviceContext.listContainersSegment(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker: marker2 }, options), { include: typeof options.include === "string" ? [options.include] : options.include, tracingOptions: updatedOptions.tracingOptions }))); + yield pipeResponseToStream(downloadResponse, writeStream); + const contentLengthHeader = downloadResponse.message.headers["content-length"]; + if (contentLengthHeader) { + const expectedLength = parseInt(contentLengthHeader); + const actualLength = utils.getArchiveFileSizeInBytes(archivePath); + if (actualLength !== expectedLength) { + throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); + } + } else { + core18.debug("Unable to validate download, no Content-Length header"); + } + }); + } + exports2.downloadCacheHttpClient = downloadCacheHttpClient; + function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { + var _a; + return __awaiter4(this, void 0, void 0, function* () { + const archiveDescriptor = yield fs17.promises.open(archivePath, "w"); + const httpClient = new http_client_1.HttpClient("actions/cache", void 0, { + socketTimeout: options.timeoutInMs, + keepAlive: true }); - } - /** - * The Filter Blobs operation enables callers to list blobs across all containers whose tags - * match a given search expression. Filter blobs searches across all containers within a - * storage account but can be scoped within the expression to a single container. - * - * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param marker - A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to find blobs by tags. - */ - async findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options = {}) { - return tracingClient.withSpan("BlobServiceClient-findBlobsByTagsSegment", options, async (updatedOptions) => { - const response = assertResponse(await this.serviceContext.filterBlobs({ - abortSignal: options.abortSignal, - where: tagFilterSqlExpression, - marker: marker2, - maxPageSize: options.maxPageSize, - tracingOptions: updatedOptions.tracingOptions + try { + const res = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCacheMetadata", () => __awaiter4(this, void 0, void 0, function* () { + return yield httpClient.request("HEAD", archiveLocation, null, {}); })); - const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { - var _a; - let tagValue = ""; - if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { - tagValue = blob.tags.blobTagSet[0].value; + const lengthHeader = res.message.headers["content-length"]; + if (lengthHeader === void 0 || lengthHeader === null) { + throw new Error("Content-Length not found on blob response"); + } + const length = parseInt(lengthHeader); + if (Number.isNaN(length)) { + throw new Error(`Could not interpret Content-Length: ${length}`); + } + const downloads = []; + const blockSize = 4 * 1024 * 1024; + for (let offset = 0; offset < length; offset += blockSize) { + const count = Math.min(blockSize, length - offset); + downloads.push({ + offset, + promiseGetter: () => __awaiter4(this, void 0, void 0, function* () { + return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count); + }) + }); + } + downloads.reverse(); + let actives = 0; + let bytesDownloaded = 0; + const progress = new DownloadProgress(length); + progress.startDisplayTimer(); + const progressFn = progress.onProgress(); + const activeDownloads = []; + let nextDownload; + const waitAndWrite = () => __awaiter4(this, void 0, void 0, function* () { + const segment = yield Promise.race(Object.values(activeDownloads)); + yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset); + actives--; + delete activeDownloads[segment.offset]; + bytesDownloaded += segment.count; + progressFn({ loadedBytes: bytesDownloaded }); + }); + while (nextDownload = downloads.pop()) { + activeDownloads[nextDownload.offset] = nextDownload.promiseGetter(); + actives++; + if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) { + yield waitAndWrite(); } - return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); - }) }); - return wrappedResponse; - }); - } - /** - * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. - * - * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param marker - A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to find blobs by tags. - */ - findBlobsByTagsSegments(tagFilterSqlExpression_1, marker_1) { - return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1(tagFilterSqlExpression, marker2, options = {}) { - let response; - if (!!marker2 || marker2 === void 0) { - do { - response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker2, options)); - response.blobs = response.blobs || []; - marker2 = response.continuationToken; - yield yield tslib.__await(response); - } while (marker2); } - }); - } - /** - * Returns an AsyncIterableIterator for blobs. - * - * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param options - Options to findBlobsByTagsItems. - */ - findBlobsByTagsItems(tagFilterSqlExpression_1) { - return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1(tagFilterSqlExpression, options = {}) { - var _a, e_1, _b, _c; - let marker2; + while (actives > 0) { + yield waitAndWrite(); + } + } finally { + httpClient.dispose(); + yield archiveDescriptor.close(); + } + }); + } + exports2.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent; + function downloadSegmentRetry(httpClient, archiveLocation, offset, count) { + return __awaiter4(this, void 0, void 0, function* () { + const retries = 5; + let failures = 0; + while (true) { try { - for (var _d = true, _e = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const segment = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); + const timeout = 3e4; + const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count)); + if (typeof result === "string") { + throw new Error("downloadSegmentRetry failed due to timeout"); } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_1) throw e_1.error; + return result; + } catch (err) { + if (failures >= retries) { + throw err; } + failures++; } - }); - } - /** - * Returns an async iterable iterator to find all blobs with specified tag - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { - * console.log(`Blob ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .findBlobsByTags("tagkey='tagvalue'") - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * ``` - * - * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param options - Options to find blobs by tags. - */ - findBlobsByTags(tagFilterSqlExpression, options = {}) { - const listSegmentOptions = Object.assign({}, options); - const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + } + }); + } + function downloadSegment(httpClient, archiveLocation, offset, count) { + return __awaiter4(this, void 0, void 0, function* () { + const partRes = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCachePart", () => __awaiter4(this, void 0, void 0, function* () { + return yield httpClient.get(archiveLocation, { + Range: `bytes=${offset}-${offset + count - 1}` + }); + })); + if (!partRes.readBodyBuffer) { + throw new Error("Expected HttpClientResponse to implement readBodyBuffer"); + } return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - } + offset, + count, + buffer: yield partRes.readBodyBuffer() }; + }); + } + function downloadCacheStorageSDK(archiveLocation, archivePath, options) { + var _a; + return __awaiter4(this, void 0, void 0, function* () { + const client = new storage_blob_1.BlockBlobClient(archiveLocation, void 0, { + retryOptions: { + // Override the timeout used when downloading each 4 MB chunk + // The default is 2 min / MB, which is way too slow + tryTimeoutInMs: options.timeoutInMs + } + }); + const properties = yield client.getProperties(); + const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; + if (contentLength < 0) { + core18.debug("Unable to determine content length, downloading file with http-client..."); + yield downloadCacheHttpClient(archiveLocation, archivePath); + } else { + const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); + const downloadProgress = new DownloadProgress(contentLength); + const fd = fs17.openSync(archivePath, "w"); + try { + downloadProgress.startDisplayTimer(); + const controller = new abort_controller_1.AbortController(); + const abortSignal = controller.signal; + while (!downloadProgress.isDone()) { + const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; + const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); + downloadProgress.nextSegment(segmentSize); + const result = yield promiseWithTimeout(options.segmentTimeoutInMs || 36e5, client.downloadToBuffer(segmentStart, segmentSize, { + abortSignal, + concurrency: options.downloadConcurrency, + onProgress: downloadProgress.onProgress() + })); + if (result === "timeout") { + controller.abort(); + throw new Error("Aborting cache download as the download time exceeded the timeout."); + } else if (Buffer.isBuffer(result)) { + fs17.writeFileSync(fd, result); + } + } + } finally { + downloadProgress.stopDisplayTimer(); + fs17.closeSync(fd); + } + } + }); + } + exports2.downloadCacheStorageSDK = downloadCacheStorageSDK; + var promiseWithTimeout = (timeoutMs, promise) => __awaiter4(void 0, void 0, void 0, function* () { + let timeoutHandle; + const timeoutPromise = new Promise((resolve8) => { + timeoutHandle = setTimeout(() => resolve8("timeout"), timeoutMs); + }); + return Promise.race([promise, timeoutPromise]).then((result) => { + clearTimeout(timeoutHandle); + return result; + }); + }); + } +}); + +// node_modules/@actions/cache/lib/options.js +var require_options = __commonJS({ + "node_modules/@actions/cache/lib/options.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getDownloadOptions = exports2.getUploadOptions = void 0; + var core18 = __importStar4(require_core()); + function getUploadOptions(copy) { + const result = { + useAzureSdk: false, + uploadConcurrency: 4, + uploadChunkSize: 32 * 1024 * 1024 + }; + if (copy) { + if (typeof copy.useAzureSdk === "boolean") { + result.useAzureSdk = copy.useAzureSdk; + } + if (typeof copy.uploadConcurrency === "number") { + result.uploadConcurrency = copy.uploadConcurrency; + } + if (typeof copy.uploadChunkSize === "number") { + result.uploadChunkSize = copy.uploadChunkSize; + } + } + result.uploadConcurrency = !isNaN(Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) ? Math.min(32, Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) : result.uploadConcurrency; + result.uploadChunkSize = !isNaN(Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"])) ? Math.min(128 * 1024 * 1024, Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"]) * 1024 * 1024) : result.uploadChunkSize; + core18.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core18.debug(`Upload concurrency: ${result.uploadConcurrency}`); + core18.debug(`Upload chunk size: ${result.uploadChunkSize}`); + return result; + } + exports2.getUploadOptions = getUploadOptions; + function getDownloadOptions(copy) { + const result = { + useAzureSdk: false, + concurrentBlobDownloads: true, + downloadConcurrency: 8, + timeoutInMs: 3e4, + segmentTimeoutInMs: 6e5, + lookupOnly: false + }; + if (copy) { + if (typeof copy.useAzureSdk === "boolean") { + result.useAzureSdk = copy.useAzureSdk; + } + if (typeof copy.concurrentBlobDownloads === "boolean") { + result.concurrentBlobDownloads = copy.concurrentBlobDownloads; + } + if (typeof copy.downloadConcurrency === "number") { + result.downloadConcurrency = copy.downloadConcurrency; + } + if (typeof copy.timeoutInMs === "number") { + result.timeoutInMs = copy.timeoutInMs; + } + if (typeof copy.segmentTimeoutInMs === "number") { + result.segmentTimeoutInMs = copy.segmentTimeoutInMs; + } + if (typeof copy.lookupOnly === "boolean") { + result.lookupOnly = copy.lookupOnly; + } + } + const segmentDownloadTimeoutMins = process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]; + if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) { + result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1e3; + } + core18.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core18.debug(`Download concurrency: ${result.downloadConcurrency}`); + core18.debug(`Request timeout (ms): ${result.timeoutInMs}`); + core18.debug(`Cache segment download timeout mins env var: ${process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]}`); + core18.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`); + core18.debug(`Lookup only: ${result.lookupOnly}`); + return result; + } + exports2.getDownloadOptions = getDownloadOptions; + } +}); + +// node_modules/@actions/cache/lib/internal/config.js +var require_config = __commonJS({ + "node_modules/@actions/cache/lib/internal/config.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getCacheServiceURL = exports2.getCacheServiceVersion = exports2.isGhes = void 0; + function isGhes() { + const ghUrl = new URL(process.env["GITHUB_SERVER_URL"] || "https://github.com"); + const hostname = ghUrl.hostname.trimEnd().toUpperCase(); + const isGitHubHost = hostname === "GITHUB.COM"; + const isGheHost = hostname.endsWith(".GHE.COM"); + const isLocalHost = hostname.endsWith(".LOCALHOST"); + return !isGitHubHost && !isGheHost && !isLocalHost; + } + exports2.isGhes = isGhes; + function getCacheServiceVersion() { + if (isGhes()) + return "v1"; + return process.env["ACTIONS_CACHE_SERVICE_V2"] ? "v2" : "v1"; + } + exports2.getCacheServiceVersion = getCacheServiceVersion; + function getCacheServiceURL() { + const version = getCacheServiceVersion(); + switch (version) { + case "v1": + return process.env["ACTIONS_CACHE_URL"] || process.env["ACTIONS_RESULTS_URL"] || ""; + case "v2": + return process.env["ACTIONS_RESULTS_URL"] || ""; + default: + throw new Error(`Unsupported cache service version: ${version}`); + } + } + exports2.getCacheServiceURL = getCacheServiceURL; + } +}); + +// node_modules/@actions/cache/package.json +var require_package2 = __commonJS({ + "node_modules/@actions/cache/package.json"(exports2, module2) { + module2.exports = { + name: "@actions/cache", + version: "4.1.0", + preview: true, + description: "Actions cache lib", + keywords: [ + "github", + "actions", + "cache" + ], + homepage: "https://github.com/actions/toolkit/tree/main/packages/cache", + license: "MIT", + main: "lib/cache.js", + types: "lib/cache.d.ts", + directories: { + lib: "lib", + test: "__tests__" + }, + files: [ + "lib", + "!.DS_Store" + ], + publishConfig: { + access: "public" + }, + repository: { + type: "git", + url: "git+https://github.com/actions/toolkit.git", + directory: "packages/cache" + }, + scripts: { + "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", + test: 'echo "Error: run tests from root" && exit 1', + tsc: "tsc" + }, + bugs: { + url: "https://github.com/actions/toolkit/issues" + }, + dependencies: { + "@actions/core": "^1.11.1", + "@actions/exec": "^1.0.1", + "@actions/glob": "^0.1.0", + "@protobuf-ts/runtime-rpc": "^2.11.1", + "@actions/http-client": "^2.1.1", + "@actions/io": "^1.0.1", + "@azure/abort-controller": "^1.1.0", + "@azure/ms-rest-js": "^2.6.0", + "@azure/storage-blob": "^12.13.0", + semver: "^6.3.1" + }, + devDependencies: { + "@types/node": "^22.13.9", + "@types/semver": "^6.0.0", + "@protobuf-ts/plugin": "^2.9.4", + typescript: "^5.2.2" + } + }; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/user-agent.js +var require_user_agent = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/user-agent.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getUserAgentString = void 0; + var packageJson = require_package2(); + function getUserAgentString() { + return `@actions/cache-${packageJson.version}`; + } + exports2.getUserAgentString = getUserAgentString; + } +}); + +// node_modules/@actions/cache/lib/internal/cacheHttpClient.js +var require_cacheHttpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/cacheHttpClient.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - /** - * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses - * - * @param marker - A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param options - Options to list containers operation. - */ - listSegments(marker_1) { - return tslib.__asyncGenerator(this, arguments, function* listSegments_1(marker2, options = {}) { - let listContainersSegmentResponse; - if (!!marker2 || marker2 === void 0) { - do { - listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker2, options)); - listContainersSegmentResponse.containerItems = listContainersSegmentResponse.containerItems || []; - marker2 = listContainersSegmentResponse.continuationToken; - yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); - } while (marker2); - } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); }); } - /** - * Returns an AsyncIterableIterator for Container Items - * - * @param options - Options to list containers operation. - */ - listItems() { - return tslib.__asyncGenerator(this, arguments, function* listItems_1(options = {}) { - var _a, e_2, _b, _c; - let marker2; + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { try { - for (var _d = true, _e = tslib.__asyncValues(this.listSegments(marker2, options)), _f; _f = yield tslib.__await(_e.next()), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const segment = _c; - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); - } - } catch (e_2_1) { - e_2 = { error: e_2_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield tslib.__await(_b.call(_e)); - } finally { - if (e_2) throw e_2.error; - } + step(generator.next(value)); + } catch (e) { + reject(e); } - }); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; + var core18 = __importStar4(require_core()); + var http_client_1 = require_lib4(); + var auth_1 = require_auth2(); + var fs17 = __importStar4(require("fs")); + var url_1 = require("url"); + var utils = __importStar4(require_cacheUtils()); + var uploadUtils_1 = require_uploadUtils(); + var downloadUtils_1 = require_downloadUtils(); + var options_1 = require_options(); + var requestUtils_1 = require_requestUtils(); + var config_1 = require_config(); + var user_agent_1 = require_user_agent(); + function getCacheApiUrl(resource) { + const baseUrl = (0, config_1.getCacheServiceURL)(); + if (!baseUrl) { + throw new Error("Cache Service Url not found, unable to restore cache."); } - /** - * Returns an async iterable iterator to list all the containers - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the containers in pages. - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const container of blobServiceClient.listContainers()) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.listContainers(); - * let containerItem = await iter.next(); - * while (!containerItem.done) { - * console.log(`Container ${i++}: ${containerItem.value.name}`); - * containerItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .listContainers() - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints 10 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * ``` - * - * @param options - Options to list containers. - * @returns An asyncIterableIterator that supports paging. - */ - listContainers(options = {}) { - if (options.prefix === "") { - options.prefix = void 0; + const url2 = `${baseUrl}_apis/artifactcache/${resource}`; + core18.debug(`Resource Url: ${url2}`); + return url2; + } + function createAcceptHeader(type2, apiVersion) { + return `${type2};api-version=${apiVersion}`; + } + function getRequestOptions() { + const requestOptions = { + headers: { + Accept: createAcceptHeader("application/json", "6.0-preview.1") } - const include2 = []; - if (options.includeDeleted) { - include2.push("deleted"); + }; + return requestOptions; + } + function createHttpClient() { + const token = process.env["ACTIONS_RUNTIME_TOKEN"] || ""; + const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); + return new http_client_1.HttpClient((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions()); + } + function getCacheEntry(keys, paths, options) { + return __awaiter4(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); + const resource = `cache?keys=${encodeURIComponent(keys.join(","))}&version=${version}`; + const response = yield (0, requestUtils_1.retryTypedResponse)("getCacheEntry", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.getJson(getCacheApiUrl(resource)); + })); + if (response.statusCode === 204) { + if (core18.isDebug()) { + yield printCachesListForDiagnostics(keys[0], httpClient, version); + } + return null; } - if (options.includeMetadata) { - include2.push("metadata"); + if (!(0, requestUtils_1.isSuccessStatusCode)(response.statusCode)) { + throw new Error(`Cache service responded with ${response.statusCode}`); } - if (options.includeSystem) { - include2.push("system"); + const cacheResult = response.result; + const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; + if (!cacheDownloadUrl) { + throw new Error("Cache not found."); } - const listSegmentOptions = Object.assign(Object.assign({}, options), include2.length > 0 ? { include: include2 } : {}); - const iter = this.listItems(listSegmentOptions); - return { - /** - * The next method, part of the iteration protocol - */ - next() { - return iter.next(); - }, - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator]() { - return this; - }, - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: (settings = {}) => { - return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + core18.setSecret(cacheDownloadUrl); + core18.debug(`Cache Result:`); + core18.debug(JSON.stringify(cacheResult)); + return cacheResult; + }); + } + exports2.getCacheEntry = getCacheEntry; + function printCachesListForDiagnostics(key, httpClient, version) { + return __awaiter4(this, void 0, void 0, function* () { + const resource = `caches?key=${encodeURIComponent(key)}`; + const response = yield (0, requestUtils_1.retryTypedResponse)("listCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.getJson(getCacheApiUrl(resource)); + })); + if (response.statusCode === 200) { + const cacheListResult = response.result; + const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount; + if (totalCount && totalCount > 0) { + core18.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env["GITHUB_REF"]}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key +Other caches with similar key:`); + for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) { + core18.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`); + } + } + } + }); + } + function downloadCache(archiveLocation, archivePath, options) { + return __awaiter4(this, void 0, void 0, function* () { + const archiveUrl = new url_1.URL(archiveLocation); + const downloadOptions = (0, options_1.getDownloadOptions)(options); + if (archiveUrl.hostname.endsWith(".blob.core.windows.net")) { + if (downloadOptions.useAzureSdk) { + yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions); + } else if (downloadOptions.concurrentBlobDownloads) { + yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions); + } else { + yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); } + } else { + yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); + } + }); + } + exports2.downloadCache = downloadCache; + function reserveCache(key, paths, options) { + return __awaiter4(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); + const reserveCacheRequest = { + key, + version, + cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize }; + const response = yield (0, requestUtils_1.retryTypedResponse)("reserveCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl("caches"), reserveCacheRequest); + })); + return response; + }); + } + exports2.reserveCache = reserveCache; + function getContentRange(start, end) { + return `bytes ${start}-${end}/*`; + } + function uploadChunk(httpClient, resourceUrl, openStream, start, end) { + return __awaiter4(this, void 0, void 0, function* () { + core18.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); + const additionalHeaders = { + "Content-Type": "application/octet-stream", + "Content-Range": getContentRange(start, end) + }; + const uploadChunkResponse = yield (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.sendStream("PATCH", resourceUrl, openStream(), additionalHeaders); + })); + if (!(0, requestUtils_1.isSuccessStatusCode)(uploadChunkResponse.message.statusCode)) { + throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); + } + }); + } + function uploadFile(httpClient, cacheId, archivePath, options) { + return __awaiter4(this, void 0, void 0, function* () { + const fileSize = utils.getArchiveFileSizeInBytes(archivePath); + const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); + const fd = fs17.openSync(archivePath, "r"); + const uploadOptions = (0, options_1.getUploadOptions)(options); + const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency); + const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize); + const parallelUploads = [...new Array(concurrency).keys()]; + core18.debug("Awaiting all uploads"); + let offset = 0; + try { + yield Promise.all(parallelUploads.map(() => __awaiter4(this, void 0, void 0, function* () { + while (offset < fileSize) { + const chunkSize = Math.min(fileSize - offset, maxChunkSize); + const start = offset; + const end = offset + chunkSize - 1; + offset += maxChunkSize; + yield uploadChunk(httpClient, resourceUrl, () => fs17.createReadStream(archivePath, { + fd, + start, + end, + autoClose: false + }).on("error", (error4) => { + throw new Error(`Cache upload failed because file read failed with ${error4.message}`); + }), start, end); + } + }))); + } finally { + fs17.closeSync(fd); + } + return; + }); + } + function commitCache(httpClient, cacheId, filesize) { + return __awaiter4(this, void 0, void 0, function* () { + const commitCacheRequest = { size: filesize }; + return yield (0, requestUtils_1.retryTypedResponse)("commitCache", () => __awaiter4(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); + })); + }); + } + function saveCache4(cacheId, archivePath, signedUploadURL, options) { + return __awaiter4(this, void 0, void 0, function* () { + const uploadOptions = (0, options_1.getUploadOptions)(options); + if (uploadOptions.useAzureSdk) { + if (!signedUploadURL) { + throw new Error("Azure Storage SDK can only be used when a signed URL is provided."); + } + yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options); + } else { + const httpClient = createHttpClient(); + core18.debug("Upload cache"); + yield uploadFile(httpClient, cacheId, archivePath, options); + core18.debug("Commiting cache"); + const cacheSize = utils.getArchiveFileSizeInBytes(archivePath); + core18.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); + const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); + if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) { + throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); + } + core18.info("Cache saved successfully"); + } + }); + } + exports2.saveCache = saveCache4; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js +var require_json_typings = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isJsonObject = exports2.typeofJsonValue = void 0; + function typeofJsonValue(value) { + let t = typeof value; + if (t == "object") { + if (Array.isArray(value)) + return "array"; + if (value === null) + return "null"; } - /** - * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). - * - * Retrieves a user delegation key for the Blob service. This is only a valid operation when using - * bearer token authentication. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key - * - * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time - * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time - */ - async getUserDelegationKey(startsOn, expiresOn2, options = {}) { - return tracingClient.withSpan("BlobServiceClient-getUserDelegationKey", options, async (updatedOptions) => { - const response = assertResponse(await this.serviceContext.getUserDelegationKey({ - startsOn: truncatedISO8061Date(startsOn, false), - expiresOn: truncatedISO8061Date(expiresOn2, false) - }, { - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })); - const userDelegationKey = { - signedObjectId: response.signedObjectId, - signedTenantId: response.signedTenantId, - signedStartsOn: new Date(response.signedStartsOn), - signedExpiresOn: new Date(response.signedExpiresOn), - signedService: response.signedService, - signedVersion: response.signedVersion, - value: response.value - }; - const res = Object.assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); - return res; - }); - } - /** - * Creates a BlobBatchClient object to conduct batch operations. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @returns A new BlobBatchClient object for this service. - */ - getBlobBatchClient() { - return new BlobBatchClient(this.url, this.pipeline); - } - /** - * Only available for BlobServiceClient constructed with a shared key credential. - * - * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas - * - * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. - * @param permissions - Specifies the list of permissions to be associated with the SAS. - * @param resourceTypes - Specifies the resource types associated with the shared access signature. - * @param options - Optional parameters. - * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - */ - generateAccountSasUrl(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + return t; + } + exports2.typeofJsonValue = typeofJsonValue; + function isJsonObject(value) { + return value !== null && typeof value == "object" && !Array.isArray(value); + } + exports2.isJsonObject = isJsonObject; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/base64.js +var require_base642 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/base64.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.base64encode = exports2.base64decode = void 0; + var encTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); + var decTable = []; + for (let i = 0; i < encTable.length; i++) + decTable[encTable[i].charCodeAt(0)] = i; + decTable["-".charCodeAt(0)] = encTable.indexOf("+"); + decTable["_".charCodeAt(0)] = encTable.indexOf("/"); + function base64decode(base64Str) { + let es = base64Str.length * 3 / 4; + if (base64Str[base64Str.length - 2] == "=") + es -= 2; + else if (base64Str[base64Str.length - 1] == "=") + es -= 1; + let bytes = new Uint8Array(es), bytePos = 0, groupPos = 0, b, p = 0; + for (let i = 0; i < base64Str.length; i++) { + b = decTable[base64Str.charCodeAt(i)]; + if (b === void 0) { + switch (base64Str[i]) { + case "=": + groupPos = 0; + // reset state when padding found + case "\n": + case "\r": + case " ": + case " ": + continue; + // skip white-space, and padding + default: + throw Error(`invalid base64 string.`); + } } - if (expiresOn2 === void 0) { - const now = /* @__PURE__ */ new Date(); - expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + switch (groupPos) { + case 0: + p = b; + groupPos = 1; + break; + case 1: + bytes[bytePos++] = p << 2 | (b & 48) >> 4; + p = b; + groupPos = 2; + break; + case 2: + bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; + p = b; + groupPos = 3; + break; + case 3: + bytes[bytePos++] = (p & 3) << 6 | b; + groupPos = 0; + break; } - const sas = generateAccountSASQueryParameters(Object.assign({ - permissions, - expiresOn: expiresOn2, - resourceTypes, - services: AccountSASServices.parse("b").toString() - }, options), this.credential).toString(); - return appendToURLQuery(this.url, sas); } - /** - * Only available for BlobServiceClient constructed with a shared key credential. - * - * Generates string to sign for a Blob account Shared Access Signature (SAS) URI based on - * the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas - * - * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. - * @param permissions - Specifies the list of permissions to be associated with the SAS. - * @param resourceTypes - Specifies the resource types associated with the shared access signature. - * @param options - Optional parameters. - * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - */ - generateSasStringToSign(expiresOn2, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + if (groupPos == 1) + throw Error(`invalid base64 string.`); + return bytes.subarray(0, bytePos); + } + exports2.base64decode = base64decode; + function base64encode(bytes) { + let base64 = "", groupPos = 0, b, p = 0; + for (let i = 0; i < bytes.length; i++) { + b = bytes[i]; + switch (groupPos) { + case 0: + base64 += encTable[b >> 2]; + p = (b & 3) << 4; + groupPos = 1; + break; + case 1: + base64 += encTable[p | b >> 4]; + p = (b & 15) << 2; + groupPos = 2; + break; + case 2: + base64 += encTable[p | b >> 6]; + base64 += encTable[b & 63]; + groupPos = 0; + break; } - if (expiresOn2 === void 0) { - const now = /* @__PURE__ */ new Date(); - expiresOn2 = new Date(now.getTime() + 3600 * 1e3); + } + if (groupPos) { + base64 += encTable[p]; + base64 += "="; + if (groupPos == 1) + base64 += "="; + } + return base64; + } + exports2.base64encode = base64encode; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js +var require_protobufjs_utf8 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.utf8read = void 0; + var fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); + function utf8read(bytes) { + if (bytes.length < 1) + return ""; + let pos = 0, parts = [], chunk = [], i = 0, t; + let len = bytes.length; + while (pos < len) { + t = bytes[pos++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 65536; + chunk[i++] = 55296 + (t >> 10); + chunk[i++] = 56320 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; + if (i > 8191) { + parts.push(fromCharCodes(chunk)); + i = 0; } - return generateAccountSASQueryParametersInternal(Object.assign({ - permissions, - expiresOn: expiresOn2, - resourceTypes, - services: AccountSASServices.parse("b").toString() - }, options), this.credential).stringToSign; } - }; - exports2.KnownEncryptionAlgorithmType = void 0; - (function(KnownEncryptionAlgorithmType) { - KnownEncryptionAlgorithmType["AES256"] = "AES256"; - })(exports2.KnownEncryptionAlgorithmType || (exports2.KnownEncryptionAlgorithmType = {})); - Object.defineProperty(exports2, "RestError", { - enumerable: true, - get: function() { - return coreRestPipeline.RestError; + if (parts.length) { + if (i) + parts.push(fromCharCodes(chunk.slice(0, i))); + return parts.join(""); } - }); - exports2.AccountSASPermissions = AccountSASPermissions; - exports2.AccountSASResourceTypes = AccountSASResourceTypes; - exports2.AccountSASServices = AccountSASServices; - exports2.AnonymousCredential = AnonymousCredential; - exports2.AnonymousCredentialPolicy = AnonymousCredentialPolicy; - exports2.AppendBlobClient = AppendBlobClient; - exports2.BaseRequestPolicy = BaseRequestPolicy; - exports2.BlobBatch = BlobBatch; - exports2.BlobBatchClient = BlobBatchClient; - exports2.BlobClient = BlobClient; - exports2.BlobLeaseClient = BlobLeaseClient; - exports2.BlobSASPermissions = BlobSASPermissions; - exports2.BlobServiceClient = BlobServiceClient; - exports2.BlockBlobClient = BlockBlobClient; - exports2.ContainerClient = ContainerClient; - exports2.ContainerSASPermissions = ContainerSASPermissions; - exports2.Credential = Credential; - exports2.CredentialPolicy = CredentialPolicy; - exports2.PageBlobClient = PageBlobClient; - exports2.Pipeline = Pipeline; - exports2.SASQueryParameters = SASQueryParameters; - exports2.StorageBrowserPolicy = StorageBrowserPolicy; - exports2.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; - exports2.StorageOAuthScopes = StorageOAuthScopes; - exports2.StorageRetryPolicy = StorageRetryPolicy; - exports2.StorageRetryPolicyFactory = StorageRetryPolicyFactory; - exports2.StorageSharedKeyCredential = StorageSharedKeyCredential; - exports2.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; - exports2.generateAccountSASQueryParameters = generateAccountSASQueryParameters; - exports2.generateBlobSASQueryParameters = generateBlobSASQueryParameters; - exports2.getBlobServiceAccountAudience = getBlobServiceAccountAudience; - exports2.isPipelineLike = isPipelineLike; - exports2.logger = logger; - exports2.newPipeline = newPipeline; + return fromCharCodes(chunk.slice(0, i)); + } + exports2.utf8read = utf8read; } }); -// node_modules/@actions/cache/lib/internal/shared/errors.js -var require_errors2 = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/errors.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js +var require_binary_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UsageError = exports2.NetworkError = exports2.GHESNotSupportedError = exports2.CacheNotFoundError = exports2.InvalidResponseError = exports2.FilesNotFoundError = void 0; - var FilesNotFoundError = class extends Error { - constructor(files = []) { - let message = "No files were found to upload"; - if (files.length > 0) { - message += `: ${files.join(", ")}`; + exports2.WireType = exports2.mergeBinaryOptions = exports2.UnknownFieldHandler = void 0; + var UnknownFieldHandler; + (function(UnknownFieldHandler2) { + UnknownFieldHandler2.symbol = Symbol.for("protobuf-ts/unknown"); + UnknownFieldHandler2.onRead = (typeName, message, fieldNo, wireType, data) => { + let container = is(message) ? message[UnknownFieldHandler2.symbol] : message[UnknownFieldHandler2.symbol] = []; + container.push({ no: fieldNo, wireType, data }); + }; + UnknownFieldHandler2.onWrite = (typeName, message, writer) => { + for (let { no, wireType, data } of UnknownFieldHandler2.list(message)) + writer.tag(no, wireType).raw(data); + }; + UnknownFieldHandler2.list = (message, fieldNo) => { + if (is(message)) { + let all = message[UnknownFieldHandler2.symbol]; + return fieldNo ? all.filter((uf) => uf.no == fieldNo) : all; + } + return []; + }; + UnknownFieldHandler2.last = (message, fieldNo) => UnknownFieldHandler2.list(message, fieldNo).slice(-1)[0]; + const is = (message) => message && Array.isArray(message[UnknownFieldHandler2.symbol]); + })(UnknownFieldHandler = exports2.UnknownFieldHandler || (exports2.UnknownFieldHandler = {})); + function mergeBinaryOptions(a, b) { + return Object.assign(Object.assign({}, a), b); + } + exports2.mergeBinaryOptions = mergeBinaryOptions; + var WireType; + (function(WireType2) { + WireType2[WireType2["Varint"] = 0] = "Varint"; + WireType2[WireType2["Bit64"] = 1] = "Bit64"; + WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited"; + WireType2[WireType2["StartGroup"] = 3] = "StartGroup"; + WireType2[WireType2["EndGroup"] = 4] = "EndGroup"; + WireType2[WireType2["Bit32"] = 5] = "Bit32"; + })(WireType = exports2.WireType || (exports2.WireType = {})); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js +var require_goog_varint = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.varint32read = exports2.varint32write = exports2.int64toString = exports2.int64fromString = exports2.varint64write = exports2.varint64read = void 0; + function varint64read() { + let lowBits = 0; + let highBits = 0; + for (let shift = 0; shift < 28; shift += 7) { + let b = this.buf[this.pos++]; + lowBits |= (b & 127) << shift; + if ((b & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; } - super(message); - this.files = files; - this.name = "FilesNotFoundError"; } - }; - exports2.FilesNotFoundError = FilesNotFoundError; - var InvalidResponseError = class extends Error { - constructor(message) { - super(message); - this.name = "InvalidResponseError"; + let middleByte = this.buf[this.pos++]; + lowBits |= (middleByte & 15) << 28; + highBits = (middleByte & 112) >> 4; + if ((middleByte & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; } - }; - exports2.InvalidResponseError = InvalidResponseError; - var CacheNotFoundError = class extends Error { - constructor(message = "Cache not found") { - super(message); - this.name = "CacheNotFoundError"; + for (let shift = 3; shift <= 31; shift += 7) { + let b = this.buf[this.pos++]; + highBits |= (b & 127) << shift; + if ((b & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } } - }; - exports2.CacheNotFoundError = CacheNotFoundError; - var GHESNotSupportedError = class extends Error { - constructor(message = "@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.") { - super(message); - this.name = "GHESNotSupportedError"; + throw new Error("invalid varint"); + } + exports2.varint64read = varint64read; + function varint64write(lo, hi, bytes) { + for (let i = 0; i < 28; i = i + 7) { + const shift = lo >>> i; + const hasNext = !(shift >>> 7 == 0 && hi == 0); + const byte = (hasNext ? shift | 128 : shift) & 255; + bytes.push(byte); + if (!hasNext) { + return; + } } - }; - exports2.GHESNotSupportedError = GHESNotSupportedError; - var NetworkError = class extends Error { - constructor(code) { - const message = `Unable to make request: ${code} -If you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`; - super(message); - this.code = code; - this.name = "NetworkError"; + const splitBits = lo >>> 28 & 15 | (hi & 7) << 4; + const hasMoreBits = !(hi >> 3 == 0); + bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255); + if (!hasMoreBits) { + return; } - }; - exports2.NetworkError = NetworkError; - NetworkError.isNetworkErrorCode = (code) => { - if (!code) - return false; - return [ - "ECONNRESET", - "ENOTFOUND", - "ETIMEDOUT", - "ECONNREFUSED", - "EHOSTUNREACH" - ].includes(code); - }; - var UsageError = class extends Error { - constructor() { - const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours. -More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; - super(message); - this.name = "UsageError"; + for (let i = 3; i < 31; i = i + 7) { + const shift = hi >>> i; + const hasNext = !(shift >>> 7 == 0); + const byte = (hasNext ? shift | 128 : shift) & 255; + bytes.push(byte); + if (!hasNext) { + return; + } } - }; - exports2.UsageError = UsageError; - UsageError.isUsageErrorMessage = (msg) => { - if (!msg) - return false; - return msg.includes("insufficient usage"); - }; + bytes.push(hi >>> 31 & 1); + } + exports2.varint64write = varint64write; + var TWO_PWR_32_DBL2 = (1 << 16) * (1 << 16); + function int64fromString(dec) { + let minus = dec[0] == "-"; + if (minus) + dec = dec.slice(1); + const base = 1e6; + let lowBits = 0; + let highBits = 0; + function add1e6digit(begin, end) { + const digit1e6 = Number(dec.slice(begin, end)); + highBits *= base; + lowBits = lowBits * base + digit1e6; + if (lowBits >= TWO_PWR_32_DBL2) { + highBits = highBits + (lowBits / TWO_PWR_32_DBL2 | 0); + lowBits = lowBits % TWO_PWR_32_DBL2; + } + } + add1e6digit(-24, -18); + add1e6digit(-18, -12); + add1e6digit(-12, -6); + add1e6digit(-6); + return [minus, lowBits, highBits]; + } + exports2.int64fromString = int64fromString; + function int64toString(bitsLow, bitsHigh) { + if (bitsHigh >>> 0 <= 2097151) { + return "" + (TWO_PWR_32_DBL2 * bitsHigh + (bitsLow >>> 0)); + } + let low = bitsLow & 16777215; + let mid = (bitsLow >>> 24 | bitsHigh << 8) >>> 0 & 16777215; + let high = bitsHigh >> 16 & 65535; + let digitA = low + mid * 6777216 + high * 6710656; + let digitB = mid + high * 8147497; + let digitC = high * 2; + let base = 1e7; + if (digitA >= base) { + digitB += Math.floor(digitA / base); + digitA %= base; + } + if (digitB >= base) { + digitC += Math.floor(digitB / base); + digitB %= base; + } + function decimalFrom1e7(digit1e7, needLeadingZeros) { + let partial = digit1e7 ? String(digit1e7) : ""; + if (needLeadingZeros) { + return "0000000".slice(partial.length) + partial; + } + return partial; + } + return decimalFrom1e7( + digitC, + /*needLeadingZeros=*/ + 0 + ) + decimalFrom1e7( + digitB, + /*needLeadingZeros=*/ + digitC + ) + // If the final 1e7 digit didn't need leading zeros, we would have + // returned via the trivial code path at the top. + decimalFrom1e7( + digitA, + /*needLeadingZeros=*/ + 1 + ); + } + exports2.int64toString = int64toString; + function varint32write(value, bytes) { + if (value >= 0) { + while (value > 127) { + bytes.push(value & 127 | 128); + value = value >>> 7; + } + bytes.push(value); + } else { + for (let i = 0; i < 9; i++) { + bytes.push(value & 127 | 128); + value = value >> 7; + } + bytes.push(1); + } + } + exports2.varint32write = varint32write; + function varint32read() { + let b = this.buf[this.pos++]; + let result = b & 127; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 7; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 14; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 21; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 15) << 28; + for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++) + b = this.buf[this.pos++]; + if ((b & 128) != 0) + throw new Error("invalid varint"); + this.assertBounds(); + return result >>> 0; + } + exports2.varint32read = varint32read; } }); -// node_modules/@actions/cache/lib/internal/uploadUtils.js -var require_uploadUtils = __commonJS({ - "node_modules/@actions/cache/lib/internal/uploadUtils.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js +var require_pb_long = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PbLong = exports2.PbULong = exports2.detectBi = void 0; + var goog_varint_1 = require_goog_varint(); + var BI; + function detectBi() { + const dv = new DataView(new ArrayBuffer(8)); + const ok = globalThis.BigInt !== void 0 && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function"; + BI = ok ? { + MIN: BigInt("-9223372036854775808"), + MAX: BigInt("9223372036854775807"), + UMIN: BigInt("0"), + UMAX: BigInt("18446744073709551615"), + C: BigInt, + V: dv + } : void 0; + } + exports2.detectBi = detectBi; + detectBi(); + function assertBi(bi) { + if (!bi) + throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); + } + var RE_DECIMAL_STR = /^-?[0-9]+$/; + var TWO_PWR_32_DBL2 = 4294967296; + var HALF_2_PWR_32 = 2147483648; + var SharedPbLong = class { + /** + * Create a new instance with the given bits. + */ + constructor(lo, hi) { + this.lo = lo | 0; + this.hi = hi | 0; } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); + /** + * Is this instance equal to 0? + */ + isZero() { + return this.lo == 0 && this.hi == 0; } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + /** + * Convert to a native number. + */ + toNumber() { + let result = this.hi * TWO_PWR_32_DBL2 + (this.lo >>> 0); + if (!Number.isSafeInteger(result)) + throw new Error("cannot convert to safe number"); + return result; + } + }; + var PbULong = class _PbULong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error("string is no integer"); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.UMIN) + throw new Error("signed value for ulong"); + if (value > BI.UMAX) + throw new Error("ulong too large"); + BI.V.setBigUint64(0, value, true); + return new _PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error("string is no integer"); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) + throw new Error("signed value for ulong"); + return new _PbULong(lo, hi); + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error("number is no integer"); + if (value < 0) + throw new Error("signed value for ulong"); + return new _PbULong(value, value / TWO_PWR_32_DBL2); } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uploadCacheArchiveSDK = exports2.UploadProgress = void 0; - var core18 = __importStar4(require_core()); - var storage_blob_1 = require_dist7(); - var errors_1 = require_errors2(); - var UploadProgress = class { - constructor(contentLength) { - this.contentLength = contentLength; - this.sentBytes = 0; - this.displayedComplete = false; - this.startTime = Date.now(); + throw new Error("unknown value " + typeof value); } /** - * Sets the number of bytes sent - * - * @param sentBytes the number of bytes sent + * Convert to decimal string. */ - setSentBytes(sentBytes) { - this.sentBytes = sentBytes; + toString() { + return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); } /** - * Returns the total number of bytes transferred. + * Convert to native bigint. */ - getTransferredBytes() { - return this.sentBytes; + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigUint64(0, true); } + }; + exports2.PbULong = PbULong; + PbULong.ZERO = new PbULong(0, 0); + var PbLong = class _PbLong extends SharedPbLong { /** - * Returns true if the upload is complete. + * Create instance from a `string`, `number` or `bigint`. */ - isDone() { - return this.getTransferredBytes() === this.contentLength; + static from(value) { + if (BI) + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error("string is no integer"); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.MIN) + throw new Error("signed long too small"); + if (value > BI.MAX) + throw new Error("signed long too large"); + BI.V.setBigInt64(0, value, true); + return new _PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + } + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error("string is no integer"); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) { + if (hi > HALF_2_PWR_32 || hi == HALF_2_PWR_32 && lo != 0) + throw new Error("signed long too small"); + } else if (hi >= HALF_2_PWR_32) + throw new Error("signed long too large"); + let pbl = new _PbLong(lo, hi); + return minus ? pbl.negate() : pbl; + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error("number is no integer"); + return value > 0 ? new _PbLong(value, value / TWO_PWR_32_DBL2) : new _PbLong(-value, -value / TWO_PWR_32_DBL2).negate(); + } + throw new Error("unknown value " + typeof value); } /** - * Prints the current upload stats. Once the upload completes, this will print one - * last line and then stop. + * Do we have a minus sign? */ - display() { - if (this.displayedComplete) { - return; - } - const transferredBytes = this.sentBytes; - const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); - const elapsedTime = Date.now() - this.startTime; - const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); - core18.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`); - if (this.isDone()) { - this.displayedComplete = true; - } + isNegative() { + return (this.hi & HALF_2_PWR_32) !== 0; } /** - * Returns a function used to handle TransferProgressEvents. + * Negate two's complement. + * Invert all the bits and add one to the result. */ - onProgress() { - return (progress) => { - this.setSentBytes(progress.loadedBytes); - }; + negate() { + let hi = ~this.hi, lo = this.lo; + if (lo) + lo = ~lo + 1; + else + hi += 1; + return new _PbLong(lo, hi); } /** - * Starts the timer that displays the stats. - * - * @param delayInMs the delay between each write + * Convert to decimal string. */ - startDisplayTimer(delayInMs = 1e3) { - const displayCallback = () => { - this.display(); - if (!this.isDone()) { - this.timeoutHandle = setTimeout(displayCallback, delayInMs); - } - }; - this.timeoutHandle = setTimeout(displayCallback, delayInMs); + toString() { + if (BI) + return this.toBigInt().toString(); + if (this.isNegative()) { + let n = this.negate(); + return "-" + goog_varint_1.int64toString(n.lo, n.hi); + } + return goog_varint_1.int64toString(this.lo, this.hi); } /** - * Stops the timer that displays the stats. As this typically indicates the upload - * is complete, this will display one last line, unless the last line has already - * been written. + * Convert to native bigint. */ - stopDisplayTimer() { - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - this.timeoutHandle = void 0; - } - this.display(); + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigInt64(0, true); } }; - exports2.UploadProgress = UploadProgress; - function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) { - var _a; - return __awaiter4(this, void 0, void 0, function* () { - const blobClient = new storage_blob_1.BlobClient(signedUploadURL); - const blockBlobClient = blobClient.getBlockBlobClient(); - const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0); - const uploadOptions = { - blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize, - concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency, - maxSingleShotSize: 128 * 1024 * 1024, - onProgress: uploadProgress.onProgress() - }; - try { - uploadProgress.startDisplayTimer(); - core18.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`); - const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions); - if (response._response.status >= 400) { - throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`); - } - return response; - } catch (error4) { - core18.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error4.message}`); - throw error4; - } finally { - uploadProgress.stopDisplayTimer(); - } - }); - } - exports2.uploadCacheArchiveSDK = uploadCacheArchiveSDK; + exports2.PbLong = PbLong; + PbLong.ZERO = new PbLong(0, 0); } }); -// node_modules/@actions/cache/lib/internal/requestUtils.js -var require_requestUtils = __commonJS({ - "node_modules/@actions/cache/lib/internal/requestUtils.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js +var require_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; - var core18 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var constants_1 = require_constants7(); - function isSuccessStatusCode(statusCode) { - if (!statusCode) { - return false; - } - return statusCode >= 200 && statusCode < 300; + exports2.BinaryReader = exports2.binaryReadOptions = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var defaultsRead = { + readUnknownField: true, + readerFactory: (bytes) => new BinaryReader(bytes) + }; + function binaryReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } - exports2.isSuccessStatusCode = isSuccessStatusCode; - function isServerErrorStatusCode(statusCode) { - if (!statusCode) { - return true; + exports2.binaryReadOptions = binaryReadOptions; + var BinaryReader = class { + constructor(buf, textDecoder) { + this.varint64 = goog_varint_1.varint64read; + this.uint32 = goog_varint_1.varint32read; + this.buf = buf; + this.len = buf.length; + this.pos = 0; + this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true + }); } - return statusCode >= 500; - } - exports2.isServerErrorStatusCode = isServerErrorStatusCode; - function isRetryableStatusCode(statusCode) { - if (!statusCode) { - return false; + /** + * Reads a tag - field number and wire type. + */ + tag() { + let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; + if (fieldNo <= 0 || wireType < 0 || wireType > 5) + throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); + return [fieldNo, wireType]; } - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.GatewayTimeout - ]; - return retryableStatusCodes.includes(statusCode); - } - exports2.isRetryableStatusCode = isRetryableStatusCode; - function sleep(milliseconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve8) => setTimeout(resolve8, milliseconds)); - }); - } - function retry3(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay2 = constants_1.DefaultRetryDelay, onError = void 0) { - return __awaiter4(this, void 0, void 0, function* () { - let errorMessage = ""; - let attempt = 1; - while (attempt <= maxAttempts) { - let response = void 0; - let statusCode = void 0; - let isRetryable = false; - try { - response = yield method(); - } catch (error4) { - if (onError) { - response = onError(error4); + /** + * Skip one element on the wire and return the skipped data. + * Supports WireType.StartGroup since v2.0.0-alpha.23. + */ + skip(wireType) { + let start = this.pos; + switch (wireType) { + case binary_format_contract_1.WireType.Varint: + while (this.buf[this.pos++] & 128) { } - isRetryable = true; - errorMessage = error4.message; - } - if (response) { - statusCode = getStatusCode(response); - if (!isServerErrorStatusCode(statusCode)) { - return response; + break; + case binary_format_contract_1.WireType.Bit64: + this.pos += 4; + case binary_format_contract_1.WireType.Bit32: + this.pos += 4; + break; + case binary_format_contract_1.WireType.LengthDelimited: + let len = this.uint32(); + this.pos += len; + break; + case binary_format_contract_1.WireType.StartGroup: + let t; + while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { + this.skip(t); } - } - if (statusCode) { - isRetryable = isRetryableStatusCode(statusCode); - errorMessage = `Cache service responded with ${statusCode}`; - } - core18.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); - if (!isRetryable) { - core18.debug(`${name} - Error is not retryable`); break; - } - yield sleep(delay2); - attempt++; + default: + throw new Error("cant skip wire type " + wireType); } - throw Error(`${name} failed: ${errorMessage}`); - }); - } - exports2.retry = retry3; - function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay2 = constants_1.DefaultRetryDelay) { - return __awaiter4(this, void 0, void 0, function* () { - return yield retry3( - name, - method, - (response) => response.statusCode, - maxAttempts, - delay2, - // If the error object contains the statusCode property, extract it and return - // an TypedResponse so it can be processed by the retry logic. - (error4) => { - if (error4 instanceof http_client_1.HttpClientError) { - return { - statusCode: error4.statusCode, - result: null, - headers: {}, - error: error4 - }; - } else { - return void 0; - } - } - ); - }); - } - exports2.retryTypedResponse = retryTypedResponse; - function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay2 = constants_1.DefaultRetryDelay) { - return __awaiter4(this, void 0, void 0, function* () { - return yield retry3(name, method, (response) => response.message.statusCode, maxAttempts, delay2); - }); - } - exports2.retryHttpClientResponse = retryHttpClientResponse; - } -}); - -// node_modules/@actions/cache/lib/internal/downloadUtils.js -var require_downloadUtils = __commonJS({ - "node_modules/@actions/cache/lib/internal/downloadUtils.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + this.assertBounds(); + return this.buf.subarray(start, this.pos); + } + /** + * Throws error if position in byte array is out of range. + */ + assertBounds() { + if (this.pos > this.len) + throw new RangeError("premature EOF"); + } + /** + * Read a `int32` field, a signed 32 bit varint. + */ + int32() { + return this.uint32() | 0; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + /** + * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. + */ + sint32() { + let zze = this.uint32(); + return zze >>> 1 ^ -(zze & 1); } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); + /** + * Read a `int64` field, a signed 64-bit varint. + */ + int64() { + return new pb_long_1.PbLong(...this.varint64()); } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; - var core18 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var storage_blob_1 = require_dist7(); - var buffer = __importStar4(require("buffer")); - var fs17 = __importStar4(require("fs")); - var stream2 = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var utils = __importStar4(require_cacheUtils()); - var constants_1 = require_constants7(); - var requestUtils_1 = require_requestUtils(); - var abort_controller_1 = require_dist5(); - function pipeResponseToStream(response, output) { - return __awaiter4(this, void 0, void 0, function* () { - const pipeline = util.promisify(stream2.pipeline); - yield pipeline(response.message, output); - }); - } - var DownloadProgress = class { - constructor(contentLength) { - this.contentLength = contentLength; - this.segmentIndex = 0; - this.segmentSize = 0; - this.segmentOffset = 0; - this.receivedBytes = 0; - this.displayedComplete = false; - this.startTime = Date.now(); + /** + * Read a `uint64` field, an unsigned 64-bit varint. + */ + uint64() { + return new pb_long_1.PbULong(...this.varint64()); } /** - * Progress to the next segment. Only call this method when the previous segment - * is complete. - * - * @param segmentSize the length of the next segment + * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. */ - nextSegment(segmentSize) { - this.segmentOffset = this.segmentOffset + this.segmentSize; - this.segmentIndex = this.segmentIndex + 1; - this.segmentSize = segmentSize; - this.receivedBytes = 0; - core18.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); + sint64() { + let [lo, hi] = this.varint64(); + let s = -(lo & 1); + lo = (lo >>> 1 | (hi & 1) << 31) ^ s; + hi = hi >>> 1 ^ s; + return new pb_long_1.PbLong(lo, hi); } /** - * Sets the number of bytes received for the current segment. - * - * @param receivedBytes the number of bytes received + * Read a `bool` field, a variant. */ - setReceivedBytes(receivedBytes) { - this.receivedBytes = receivedBytes; + bool() { + let [lo, hi] = this.varint64(); + return lo !== 0 || hi !== 0; } /** - * Returns the total number of bytes transferred. + * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. */ - getTransferredBytes() { - return this.segmentOffset + this.receivedBytes; + fixed32() { + return this.view.getUint32((this.pos += 4) - 4, true); } /** - * Returns true if the download is complete. + * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. */ - isDone() { - return this.getTransferredBytes() === this.contentLength; + sfixed32() { + return this.view.getInt32((this.pos += 4) - 4, true); } /** - * Prints the current download stats. Once the download completes, this will print one - * last line and then stop. + * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. */ - display() { - if (this.displayedComplete) { - return; - } - const transferredBytes = this.segmentOffset + this.receivedBytes; - const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); - const elapsedTime = Date.now() - this.startTime; - const downloadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1); - core18.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); - if (this.isDone()) { - this.displayedComplete = true; - } + fixed64() { + return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); } /** - * Returns a function used to handle TransferProgressEvents. + * Read a `fixed64` field, a signed, fixed-length 64-bit integer. */ - onProgress() { - return (progress) => { - this.setReceivedBytes(progress.loadedBytes); - }; + sfixed64() { + return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); } /** - * Starts the timer that displays the stats. - * - * @param delayInMs the delay between each write + * Read a `float` field, 32-bit floating point number. */ - startDisplayTimer(delayInMs = 1e3) { - const displayCallback = () => { - this.display(); - if (!this.isDone()) { - this.timeoutHandle = setTimeout(displayCallback, delayInMs); - } - }; - this.timeoutHandle = setTimeout(displayCallback, delayInMs); + float() { + return this.view.getFloat32((this.pos += 4) - 4, true); } /** - * Stops the timer that displays the stats. As this typically indicates the download - * is complete, this will display one last line, unless the last line has already - * been written. + * Read a `double` field, a 64-bit floating point number. */ - stopDisplayTimer() { - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - this.timeoutHandle = void 0; - } - this.display(); + double() { + return this.view.getFloat64((this.pos += 8) - 8, true); + } + /** + * Read a `bytes` field, length-delimited arbitrary data. + */ + bytes() { + let len = this.uint32(); + let start = this.pos; + this.pos += len; + this.assertBounds(); + return this.buf.subarray(start, start + len); + } + /** + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); } }; - exports2.DownloadProgress = DownloadProgress; - function downloadCacheHttpClient(archiveLocation, archivePath) { - return __awaiter4(this, void 0, void 0, function* () { - const writeStream = fs17.createWriteStream(archivePath); - const httpClient = new http_client_1.HttpClient("actions/cache"); - const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.get(archiveLocation); - })); - downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { - downloadResponse.message.destroy(); - core18.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); - }); - yield pipeResponseToStream(downloadResponse, writeStream); - const contentLengthHeader = downloadResponse.message.headers["content-length"]; - if (contentLengthHeader) { - const expectedLength = parseInt(contentLengthHeader); - const actualLength = utils.getArchiveFileSizeInBytes(archivePath); - if (actualLength !== expectedLength) { - throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); - } - } else { - core18.debug("Unable to validate download, no Content-Length header"); - } - }); + exports2.BinaryReader = BinaryReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js +var require_assert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; + function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } } - exports2.downloadCacheHttpClient = downloadCacheHttpClient; - function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { - var _a; - return __awaiter4(this, void 0, void 0, function* () { - const archiveDescriptor = yield fs17.promises.open(archivePath, "w"); - const httpClient = new http_client_1.HttpClient("actions/cache", void 0, { - socketTimeout: options.timeoutInMs, - keepAlive: true - }); - try { - const res = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCacheMetadata", () => __awaiter4(this, void 0, void 0, function* () { - return yield httpClient.request("HEAD", archiveLocation, null, {}); - })); - const lengthHeader = res.message.headers["content-length"]; - if (lengthHeader === void 0 || lengthHeader === null) { - throw new Error("Content-Length not found on blob response"); - } - const length = parseInt(lengthHeader); - if (Number.isNaN(length)) { - throw new Error(`Could not interpret Content-Length: ${length}`); - } - const downloads = []; - const blockSize = 4 * 1024 * 1024; - for (let offset = 0; offset < length; offset += blockSize) { - const count = Math.min(blockSize, length - offset); - downloads.push({ - offset, - promiseGetter: () => __awaiter4(this, void 0, void 0, function* () { - return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count); - }) - }); - } - downloads.reverse(); - let actives = 0; - let bytesDownloaded = 0; - const progress = new DownloadProgress(length); - progress.startDisplayTimer(); - const progressFn = progress.onProgress(); - const activeDownloads = []; - let nextDownload; - const waitAndWrite = () => __awaiter4(this, void 0, void 0, function* () { - const segment = yield Promise.race(Object.values(activeDownloads)); - yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset); - actives--; - delete activeDownloads[segment.offset]; - bytesDownloaded += segment.count; - progressFn({ loadedBytes: bytesDownloaded }); - }); - while (nextDownload = downloads.pop()) { - activeDownloads[nextDownload.offset] = nextDownload.promiseGetter(); - actives++; - if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) { - yield waitAndWrite(); - } - } - while (actives > 0) { - yield waitAndWrite(); - } - } finally { - httpClient.dispose(); - yield archiveDescriptor.close(); - } - }); + exports2.assert = assert; + function assertNever2(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); } - exports2.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent; - function downloadSegmentRetry(httpClient, archiveLocation, offset, count) { - return __awaiter4(this, void 0, void 0, function* () { - const retries = 5; - let failures = 0; - while (true) { - try { - const timeout = 3e4; - const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count)); - if (typeof result === "string") { - throw new Error("downloadSegmentRetry failed due to timeout"); - } - return result; - } catch (err) { - if (failures >= retries) { - throw err; - } - failures++; - } - } - }); + exports2.assertNever = assertNever2; + var FLOAT32_MAX = 34028234663852886e22; + var FLOAT32_MIN = -34028234663852886e22; + var UINT32_MAX = 4294967295; + var INT32_MAX = 2147483647; + var INT32_MIN = -2147483648; + function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid int 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error("invalid int 32: " + arg); } - function downloadSegment(httpClient, archiveLocation, offset, count) { - return __awaiter4(this, void 0, void 0, function* () { - const partRes = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCachePart", () => __awaiter4(this, void 0, void 0, function* () { - return yield httpClient.get(archiveLocation, { - Range: `bytes=${offset}-${offset + count - 1}` - }); - })); - if (!partRes.readBodyBuffer) { - throw new Error("Expected HttpClientResponse to implement readBodyBuffer"); - } - return { - offset, - count, - buffer: yield partRes.readBodyBuffer() - }; - }); + exports2.assertInt32 = assertInt32; + function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid uint 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error("invalid uint 32: " + arg); } - function downloadCacheStorageSDK(archiveLocation, archivePath, options) { - var _a; - return __awaiter4(this, void 0, void 0, function* () { - const client = new storage_blob_1.BlockBlobClient(archiveLocation, void 0, { - retryOptions: { - // Override the timeout used when downloading each 4 MB chunk - // The default is 2 min / MB, which is way too slow - tryTimeoutInMs: options.timeoutInMs - } - }); - const properties = yield client.getProperties(); - const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; - if (contentLength < 0) { - core18.debug("Unable to determine content length, downloading file with http-client..."); - yield downloadCacheHttpClient(archiveLocation, archivePath); - } else { - const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); - const downloadProgress = new DownloadProgress(contentLength); - const fd = fs17.openSync(archivePath, "w"); - try { - downloadProgress.startDisplayTimer(); - const controller = new abort_controller_1.AbortController(); - const abortSignal = controller.signal; - while (!downloadProgress.isDone()) { - const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; - const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); - downloadProgress.nextSegment(segmentSize); - const result = yield promiseWithTimeout(options.segmentTimeoutInMs || 36e5, client.downloadToBuffer(segmentStart, segmentSize, { - abortSignal, - concurrency: options.downloadConcurrency, - onProgress: downloadProgress.onProgress() - })); - if (result === "timeout") { - controller.abort(); - throw new Error("Aborting cache download as the download time exceeded the timeout."); - } else if (Buffer.isBuffer(result)) { - fs17.writeFileSync(fd, result); - } - } - } finally { - downloadProgress.stopDisplayTimer(); - fs17.closeSync(fd); - } - } - }); + exports2.assertUInt32 = assertUInt32; + function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error("invalid float 32: " + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error("invalid float 32: " + arg); } - exports2.downloadCacheStorageSDK = downloadCacheStorageSDK; - var promiseWithTimeout = (timeoutMs, promise) => __awaiter4(void 0, void 0, void 0, function* () { - let timeoutHandle; - const timeoutPromise = new Promise((resolve8) => { - timeoutHandle = setTimeout(() => resolve8("timeout"), timeoutMs); - }); - return Promise.race([promise, timeoutPromise]).then((result) => { - clearTimeout(timeoutHandle); - return result; - }); - }); + exports2.assertFloat32 = assertFloat32; } }); -// node_modules/@actions/cache/lib/options.js -var require_options = __commonJS({ - "node_modules/@actions/cache/lib/options.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js +var require_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var assert_1 = require_assert(); + var defaultsWrite = { + writeUnknownFields: true, + writerFactory: () => new BinaryWriter() + }; + function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.binaryWriteOptions = binaryWriteOptions; + var BinaryWriter = class { + constructor(textEncoder) { + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; + } + this.chunks = []; + return bytes; + } + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; + } + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + let chunk = this.finish(); + let prev = this.stack.pop(); + if (!prev) + throw new Error("invalid state, fork stack empty"); + this.chunks = prev.chunks; + this.buf = prev.buf; + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type2) { + return this.uint32((fieldNo << 3 | type2) >>> 0); } - __setModuleDefault4(result, mod); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getDownloadOptions = exports2.getUploadOptions = void 0; - var core18 = __importStar4(require_core()); - function getUploadOptions(copy) { - const result = { - useAzureSdk: false, - uploadConcurrency: 4, - uploadChunkSize: 32 * 1024 * 1024 - }; - if (copy) { - if (typeof copy.useAzureSdk === "boolean") { - result.useAzureSdk = copy.useAzureSdk; - } - if (typeof copy.uploadConcurrency === "number") { - result.uploadConcurrency = copy.uploadConcurrency; - } - if (typeof copy.uploadChunkSize === "number") { - result.uploadChunkSize = copy.uploadChunkSize; + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; } + this.chunks.push(chunk); + return this; } - result.uploadConcurrency = !isNaN(Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) ? Math.min(32, Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) : result.uploadConcurrency; - result.uploadChunkSize = !isNaN(Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"])) ? Math.min(128 * 1024 * 1024, Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"]) * 1024 * 1024) : result.uploadChunkSize; - core18.debug(`Use Azure SDK: ${result.useAzureSdk}`); - core18.debug(`Upload concurrency: ${result.uploadConcurrency}`); - core18.debug(`Upload chunk size: ${result.uploadChunkSize}`); - return result; - } - exports2.getUploadOptions = getUploadOptions; - function getDownloadOptions(copy) { - const result = { - useAzureSdk: false, - concurrentBlobDownloads: true, - downloadConcurrency: 8, - timeoutInMs: 3e4, - segmentTimeoutInMs: 6e5, - lookupOnly: false - }; - if (copy) { - if (typeof copy.useAzureSdk === "boolean") { - result.useAzureSdk = copy.useAzureSdk; - } - if (typeof copy.concurrentBlobDownloads === "boolean") { - result.concurrentBlobDownloads = copy.concurrentBlobDownloads; - } - if (typeof copy.downloadConcurrency === "number") { - result.downloadConcurrency = copy.downloadConcurrency; - } - if (typeof copy.timeoutInMs === "number") { - result.timeoutInMs = copy.timeoutInMs; - } - if (typeof copy.segmentTimeoutInMs === "number") { - result.segmentTimeoutInMs = copy.segmentTimeoutInMs; - } - if (typeof copy.lookupOnly === "boolean") { - result.lookupOnly = copy.lookupOnly; + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); + while (value > 127) { + this.buf.push(value & 127 | 128); + value = value >>> 7; } + this.buf.push(value); + return this; } - const segmentDownloadTimeoutMins = process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]; - if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) { - result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1e3; + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; } - core18.debug(`Use Azure SDK: ${result.useAzureSdk}`); - core18.debug(`Download concurrency: ${result.downloadConcurrency}`); - core18.debug(`Request timeout (ms): ${result.timeoutInMs}`); - core18.debug(`Cache segment download timeout mins env var: ${process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]}`); - core18.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`); - core18.debug(`Lookup only: ${result.lookupOnly}`); - return result; - } - exports2.getDownloadOptions = getDownloadOptions; + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; + } + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); + return this.raw(value); + } + /** + * Write a `string` value, length-delimited data converted to UTF-8 text. + */ + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Write a `float` value, 32-bit floating point number. + */ + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `double` value, a 64-bit floating point number. + */ + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); + } + /** + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + */ + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + */ + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + */ + sint32(value) { + assert_1.assertInt32(value); + value = (value << 1 ^ value >> 31) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + */ + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + */ + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `int64` value, a signed 64-bit varint. + */ + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + /** + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + */ + sint64(value) { + let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; + } + /** + * Write a `uint64` value, an unsigned 64-bit varint. + */ + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + }; + exports2.BinaryWriter = BinaryWriter; } }); -// node_modules/@actions/cache/lib/internal/config.js -var require_config = __commonJS({ - "node_modules/@actions/cache/lib/internal/config.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js +var require_json_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getCacheServiceURL = exports2.getCacheServiceVersion = exports2.isGhes = void 0; - function isGhes() { - const ghUrl = new URL(process.env["GITHUB_SERVER_URL"] || "https://github.com"); - const hostname = ghUrl.hostname.trimEnd().toUpperCase(); - const isGitHubHost = hostname === "GITHUB.COM"; - const isGheHost = hostname.endsWith(".GHE.COM"); - const isLocalHost = hostname.endsWith(".LOCALHOST"); - return !isGitHubHost && !isGheHost && !isLocalHost; + exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; + var defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0 + }; + var defaultsRead = { + ignoreUnknownFields: false + }; + function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } - exports2.isGhes = isGhes; - function getCacheServiceVersion() { - if (isGhes()) - return "v1"; - return process.env["ACTIONS_CACHE_SERVICE_V2"] ? "v2" : "v1"; + exports2.jsonReadOptions = jsonReadOptions; + function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; } - exports2.getCacheServiceVersion = getCacheServiceVersion; - function getCacheServiceURL() { - const version = getCacheServiceVersion(); - switch (version) { - case "v1": - return process.env["ACTIONS_CACHE_URL"] || process.env["ACTIONS_RESULTS_URL"] || ""; - case "v2": - return process.env["ACTIONS_RESULTS_URL"] || ""; - default: - throw new Error(`Unsupported cache service version: ${version}`); - } + exports2.jsonWriteOptions = jsonWriteOptions; + function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; + return c; } - exports2.getCacheServiceURL = getCacheServiceURL; - } -}); - -// node_modules/@actions/cache/package.json -var require_package2 = __commonJS({ - "node_modules/@actions/cache/package.json"(exports2, module2) { - module2.exports = { - name: "@actions/cache", - version: "4.1.0", - preview: true, - description: "Actions cache lib", - keywords: [ - "github", - "actions", - "cache" - ], - homepage: "https://github.com/actions/toolkit/tree/main/packages/cache", - license: "MIT", - main: "lib/cache.js", - types: "lib/cache.d.ts", - directories: { - lib: "lib", - test: "__tests__" - }, - files: [ - "lib", - "!.DS_Store" - ], - publishConfig: { - access: "public" - }, - repository: { - type: "git", - url: "git+https://github.com/actions/toolkit.git", - directory: "packages/cache" - }, - scripts: { - "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", - test: 'echo "Error: run tests from root" && exit 1', - tsc: "tsc" - }, - bugs: { - url: "https://github.com/actions/toolkit/issues" - }, - dependencies: { - "@actions/core": "^1.11.1", - "@actions/exec": "^1.0.1", - "@actions/glob": "^0.1.0", - "@protobuf-ts/runtime-rpc": "^2.11.1", - "@actions/http-client": "^2.1.1", - "@actions/io": "^1.0.1", - "@azure/abort-controller": "^1.1.0", - "@azure/ms-rest-js": "^2.6.0", - "@azure/storage-blob": "^12.13.0", - semver: "^6.3.1" - }, - devDependencies: { - "@types/node": "^22.13.9", - "@types/semver": "^6.0.0", - "@protobuf-ts/plugin": "^2.9.4", - typescript: "^5.2.2" - } - }; + exports2.mergeJsonOptions = mergeJsonOptions; } }); -// node_modules/@actions/cache/lib/internal/shared/user-agent.js -var require_user_agent = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/user-agent.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js +var require_message_type_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUserAgentString = void 0; - var packageJson = require_package2(); - function getUserAgentString() { - return `@actions/cache-${packageJson.version}`; - } - exports2.getUserAgentString = getUserAgentString; + exports2.MESSAGE_TYPE = void 0; + exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); } }); -// node_modules/@actions/cache/lib/internal/cacheHttpClient.js -var require_cacheHttpClient = __commonJS({ - "node_modules/@actions/cache/lib/internal/cacheHttpClient.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js +var require_lower_camel_case = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; - var core18 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); - var fs17 = __importStar4(require("fs")); - var url_1 = require("url"); - var utils = __importStar4(require_cacheUtils()); - var uploadUtils_1 = require_uploadUtils(); - var downloadUtils_1 = require_downloadUtils(); - var options_1 = require_options(); - var requestUtils_1 = require_requestUtils(); - var config_1 = require_config(); - var user_agent_1 = require_user_agent(); - function getCacheApiUrl(resource) { - const baseUrl = (0, config_1.getCacheServiceURL)(); - if (!baseUrl) { - throw new Error("Cache Service Url not found, unable to restore cache."); - } - const url2 = `${baseUrl}_apis/artifactcache/${resource}`; - core18.debug(`Resource Url: ${url2}`); - return url2; - } - function createAcceptHeader(type2, apiVersion) { - return `${type2};api-version=${apiVersion}`; - } - function getRequestOptions() { - const requestOptions = { - headers: { - Accept: createAcceptHeader("application/json", "6.0-preview.1") - } - }; - return requestOptions; - } - function createHttpClient() { - const token = process.env["ACTIONS_RUNTIME_TOKEN"] || ""; - const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); - return new http_client_1.HttpClient((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions()); - } - function getCacheEntry(keys, paths, options) { - return __awaiter4(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); - const resource = `cache?keys=${encodeURIComponent(keys.join(","))}&version=${version}`; - const response = yield (0, requestUtils_1.retryTypedResponse)("getCacheEntry", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.getJson(getCacheApiUrl(resource)); - })); - if (response.statusCode === 204) { - if (core18.isDebug()) { - yield printCachesListForDiagnostics(keys[0], httpClient, version); - } - return null; - } - if (!(0, requestUtils_1.isSuccessStatusCode)(response.statusCode)) { - throw new Error(`Cache service responded with ${response.statusCode}`); - } - const cacheResult = response.result; - const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; - if (!cacheDownloadUrl) { - throw new Error("Cache not found."); - } - core18.setSecret(cacheDownloadUrl); - core18.debug(`Cache Result:`); - core18.debug(JSON.stringify(cacheResult)); - return cacheResult; - }); - } - exports2.getCacheEntry = getCacheEntry; - function printCachesListForDiagnostics(key, httpClient, version) { - return __awaiter4(this, void 0, void 0, function* () { - const resource = `caches?key=${encodeURIComponent(key)}`; - const response = yield (0, requestUtils_1.retryTypedResponse)("listCache", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.getJson(getCacheApiUrl(resource)); - })); - if (response.statusCode === 200) { - const cacheListResult = response.result; - const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount; - if (totalCount && totalCount > 0) { - core18.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env["GITHUB_REF"]}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key -Other caches with similar key:`); - for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) { - core18.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`); - } - } - } - }); - } - function downloadCache(archiveLocation, archivePath, options) { - return __awaiter4(this, void 0, void 0, function* () { - const archiveUrl = new url_1.URL(archiveLocation); - const downloadOptions = (0, options_1.getDownloadOptions)(options); - if (archiveUrl.hostname.endsWith(".blob.core.windows.net")) { - if (downloadOptions.useAzureSdk) { - yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions); - } else if (downloadOptions.concurrentBlobDownloads) { - yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions); - } else { - yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); - } + exports2.lowerCamelCase = void 0; + function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == "_") { + capNext = true; + } else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } else if (i == 0) { + sb.push(next.toLowerCase()); } else { - yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); + sb.push(next); } - }); - } - exports2.downloadCache = downloadCache; - function reserveCache(key, paths, options) { - return __awaiter4(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); - const reserveCacheRequest = { - key, - version, - cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize - }; - const response = yield (0, requestUtils_1.retryTypedResponse)("reserveCache", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl("caches"), reserveCacheRequest); - })); - return response; - }); - } - exports2.reserveCache = reserveCache; - function getContentRange(start, end) { - return `bytes ${start}-${end}/*`; + } + return sb.join(""); } - function uploadChunk(httpClient, resourceUrl, openStream, start, end) { - return __awaiter4(this, void 0, void 0, function* () { - core18.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); - const additionalHeaders = { - "Content-Type": "application/octet-stream", - "Content-Range": getContentRange(start, end) - }; - const uploadChunkResponse = yield (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.sendStream("PATCH", resourceUrl, openStream(), additionalHeaders); - })); - if (!(0, requestUtils_1.isSuccessStatusCode)(uploadChunkResponse.message.statusCode)) { - throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); - } - }); + exports2.lowerCamelCase = lowerCamelCase; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js +var require_reflection_info = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; + var lower_camel_case_1 = require_lower_camel_case(); + var ScalarType; + (function(ScalarType2) { + ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; + ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; + ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; + ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; + ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; + ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; + ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; + ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; + ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; + ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; + ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; + ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; + ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; + ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; + ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; + })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); + var LongType; + (function(LongType2) { + LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; + LongType2[LongType2["STRING"] = 1] = "STRING"; + LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; + })(LongType = exports2.LongType || (exports2.LongType = {})); + var RepeatType; + (function(RepeatType2) { + RepeatType2[RepeatType2["NO"] = 0] = "NO"; + RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; + RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; + })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); + function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; + return field; } - function uploadFile(httpClient, cacheId, archivePath, options) { - return __awaiter4(this, void 0, void 0, function* () { - const fileSize = utils.getArchiveFileSizeInBytes(archivePath); - const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); - const fd = fs17.openSync(archivePath, "r"); - const uploadOptions = (0, options_1.getUploadOptions)(options); - const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency); - const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize); - const parallelUploads = [...new Array(concurrency).keys()]; - core18.debug("Awaiting all uploads"); - let offset = 0; - try { - yield Promise.all(parallelUploads.map(() => __awaiter4(this, void 0, void 0, function* () { - while (offset < fileSize) { - const chunkSize = Math.min(fileSize - offset, maxChunkSize); - const start = offset; - const end = offset + chunkSize - 1; - offset += maxChunkSize; - yield uploadChunk(httpClient, resourceUrl, () => fs17.createReadStream(archivePath, { - fd, - start, - end, - autoClose: false - }).on("error", (error4) => { - throw new Error(`Cache upload failed because file read failed with ${error4.message}`); - }), start, end); - } - }))); - } finally { - fs17.closeSync(fd); - } - return; - }); + exports2.normalizeFieldInfo = normalizeFieldInfo; + function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; } - function commitCache(httpClient, cacheId, filesize) { - return __awaiter4(this, void 0, void 0, function* () { - const commitCacheRequest = { size: filesize }; - return yield (0, requestUtils_1.retryTypedResponse)("commitCache", () => __awaiter4(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); - })); - }); + exports2.readFieldOptions = readFieldOptions; + function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - function saveCache4(cacheId, archivePath, signedUploadURL, options) { - return __awaiter4(this, void 0, void 0, function* () { - const uploadOptions = (0, options_1.getUploadOptions)(options); - if (uploadOptions.useAzureSdk) { - if (!signedUploadURL) { - throw new Error("Azure Storage SDK can only be used when a signed URL is provided."); - } - yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options); - } else { - const httpClient = createHttpClient(); - core18.debug("Upload cache"); - yield uploadFile(httpClient, cacheId, archivePath, options); - core18.debug("Commiting cache"); - const cacheSize = utils.getArchiveFileSizeInBytes(archivePath); - core18.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); - const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); - if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) { - throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); - } - core18.info("Cache saved successfully"); - } - }); + exports2.readFieldOption = readFieldOption; + function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.saveCache = saveCache4; + exports2.readMessageOption = readMessageOption; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js -var require_json_typings = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/json-typings.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js +var require_oneof = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isJsonObject = exports2.typeofJsonValue = void 0; - function typeofJsonValue(value) { - let t = typeof value; - if (t == "object") { - if (Array.isArray(value)) - return "array"; - if (value === null) - return "null"; + exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; + function isOneofGroup(any) { + if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === void 0) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; } - return t; } - exports2.typeofJsonValue = typeofJsonValue; - function isJsonObject(value) { - return value !== null && typeof value == "object" && !Array.isArray(value); + exports2.isOneofGroup = isOneofGroup; + function getOneofValue(oneof, kind) { + return oneof[kind]; } - exports2.isJsonObject = isJsonObject; + exports2.getOneofValue = getOneofValue; + function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== void 0) { + oneof[kind] = value; + } + } + exports2.setOneofValue = setOneofValue; + function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== void 0 && kind !== void 0) { + oneof[kind] = value; + } + } + exports2.setUnknownOneofValue = setUnknownOneofValue; + function clearOneofValue(oneof) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = void 0; + } + exports2.clearOneofValue = clearOneofValue; + function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === void 0) { + return void 0; + } + return oneof[oneof.oneofKind]; + } + exports2.getSelectedOneofValue = getSelectedOneofValue; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/base64.js -var require_base642 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/base64.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js +var require_reflection_type_check = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.base64encode = exports2.base64decode = void 0; - var encTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); - var decTable = []; - for (let i = 0; i < encTable.length; i++) - decTable[encTable[i].charCodeAt(0)] = i; - decTable["-".charCodeAt(0)] = encTable.indexOf("+"); - decTable["_".charCodeAt(0)] = encTable.indexOf("/"); - function base64decode(base64Str) { - let es = base64Str.length * 3 / 4; - if (base64Str[base64Str.length - 2] == "=") - es -= 2; - else if (base64Str[base64Str.length - 1] == "=") - es -= 1; - let bytes = new Uint8Array(es), bytePos = 0, groupPos = 0, b, p = 0; - for (let i = 0; i < base64Str.length; i++) { - b = decTable[base64Str.charCodeAt(i)]; - if (b === void 0) { - switch (base64Str[i]) { - case "=": - groupPos = 0; - // reset state when padding found - case "\n": - case "\r": - case " ": - case " ": - continue; - // skip white-space, and padding - default: - throw Error(`invalid base64 string.`); + exports2.ReflectionTypeCheck = void 0; + var reflection_info_1 = require_reflection_info(); + var oneof_1 = require_oneof(); + var ReflectionTypeCheck = class { + constructor(info7) { + var _a; + this.fields = (_a = info7.fields) !== null && _a !== void 0 ? _a : []; + } + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); + } + } else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; + } } } - switch (groupPos) { - case 0: - p = b; - groupPos = 1; - break; - case 1: - bytes[bytePos++] = p << 2 | (b & 48) >> 4; - p = b; - groupPos = 2; - break; - case 2: - bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; - p = b; - groupPos = 3; - break; - case 3: - bytes[bytePos++] = (p & 3) << 6 | b; - groupPos = 0; - break; + this.data = { req, known, oneofs: Object.values(oneofs) }; + } + /** + * Is the argument a valid message as specified by the + * reflection information? + * + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. + * + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. + */ + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === void 0 || typeof message != "object") + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + if (keys.some((k) => !data.known.includes(k))) + return false; + } + if (depth < 1) { + return true; + } + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === void 0) + continue; + const field = this.fields.find((f) => f.localName === group.oneofKind); + if (!field) + return false; + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + for (const field of this.fields) { + if (field.oneof !== void 0) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; } + return true; } - if (groupPos == 1) - throw Error(`invalid base64 string.`); - return bytes.subarray(0, bytePos); - } - exports2.base64decode = base64decode; - function base64encode(bytes) { - let base64 = "", groupPos = 0, b, p = 0; - for (let i = 0; i < bytes.length; i++) { - b = bytes[i]; - switch (groupPos) { - case 0: - base64 += encTable[b >> 2]; - p = (b & 3) << 4; - groupPos = 1; - break; - case 1: - base64 += encTable[p | b >> 4]; - p = (b & 15) << 2; - groupPos = 2; - break; - case 2: - base64 += encTable[p | b >> 6]; - base64 += encTable[b & 63]; - groupPos = 0; + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === void 0) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != "object" || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } break; } + return true; } - if (groupPos) { - base64 += encTable[p]; - base64 += "="; - if (groupPos == 1) - base64 += "="; + message(arg, type2, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type2.isAssignable(arg, depth); + } + return type2.is(arg, depth); + } + messages(arg, type2, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.isAssignable(arg[i], depth - 1)) + return false; + } else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.is(arg[i], depth - 1)) + return false; + } + return true; + } + scalar(arg, type2, longType) { + let argType = typeof arg; + switch (type2) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == "boolean"; + case reflection_info_1.ScalarType.STRING: + return argType == "string"; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == "number" && !isNaN(arg); + default: + return argType == "number" && Number.isInteger(arg); + } } - return base64; - } - exports2.base64encode = base64encode; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js -var require_protobufjs_utf8 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.utf8read = void 0; - var fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); - function utf8read(bytes) { - if (bytes.length < 1) - return ""; - let pos = 0, parts = [], chunk = [], i = 0, t; - let len = bytes.length; - while (pos < len) { - t = bytes[pos++]; - if (t < 128) - chunk[i++] = t; - else if (t > 191 && t < 224) - chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 65536; - chunk[i++] = 55296 + (t >> 10); - chunk[i++] = 56320 + (t & 1023); - } else - chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; - if (i > 8191) { - parts.push(fromCharCodes(chunk)); - i = 0; + scalars(arg, type2, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type2, longType)) + return false; } + return true; } - if (parts.length) { - if (i) - parts.push(fromCharCodes(chunk.slice(0, i))); - return parts.join(""); + mapKeys(map2, type2, depth) { + let keys = Object.keys(map2); + switch (type2) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); + default: + return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + } } - return fromCharCodes(chunk.slice(0, i)); - } - exports2.utf8read = utf8read; + }; + exports2.ReflectionTypeCheck = ReflectionTypeCheck; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js -var require_binary_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js +var require_reflection_long_convert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WireType = exports2.mergeBinaryOptions = exports2.UnknownFieldHandler = void 0; - var UnknownFieldHandler; - (function(UnknownFieldHandler2) { - UnknownFieldHandler2.symbol = Symbol.for("protobuf-ts/unknown"); - UnknownFieldHandler2.onRead = (typeName, message, fieldNo, wireType, data) => { - let container = is(message) ? message[UnknownFieldHandler2.symbol] : message[UnknownFieldHandler2.symbol] = []; - container.push({ no: fieldNo, wireType, data }); - }; - UnknownFieldHandler2.onWrite = (typeName, message, writer) => { - for (let { no, wireType, data } of UnknownFieldHandler2.list(message)) - writer.tag(no, wireType).raw(data); - }; - UnknownFieldHandler2.list = (message, fieldNo) => { - if (is(message)) { - let all = message[UnknownFieldHandler2.symbol]; - return fieldNo ? all.filter((uf) => uf.no == fieldNo) : all; - } - return []; - }; - UnknownFieldHandler2.last = (message, fieldNo) => UnknownFieldHandler2.list(message, fieldNo).slice(-1)[0]; - const is = (message) => message && Array.isArray(message[UnknownFieldHandler2.symbol]); - })(UnknownFieldHandler = exports2.UnknownFieldHandler || (exports2.UnknownFieldHandler = {})); - function mergeBinaryOptions(a, b) { - return Object.assign(Object.assign({}, a), b); + exports2.reflectionLongConvert = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionLongConvert(long, type2) { + switch (type2) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + return long.toString(); + } } - exports2.mergeBinaryOptions = mergeBinaryOptions; - var WireType; - (function(WireType2) { - WireType2[WireType2["Varint"] = 0] = "Varint"; - WireType2[WireType2["Bit64"] = 1] = "Bit64"; - WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited"; - WireType2[WireType2["StartGroup"] = 3] = "StartGroup"; - WireType2[WireType2["EndGroup"] = 4] = "EndGroup"; - WireType2[WireType2["Bit32"] = 5] = "Bit32"; - })(WireType = exports2.WireType || (exports2.WireType = {})); + exports2.reflectionLongConvert = reflectionLongConvert; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js -var require_goog_varint = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js +var require_reflection_json_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.varint32read = exports2.varint32write = exports2.int64toString = exports2.int64fromString = exports2.varint64write = exports2.varint64read = void 0; - function varint64read() { - let lowBits = 0; - let highBits = 0; - for (let shift = 0; shift < 28; shift += 7) { - let b = this.buf[this.pos++]; - lowBits |= (b & 127) << shift; - if ((b & 128) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } - } - let middleByte = this.buf[this.pos++]; - lowBits |= (middleByte & 15) << 28; - highBits = (middleByte & 112) >> 4; - if ((middleByte & 128) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } - for (let shift = 3; shift <= 31; shift += 7) { - let b = this.buf[this.pos++]; - highBits |= (b & 127) << shift; - if ((b & 128) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } + exports2.ReflectionJsonReader = void 0; + var json_typings_1 = require_json_typings(); + var base64_1 = require_base642(); + var reflection_info_1 = require_reflection_info(); + var pb_long_1 = require_pb_long(); + var assert_1 = require_assert(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var ReflectionJsonReader = class { + constructor(info7) { + this.info = info7; } - throw new Error("invalid varint"); - } - exports2.varint64read = varint64read; - function varint64write(lo, hi, bytes) { - for (let i = 0; i < 28; i = i + 7) { - const shift = lo >>> i; - const hasNext = !(shift >>> 7 == 0 && hi == 0); - const byte = (hasNext ? shift | 128 : shift) & 255; - bytes.push(byte); - if (!hasNext) { - return; + prepare() { + var _a; + if (this.fMap === void 0) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } } } - const splitBits = lo >>> 28 & 15 | (hi & 7) << 4; - const hasMoreBits = !(hi >> 3 == 0); - bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255); - if (!hasMoreBits) { - return; - } - for (let i = 3; i < 31; i = i + 7) { - const shift = hi >>> i; - const hasNext = !(shift >>> 7 == 0); - const byte = (hasNext ? shift | 128 : shift) & 255; - bytes.push(byte); - if (!hasNext) { - return; + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); } } - bytes.push(hi >>> 31 & 1); - } - exports2.varint64write = varint64write; - var TWO_PWR_32_DBL2 = (1 << 16) * (1 << 16); - function int64fromString(dec) { - let minus = dec[0] == "-"; - if (minus) - dec = dec.slice(1); - const base = 1e6; - let lowBits = 0; - let highBits = 0; - function add1e6digit(begin, end) { - const digit1e6 = Number(dec.slice(begin, end)); - highBits *= base; - lowBits = lowBits * base + digit1e6; - if (lowBits >= TWO_PWR_32_DBL2) { - highBits = highBits + (lowBits / TWO_PWR_32_DBL2 | 0); - lowBits = lowBits % TWO_PWR_32_DBL2; + /** + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + let target; + if (field.oneof) { + if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { + continue; + } + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } else { + target = message; + } + if (field.kind == "map") { + if (jsonValue === null) { + continue; + } + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + const fieldObj = target[localName]; + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + let val2; + switch (field.V.kind) { + case "message": + val2 = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val2; + } + } else if (field.repeat) { + if (jsonValue === null) + continue; + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + const fieldArr = target[localName]; + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val2; + switch (field.kind) { + case "message": + val2 = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name, jsonValue); + fieldArr.push(val2); + } + } else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { + this.assert(field.oneof === void 0, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + if (jsonValue === null) + continue; + let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + target[localName] = val2; + break; + case "scalar": + if (jsonValue === null) + continue; + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } } } - add1e6digit(-24, -18); - add1e6digit(-18, -12); - add1e6digit(-12, -6); - add1e6digit(-6); - return [minus, lowBits, highBits]; - } - exports2.int64fromString = int64fromString; - function int64toString(bitsLow, bitsHigh) { - if (bitsHigh >>> 0 <= 2097151) { - return "" + (TWO_PWR_32_DBL2 * bitsHigh + (bitsLow >>> 0)); - } - let low = bitsLow & 16777215; - let mid = (bitsLow >>> 24 | bitsHigh << 8) >>> 0 & 16777215; - let high = bitsHigh >> 16 & 65535; - let digitA = low + mid * 6777216 + high * 6710656; - let digitB = mid + high * 8147497; - let digitC = high * 2; - let base = 1e7; - if (digitA >= base) { - digitB += Math.floor(digitA / base); - digitA %= base; - } - if (digitB >= base) { - digitC += Math.floor(digitB / base); - digitB %= base; - } - function decimalFrom1e7(digit1e7, needLeadingZeros) { - let partial = digit1e7 ? String(digit1e7) : ""; - if (needLeadingZeros) { - return "0000000".slice(partial.length) + partial; + /** + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + */ + enum(type2, json2, fieldName, ignoreUnknownFields) { + if (type2[0] == "google.protobuf.NullValue") + assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); + if (json2 === null) + return 0; + switch (typeof json2) { + case "number": + assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); + return json2; + case "string": + let localEnumName = json2; + if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) + localEnumName = json2.substring(type2[2].length); + let enumNumber = type2[1][localEnumName]; + if (typeof enumNumber === "undefined" && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); + return enumNumber; } - return partial; + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); } - return decimalFrom1e7( - digitC, - /*needLeadingZeros=*/ - 0 - ) + decimalFrom1e7( - digitB, - /*needLeadingZeros=*/ - digitC - ) + // If the final 1e7 digit didn't need leading zeros, we would have - // returned via the trivial code path at the top. - decimalFrom1e7( - digitA, - /*needLeadingZeros=*/ - 1 - ); - } - exports2.int64toString = int64toString; - function varint32write(value, bytes) { - if (value >= 0) { - while (value > 127) { - bytes.push(value & 127 | 128); - value = value >>> 7; - } - bytes.push(value); - } else { - for (let i = 0; i < 9; i++) { - bytes.push(value & 127 | 128); - value = value >> 7; + scalar(json2, type2, longType, fieldName) { + let e; + try { + switch (type2) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json2 === null) + return 0; + if (json2 === "NaN") + return Number.NaN; + if (json2 === "Infinity") + return Number.POSITIVE_INFINITY; + if (json2 === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json2 === "") { + e = "empty string"; + break; + } + if (typeof json2 == "string" && json2.trim().length !== json2.length) { + e = "extra whitespace"; + break; + } + if (typeof json2 != "string" && typeof json2 != "number") { + break; + } + let float2 = Number(json2); + if (Number.isNaN(float2)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float2)) { + e = "too large or small"; + break; + } + if (type2 == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float2); + return float2; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json2 === null) + return 0; + let int32; + if (typeof json2 == "number") + int32 = json2; + else if (json2 === "") + e = "empty string"; + else if (typeof json2 == "string") { + if (json2.trim().length !== json2.length) + e = "extra whitespace"; + else + int32 = Number(json2); + } + if (int32 === void 0) + break; + if (type2 == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json2 === null) + return false; + if (typeof json2 !== "boolean") + break; + return json2; + // string: + case reflection_info_1.ScalarType.STRING: + if (json2 === null) + return ""; + if (typeof json2 !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json2); + } catch (e2) { + e2 = "invalid UTF8"; + break; + } + return json2; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json2 === null || json2 === "") + return new Uint8Array(0); + if (typeof json2 !== "string") + break; + return base64_1.base64decode(json2); + } + } catch (error4) { + e = error4.message; } - bytes.push(1); - } - } - exports2.varint32write = varint32write; - function varint32read() { - let b = this.buf[this.pos++]; - let result = b & 127; - if ((b & 128) == 0) { - this.assertBounds(); - return result; - } - b = this.buf[this.pos++]; - result |= (b & 127) << 7; - if ((b & 128) == 0) { - this.assertBounds(); - return result; - } - b = this.buf[this.pos++]; - result |= (b & 127) << 14; - if ((b & 128) == 0) { - this.assertBounds(); - return result; - } - b = this.buf[this.pos++]; - result |= (b & 127) << 21; - if ((b & 128) == 0) { - this.assertBounds(); - return result; + this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - b = this.buf[this.pos++]; - result |= (b & 15) << 28; - for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++) - b = this.buf[this.pos++]; - if ((b & 128) != 0) - throw new Error("invalid varint"); - this.assertBounds(); - return result >>> 0; - } - exports2.varint32read = varint32read; + }; + exports2.ReflectionJsonReader = ReflectionJsonReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js -var require_pb_long = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js +var require_reflection_json_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PbLong = exports2.PbULong = exports2.detectBi = void 0; - var goog_varint_1 = require_goog_varint(); - var BI; - function detectBi() { - const dv = new DataView(new ArrayBuffer(8)); - const ok = globalThis.BigInt !== void 0 && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function"; - BI = ok ? { - MIN: BigInt("-9223372036854775808"), - MAX: BigInt("9223372036854775807"), - UMIN: BigInt("0"), - UMAX: BigInt("18446744073709551615"), - C: BigInt, - V: dv - } : void 0; - } - exports2.detectBi = detectBi; - detectBi(); - function assertBi(bi) { - if (!bi) - throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); - } - var RE_DECIMAL_STR = /^-?[0-9]+$/; - var TWO_PWR_32_DBL2 = 4294967296; - var HALF_2_PWR_32 = 2147483648; - var SharedPbLong = class { - /** - * Create a new instance with the given bits. - */ - constructor(lo, hi) { - this.lo = lo | 0; - this.hi = hi | 0; - } - /** - * Is this instance equal to 0? - */ - isZero() { - return this.lo == 0 && this.hi == 0; + exports2.ReflectionJsonWriter = void 0; + var base64_1 = require_base642(); + var pb_long_1 = require_pb_long(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); + var ReflectionJsonWriter = class { + constructor(info7) { + var _a; + this.fields = (_a = info7.fields) !== null && _a !== void 0 ? _a : []; } /** - * Convert to a native number. + * Converts the message to a JSON object, based on the field descriptors. */ - toNumber() { - let result = this.hi * TWO_PWR_32_DBL2 + (this.lo >>> 0); - if (!Number.isSafeInteger(result)) - throw new Error("cannot convert to safe number"); - return result; + write(message, options) { + const json2 = {}, source = message; + for (const field of this.fields) { + if (!field.oneof) { + let jsonValue2 = this.field(field, source[field.localName], options); + if (jsonValue2 !== void 0) + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; + continue; + } + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; + const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== void 0); + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + } + return json2; } - }; - var PbULong = class _PbULong extends SharedPbLong { - /** - * Create instance from a `string`, `number` or `bigint`. - */ - static from(value) { - if (BI) - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - if (value == "") - throw new Error("string is no integer"); - value = BI.C(value); - case "number": - if (value === 0) - return this.ZERO; - value = BI.C(value); - case "bigint": - if (!value) - return this.ZERO; - if (value < BI.UMIN) - throw new Error("signed value for ulong"); - if (value > BI.UMAX) - throw new Error("ulong too large"); - BI.V.setBigUint64(0, value, true); - return new _PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + field(field, value, options) { + let jsonValue = void 0; + if (field.kind == "map") { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); + const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; } - else - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - value = value.trim(); - if (!RE_DECIMAL_STR.test(value)) - throw new Error("string is no integer"); - let [minus, lo, hi] = goog_varint_1.int64fromString(value); - if (minus) - throw new Error("signed value for ulong"); - return new _PbULong(lo, hi); - case "number": - if (value == 0) - return this.ZERO; - if (!Number.isSafeInteger(value)) - throw new Error("number is no integer"); - if (value < 0) - throw new Error("signed value for ulong"); - return new _PbULong(value, value / TWO_PWR_32_DBL2); + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); + const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val2 = this.message(messageType, value[i], field.name, options); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; } - throw new Error("unknown value " + typeof value); + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } + } + return jsonValue; } /** - * Convert to decimal string. + * Returns `null` as the default for google.protobuf.NullValue. */ - toString() { - return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); + enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type2[0] == "google.protobuf.NullValue") + return !emitDefaultValues && !optional ? void 0 : null; + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + if (value === 0 && !emitDefaultValues && !optional) + return void 0; + assert_1.assert(typeof value == "number"); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type2[1].hasOwnProperty(value)) + return value; + if (type2[2]) + return type2[2] + type2[1][value]; + return type2[1][value]; } - /** - * Convert to native bigint. - */ - toBigInt() { - assertBi(BI); - BI.V.setInt32(0, this.lo, true); - BI.V.setInt32(4, this.hi, true); - return BI.V.getBigUint64(0, true); + message(type2, value, fieldName, options) { + if (value === void 0) + return options.emitDefaultValues ? null : void 0; + return type2.internalJsonWrite(value, options); + } + scalar(type2, value, fieldName, optional, emitDefaultValues) { + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + const ed = emitDefaultValues || optional; + switch (type2) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assert(typeof value == "number"); + if (Number.isNaN(value)) + return "NaN"; + if (value === Number.POSITIVE_INFINITY) + return "Infinity"; + if (value === Number.NEGATIVE_INFINITY) + return "-Infinity"; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? "" : void 0; + assert_1.assert(typeof value == "string"); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : void 0; + assert_1.assert(typeof value == "boolean"); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return void 0; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return void 0; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : void 0; + return base64_1.base64encode(value); + } } }; - exports2.PbULong = PbULong; - PbULong.ZERO = new PbULong(0, 0); - var PbLong = class _PbLong extends SharedPbLong { + exports2.ReflectionJsonWriter = ReflectionJsonWriter; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js +var require_reflection_scalar_default = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionScalarDefault = void 0; + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var pb_long_1 = require_pb_long(); + function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { + switch (type2) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + return 0; + } + } + exports2.reflectionScalarDefault = reflectionScalarDefault; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js +var require_reflection_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionBinaryReader = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var ReflectionBinaryReader = class { + constructor(info7) { + this.info = info7; + } + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + } + } /** - * Create instance from a `string`, `number` or `bigint`. + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. */ - static from(value) { - if (BI) - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - if (value == "") - throw new Error("string is no integer"); - value = BI.C(value); - case "number": - if (value === 0) - return this.ZERO; - value = BI.C(value); - case "bigint": - if (!value) - return this.ZERO; - if (value < BI.MIN) - throw new Error("signed long too small"); - if (value > BI.MAX) - throw new Error("signed long too large"); - BI.V.setBigInt64(0, value, true); - return new _PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + read(reader, message, options, length) { + this.prepare(); + const end = length === void 0 ? reader.len : reader.pos + length; + while (reader.pos < end) { + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; } - else - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - value = value.trim(); - if (!RE_DECIMAL_STR.test(value)) - throw new Error("string is no integer"); - let [minus, lo, hi] = goog_varint_1.int64fromString(value); - if (minus) { - if (hi > HALF_2_PWR_32 || hi == HALF_2_PWR_32 && lo != 0) - throw new Error("signed long too small"); - } else if (hi >= HALF_2_PWR_32) - throw new Error("signed long too large"); - let pbl = new _PbLong(lo, hi); - return minus ? pbl.negate() : pbl; - case "number": - if (value == 0) - return this.ZERO; - if (!Number.isSafeInteger(value)) - throw new Error("number is no integer"); - return value > 0 ? new _PbLong(value, value / TWO_PWR_32_DBL2) : new _PbLong(-value, -value / TWO_PWR_32_DBL2).negate(); + let target = message, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + target = target[field.oneof]; + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : void 0; + if (repeated) { + let arr = target[localName]; + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } else + arr.push(this.scalar(reader, T, L)); + } else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + target[localName][mapKey] = mapVal; + break; } - throw new Error("unknown value " + typeof value); - } - /** - * Do we have a minus sign? - */ - isNegative() { - return (this.hi & HALF_2_PWR_32) !== 0; - } - /** - * Negate two's complement. - * Invert all the bits and add one to the result. - */ - negate() { - let hi = ~this.hi, lo = this.lo; - if (lo) - lo = ~lo + 1; - else - hi += 1; - return new _PbLong(lo, hi); + } } /** - * Convert to decimal string. + * Read a map field, expecting key field = 1, value field = 2 */ - toString() { - if (BI) - return this.toBigInt().toString(); - if (this.isNegative()) { - let n = this.negate(); - return "-" + goog_varint_1.int64toString(n.lo, n.hi); + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = void 0; + let val2 = void 0; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val2 = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val2 = reader.int32(); + break; + case "message": + val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } } - return goog_varint_1.int64toString(this.lo, this.hi); + if (key === void 0) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val2 === void 0) + switch (field.V.kind) { + case "scalar": + val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val2 = 0; + break; + case "message": + val2 = field.V.T().create(); + break; + } + return [key, val2]; } - /** - * Convert to native bigint. - */ - toBigInt() { - assertBi(BI); - BI.V.setInt32(0, this.lo, true); - BI.V.setInt32(4, this.hi, true); - return BI.V.getBigInt64(0, true); + scalar(reader, type2, longType) { + switch (type2) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } } }; - exports2.PbLong = PbLong; - PbLong.ZERO = new PbLong(0, 0); + exports2.ReflectionBinaryReader = ReflectionBinaryReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js -var require_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js +var require_reflection_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryReader = exports2.binaryReadOptions = void 0; + exports2.ReflectionBinaryWriter = void 0; var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); - var defaultsRead = { - readUnknownField: true, - readerFactory: (bytes) => new BinaryReader(bytes) - }; - function binaryReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.binaryReadOptions = binaryReadOptions; - var BinaryReader = class { - constructor(buf, textDecoder) { - this.varint64 = goog_varint_1.varint64read; - this.uint32 = goog_varint_1.varint32read; - this.buf = buf; - this.len = buf.length; - this.pos = 0; - this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); - this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { - fatal: true, - ignoreBOM: true - }); + var ReflectionBinaryWriter = class { + constructor(info7) { + this.info = info7; } - /** - * Reads a tag - field number and wire type. - */ - tag() { - let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; - if (fieldNo <= 0 || wireType < 0 || wireType > 5) - throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); - return [fieldNo, wireType]; + prepare() { + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); + } } /** - * Skip one element on the wire and return the skipped data. - * Supports WireType.StartGroup since v2.0.0-alpha.23. + * Writes the message to binary format. */ - skip(wireType) { - let start = this.pos; - switch (wireType) { - case binary_format_contract_1.WireType.Varint: - while (this.buf[this.pos++] & 128) { - } + write(message, writer, options) { + this.prepare(); + for (const field of this.fields) { + let value, emitDefault, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; + value = group[localName]; + emitDefault = true; + } else { + value = message[localName]; + emitDefault = false; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } else if (value === void 0) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == "object" && value !== null); + for (const [key, val2] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val2); + break; + } + } + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); + } + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); break; - case binary_format_contract_1.WireType.Bit64: - this.pos += 4; - case binary_format_contract_1.WireType.Bit32: - this.pos += 4; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == "true" || key == "false"); + keyValue = key == "true"; break; - case binary_format_contract_1.WireType.LengthDelimited: - let len = this.uint32(); - this.pos += len; + } + this.scalar(writer, field.K, 1, keyValue, true); + switch (field.V.kind) { + case "scalar": + this.scalar(writer, field.V.T, 2, value, true); break; - case binary_format_contract_1.WireType.StartGroup: - let t; - while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { - this.skip(t); - } + case "enum": + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; + case "message": + this.message(writer, options, field.V.T(), 2, value); break; - default: - throw new Error("cant skip wire type " + wireType); } - this.assertBounds(); - return this.buf.subarray(start, this.pos); - } - /** - * Throws error if position in byte array is out of range. - */ - assertBounds() { - if (this.pos > this.len) - throw new RangeError("premature EOF"); - } - /** - * Read a `int32` field, a signed 32 bit varint. - */ - int32() { - return this.uint32() | 0; - } - /** - * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. - */ - sint32() { - let zze = this.uint32(); - return zze >>> 1 ^ -(zze & 1); - } - /** - * Read a `int64` field, a signed 64-bit varint. - */ - int64() { - return new pb_long_1.PbLong(...this.varint64()); - } - /** - * Read a `uint64` field, an unsigned 64-bit varint. - */ - uint64() { - return new pb_long_1.PbULong(...this.varint64()); - } - /** - * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. - */ - sint64() { - let [lo, hi] = this.varint64(); - let s = -(lo & 1); - lo = (lo >>> 1 | (hi & 1) << 31) ^ s; - hi = hi >>> 1 ^ s; - return new pb_long_1.PbLong(lo, hi); - } - /** - * Read a `bool` field, a variant. - */ - bool() { - let [lo, hi] = this.varint64(); - return lo !== 0 || hi !== 0; - } - /** - * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. - */ - fixed32() { - return this.view.getUint32((this.pos += 4) - 4, true); - } - /** - * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. - */ - sfixed32() { - return this.view.getInt32((this.pos += 4) - 4, true); - } - /** - * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. - */ - fixed64() { - return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); - } - /** - * Read a `fixed64` field, a signed, fixed-length 64-bit integer. - */ - sfixed64() { - return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); + writer.join(); } - /** - * Read a `float` field, 32-bit floating point number. - */ - float() { - return this.view.getFloat32((this.pos += 4) - 4, true); + message(writer, options, handler, fieldNo, value) { + if (value === void 0) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); } /** - * Read a `double` field, a 64-bit floating point number. + * Write a single scalar value. */ - double() { - return this.view.getFloat64((this.pos += 8) - 8, true); + scalar(writer, type2, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type2, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); + } } /** - * Read a `bytes` field, length-delimited arbitrary data. + * Write an array of scalar values in packed format. */ - bytes() { - let len = this.uint32(); - let start = this.pos; - this.pos += len; - this.assertBounds(); - return this.buf.subarray(start, start + len); + packed(writer, type2, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let [, method] = this.scalarInfo(type2); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + writer.join(); } /** - * Read a `string` field, length-delimited data converted to UTF-8 text. + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. */ - string() { - return this.textDecoder.decode(this.bytes()); + scalarInfo(type2, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === void 0; + let d = value === 0; + switch (type2) { + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; + case reflection_info_1.ScalarType.STRING: + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; + case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; + case reflection_info_1.ScalarType.FLOAT: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; + case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; + case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; + case reflection_info_1.ScalarType.SINT32: + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; + } + return [t, m, i || d]; } }; - exports2.BinaryReader = BinaryReader; + exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js +var require_reflection_create = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionCreate = void 0; + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var message_type_contract_1 = require_message_type_contract(); + function reflectionCreate(type2) { + const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); + for (let field of type2.fields) { + let name = field.localName; + if (field.opt) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: void 0 }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } + } + return msg; + } + exports2.reflectionCreate = reflectionCreate; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js -var require_assert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js +var require_reflection_merge_partial = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; - function assert(condition, msg) { - if (!condition) { - throw new Error(msg); + exports2.reflectionMergePartial = void 0; + function reflectionMergePartial(info7, target, source) { + let fieldValue, input = source, output; + for (let field of info7.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { + continue; + } + fieldValue = group[name]; + output = target[field.oneof]; + output.oneofKind = group.oneofKind; + if (fieldValue == void 0) { + delete output[name]; + continue; + } + } else { + fieldValue = input[name]; + output = target; + if (fieldValue == void 0) { + continue; + } + } + if (field.repeat) + output[name].length = fieldValue.length; + switch (field.kind) { + case "scalar": + case "enum": + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; + else + output[name] = fieldValue; + break; + case "message": + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === void 0) + output[name] = T.create(fieldValue); + else + T.mergePartial(output[name], fieldValue); + break; + case "map": + switch (field.V.kind) { + case "scalar": + case "enum": + Object.assign(output[name], fieldValue); + break; + case "message": + let T2 = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T2.create(fieldValue[k]); + break; + } + break; + } } } - exports2.assert = assert; - function assertNever2(value, msg) { - throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + exports2.reflectionMergePartial = reflectionMergePartial; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js +var require_reflection_equals = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionEquals = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionEquals(info7, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info7.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) + return false; + break; + } + } + return true; } - exports2.assertNever = assertNever2; - var FLOAT32_MAX = 34028234663852886e22; - var FLOAT32_MIN = -34028234663852886e22; - var UINT32_MAX = 4294967295; - var INT32_MAX = 2147483647; - var INT32_MIN = -2147483648; - function assertInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid int 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) - throw new Error("invalid int 32: " + arg); + exports2.reflectionEquals = reflectionEquals; + var objectValues = Object.values; + function primitiveEq(type2, a, b) { + if (a === b) + return true; + if (type2 !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; } - exports2.assertInt32 = assertInt32; - function assertUInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid uint 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) - throw new Error("invalid uint 32: " + arg); + function repeatedPrimitiveEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type2, a[i], b[i])) + return false; + return true; } - exports2.assertUInt32 = assertUInt32; - function assertFloat32(arg) { - if (typeof arg !== "number") - throw new Error("invalid float 32: " + typeof arg); - if (!Number.isFinite(arg)) - return; - if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) - throw new Error("invalid float 32: " + arg); + function repeatedMsgEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type2.equals(a[i], b[i])) + return false; + return true; } - exports2.assertFloat32 = assertFloat32; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js -var require_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js +var require_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; - var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); - var assert_1 = require_assert(); - var defaultsWrite = { - writeUnknownFields: true, - writerFactory: () => new BinaryWriter() - }; - function binaryWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.binaryWriteOptions = binaryWriteOptions; - var BinaryWriter = class { - constructor(textEncoder) { - this.stack = []; - this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); - this.chunks = []; - this.buf = []; + exports2.MessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_type_check_1 = require_reflection_type_check(); + var reflection_json_reader_1 = require_reflection_json_reader(); + var reflection_json_writer_1 = require_reflection_json_writer(); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + var reflection_create_1 = require_reflection_create(); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + var json_typings_1 = require_json_typings(); + var json_format_contract_1 = require_json_format_contract(); + var reflection_equals_1 = require_reflection_equals(); + var binary_writer_1 = require_binary_writer(); + var binary_reader_1 = require_binary_reader(); + var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); + var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; + var MessageType = class { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + messageTypeDescriptor.value = this; + this.messagePrototype = Object.create(null, baseDescriptors); + this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); + this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); + this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } - /** - * Return all bytes written and reset this writer. - */ - finish() { - this.chunks.push(new Uint8Array(this.buf)); - let len = 0; - for (let i = 0; i < this.chunks.length; i++) - len += this.chunks[i].length; - let bytes = new Uint8Array(len); - let offset = 0; - for (let i = 0; i < this.chunks.length; i++) { - bytes.set(this.chunks[i], offset); - offset += this.chunks[i].length; + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== void 0) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); } - this.chunks = []; - return bytes; - } - /** - * Start a new fork for length-delimited data like a message - * or a packed repeated field. - * - * Must be joined later with `join()`. - */ - fork() { - this.stack.push({ chunks: this.chunks, buf: this.buf }); - this.chunks = []; - this.buf = []; - return this; - } - /** - * Join the last fork. Write its length and bytes, then - * return to the previous state. - */ - join() { - let chunk = this.finish(); - let prev = this.stack.pop(); - if (!prev) - throw new Error("invalid state, fork stack empty"); - this.chunks = prev.chunks; - this.buf = prev.buf; - this.uint32(chunk.byteLength); - return this.raw(chunk); + return message; } /** - * Writes a tag (field number and wire type). - * - * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * Clone the message. * - * Generated code should compute the tag ahead of time and call `uint32()`. - */ - tag(fieldNo, type2) { - return this.uint32((fieldNo << 3 | type2) >>> 0); - } - /** - * Write a chunk of raw bytes. - */ - raw(chunk) { - if (this.buf.length) { - this.chunks.push(new Uint8Array(this.buf)); - this.buf = []; - } - this.chunks.push(chunk); - return this; - } - /** - * Write a `uint32` value, an unsigned 32 bit varint. - */ - uint32(value) { - assert_1.assertUInt32(value); - while (value > 127) { - this.buf.push(value & 127 | 128); - value = value >>> 7; - } - this.buf.push(value); - return this; - } - /** - * Write a `int32` value, a signed 32 bit varint. - */ - int32(value) { - assert_1.assertInt32(value); - goog_varint_1.varint32write(value, this.buf); - return this; - } - /** - * Write a `bool` value, a variant. - */ - bool(value) { - this.buf.push(value ? 1 : 0); - return this; - } - /** - * Write a `bytes` value, length-delimited arbitrary data. + * Unknown fields are discarded. */ - bytes(value) { - this.uint32(value.byteLength); - return this.raw(value); + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; } /** - * Write a `string` value, length-delimited data converted to UTF-8 text. + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. */ - string(value) { - let chunk = this.textEncoder.encode(value); - this.uint32(chunk.byteLength); - return this.raw(chunk); + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); } /** - * Write a `float` value, 32-bit floating point number. + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? */ - float(value) { - assert_1.assertFloat32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setFloat32(0, value, true); - return this.raw(chunk); + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); } /** - * Write a `double` value, a 64-bit floating point number. + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? */ - double(value) { - let chunk = new Uint8Array(8); - new DataView(chunk.buffer).setFloat64(0, value, true); - return this.raw(chunk); + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); } /** - * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + * Copy partial data into the target message. */ - fixed32(value) { - assert_1.assertUInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setUint32(0, value, true); - return this.raw(chunk); + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); } /** - * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + * Create a new message from binary format. */ - sfixed32(value) { - assert_1.assertInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setInt32(0, value, true); - return this.raw(chunk); + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); } /** - * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + * Read a new message from a JSON value. */ - sint32(value) { - assert_1.assertInt32(value); - value = (value << 1 ^ value >> 31) >>> 0; - goog_varint_1.varint32write(value, this.buf); - return this; + fromJson(json2, options) { + return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); } /** - * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. */ - sfixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbLong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + fromJsonString(json2, options) { + let value = JSON.parse(json2); + return this.fromJson(value, options); } /** - * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + * Write the message to canonical JSON value. */ - fixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbULong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); } /** - * Write a `int64` value, a signed 64-bit varint. + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` */ - int64(value) { - let long = pb_long_1.PbLong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); } /** - * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + * Write the message to binary format. */ - sint64(value) { - let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; - goog_varint_1.varint64write(lo, hi, this.buf); - return this; + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); } /** - * Write a `uint64` value, an unsigned 64-bit varint. + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. */ - uint64(value) { - let long = pb_long_1.PbULong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; - } - }; - exports2.BinaryWriter = BinaryWriter; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js -var require_json_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; - var defaultsWrite = { - emitDefaultValues: false, - enumAsInteger: false, - useProtoFieldName: false, - prettySpaces: 0 - }; - var defaultsRead = { - ignoreUnknownFields: false - }; - function jsonReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.jsonReadOptions = jsonReadOptions; - function jsonWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.jsonWriteOptions = jsonWriteOptions; - function mergeJsonOptions(a, b) { - var _a, _b; - let c = Object.assign(Object.assign({}, a), b); - c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; - return c; - } - exports2.mergeJsonOptions = mergeJsonOptions; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js -var require_message_type_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MESSAGE_TYPE = void 0; - exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js -var require_lower_camel_case = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.lowerCamelCase = void 0; - function lowerCamelCase(snakeCase) { - let capNext = false; - const sb = []; - for (let i = 0; i < snakeCase.length; i++) { - let next = snakeCase.charAt(i); - if (next == "_") { - capNext = true; - } else if (/\d/.test(next)) { - sb.push(next); - capNext = true; - } else if (capNext) { - sb.push(next.toUpperCase()); - capNext = false; - } else if (i == 0) { - sb.push(next.toLowerCase()); - } else { - sb.push(next); + internalJsonRead(json2, options, target) { + if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json2, message, options); + return message; } + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); } - return sb.join(""); - } - exports2.lowerCamelCase = lowerCamelCase; + /** + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). + * + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); + } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. + * + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. + */ + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; + } + /** + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. + * + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. + */ + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; + } + }; + exports2.MessageType = MessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js -var require_reflection_info = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js +var require_reflection_contains_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; - var lower_camel_case_1 = require_lower_camel_case(); - var ScalarType; - (function(ScalarType2) { - ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; - ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; - ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; - ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; - ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; - ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; - ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; - ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; - ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; - ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; - ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; - ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; - ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; - ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; - ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; - })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); - var LongType; - (function(LongType2) { - LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; - LongType2[LongType2["STRING"] = 1] = "STRING"; - LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; - })(LongType = exports2.LongType || (exports2.LongType = {})); - var RepeatType; - (function(RepeatType2) { - RepeatType2[RepeatType2["NO"] = 0] = "NO"; - RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; - RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; - })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); - function normalizeFieldInfo(field) { - var _a, _b, _c, _d; - field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); - field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); - field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; - field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; - return field; - } - exports2.normalizeFieldInfo = normalizeFieldInfo; - function readFieldOptions(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readFieldOptions = readFieldOptions; - function readFieldOption(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readFieldOption = readFieldOption; - function readMessageOption(messageType, extensionName, extensionType) { - const options = messageType.options; - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; + exports2.containsMessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; } - exports2.readMessageOption = readMessageOption; + exports2.containsMessageType = containsMessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js -var require_oneof = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js +var require_enum_object = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; - function isOneofGroup(any) { - if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; + function isEnumObject(arg) { + if (typeof arg != "object" || arg === null) { return false; } - switch (typeof any.oneofKind) { - case "string": - if (any[any.oneofKind] === void 0) - return false; - return Object.keys(any).length == 2; - case "undefined": - return Object.keys(any).length == 1; - default: - return false; - } - } - exports2.isOneofGroup = isOneofGroup; - function getOneofValue(oneof, kind) { - return oneof[kind]; - } - exports2.getOneofValue = getOneofValue; - function setOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + if (!arg.hasOwnProperty(0)) { + return false; } - oneof.oneofKind = kind; - if (value !== void 0) { - oneof[kind] = value; + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + let nam = arg[num]; + if (nam === void 0) + return false; + if (arg[nam] !== num) + return false; + } else { + let num2 = arg[k]; + if (num2 === void 0) + return false; + if (typeof num2 !== "number") + return false; + if (arg[num2] === void 0) + return false; + } } + return true; } - exports2.setOneofValue = setOneofValue; - function setUnknownOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== void 0 && kind !== void 0) { - oneof[kind] = value; - } + exports2.isEnumObject = isEnumObject; + function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; } - exports2.setUnknownOneofValue = setUnknownOneofValue; - function clearOneofValue(oneof) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = void 0; + exports2.listEnumValues = listEnumValues; + function listEnumNames(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.name); } - exports2.clearOneofValue = clearOneofValue; - function getSelectedOneofValue(oneof) { - if (oneof.oneofKind === void 0) { - return void 0; - } - return oneof[oneof.oneofKind]; + exports2.listEnumNames = listEnumNames; + function listEnumNumbers(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); } - exports2.getSelectedOneofValue = getSelectedOneofValue; + exports2.listEnumNumbers = listEnumNumbers; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js -var require_reflection_type_check = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionTypeCheck = void 0; + var json_typings_1 = require_json_typings(); + Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { + return json_typings_1.typeofJsonValue; + } }); + Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { + return json_typings_1.isJsonObject; + } }); + var base64_1 = require_base642(); + Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { + return base64_1.base64decode; + } }); + Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { + return base64_1.base64encode; + } }); + var protobufjs_utf8_1 = require_protobufjs_utf8(); + Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { + return protobufjs_utf8_1.utf8read; + } }); + var binary_format_contract_1 = require_binary_format_contract(); + Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { + return binary_format_contract_1.WireType; + } }); + Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { + return binary_format_contract_1.mergeBinaryOptions; + } }); + Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { + return binary_format_contract_1.UnknownFieldHandler; + } }); + var binary_reader_1 = require_binary_reader(); + Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { + return binary_reader_1.BinaryReader; + } }); + Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { + return binary_reader_1.binaryReadOptions; + } }); + var binary_writer_1 = require_binary_writer(); + Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { + return binary_writer_1.BinaryWriter; + } }); + Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { + return binary_writer_1.binaryWriteOptions; + } }); + var pb_long_1 = require_pb_long(); + Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { + return pb_long_1.PbLong; + } }); + Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { + return pb_long_1.PbULong; + } }); + var json_format_contract_1 = require_json_format_contract(); + Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonReadOptions; + } }); + Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonWriteOptions; + } }); + Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { + return json_format_contract_1.mergeJsonOptions; + } }); + var message_type_contract_1 = require_message_type_contract(); + Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { + return message_type_contract_1.MESSAGE_TYPE; + } }); + var message_type_1 = require_message_type(); + Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { + return message_type_1.MessageType; + } }); var reflection_info_1 = require_reflection_info(); + Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { + return reflection_info_1.ScalarType; + } }); + Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { + return reflection_info_1.LongType; + } }); + Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { + return reflection_info_1.RepeatType; + } }); + Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { + return reflection_info_1.normalizeFieldInfo; + } }); + Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { + return reflection_info_1.readFieldOptions; + } }); + Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { + return reflection_info_1.readFieldOption; + } }); + Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { + return reflection_info_1.readMessageOption; + } }); + var reflection_type_check_1 = require_reflection_type_check(); + Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { + return reflection_type_check_1.ReflectionTypeCheck; + } }); + var reflection_create_1 = require_reflection_create(); + Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { + return reflection_create_1.reflectionCreate; + } }); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { + return reflection_scalar_default_1.reflectionScalarDefault; + } }); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { + return reflection_merge_partial_1.reflectionMergePartial; + } }); + var reflection_equals_1 = require_reflection_equals(); + Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { + return reflection_equals_1.reflectionEquals; + } }); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { + return reflection_binary_reader_1.ReflectionBinaryReader; + } }); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { + return reflection_binary_writer_1.ReflectionBinaryWriter; + } }); + var reflection_json_reader_1 = require_reflection_json_reader(); + Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { + return reflection_json_reader_1.ReflectionJsonReader; + } }); + var reflection_json_writer_1 = require_reflection_json_writer(); + Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { + return reflection_json_writer_1.ReflectionJsonWriter; + } }); + var reflection_contains_message_type_1 = require_reflection_contains_message_type(); + Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { + return reflection_contains_message_type_1.containsMessageType; + } }); var oneof_1 = require_oneof(); - var ReflectionTypeCheck = class { - constructor(info7) { - var _a; - this.fields = (_a = info7.fields) !== null && _a !== void 0 ? _a : []; - } - prepare() { - if (this.data) - return; - const req = [], known = [], oneofs = []; - for (let field of this.fields) { - if (field.oneof) { - if (!oneofs.includes(field.oneof)) { - oneofs.push(field.oneof); - req.push(field.oneof); - known.push(field.oneof); - } - } else { - known.push(field.localName); - switch (field.kind) { - case "scalar": - case "enum": - if (!field.opt || field.repeat) - req.push(field.localName); - break; - case "message": - if (field.repeat) - req.push(field.localName); - break; - case "map": - req.push(field.localName); - break; - } - } - } - this.data = { req, known, oneofs: Object.values(oneofs) }; - } - /** - * Is the argument a valid message as specified by the - * reflection information? - * - * Checks all field types recursively. The `depth` - * specifies how deep into the structure the check will be. - * - * With a depth of 0, only the presence of fields - * is checked. - * - * With a depth of 1 or more, the field types are checked. - * - * With a depth of 2 or more, the members of map, repeated - * and message fields are checked. - * - * Message fields will be checked recursively with depth - 1. - * - * The number of map entries / repeated values being checked - * is < depth. - */ - is(message, depth, allowExcessProperties = false) { - if (depth < 0) - return true; - if (message === null || message === void 0 || typeof message != "object") - return false; - this.prepare(); - let keys = Object.keys(message), data = this.data; - if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) - return false; - if (!allowExcessProperties) { - if (keys.some((k) => !data.known.includes(k))) - return false; - } - if (depth < 1) { - return true; - } - for (const name of data.oneofs) { - const group = message[name]; - if (!oneof_1.isOneofGroup(group)) - return false; - if (group.oneofKind === void 0) - continue; - const field = this.fields.find((f) => f.localName === group.oneofKind); - if (!field) - return false; - if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) - return false; - } - for (const field of this.fields) { - if (field.oneof !== void 0) - continue; - if (!this.field(message[field.localName], field, allowExcessProperties, depth)) - return false; - } - return true; - } - field(arg, field, allowExcessProperties, depth) { - let repeated = field.repeat; - switch (field.kind) { - case "scalar": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, field.T, depth, field.L); - return this.scalar(arg, field.T, field.L); - case "enum": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); - return this.scalar(arg, reflection_info_1.ScalarType.INT32); - case "message": - if (arg === void 0) - return true; - if (repeated) - return this.messages(arg, field.T(), allowExcessProperties, depth); - return this.message(arg, field.T(), allowExcessProperties, depth); - case "map": - if (typeof arg != "object" || arg === null) - return false; - if (depth < 2) - return true; - if (!this.mapKeys(arg, field.K, depth)) - return false; - switch (field.V.kind) { - case "scalar": - return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); - case "enum": - return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); - case "message": - return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); - } - break; - } - return true; - } - message(arg, type2, allowExcessProperties, depth) { - if (allowExcessProperties) { - return type2.isAssignable(arg, depth); - } - return type2.is(arg, depth); - } - messages(arg, type2, allowExcessProperties, depth) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (allowExcessProperties) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.isAssignable(arg[i], depth - 1)) - return false; - } else { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.is(arg[i], depth - 1)) - return false; - } - return true; + Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { + return oneof_1.isOneofGroup; + } }); + Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { + return oneof_1.setOneofValue; + } }); + Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { + return oneof_1.getOneofValue; + } }); + Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { + return oneof_1.clearOneofValue; + } }); + Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { + return oneof_1.getSelectedOneofValue; + } }); + var enum_object_1 = require_enum_object(); + Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { + return enum_object_1.listEnumValues; + } }); + Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { + return enum_object_1.listEnumNames; + } }); + Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { + return enum_object_1.listEnumNumbers; + } }); + Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { + return enum_object_1.isEnumObject; + } }); + var lower_camel_case_1 = require_lower_camel_case(); + Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { + return lower_camel_case_1.lowerCamelCase; + } }); + var assert_1 = require_assert(); + Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { + return assert_1.assert; + } }); + Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { + return assert_1.assertNever; + } }); + Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { + return assert_1.assertInt32; + } }); + Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { + return assert_1.assertUInt32; + } }); + Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { + return assert_1.assertFloat32; + } }); + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js +var require_reflection_info2 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + var runtime_1 = require_commonjs11(); + function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + m.serverStreaming = !!m.serverStreaming; + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; + return m; + } + exports2.normalizeMethodInfo = normalizeMethodInfo; + function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readMethodOptions = readMethodOptions; + function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; } - scalar(arg, type2, longType) { - let argType = typeof arg; - switch (type2) { - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - switch (longType) { - case reflection_info_1.LongType.BIGINT: - return argType == "bigint"; - case reflection_info_1.LongType.NUMBER: - return argType == "number" && !isNaN(arg); - default: - return argType == "string"; - } - case reflection_info_1.ScalarType.BOOL: - return argType == "boolean"; - case reflection_info_1.ScalarType.STRING: - return argType == "string"; - case reflection_info_1.ScalarType.BYTES: - return arg instanceof Uint8Array; - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return argType == "number" && !isNaN(arg); - default: - return argType == "number" && Number.isInteger(arg); - } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - scalars(arg, type2, depth, longType) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (Array.isArray(arg)) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!this.scalar(arg[i], type2, longType)) - return false; - } - return true; + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMethodOption = readMethodOption; + function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return void 0; } - mapKeys(map2, type2, depth) { - let keys = Object.keys(map2); - switch (type2) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); - case reflection_info_1.ScalarType.BOOL: - return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); - default: - return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); - } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - }; - exports2.ReflectionTypeCheck = ReflectionTypeCheck; + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readServiceOption = readServiceOption; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js -var require_reflection_long_convert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js +var require_service_type = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionLongConvert = void 0; - var reflection_info_1 = require_reflection_info(); - function reflectionLongConvert(long, type2) { - switch (type2) { - case reflection_info_1.LongType.BIGINT: - return long.toBigInt(); - case reflection_info_1.LongType.NUMBER: - return long.toNumber(); - default: - return long.toString(); + exports2.ServiceType = void 0; + var reflection_info_1 = require_reflection_info2(); + var ServiceType = class { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; } - } - exports2.reflectionLongConvert = reflectionLongConvert; + }; + exports2.ServiceType = ServiceType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js -var require_reflection_json_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js +var require_rpc_error = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonReader = void 0; - var json_typings_1 = require_json_typings(); - var base64_1 = require_base642(); - var reflection_info_1 = require_reflection_info(); - var pb_long_1 = require_pb_long(); - var assert_1 = require_assert(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var ReflectionJsonReader = class { - constructor(info7) { - this.info = info7; + exports2.RpcError = void 0; + var RpcError = class extends Error { + constructor(message, code = "UNKNOWN", meta) { + super(message); + this.name = "RpcError"; + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; } - prepare() { - var _a; - if (this.fMap === void 0) { - this.fMap = {}; - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - for (const field of fieldsInput) { - this.fMap[field.name] = field; - this.fMap[field.jsonName] = field; - this.fMap[field.localName] = field; - } + toString() { + const l = [this.name + ": " + this.message]; + if (this.code) { + l.push(""); + l.push("Code: " + this.code); } - } - // Cannot parse JSON for #. - assert(condition, fieldName, jsonValue) { - if (!condition) { - let what = json_typings_1.typeofJsonValue(jsonValue); - if (what == "number" || what == "boolean") - what = jsonValue.toString(); - throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + if (this.serviceName && this.methodName) { + l.push("Method: " + this.serviceName + "/" + this.methodName); } - } - /** - * Reads a message from canonical JSON format into the target message. - * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. - * - * If a message field is already present, it will be merged with the - * new data. - */ - read(input, message, options) { - this.prepare(); - const oneofsHandled = []; - for (const [jsonKey, jsonValue] of Object.entries(input)) { - const field = this.fMap[jsonKey]; - if (!field) { - if (!options.ignoreUnknownFields) - throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); - continue; - } - const localName = field.localName; - let target; - if (field.oneof) { - if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { - continue; - } - if (oneofsHandled.includes(field.oneof)) - throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); - oneofsHandled.push(field.oneof); - target = message[field.oneof] = { - oneofKind: localName - }; - } else { - target = message; - } - if (field.kind == "map") { - if (jsonValue === null) { - continue; - } - this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); - const fieldObj = target[localName]; - for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { - this.assert(jsonObjValue !== null, field.name + " map value", null); - let val2; - switch (field.V.kind) { - case "message": - val2 = field.V.T().internalJsonRead(jsonObjValue, options); - break; - case "enum": - val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); - let key = jsonObjKey; - if (field.K == reflection_info_1.ScalarType.BOOL) - key = key == "true" ? true : key == "false" ? false : key; - key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); - fieldObj[key] = val2; - } - } else if (field.repeat) { - if (jsonValue === null) - continue; - this.assert(Array.isArray(jsonValue), field.name, jsonValue); - const fieldArr = target[localName]; - for (const jsonItem of jsonValue) { - this.assert(jsonItem !== null, field.name, null); - let val2; - switch (field.kind) { - case "message": - val2 = field.T().internalJsonRead(jsonItem, options); - break; - case "enum": - val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonItem, field.T, field.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name, jsonValue); - fieldArr.push(val2); - } - } else { - switch (field.kind) { - case "message": - if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { - this.assert(field.oneof === void 0, field.name + " (oneof member)", null); - continue; - } - target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); - break; - case "enum": - if (jsonValue === null) - continue; - let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - target[localName] = val2; - break; - case "scalar": - if (jsonValue === null) - continue; - target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); - break; - } + let m = Object.entries(this.meta); + if (m.length) { + l.push(""); + l.push("Meta:"); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); } } + return l.join("\n"); } - /** - * Returns `false` for unrecognized string representations. - * - * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). - */ - enum(type2, json2, fieldName, ignoreUnknownFields) { - if (type2[0] == "google.protobuf.NullValue") - assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); - if (json2 === null) - return 0; - switch (typeof json2) { - case "number": - assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); - return json2; - case "string": - let localEnumName = json2; - if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) - localEnumName = json2.substring(type2[2].length); - let enumNumber = type2[1][localEnumName]; - if (typeof enumNumber === "undefined" && ignoreUnknownFields) { - return false; - } - assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); - return enumNumber; + }; + exports2.RpcError = RpcError; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js +var require_rpc_options = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.mergeRpcOptions = void 0; + var runtime_1 = require_commonjs11(); + function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val2 = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); + break; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); + break; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); + break; } - assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); } - scalar(json2, type2, longType, fieldName) { - let e; - try { - switch (type2) { - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - if (json2 === null) - return 0; - if (json2 === "NaN") - return Number.NaN; - if (json2 === "Infinity") - return Number.POSITIVE_INFINITY; - if (json2 === "-Infinity") - return Number.NEGATIVE_INFINITY; - if (json2 === "") { - e = "empty string"; - break; - } - if (typeof json2 == "string" && json2.trim().length !== json2.length) { - e = "extra whitespace"; - break; - } - if (typeof json2 != "string" && typeof json2 != "number") { - break; - } - let float2 = Number(json2); - if (Number.isNaN(float2)) { - e = "not a number"; - break; - } - if (!Number.isFinite(float2)) { - e = "too large or small"; - break; - } - if (type2 == reflection_info_1.ScalarType.FLOAT) - assert_1.assertFloat32(float2); - return float2; - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - if (json2 === null) - return 0; - let int32; - if (typeof json2 == "number") - int32 = json2; - else if (json2 === "") - e = "empty string"; - else if (typeof json2 == "string") { - if (json2.trim().length !== json2.length) - e = "extra whitespace"; - else - int32 = Number(json2); - } - if (int32 === void 0) - break; - if (type2 == reflection_info_1.ScalarType.UINT32) - assert_1.assertUInt32(int32); - else - assert_1.assertInt32(int32); - return int32; - // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.UINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); - // bool: - case reflection_info_1.ScalarType.BOOL: - if (json2 === null) - return false; - if (typeof json2 !== "boolean") - break; - return json2; - // string: - case reflection_info_1.ScalarType.STRING: - if (json2 === null) - return ""; - if (typeof json2 !== "string") { - e = "extra whitespace"; - break; - } - try { - encodeURIComponent(json2); - } catch (e2) { - e2 = "invalid UTF8"; - break; - } - return json2; - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - if (json2 === null || json2 === "") - return new Uint8Array(0); - if (typeof json2 !== "string") - break; - return base64_1.base64decode(json2); - } - } catch (error4) { - e = error4.message; - } - this.assert(false, fieldName + (e ? " - " + e : ""), json2); + return o; + } + exports2.mergeRpcOptions = mergeRpcOptions; + function copy(a, into) { + if (!a) + return; + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; } - }; - exports2.ReflectionJsonReader = ReflectionJsonReader; + } } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js -var require_reflection_json_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js +var require_deferred = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonWriter = void 0; - var base64_1 = require_base642(); - var pb_long_1 = require_pb_long(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var ReflectionJsonWriter = class { - constructor(info7) { - var _a; - this.fields = (_a = info7.fields) !== null && _a !== void 0 ? _a : []; - } + exports2.Deferred = exports2.DeferredState = void 0; + var DeferredState; + (function(DeferredState2) { + DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; + DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; + DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; + })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); + var Deferred = class { /** - * Converts the message to a JSON object, based on the field descriptors. + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. */ - write(message, options) { - const json2 = {}, source = message; - for (const field of this.fields) { - if (!field.oneof) { - let jsonValue2 = this.field(field, source[field.localName], options); - if (jsonValue2 !== void 0) - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; - continue; - } - const group = source[field.oneof]; - if (group.oneofKind !== field.localName) - continue; - const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; - let jsonValue = this.field(field, group[field.localName], opt); - assert_1.assert(jsonValue !== void 0); - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve8, reject) => { + this._resolve = resolve8; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch((_2) => { + }); } - return json2; } - field(field, value, options) { - let jsonValue = void 0; - if (field.kind == "map") { - assert_1.assert(typeof value == "object" && value !== null); - const jsonObj = {}; - switch (field.V.kind) { - case "scalar": - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "message": - const messageType = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.message(messageType, entryValue, field.name, options); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "enum": - const enumInfo = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); - const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - } - if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) - jsonValue = jsonObj; - } else if (field.repeat) { - assert_1.assert(Array.isArray(value)); - const jsonArr = []; - switch (field.kind) { - case "scalar": - for (let i = 0; i < value.length; i++) { - const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "enum": - const enumInfo = field.T(); - for (let i = 0; i < value.length; i++) { - assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); - const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "message": - const messageType = field.T(); - for (let i = 0; i < value.length; i++) { - const val2 = this.message(messageType, value[i], field.name, options); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - } - if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) - jsonValue = jsonArr; - } else { - switch (field.kind) { - case "scalar": - jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); - break; - case "enum": - jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); - break; - case "message": - jsonValue = this.message(field.T(), value, field.name, options); - break; - } - } - return jsonValue; + /** + * Get the current state of the promise. + */ + get state() { + return this._state; } /** - * Returns `null` as the default for google.protobuf.NullValue. + * Get the deferred promise. */ - enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { - if (type2[0] == "google.protobuf.NullValue") - return !emitDefaultValues && !optional ? void 0 : null; - if (value === void 0) { - assert_1.assert(optional); - return void 0; - } - if (value === 0 && !emitDefaultValues && !optional) - return void 0; - assert_1.assert(typeof value == "number"); - assert_1.assert(Number.isInteger(value)); - if (enumAsInteger || !type2[1].hasOwnProperty(value)) - return value; - if (type2[2]) - return type2[2] + type2[1][value]; - return type2[1][value]; + get promise() { + return this._promise; } - message(type2, value, fieldName, options) { - if (value === void 0) - return options.emitDefaultValues ? null : void 0; - return type2.internalJsonWrite(value, options); + /** + * Resolve the promise. Throws if the promise is already resolved or rejected. + */ + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; } - scalar(type2, value, fieldName, optional, emitDefaultValues) { - if (value === void 0) { - assert_1.assert(optional); - return void 0; - } - const ed = emitDefaultValues || optional; - switch (type2) { - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertInt32(value); - return value; - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertUInt32(value); - return value; - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.FLOAT: - assert_1.assertFloat32(value); - case reflection_info_1.ScalarType.DOUBLE: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assert(typeof value == "number"); - if (Number.isNaN(value)) - return "NaN"; - if (value === Number.POSITIVE_INFINITY) - return "Infinity"; - if (value === Number.NEGATIVE_INFINITY) - return "-Infinity"; - return value; - // string: - case reflection_info_1.ScalarType.STRING: - if (value === "") - return ed ? "" : void 0; - assert_1.assert(typeof value == "string"); - return value; - // bool: - case reflection_info_1.ScalarType.BOOL: - if (value === false) - return ed ? false : void 0; - assert_1.assert(typeof value == "boolean"); - return value; - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let ulong = pb_long_1.PbULong.from(value); - if (ulong.isZero() && !ed) - return void 0; - return ulong.toString(); - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let long = pb_long_1.PbLong.from(value); - if (long.isZero() && !ed) - return void 0; - return long.toString(); - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - assert_1.assert(value instanceof Uint8Array); - if (!value.byteLength) - return ed ? "" : void 0; - return base64_1.base64encode(value); - } + /** + * Reject the promise. Throws if the promise is already resolved or rejected. + */ + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; + } + /** + * Resolve the promise. Ignore if not pending. + */ + resolvePending(val2) { + if (this._state === DeferredState.PENDING) + this.resolve(val2); + } + /** + * Reject the promise. Ignore if not pending. + */ + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); } }; - exports2.ReflectionJsonWriter = ReflectionJsonWriter; + exports2.Deferred = Deferred; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js -var require_reflection_scalar_default = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js +var require_rpc_output_stream = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionScalarDefault = void 0; - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var pb_long_1 = require_pb_long(); - function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { - switch (type2) { - case reflection_info_1.ScalarType.BOOL: - return false; - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return 0; - case reflection_info_1.ScalarType.BYTES: - return new Uint8Array(0); - case reflection_info_1.ScalarType.STRING: - return ""; - default: - return 0; + exports2.RpcOutputStreamController = void 0; + var deferred_1 = require_deferred(); + var runtime_1 = require_commonjs11(); + var RpcOutputStreamController = class { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [] + }; + this._closed = false; + this._itState = { q: [] }; } - } - exports2.reflectionScalarDefault = reflectionScalarDefault; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js -var require_reflection_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryReader = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var ReflectionBinaryReader = class { - constructor(info7) { - this.info = info7; + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); } - prepare() { - var _a; - if (!this.fieldNoToField) { - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); - } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); } + // --- Controller API /** - * Reads a message from binary format into the target message. - * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. - * - * If a message field is already present, it will be merged with the - * new data. + * Is this stream already closed by a completion or error? */ - read(reader, message, options, length) { - this.prepare(); - const end = length === void 0 ? reader.len : reader.pos + length; - while (reader.pos < end) { - const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); - if (!field) { - let u = options.readUnknownField; - if (u == "throw") - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); - continue; - } - let target = message, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - target = target[field.oneof]; - if (target.oneofKind !== localName) - target = message[field.oneof] = { - oneofKind: localName - }; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - let L = field.kind == "scalar" ? field.L : void 0; - if (repeated) { - let arr = target[localName]; - if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { - let e = reader.uint32() + reader.pos; - while (reader.pos < e) - arr.push(this.scalar(reader, T, L)); - } else - arr.push(this.scalar(reader, T, L)); - } else - target[localName] = this.scalar(reader, T, L); - break; - case "message": - if (repeated) { - let arr = target[localName]; - let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); - arr.push(msg); - } else - target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); - break; - case "map": - let [mapKey, mapVal] = this.mapEntry(field, reader, options); - target[localName][mapKey] = mapVal; - break; - } - } + get closed() { + return this._closed !== false; } /** - * Read a map field, expecting key field = 1, value field = 2 + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. */ - mapEntry(field, reader, options) { - let length = reader.uint32(); - let end = reader.pos + length; - let key = void 0; - let val2 = void 0; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case 1: - if (field.K == reflection_info_1.ScalarType.BOOL) - key = reader.bool().toString(); - else - key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); - break; - case 2: - switch (field.V.kind) { - case "scalar": - val2 = this.scalar(reader, field.V.T, field.V.L); - break; - case "enum": - val2 = reader.int32(); - break; - case "message": - val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); - break; - } - break; - default: - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); - } - } - if (key === void 0) { - let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); - key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; - } - if (val2 === void 0) - switch (field.V.kind) { - case "scalar": - val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); - break; - case "enum": - val2 = 0; - break; - case "message": - val2 = field.V.T().create(); - break; + notifyNext(message, error4, complete) { + runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); + if (message) + this.notifyMessage(message); + if (error4) + this.notifyError(error4); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. + * + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, "stream is closed"); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach((l) => l(message)); + this._lis.nxt.forEach((l) => l(message, void 0, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. + * + * Triggers onNext and onError callbacks. + */ + notifyError(error4) { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = error4; + this.pushIt(error4); + this._lis.err.forEach((l) => l(error4)); + this._lis.nxt.forEach((l) => l(void 0, error4, false)); + this.clearLis(); + } + /** + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. + */ + notifyComplete() { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach((l) => l()); + this._lis.nxt.forEach((l) => l(void 0, void 0, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); + runtime_1.assert(!state.p, "iterator contract broken"); + let first = state.q.shift(); + if (first) + return "value" in first ? Promise.resolve(first) : Promise.reject(first); + state.p = new deferred_1.Deferred(); + return state.p.promise; } - return [key, val2]; + }; } - scalar(reader, type2, longType) { - switch (type2) { - case reflection_info_1.ScalarType.INT32: - return reader.int32(); - case reflection_info_1.ScalarType.STRING: - return reader.string(); - case reflection_info_1.ScalarType.BOOL: - return reader.bool(); - case reflection_info_1.ScalarType.DOUBLE: - return reader.double(); - case reflection_info_1.ScalarType.FLOAT: - return reader.float(); - case reflection_info_1.ScalarType.INT64: - return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); - case reflection_info_1.ScalarType.UINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); - case reflection_info_1.ScalarType.FIXED32: - return reader.fixed32(); - case reflection_info_1.ScalarType.BYTES: - return reader.bytes(); - case reflection_info_1.ScalarType.UINT32: - return reader.uint32(); - case reflection_info_1.ScalarType.SFIXED32: - return reader.sfixed32(); - case reflection_info_1.ScalarType.SFIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); - case reflection_info_1.ScalarType.SINT32: - return reader.sint32(); - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (state.p) { + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + "value" in result ? p.resolve(result) : p.reject(result); + delete state.p; + } else { + state.q.push(result); } } }; - exports2.ReflectionBinaryReader = ReflectionBinaryReader; + exports2.RpcOutputStreamController = RpcOutputStreamController; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js -var require_reflection_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js +var require_unary_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryWriter = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var pb_long_1 = require_pb_long(); - var ReflectionBinaryWriter = class { - constructor(info7) { - this.info = info7; - } - prepare() { - if (!this.fields) { - const fieldsInput = this.info.fields ? this.info.fields.concat() : []; - this.fields = fieldsInput.sort((a, b) => a.no - b.no); - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - /** - * Writes the message to binary format. - */ - write(message, writer, options) { - this.prepare(); - for (const field of this.fields) { - let value, emitDefault, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - const group = message[field.oneof]; - if (group.oneofKind !== localName) - continue; - value = group[localName]; - emitDefault = true; - } else { - value = message[localName]; - emitDefault = false; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (repeated) { - assert_1.assert(Array.isArray(value)); - if (repeated == reflection_info_1.RepeatType.PACKED) - this.packed(writer, T, field.no, value); - else - for (const item of value) - this.scalar(writer, T, field.no, item, true); - } else if (value === void 0) - assert_1.assert(field.opt); - else - this.scalar(writer, T, field.no, value, emitDefault || field.opt); - break; - case "message": - if (repeated) { - assert_1.assert(Array.isArray(value)); - for (const item of value) - this.message(writer, options, field.T(), field.no, item); - } else { - this.message(writer, options, field.T(), field.no, value); - } - break; - case "map": - assert_1.assert(typeof value == "object" && value !== null); - for (const [key, val2] of Object.entries(value)) - this.mapEntry(writer, options, field, key, val2); - break; + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - let u = options.writeUnknownFields; - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); - } - mapEntry(writer, options, field, key, value) { - writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let keyValue = key; - switch (field.K) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - keyValue = Number.parseInt(key); - break; - case reflection_info_1.ScalarType.BOOL: - assert_1.assert(key == "true" || key == "false"); - keyValue = key == "true"; - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - this.scalar(writer, field.K, 1, keyValue, true); - switch (field.V.kind) { - case "scalar": - this.scalar(writer, field.V.T, 2, value, true); - break; - case "enum": - this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); - break; - case "message": - this.message(writer, options, field.V.T(), 2, value); - break; + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } - writer.join(); - } - message(writer, options, handler, fieldNo, value) { - if (value === void 0) - return; - handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); - writer.join(); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UnaryCall = void 0; + var UnaryCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; } /** - * Write a single scalar value. + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. */ - scalar(writer, type2, fieldNo, value, emitDefault) { - let [wireType, method, isDefault] = this.scalarInfo(type2, value); - if (!isDefault || emitDefault) { - writer.tag(fieldNo, wireType); - writer[method](value); + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.UnaryCall = UnaryCall; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js +var require_server_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerStreamingCall = void 0; + var ServerStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } /** - * Write an array of scalar values in packed format. + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. */ - packed(writer, type2, fieldNo, value) { - if (!value.length) - return; - assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); - writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let [, method] = this.scalarInfo(type2); - for (let i = 0; i < value.length; i++) - writer[method](value[i]); - writer.join(); + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } - /** - * Get information for writing a scalar value. - * - * Returns tuple: - * [0]: appropriate WireType - * [1]: name of the appropriate method of IBinaryWriter - * [2]: whether the given value is a default value - * - * If argument `value` is omitted, [2] is always false. - */ - scalarInfo(type2, value) { - let t = binary_format_contract_1.WireType.Varint; - let m; - let i = value === void 0; - let d = value === 0; - switch (type2) { - case reflection_info_1.ScalarType.INT32: - m = "int32"; - break; - case reflection_info_1.ScalarType.STRING: - d = i || !value.length; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "string"; - break; - case reflection_info_1.ScalarType.BOOL: - d = value === false; - m = "bool"; - break; - case reflection_info_1.ScalarType.UINT32: - m = "uint32"; - break; - case reflection_info_1.ScalarType.DOUBLE: - t = binary_format_contract_1.WireType.Bit64; - m = "double"; - break; - case reflection_info_1.ScalarType.FLOAT: - t = binary_format_contract_1.WireType.Bit32; - m = "float"; - break; - case reflection_info_1.ScalarType.INT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "int64"; - break; - case reflection_info_1.ScalarType.UINT64: - d = i || pb_long_1.PbULong.from(value).isZero(); - m = "uint64"; - break; - case reflection_info_1.ScalarType.FIXED64: - d = i || pb_long_1.PbULong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "fixed64"; - break; - case reflection_info_1.ScalarType.BYTES: - d = i || !value.byteLength; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "bytes"; - break; - case reflection_info_1.ScalarType.FIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "fixed32"; - break; - case reflection_info_1.ScalarType.SFIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "sfixed32"; - break; - case reflection_info_1.ScalarType.SFIXED64: - d = i || pb_long_1.PbLong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "sfixed64"; - break; - case reflection_info_1.ScalarType.SINT32: - m = "sint32"; - break; - case reflection_info_1.ScalarType.SINT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "sint64"; - break; - } - return [t, m, i || d]; + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + exports2.ServerStreamingCall = ServerStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js -var require_reflection_create = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js +var require_client_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionCreate = void 0; - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var message_type_contract_1 = require_message_type_contract(); - function reflectionCreate(type2) { - const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); - for (let field of type2.fields) { - let name = field.localName; - if (field.opt) - continue; - if (field.oneof) - msg[field.oneof] = { oneofKind: void 0 }; - else if (field.repeat) - msg[name] = []; - else - switch (field.kind) { - case "scalar": - msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); - break; - case "enum": - msg[name] = 0; - break; - case "map": - msg[name] = {}; - break; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ClientStreamingCall = void 0; + var ClientStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; } - return msg; - } - exports2.reflectionCreate = reflectionCreate; + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.ClientStreamingCall = ClientStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js -var require_reflection_merge_partial = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js +var require_duplex_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionMergePartial = void 0; - function reflectionMergePartial(info7, target, source) { - let fieldValue, input = source, output; - for (let field of info7.fields) { - let name = field.localName; - if (field.oneof) { - const group = input[field.oneof]; - if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { - continue; - } - fieldValue = group[name]; - output = target[field.oneof]; - output.oneofKind = group.oneofKind; - if (fieldValue == void 0) { - delete output[name]; - continue; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - } else { - fieldValue = input[name]; - output = target; - if (fieldValue == void 0) { - continue; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - if (field.repeat) - output[name].length = fieldValue.length; - switch (field.kind) { - case "scalar": - case "enum": - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = fieldValue[i]; - else - output[name] = fieldValue; - break; - case "message": - let T = field.T(); - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = T.create(fieldValue[i]); - else if (output[name] === void 0) - output[name] = T.create(fieldValue); - else - T.mergePartial(output[name], fieldValue); - break; - case "map": - switch (field.V.kind) { - case "scalar": - case "enum": - Object.assign(output[name], fieldValue); - break; - case "message": - let T2 = field.V.T(); - for (let k of Object.keys(fieldValue)) - output[name][k] = T2.create(fieldValue[k]); - break; - } - break; + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } - } - } - exports2.reflectionMergePartial = reflectionMergePartial; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js -var require_reflection_equals = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { - "use strict"; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionEquals = void 0; - var reflection_info_1 = require_reflection_info(); - function reflectionEquals(info7, a, b) { - if (a === b) - return true; - if (!a || !b) - return false; - for (let field of info7.fields) { - let localName = field.localName; - let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; - let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; - switch (field.kind) { - case "enum": - case "scalar": - let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) - return false; - break; - case "map": - if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) - return false; - break; - case "message": - let T = field.T(); - if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) - return false; - break; - } + exports2.DuplexStreamingCall = void 0; + var DuplexStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } - return true; - } - exports2.reflectionEquals = reflectionEquals; - var objectValues = Object.values; - function primitiveEq(type2, a, b) { - if (a === b) - return true; - if (type2 !== reflection_info_1.ScalarType.BYTES) - return false; - let ba = a; - let bb = b; - if (ba.length !== bb.length) - return false; - for (let i = 0; i < ba.length; i++) - if (ba[i] != bb[i]) - return false; - return true; - } - function repeatedPrimitiveEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!primitiveEq(type2, a[i], b[i])) - return false; - return true; - } - function repeatedMsgEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!type2.equals(a[i], b[i])) - return false; - return true; - } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers + }; + }); + } + }; + exports2.DuplexStreamingCall = DuplexStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js -var require_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js +var require_test_transport = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_type_check_1 = require_reflection_type_check(); - var reflection_json_reader_1 = require_reflection_json_reader(); - var reflection_json_writer_1 = require_reflection_json_writer(); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - var reflection_create_1 = require_reflection_create(); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - var json_typings_1 = require_json_typings(); - var json_format_contract_1 = require_json_format_contract(); - var reflection_equals_1 = require_reflection_equals(); - var binary_writer_1 = require_binary_writer(); - var binary_reader_1 = require_binary_reader(); - var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); - var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; - var MessageType = class { - constructor(name, fields, options) { - this.defaultCheckDepth = 16; - this.typeName = name; - this.fields = fields.map(reflection_info_1.normalizeFieldInfo); - this.options = options !== null && options !== void 0 ? options : {}; - messageTypeDescriptor.value = this; - this.messagePrototype = Object.create(null, baseDescriptors); - this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); - this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); - this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); - this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); - this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - create(value) { - let message = reflection_create_1.reflectionCreate(this); - if (value !== void 0) { - reflection_merge_partial_1.reflectionMergePartial(this, message, value); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - return message; - } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TestTransport = void 0; + var rpc_error_1 = require_rpc_error(); + var runtime_1 = require_commonjs11(); + var rpc_output_stream_1 = require_rpc_output_stream(); + var rpc_options_1 = require_rpc_options(); + var unary_call_1 = require_unary_call(); + var server_streaming_call_1 = require_server_streaming_call(); + var client_streaming_call_1 = require_client_streaming_call(); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + var TestTransport = class _TestTransport { /** - * Clone the message. - * - * Unknown fields are discarded. + * Initialize with mock data. Omitted fields have default value. */ - clone(message) { - let copy = this.create(); - reflection_merge_partial_1.reflectionMergePartial(this, copy, message); - return copy; + constructor(data) { + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; } /** - * Determines whether two message of the same type have the same field values. - * Checks for deep equality, traversing repeated fields, oneof groups, maps - * and messages recursively. - * Will also return true if both messages are `undefined`. + * Sent message(s) during the last operation. */ - equals(a, b) { - return reflection_equals_1.reflectionEquals(this, a, b); + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; + } else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; } /** - * Is the given value assignable to our message type - * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + * Sending message(s) completed? */ - is(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, false); + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } else if (typeof this.lastInput == "object") { + return true; + } + return false; } - /** - * Is the given value assignable to our message type, - * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? - */ - isAssignable(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, true); + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); } - /** - * Copy partial data into the target message. - */ - mergePartial(target, source) { - reflection_merge_partial_1.reflectionMergePartial(this, target, source); + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } else if (this.data.response !== void 0) { + r = this.data.response; + } else { + r = method.O.create(); + } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); } /** - * Create a new message from binary format. + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. */ - fromBinary(data, options) { - let opt = binary_reader_1.binaryReadOptions(options); - return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + streamResponses(method, stream2, abort) { + return __awaiter4(this, void 0, void 0, function* () { + const messages = []; + if (this.data.response === void 0) { + messages.push(method.O.create()); + } else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + try { + yield delay2(this.responseDelay, abort)(void 0); + } catch (error4) { + stream2.notifyError(error4); + return; + } + if (this.data.response instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.response); + return; + } + for (let msg of messages) { + stream2.notifyMessage(msg); + try { + yield delay2(this.betweenResponseDelay, abort)(void 0); + } catch (error4) { + stream2.notifyError(error4); + return; + } + } + if (this.data.status instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.status); + return; + } + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.trailers); + return; + } + stream2.notifyComplete(); + }); + } + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); + } + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); + } + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } + } + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); + } + unary(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { + }).then(delay2(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); + } + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); + } + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { + }).then(delay2(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + } + }; + exports2.TestTransport = TestTransport; + TestTransport.defaultHeaders = { + responseHeader: "test" + }; + TestTransport.defaultStatus = { + code: "OK", + detail: "all good" + }; + TestTransport.defaultTrailers = { + responseTrailer: "test" + }; + function delay2(ms, abort) { + return (v) => new Promise((resolve8, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } else { + const id = setTimeout(() => resolve8(v), ms); + if (abort) { + abort.addEventListener("abort", (ev) => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } + } + }); + } + var TestInputStream = class { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; + } + get sent() { + return this._sent; + } + get completed() { + return this._completed; + } + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); + } + const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; + return Promise.resolve(void 0).then(() => { + this._sent.push(message); + }).then(delay2(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); + } + const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; + return Promise.resolve(void 0).then(() => { + this._completed = true; + }).then(delay2(delayMs, this.abort)); } - /** - * Read a new message from a JSON value. - */ - fromJson(json2, options) { - return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + }; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js +var require_rpc_interceptor = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; + var runtime_1 = require_commonjs11(); + function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + } + return tail(method, input, options); } - /** - * Read a new message from a JSON string. - * This is equivalent to `T.fromJson(JSON.parse(json))`. - */ - fromJsonString(json2, options) { - let value = JSON.parse(json2); - return this.fromJson(value, options); + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); } - /** - * Write the message to canonical JSON value. - */ - toJson(message, options) { - return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + } + return tail(method, options); } - /** - * Convert the message to canonical JSON string. - * This is equivalent to `JSON.stringify(T.toJson(t))` - */ - toJsonString(message, options) { - var _a; - let value = this.toJson(message, options); - return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); } - /** - * Write the message to binary format. - */ - toBinary(message, options) { - let opt = binary_writer_1.binaryWriteOptions(options); - return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + runtime_1.assertNever(kind); + } + exports2.stackIntercept = stackIntercept; + function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); + } + exports2.stackUnaryInterceptors = stackUnaryInterceptors; + function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); + } + exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; + function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); + } + exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; + function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); + } + exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js +var require_server_call_context = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerCallContextController = void 0; + var ServerCallContextController = class { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; } /** - * This is an internal method. If you just want to read a message from - * JSON, use `fromJson()` or `fromJsonString()`. + * Set the call cancelled. * - * Reads JSON value and merges the fields into the target - * according to protobuf rules. If the target is omitted, - * a new instance is created first. + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. */ - internalJsonRead(json2, options, target) { - if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refJsonReader.read(json2, message, options); - return message; + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } } - throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); } /** - * This is an internal method. If you just want to write a message - * to JSON, use `toJson()` or `toJsonString(). - * - * Writes JSON value and returns it. + * Send response headers. */ - internalJsonWrite(message, options) { - return this.refJsonWriter.write(message, options); + sendResponseHeaders(data) { + this._sendRH(data); } /** - * This is an internal method. If you just want to write a message - * in binary format, use `toBinary()`. + * Is the call cancelled? * - * Serializes the message in binary format and appends it to the given - * writer. Returns passed writer. + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. */ - internalBinaryWrite(message, writer, options) { - this.refBinWriter.write(message, writer, options); - return writer; + get cancelled() { + return this._cancelled; } /** - * This is an internal method. If you just want to read a message from - * binary data, use `fromBinary()`. - * - * Reads data from binary format and merges the fields into - * the target according to protobuf rules. If the target is - * omitted, a new instance is created first. + * Add a callback for cancellation. */ - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refBinReader.read(reader, message, options, length); - return message; + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; } }; - exports2.MessageType = MessageType; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js -var require_reflection_contains_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.containsMessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - function containsMessageType(msg) { - return msg[message_type_contract_1.MESSAGE_TYPE] != null; - } - exports2.containsMessageType = containsMessageType; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js -var require_enum_object = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; - function isEnumObject(arg) { - if (typeof arg != "object" || arg === null) { - return false; - } - if (!arg.hasOwnProperty(0)) { - return false; - } - for (let k of Object.keys(arg)) { - let num = parseInt(k); - if (!Number.isNaN(num)) { - let nam = arg[num]; - if (nam === void 0) - return false; - if (arg[nam] !== num) - return false; - } else { - let num2 = arg[k]; - if (num2 === void 0) - return false; - if (typeof num2 !== "number") - return false; - if (arg[num2] === void 0) - return false; - } - } - return true; - } - exports2.isEnumObject = isEnumObject; - function listEnumValues(enumObject) { - if (!isEnumObject(enumObject)) - throw new Error("not a typescript enum object"); - let values = []; - for (let [name, number] of Object.entries(enumObject)) - if (typeof number == "number") - values.push({ name, number }); - return values; - } - exports2.listEnumValues = listEnumValues; - function listEnumNames(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.name); - } - exports2.listEnumNames = listEnumNames; - function listEnumNumbers(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); - } - exports2.listEnumNumbers = listEnumNumbers; + exports2.ServerCallContextController = ServerCallContextController; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/index.js -var require_commonjs11 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var json_typings_1 = require_json_typings(); - Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { - return json_typings_1.typeofJsonValue; - } }); - Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { - return json_typings_1.isJsonObject; - } }); - var base64_1 = require_base642(); - Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { - return base64_1.base64decode; - } }); - Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { - return base64_1.base64encode; - } }); - var protobufjs_utf8_1 = require_protobufjs_utf8(); - Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { - return protobufjs_utf8_1.utf8read; - } }); - var binary_format_contract_1 = require_binary_format_contract(); - Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { - return binary_format_contract_1.WireType; - } }); - Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { - return binary_format_contract_1.mergeBinaryOptions; - } }); - Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { - return binary_format_contract_1.UnknownFieldHandler; - } }); - var binary_reader_1 = require_binary_reader(); - Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { - return binary_reader_1.BinaryReader; - } }); - Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { - return binary_reader_1.binaryReadOptions; - } }); - var binary_writer_1 = require_binary_writer(); - Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { - return binary_writer_1.BinaryWriter; - } }); - Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { - return binary_writer_1.binaryWriteOptions; - } }); - var pb_long_1 = require_pb_long(); - Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { - return pb_long_1.PbLong; - } }); - Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { - return pb_long_1.PbULong; - } }); - var json_format_contract_1 = require_json_format_contract(); - Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonReadOptions; - } }); - Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonWriteOptions; - } }); - Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { - return json_format_contract_1.mergeJsonOptions; - } }); - var message_type_contract_1 = require_message_type_contract(); - Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { - return message_type_contract_1.MESSAGE_TYPE; - } }); - var message_type_1 = require_message_type(); - Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { - return message_type_1.MessageType; - } }); - var reflection_info_1 = require_reflection_info(); - Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { - return reflection_info_1.ScalarType; - } }); - Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { - return reflection_info_1.LongType; - } }); - Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { - return reflection_info_1.RepeatType; - } }); - Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { - return reflection_info_1.normalizeFieldInfo; - } }); - Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { - return reflection_info_1.readFieldOptions; - } }); - Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { - return reflection_info_1.readFieldOption; - } }); - Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { - return reflection_info_1.readMessageOption; - } }); - var reflection_type_check_1 = require_reflection_type_check(); - Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { - return reflection_type_check_1.ReflectionTypeCheck; - } }); - var reflection_create_1 = require_reflection_create(); - Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { - return reflection_create_1.reflectionCreate; - } }); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { - return reflection_scalar_default_1.reflectionScalarDefault; - } }); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { - return reflection_merge_partial_1.reflectionMergePartial; - } }); - var reflection_equals_1 = require_reflection_equals(); - Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { - return reflection_equals_1.reflectionEquals; - } }); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { - return reflection_binary_reader_1.ReflectionBinaryReader; - } }); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { - return reflection_binary_writer_1.ReflectionBinaryWriter; - } }); - var reflection_json_reader_1 = require_reflection_json_reader(); - Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { - return reflection_json_reader_1.ReflectionJsonReader; - } }); - var reflection_json_writer_1 = require_reflection_json_writer(); - Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { - return reflection_json_writer_1.ReflectionJsonWriter; - } }); - var reflection_contains_message_type_1 = require_reflection_contains_message_type(); - Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { - return reflection_contains_message_type_1.containsMessageType; - } }); - var oneof_1 = require_oneof(); - Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { - return oneof_1.isOneofGroup; + var service_type_1 = require_service_type(); + Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { + return service_type_1.ServiceType; } }); - Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { - return oneof_1.setOneofValue; + var reflection_info_1 = require_reflection_info2(); + Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { + return reflection_info_1.readMethodOptions; } }); - Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { - return oneof_1.getOneofValue; + Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { + return reflection_info_1.readMethodOption; } }); - Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { - return oneof_1.clearOneofValue; + Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { + return reflection_info_1.readServiceOption; } }); - Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { - return oneof_1.getSelectedOneofValue; + var rpc_error_1 = require_rpc_error(); + Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { + return rpc_error_1.RpcError; } }); - var enum_object_1 = require_enum_object(); - Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { - return enum_object_1.listEnumValues; + var rpc_options_1 = require_rpc_options(); + Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { + return rpc_options_1.mergeRpcOptions; } }); - Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { - return enum_object_1.listEnumNames; + var rpc_output_stream_1 = require_rpc_output_stream(); + Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { + return rpc_output_stream_1.RpcOutputStreamController; } }); - Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { - return enum_object_1.listEnumNumbers; + var test_transport_1 = require_test_transport(); + Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { + return test_transport_1.TestTransport; } }); - Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { - return enum_object_1.isEnumObject; + var deferred_1 = require_deferred(); + Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { + return deferred_1.Deferred; } }); - var lower_camel_case_1 = require_lower_camel_case(); - Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { - return lower_camel_case_1.lowerCamelCase; + Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { + return deferred_1.DeferredState; } }); - var assert_1 = require_assert(); - Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { - return assert_1.assert; + var duplex_streaming_call_1 = require_duplex_streaming_call(); + Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { + return duplex_streaming_call_1.DuplexStreamingCall; } }); - Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { - return assert_1.assertNever; + var client_streaming_call_1 = require_client_streaming_call(); + Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { + return client_streaming_call_1.ClientStreamingCall; } }); - Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { - return assert_1.assertInt32; + var server_streaming_call_1 = require_server_streaming_call(); + Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { + return server_streaming_call_1.ServerStreamingCall; } }); - Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { - return assert_1.assertUInt32; + var unary_call_1 = require_unary_call(); + Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { + return unary_call_1.UnaryCall; } }); - Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { - return assert_1.assertFloat32; + var rpc_interceptor_1 = require_rpc_interceptor(); + Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { + return rpc_interceptor_1.stackIntercept; + } }); + Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackDuplexStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackClientStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackServerStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackUnaryInterceptors; + } }); + var server_call_context_1 = require_server_call_context(); + Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { + return server_call_context_1.ServerCallContextController; } }); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js -var require_reflection_info2 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; - var runtime_1 = require_commonjs11(); - function normalizeMethodInfo(method, service) { - var _a, _b, _c; - let m = method; - m.service = service; - m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); - m.serverStreaming = !!m.serverStreaming; - m.clientStreaming = !!m.clientStreaming; - m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; - m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; - return m; - } - exports2.normalizeMethodInfo = normalizeMethodInfo; - function readMethodOptions(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readMethodOptions = readMethodOptions; - function readMethodOption(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readMethodOption = readMethodOption; - function readServiceOption(service, extensionName, extensionType) { - const options = service.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readServiceOption = readServiceOption; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js -var require_service_type = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js +var require_cachescope = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceType = void 0; - var reflection_info_1 = require_reflection_info2(); - var ServiceType = class { - constructor(typeName, methods, options) { - this.typeName = typeName; - this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); - this.options = options !== null && options !== void 0 ? options : {}; + exports2.CacheScope = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var CacheScope$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheScope", [ + { + no: 1, + name: "scope", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "permission", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + create(value) { + const message = { scope: "", permission: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string scope */ + 1: + message.scope = reader.string(); + break; + case /* int64 permission */ + 2: + message.permission = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.scope !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); + if (message.permission !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.ServiceType = ServiceType; + exports2.CacheScope = new CacheScope$Type(); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js -var require_rpc_error = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js +var require_cachemetadata = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcError = void 0; - var RpcError = class extends Error { - constructor(message, code = "UNKNOWN", meta) { - super(message); - this.name = "RpcError"; - Object.setPrototypeOf(this, new.target.prototype); - this.code = code; - this.meta = meta !== null && meta !== void 0 ? meta : {}; + exports2.CacheMetadata = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachescope_1 = require_cachescope(); + var CacheMetadata$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheMetadata", [ + { + no: 1, + name: "repository_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } + ]); } - toString() { - const l = [this.name + ": " + this.message]; - if (this.code) { - l.push(""); - l.push("Code: " + this.code); - } - if (this.serviceName && this.methodName) { - l.push("Method: " + this.serviceName + "/" + this.methodName); - } - let m = Object.entries(this.meta); - if (m.length) { - l.push(""); - l.push("Meta:"); - for (let [k, v] of m) { - l.push(` ${k}: ${v}`); + create(value) { + const message = { repositoryId: "0", scope: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 repository_id */ + 1: + message.repositoryId = reader.int64().toString(); + break; + case /* repeated github.actions.results.entities.v1.CacheScope scope */ + 2: + message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - return l.join("\n"); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.repositoryId !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); + for (let i = 0; i < message.scope.length; i++) + cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.RpcError = RpcError; + exports2.CacheMetadata = new CacheMetadata$Type(); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js -var require_rpc_options = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js +var require_cache2 = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeRpcOptions = void 0; + exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); var runtime_1 = require_commonjs11(); - function mergeRpcOptions(defaults, options) { - if (!options) - return defaults; - let o = {}; - copy(defaults, o); - copy(options, o); - for (let key of Object.keys(options)) { - let val2 = options[key]; - switch (key) { - case "jsonOptions": - o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); - break; - case "binaryOptions": - o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); - break; - case "meta": - o.meta = {}; - copy(defaults.meta, o.meta); - copy(options.meta, o.meta); - break; - case "interceptors": - o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); - break; + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachemetadata_1 = require_cachemetadata(); + var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* string version */ + 3: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.version !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); + var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedUploadUrl: "", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); + var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size_bytes", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", sizeBytes: "0", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* int64 size_bytes */ + 3: + message.sizeBytes = reader.int64().toString(); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.sizeBytes !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); + var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "entry_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, entryId: "0", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* int64 entry_id */ + 2: + message.entryId = reader.int64().toString(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.entryId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - return o; - } - exports2.mergeRpcOptions = mergeRpcOptions; - function copy(a, into) { - if (!a) - return; - let c = into; - for (let [k, v] of Object.entries(a)) { - if (v instanceof Date) - c[k] = new Date(v.getTime()); - else if (Array.isArray(v)) - c[k] = v.concat(); - else - c[k] = v; + }; + exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); + var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "restore_keys", + kind: "scalar", + repeat: 2, + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - } - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js -var require_deferred = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Deferred = exports2.DeferredState = void 0; - var DeferredState; - (function(DeferredState2) { - DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; - DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; - DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; - })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); - var Deferred = class { - /** - * @param preventUnhandledRejectionWarning - prevents the warning - * "Unhandled Promise rejection" by adding a noop rejection handler. - * Working with calls returned from the runtime-rpc package in an - * async function usually means awaiting one call property after - * the other. This means that the "status" is not being awaited when - * an earlier await for the "headers" is rejected. This causes the - * "unhandled promise reject" warning. A more correct behaviour for - * calls might be to become aware whether at least one of the - * promises is handled and swallow the rejection warning for the - * others. - */ - constructor(preventUnhandledRejectionWarning = true) { - this._state = DeferredState.PENDING; - this._promise = new Promise((resolve8, reject) => { - this._resolve = resolve8; - this._reject = reject; - }); - if (preventUnhandledRejectionWarning) { - this._promise.catch((_2) => { - }); - } + create(value) { + const message = { key: "", restoreKeys: [], version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - /** - * Get the current state of the promise. - */ - get state() { - return this._state; + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* repeated string restore_keys */ + 3: + message.restoreKeys.push(reader.string()); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - /** - * Get the deferred promise. - */ - get promise() { - return this._promise; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + for (let i = 0; i < message.restoreKeys.length; i++) + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - /** - * Resolve the promise. Throws if the promise is already resolved or rejected. - */ - resolve(value) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); - this._resolve(value); - this._state = DeferredState.RESOLVED; + }; + exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); + var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_download_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "matched_key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - /** - * Reject the promise. Throws if the promise is already resolved or rejected. - */ - reject(reason) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); - this._reject(reason); - this._state = DeferredState.REJECTED; + create(value) { + const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - /** - * Resolve the promise. Ignore if not pending. - */ - resolvePending(val2) { - if (this._state === DeferredState.PENDING) - this.resolve(val2); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_download_url */ + 2: + message.signedDownloadUrl = reader.string(); + break; + case /* string matched_key */ + 3: + message.matchedKey = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - /** - * Reject the promise. Ignore if not pending. - */ - rejectPending(reason) { - if (this._state === DeferredState.PENDING) - this.reject(reason); + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedDownloadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); + if (message.matchedKey !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.Deferred = Deferred; + exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); + exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ + { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, + { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, + { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } + ]); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js -var require_rpc_output_stream = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js +var require_cache_twirp_client = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcOutputStreamController = void 0; - var deferred_1 = require_deferred(); - var runtime_1 = require_commonjs11(); - var RpcOutputStreamController = class { - constructor() { - this._lis = { - nxt: [], - msg: [], - err: [], - cmp: [] - }; - this._closed = false; - this._itState = { q: [] }; - } - // --- RpcOutputStream callback API - onNext(callback) { - return this.addLis(callback, this._lis.nxt); - } - onMessage(callback) { - return this.addLis(callback, this._lis.msg); - } - onError(callback) { - return this.addLis(callback, this._lis.err); - } - onComplete(callback) { - return this.addLis(callback, this._lis.cmp); - } - addLis(callback, list) { - list.push(callback); - return () => { - let i = list.indexOf(callback); - if (i >= 0) - list.splice(i, 1); - }; - } - // remove all listeners - clearLis() { - for (let l of Object.values(this._lis)) - l.splice(0, l.length); + exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; + var cache_1 = require_cache2(); + var CacheServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - // --- Controller API - /** - * Is this stream already closed by a completion or error? - */ - get closed() { - return this._closed !== false; + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Emit message, close with error, or close successfully, but only one - * at a time. - * Can be used to wrap a stream by using the other stream's `onNext`. - */ - notifyNext(message, error4, complete) { - runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); - if (message) - this.notifyMessage(message); - if (error4) - this.notifyError(error4); - if (complete) - this.notifyComplete(); + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Emits a new message. Throws if stream is closed. - * - * Triggers onNext and onMessage callbacks. - */ - notifyMessage(message) { - runtime_1.assert(!this.closed, "stream is closed"); - this.pushIt({ value: message, done: false }); - this._lis.msg.forEach((l) => l(message)); - this._lis.nxt.forEach((l) => l(message, void 0, false)); + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Closes the stream with an error. Throws if stream is closed. - * - * Triggers onNext and onError callbacks. - */ - notifyError(error4) { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = error4; - this.pushIt(error4); - this._lis.err.forEach((l) => l(error4)); - this._lis.nxt.forEach((l) => l(void 0, error4, false)); - this.clearLis(); + }; + exports2.CacheServiceClientJSON = CacheServiceClientJSON; + var CacheServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - /** - * Closes the stream successfully. Throws if stream is closed. - * - * Triggers onNext and onComplete callbacks. - */ - notifyComplete() { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = true; - this.pushIt({ value: null, done: true }); - this._lis.cmp.forEach((l) => l()); - this._lis.nxt.forEach((l) => l(void 0, void 0, true)); - this.clearLis(); + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); } - /** - * Creates an async iterator (that can be used with `for await {...}`) - * to consume the stream. - * - * Some things to note: - * - If an error occurs, the `for await` will throw it. - * - If an error occurred before the `for await` was started, `for await` - * will re-throw it. - * - If the stream is already complete, the `for await` will be empty. - * - If your `for await` consumes slower than the stream produces, - * for example because you are relaying messages in a slow operation, - * messages are queued. - */ - [Symbol.asyncIterator]() { - if (this._closed === true) - this.pushIt({ value: null, done: true }); - else if (this._closed !== false) - this.pushIt(this._closed); - return { - next: () => { - let state = this._itState; - runtime_1.assert(state, "bad state"); - runtime_1.assert(!state.p, "iterator contract broken"); - let first = state.q.shift(); - if (first) - return "value" in first ? Promise.resolve(first) : Promise.reject(first); - state.p = new deferred_1.Deferred(); - return state.p.promise; - } - }; + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); } - // "push" a new iterator result. - // this either resolves a pending promise, or enqueues the result. - pushIt(result) { - let state = this._itState; - if (state.p) { - const p = state.p; - runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); - "value" in result ? p.resolve(result) : p.reject(result); - delete state.p; - } else { - state.q.push(result); - } + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.RpcOutputStreamController = RpcOutputStreamController; + exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js -var require_unary_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/util.js +var require_util10 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UnaryCall = void 0; - var UnaryCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; + exports2.maskSecretUrls = exports2.maskSigUrl = void 0; + var core_1 = require_core(); + function maskSigUrl(url2) { + if (!url2) + return; + try { + const parsedUrl = new URL(url2); + const signature = parsedUrl.searchParams.get("sig"); + if (signature) { + (0, core_1.setSecret)(signature); + (0, core_1.setSecret)(encodeURIComponent(signature)); + } + } catch (error4) { + (0, core_1.debug)(`Failed to parse URL: ${url2} ${error4 instanceof Error ? error4.message : String(error4)}`); + } + } + exports2.maskSigUrl = maskSigUrl; + function maskSecretUrls(body) { + if (typeof body !== "object" || body === null) { + (0, core_1.debug)("body is not an object or is null"); + return; } - /** - * If you are only interested in the final outcome of this call, - * you can await it to receive a `FinishedUnaryCall`. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { + maskSigUrl(body.signed_upload_url); } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - response, - status, - trailers - }; - }); + if ("signed_download_url" in body && typeof body.signed_download_url === "string") { + maskSigUrl(body.signed_download_url); } - }; - exports2.UnaryCall = UnaryCall; + } + exports2.maskSecretUrls = maskSecretUrls; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js -var require_server_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js +var require_cacheTwirpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -72465,117 +75398,182 @@ var require_server_streaming_call = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerStreamingCall = void 0; - var ServerStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * You should first setup some listeners to the `request` to - * see the actual messages the server replied with. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + exports2.internalCacheTwirpClient = void 0; + var core_1 = require_core(); + var user_agent_1 = require_user_agent(); + var errors_1 = require_errors2(); + var config_1 = require_config(); + var cacheUtils_1 = require_cacheUtils(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib4(); + var cache_twirp_client_1 = require_cache_twirp_client(); + var util_1 = require_util10(); + var CacheServiceClient = class { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3e3; + this.retryMultiplier = 1.5; + const token = (0, cacheUtils_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getCacheServiceURL)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; + } + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) + ]); } - promiseFinished() { + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - status, - trailers + const url2 = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url2}`); + const headers = { + "Content-Type": contentType }; + try { + const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { + return this.httpClient.post(url2, JSON.stringify(data), headers); + })); + return body; + } catch (error4) { + throw new Error(`Failed to ${method}: ${error4.message}`); + } }); } - }; - exports2.ServerStreamingCall = ServerStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js -var require_client_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); + retryableRequest(operation) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ""; + let rawBody = ""; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, util_1.maskSecretUrls)(body); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } catch (error4) { + if (error4 instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + } + if (error4 instanceof errors_1.UsageError) { + throw error4; + } + if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { + throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + } + isRetryable = true; + errorMessage = error4.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; + } + throw new Error(`Request failed`); }); } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ClientStreamingCall = void 0; - var ClientStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); } - promiseFinished() { + sleep(milliseconds) { return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - response, - status, - trailers - }; + return new Promise((resolve8) => setTimeout(resolve8, milliseconds)); }); } + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error("attempt should be a positive integer"); + } + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); + } }; - exports2.ClientStreamingCall = ClientStreamingCall; + function internalCacheTwirpClient(options) { + const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new cache_twirp_client_1.CacheServiceClientJSON(client); + } + exports2.internalCacheTwirpClient = internalCacheTwirpClient; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js -var require_duplex_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { +// node_modules/@actions/cache/lib/internal/tar.js +var require_tar = __commonJS({ + "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve8) { @@ -72604,46 +75602,221 @@ var require_duplex_streaming_call = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DuplexStreamingCall = void 0; - var DuplexStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - status, - trailers - }; - }); + exports2.createTar = exports2.extractTar = exports2.listTar = void 0; + var exec_1 = require_exec(); + var io7 = __importStar4(require_io()); + var fs_1 = require("fs"); + var path15 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var IS_WINDOWS = process.platform === "win32"; + function getTarPath() { + return __awaiter4(this, void 0, void 0, function* () { + switch (process.platform) { + case "win32": { + const gnuTar = yield utils.getGnuTarPathOnWindows(); + const systemTar = constants_1.SystemTarPathOnWindows; + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else if ((0, fs_1.existsSync)(systemTar)) { + return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; + } + break; + } + case "darwin": { + const gnuTar = yield io7.which("gtar", false); + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else { + return { + path: yield io7.which("tar", true), + type: constants_1.ArchiveToolType.BSD + }; + } + } + default: + break; + } + return { + path: yield io7.which("tar", true), + type: constants_1.ArchiveToolType.GNU + }; + }); + } + function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + const args = [`"${tarPath.path}"`]; + const cacheFileName = utils.getCacheFileName(compressionMethod); + const tarFile = "cache.tar"; + const workingDirectory = getWorkingDirectory(); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (type2) { + case "create": + args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); + break; + case "extract": + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path15.sep}`, "g"), "/")); + break; + case "list": + args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "-P"); + break; + } + if (tarPath.type === constants_1.ArchiveToolType.GNU) { + switch (process.platform) { + case "win32": + args.push("--force-local"); + break; + case "darwin": + args.push("--delay-directory-restore"); + break; + } + } + return args; + }); + } + function getCommands(compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + let args; + const tarPath = yield getTarPath(); + const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); + const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + if (BSD_TAR_ZSTD && type2 !== "create") { + args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; + } else { + args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; + } + if (BSD_TAR_ZSTD) { + return args; + } + return [args.join(" ")]; + }); + } + function getWorkingDirectory() { + var _a; + return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); + } + function getDecompressionProgram(tarPath, compressionMethod, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -d --long=30 --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path15.sep}`, "g"), "/") + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -d --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path15.sep}`, "g"), "/") + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; + default: + return ["-z"]; + } + }); + } + function getCompressionProgram(tarPath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheFileName = utils.getCacheFileName(compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --long=30 --force -o", + cacheFileName.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), + constants_1.TarFilename + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --force -o", + cacheFileName.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), + constants_1.TarFilename + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; + default: + return ["-z"]; + } + }); + } + function execCommands(commands, cwd) { + return __awaiter4(this, void 0, void 0, function* () { + for (const command of commands) { + try { + yield (0, exec_1.exec)(command, void 0, { + cwd, + env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) + }); + } catch (error4) { + throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + } + } + }); + } + function listTar(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const commands = yield getCommands(compressionMethod, "list", archivePath); + yield execCommands(commands); + }); + } + exports2.listTar = listTar; + function extractTar2(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const workingDirectory = getWorkingDirectory(); + yield io7.mkdirP(workingDirectory); + const commands = yield getCommands(compressionMethod, "extract", archivePath); + yield execCommands(commands); + }); + } + exports2.extractTar = extractTar2; + function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + (0, fs_1.writeFileSync)(path15.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); + const commands = yield getCommands(compressionMethod, "create"); + yield execCommands(commands, archiveFolder); + }); + } + exports2.createTar = createTar; + } +}); + +// node_modules/@actions/cache/lib/cache.js +var require_cache3 = __commonJS({ + "node_modules/@actions/cache/lib/cache.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.DuplexStreamingCall = DuplexStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js -var require_test_transport = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve8) { @@ -72672,1374 +75845,1218 @@ var require_test_transport = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TestTransport = void 0; - var rpc_error_1 = require_rpc_error(); - var runtime_1 = require_commonjs11(); - var rpc_output_stream_1 = require_rpc_output_stream(); - var rpc_options_1 = require_rpc_options(); - var unary_call_1 = require_unary_call(); - var server_streaming_call_1 = require_server_streaming_call(); - var client_streaming_call_1 = require_client_streaming_call(); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - var TestTransport = class _TestTransport { - /** - * Initialize with mock data. Omitted fields have default value. - */ - constructor(data) { - this.suppressUncaughtRejections = true; - this.headerDelay = 10; - this.responseDelay = 50; - this.betweenResponseDelay = 10; - this.afterResponseDelay = 10; - this.data = data !== null && data !== void 0 ? data : {}; + exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + var core18 = __importStar4(require_core()); + var path15 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var cacheHttpClient = __importStar4(require_cacheHttpClient()); + var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); + var config_1 = require_config(); + var tar_1 = require_tar(); + var http_client_1 = require_lib4(); + var ValidationError = class _ValidationError extends Error { + constructor(message) { + super(message); + this.name = "ValidationError"; + Object.setPrototypeOf(this, _ValidationError.prototype); } - /** - * Sent message(s) during the last operation. - */ - get sentMessages() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.sent; - } else if (typeof this.lastInput == "object") { - return [this.lastInput.single]; - } - return []; + }; + exports2.ValidationError = ValidationError; + var ReserveCacheError2 = class _ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = "ReserveCacheError"; + Object.setPrototypeOf(this, _ReserveCacheError.prototype); } - /** - * Sending message(s) completed? - */ - get sendComplete() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.completed; - } else if (typeof this.lastInput == "object") { - return true; - } - return false; + }; + exports2.ReserveCacheError = ReserveCacheError2; + var FinalizeCacheError = class _FinalizeCacheError extends Error { + constructor(message) { + super(message); + this.name = "FinalizeCacheError"; + Object.setPrototypeOf(this, _FinalizeCacheError.prototype); } - // Creates a promise for response headers from the mock data. - promiseHeaders() { - var _a; - const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; - return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); + }; + exports2.FinalizeCacheError = FinalizeCacheError; + function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); } - // Creates a promise for a single, valid, message from the mock data. - promiseSingleResponse(method) { - if (this.data.response instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.response); + } + function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } + } + function isFeatureAvailable() { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + switch (cacheServiceVersion) { + case "v2": + return !!process.env["ACTIONS_RESULTS_URL"]; + case "v1": + default: + return !!process.env["ACTIONS_CACHE_URL"]; + } + } + exports2.isFeatureAvailable = isFeatureAvailable; + function restoreCache4(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core18.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + switch (cacheServiceVersion) { + case "v2": + return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + case "v1": + default: + return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); } - let r; - if (Array.isArray(this.data.response)) { - runtime_1.assert(this.data.response.length > 0); - r = this.data.response[0]; - } else if (this.data.response !== void 0) { - r = this.data.response; - } else { - r = method.O.create(); + }); + } + exports2.restoreCache = restoreCache4; + function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core18.debug("Resolved Keys:"); + core18.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); } - runtime_1.assert(method.O.is(r)); - return Promise.resolve(r); - } - /** - * Pushes response messages from the mock data to the output stream. - * If an error response, status or trailers are mocked, the stream is - * closed with the respective error. - * Otherwise, stream is completed successfully. - * - * The returned promise resolves when the stream is closed. It should - * not reject. If it does, code is broken. - */ - streamResponses(method, stream2, abort) { - return __awaiter4(this, void 0, void 0, function* () { - const messages = []; - if (this.data.response === void 0) { - messages.push(method.O.create()); - } else if (Array.isArray(this.data.response)) { - for (let msg of this.data.response) { - runtime_1.assert(method.O.is(msg)); - messages.push(msg); + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + let archivePath = ""; + try { + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod, + enableCrossOsArchive + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + return void 0; + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core18.info("Lookup only - skipping download"); + return cacheEntry.cacheKey; + } + archivePath = path15.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core18.debug(`Archive Path: ${archivePath}`); + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core18.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core18.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core18.info("Cache restored successfully"); + return cacheEntry.cacheKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core18.error(`Failed to restore: ${error4.message}`); + } else { + core18.warning(`Failed to restore: ${error4.message}`); } - } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { - runtime_1.assert(method.O.is(this.data.response)); - messages.push(this.data.response); } + } finally { try { - yield delay2(this.responseDelay, abort)(void 0); + yield utils.unlinkFile(archivePath); } catch (error4) { - stream2.notifyError(error4); - return; + core18.debug(`Failed to delete archive: ${error4}`); } - if (this.data.response instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.response); - return; + } + return void 0; + }); + } + function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core18.debug("Resolved Keys:"); + core18.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + let archivePath = ""; + try { + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + const compressionMethod = yield utils.getCompressionMethod(); + const request = { + key: primaryKey, + restoreKeys, + version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) + }; + const response = yield twirpClient.GetCacheEntryDownloadURL(request); + if (!response.ok) { + core18.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); + return void 0; } - for (let msg of messages) { - stream2.notifyMessage(msg); - try { - yield delay2(this.betweenResponseDelay, abort)(void 0); - } catch (error4) { - stream2.notifyError(error4); - return; + const isRestoreKeyMatch = request.key !== response.matchedKey; + if (isRestoreKeyMatch) { + core18.info(`Cache hit for restore-key: ${response.matchedKey}`); + } else { + core18.info(`Cache hit for: ${response.matchedKey}`); + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core18.info("Lookup only - skipping download"); + return response.matchedKey; + } + archivePath = path15.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core18.debug(`Archive path: ${archivePath}`); + core18.debug(`Starting download of archive to: ${archivePath}`); + yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core18.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + if (core18.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core18.info("Cache restored successfully"); + return response.matchedKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core18.error(`Failed to restore: ${error4.message}`); + } else { + core18.warning(`Failed to restore: ${error4.message}`); } } - if (this.data.status instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.status); - return; + } finally { + try { + if (archivePath) { + yield utils.unlinkFile(archivePath); + } + } catch (error4) { + core18.debug(`Failed to delete archive: ${error4}`); } - if (this.data.trailers instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.trailers); - return; + } + return void 0; + }); + } + function saveCache4(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core18.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + checkKey(key); + switch (cacheServiceVersion) { + case "v2": + return yield saveCacheV2(paths, key, options, enableCrossOsArchive); + case "v1": + default: + return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + } + }); + } + exports2.saveCache = saveCache4; + function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { + var _a, _b, _c, _d, _e; + return __awaiter4(this, void 0, void 0, function* () { + const compressionMethod = yield utils.getCompressionMethod(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core18.debug("Cache Paths:"); + core18.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path15.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core18.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core18.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); } - stream2.notifyComplete(); - }); - } - // Creates a promise for response status from the mock data. - promiseStatus() { - var _a; - const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; - return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); - } - // Creates a promise for response trailers from the mock data. - promiseTrailers() { - var _a; - const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; - return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); - } - maybeSuppressUncaught(...promise) { - if (this.suppressUncaughtRejections) { - for (let p of promise) { - p.catch(() => { - }); + const fileSizeLimit = 10 * 1024 * 1024 * 1024; + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core18.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core18.debug("Reserving Cache"); + const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod, + enableCrossOsArchive, + cacheSize: archiveFileSize + }); + if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { + cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { + throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); + } else { + throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); + } + core18.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError2.name) { + core18.info(`Failed to save: ${typedError.message}`); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core18.error(`Failed to save: ${typedError.message}`); + } else { + core18.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core18.debug(`Failed to delete archive: ${error4}`); } } - } - mergeOptions(options) { - return rpc_options_1.mergeRpcOptions({}, options); - } - unary(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { - }).then(delay2(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); - } - serverStreaming(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); - } - clientStreaming(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_2) => { - }).then(delay2(this.responseDelay, options.abort)).then((_2) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_2) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseStatus()), trailersPromise = responsePromise.catch((_2) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_2) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); - } - duplex(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); - } - }; - exports2.TestTransport = TestTransport; - TestTransport.defaultHeaders = { - responseHeader: "test" - }; - TestTransport.defaultStatus = { - code: "OK", - detail: "all good" - }; - TestTransport.defaultTrailers = { - responseTrailer: "test" - }; - function delay2(ms, abort) { - return (v) => new Promise((resolve8, reject) => { - if (abort === null || abort === void 0 ? void 0 : abort.aborted) { - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - } else { - const id = setTimeout(() => resolve8(v), ms); - if (abort) { - abort.addEventListener("abort", (ev) => { - clearTimeout(id); - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - }); + return cacheId; + }); + } + function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); + const compressionMethod = yield utils.getCompressionMethod(); + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core18.debug("Cache Paths:"); + core18.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path15.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core18.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core18.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core18.debug(`File Size: ${archiveFileSize}`); + options.archiveSizeBytes = archiveFileSize; + core18.debug("Reserving Cache"); + const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); + const request = { + key, + version + }; + let signedUploadUrl; + try { + const response = yield twirpClient.CreateCacheEntry(request); + if (!response.ok) { + if (response.message) { + core18.warning(`Cache reservation failed: ${response.message}`); + } + throw new Error(response.message || "Response was not ok"); + } + signedUploadUrl = response.signedUploadUrl; + } catch (error4) { + core18.debug(`Failed to reserve cache: ${error4}`); + throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); + } + core18.debug(`Attempting to upload cache located at: ${archivePath}`); + yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); + const finalizeRequest = { + key, + version, + sizeBytes: `${archiveFileSize}` + }; + const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); + core18.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); + if (!finalizeResponse.ok) { + if (finalizeResponse.message) { + throw new FinalizeCacheError(finalizeResponse.message); + } + throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); + } + cacheId = parseInt(finalizeResponse.entryId); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError2.name) { + core18.info(`Failed to save: ${typedError.message}`); + } else if (typedError.name === FinalizeCacheError.name) { + core18.warning(typedError.message); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core18.error(`Failed to save: ${typedError.message}`); + } else { + core18.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core18.debug(`Failed to delete archive: ${error4}`); } } + return cacheId; }); } - var TestInputStream = class { - constructor(data, abort) { - this._completed = false; - this._sent = []; - this.data = data; - this.abort = abort; - } - get sent() { - return this._sent; - } - get completed() { - return this._completed; - } - send(message) { - if (this.data.inputMessage instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputMessage); - } - const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; - return Promise.resolve(void 0).then(() => { - this._sent.push(message); - }).then(delay2(delayMs, this.abort)); - } - complete() { - if (this.data.inputComplete instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputComplete); - } - const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; - return Promise.resolve(void 0).then(() => { - this._completed = true; - }).then(delay2(delayMs, this.abort)); - } - }; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js -var require_rpc_interceptor = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { +// node_modules/@actions/tool-cache/lib/manifest.js +var require_manifest = __commonJS({ + "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; - var runtime_1 = require_commonjs11(); - function stackIntercept(kind, transport, method, options, input) { - var _a, _b, _c, _d; - if (kind == "unary") { - let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); - for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); - } - return tail(method, input, options); - } - if (kind == "serverStreaming") { - let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); - for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); - } - return tail(method, input, options); - } - if (kind == "clientStreaming") { - let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); - for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); - } - return tail(method, options); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - if (kind == "duplex") { - let tail = (mtd, opt) => transport.duplex(mtd, opt); - for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); - } - return tail(method, options); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - runtime_1.assertNever(kind); - } - exports2.stackIntercept = stackIntercept; - function stackUnaryInterceptors(transport, method, input, options) { - return stackIntercept("unary", transport, method, options, input); - } - exports2.stackUnaryInterceptors = stackUnaryInterceptors; - function stackServerStreamingInterceptors(transport, method, input, options) { - return stackIntercept("serverStreaming", transport, method, options, input); - } - exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; - function stackClientStreamingInterceptors(transport, method, options) { - return stackIntercept("clientStreaming", transport, method, options); - } - exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; - function stackDuplexStreamingInterceptors(transport, method, options) { - return stackIntercept("duplex", transport, method, options); - } - exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js -var require_server_call_context = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerCallContextController = void 0; - var ServerCallContextController = class { - constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { - this._cancelled = false; - this._listeners = []; - this.method = method; - this.headers = headers; - this.deadline = deadline; - this.trailers = {}; - this._sendRH = sendResponseHeadersFn; - this.status = defaultStatus; + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - /** - * Set the call cancelled. - * - * Invokes all callbacks registered with onCancel() and - * sets `cancelled = true`. - */ - notifyCancelled() { - if (!this._cancelled) { - this._cancelled = true; - for (let l of this._listeners) { - l(); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - } - /** - * Send response headers. - */ - sendResponseHeaders(data) { - this._sendRH(data); - } - /** - * Is the call cancelled? - * - * When the client closes the connection before the server - * is done, the call is cancelled. - * - * If you want to cancel a request on the server, throw a - * RpcError with the CANCELLED status code. - */ - get cancelled() { - return this._cancelled; - } - /** - * Add a callback for cancellation. - */ - onCancel(callback) { - const l = this._listeners; - l.push(callback); - return () => { - let i = l.indexOf(callback); - if (i >= 0) - l.splice(i, 1); - }; - } - }; - exports2.ServerCallContextController = ServerCallContextController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js -var require_commonjs12 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var service_type_1 = require_service_type(); - Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { - return service_type_1.ServiceType; - } }); - var reflection_info_1 = require_reflection_info2(); - Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { - return reflection_info_1.readMethodOptions; - } }); - Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { - return reflection_info_1.readMethodOption; - } }); - Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { - return reflection_info_1.readServiceOption; - } }); - var rpc_error_1 = require_rpc_error(); - Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { - return rpc_error_1.RpcError; - } }); - var rpc_options_1 = require_rpc_options(); - Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { - return rpc_options_1.mergeRpcOptions; - } }); - var rpc_output_stream_1 = require_rpc_output_stream(); - Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { - return rpc_output_stream_1.RpcOutputStreamController; - } }); - var test_transport_1 = require_test_transport(); - Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { - return test_transport_1.TestTransport; - } }); - var deferred_1 = require_deferred(); - Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { - return deferred_1.Deferred; - } }); - Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { - return deferred_1.DeferredState; - } }); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { - return duplex_streaming_call_1.DuplexStreamingCall; - } }); - var client_streaming_call_1 = require_client_streaming_call(); - Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { - return client_streaming_call_1.ClientStreamingCall; - } }); - var server_streaming_call_1 = require_server_streaming_call(); - Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { - return server_streaming_call_1.ServerStreamingCall; - } }); - var unary_call_1 = require_unary_call(); - Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { - return unary_call_1.UnaryCall; - } }); - var rpc_interceptor_1 = require_rpc_interceptor(); - Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { - return rpc_interceptor_1.stackIntercept; - } }); - Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackDuplexStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackClientStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackServerStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackUnaryInterceptors; - } }); - var server_call_context_1 = require_server_call_context(); - Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { - return server_call_context_1.ServerCallContextController; - } }); - } -}); - -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js -var require_cachescope = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheScope = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var CacheScope$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheScope", [ - { - no: 1, - name: "scope", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "permission", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - } - ]); - } - create(value) { - const message = { scope: "", permission: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string scope */ - 1: - message.scope = reader.string(); - break; - case /* int64 permission */ - 2: - message.permission = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.scope !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); - if (message.permission !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - exports2.CacheScope = new CacheScope$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js -var require_cachemetadata = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { - "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheMetadata = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachescope_1 = require_cachescope(); - var CacheMetadata$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheMetadata", [ - { - no: 1, - name: "repository_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } - ]); - } - create(value) { - const message = { repositoryId: "0", scope: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int64 repository_id */ - 1: - message.repositoryId = reader.int64().toString(); - break; - case /* repeated github.actions.results.entities.v1.CacheScope scope */ - 2: - message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; + var semver8 = __importStar4(require_semver2()); + var core_1 = require_core(); + var os3 = require("os"); + var cp = require("child_process"); + var fs17 = require("fs"); + function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os3.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); + if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + file = candidate.files.find((item) => { + (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module2.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } else { + chk = semver8.satisfies(osVersion, item.platform_version); + } + } + return chk; + }); + if (file) { + (0, core_1.debug)(`matched ${candidate.version}`); + match = candidate; break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + } + if (match && file) { + result = Object.assign({}, match); + result.files = [file]; + } + return result; + }); + } + exports2._findMatch = _findMatch; + function _getOsVersion() { + const plat = os3.platform(); + let version = ""; + if (plat === "darwin") { + version = cp.execSync("sw_vers -productVersion").toString(); + } else if (plat === "linux") { + const lsbContents = module2.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split("\n"); + for (const line of lines) { + const parts = line.split("="); + if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { + version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); + break; + } } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.repositoryId !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); - for (let i = 0; i < message.scope.length; i++) - cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; } - }; - exports2.CacheMetadata = new CacheMetadata$Type(); + return version; + } + exports2._getOsVersion = _getOsVersion; + function _readLinuxVersionFile() { + const lsbReleaseFile = "/etc/lsb-release"; + const osReleaseFile = "/etc/os-release"; + let contents = ""; + if (fs17.existsSync(lsbReleaseFile)) { + contents = fs17.readFileSync(lsbReleaseFile).toString(); + } else if (fs17.existsSync(osReleaseFile)) { + contents = fs17.readFileSync(osReleaseFile).toString(); + } + return contents; + } + exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js -var require_cache2 = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachemetadata_1 = require_cachemetadata(); - var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); - } - create(value) { - const message = { key: "", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* string version */ - 3: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - return message; + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.version !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - }; - exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); - var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_upload_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - create(value) { - const message = { ok: false, signedUploadUrl: "", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_upload_url */ - 2: - message.signedUploadUrl = reader.string(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; } }; - exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); - var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "size_bytes", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + } +}); + +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - create(value) { - const message = { key: "", sizeBytes: "0", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* int64 size_bytes */ - 3: - message.sizeBytes = reader.int64().toString(); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return message; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.sizeBytes !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); + }); } }; - exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); - var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "entry_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - ]); - } - create(value) { - const message = { ok: false, entryId: "0", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 entry_id */ - 2: - message.entryId = reader.int64().toString(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.entryId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); - var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "restore_keys", - kind: "scalar", - repeat: 2, - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - create(value) { - const message = { key: "", restoreKeys: [], version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* repeated string restore_keys */ - 3: - message.restoreKeys.push(reader.string()); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - for (let i = 0; i < message.restoreKeys.length; i++) - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - }; - exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); - var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_download_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "matched_key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - create(value) { - const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_download_url */ - 2: - message.signedDownloadUrl = reader.string(); - break; - case /* string matched_key */ - 3: - message.matchedKey = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedDownloadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); - if (message.matchedKey !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - }; - exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); - exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ - { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, - { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, - { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } - ]); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js -var require_cache_twirp_client = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; - var cache_1 = require_cache2(); - var CacheServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - }; - exports2.CacheServiceClientJSON = CacheServiceClientJSON; - var CacheServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - }; - exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; - } -}); - -// node_modules/@actions/cache/lib/internal/shared/util.js -var require_util10 = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.maskSecretUrls = exports2.maskSigUrl = void 0; - var core_1 = require_core(); - function maskSigUrl(url2) { - if (!url2) - return; - try { - const parsedUrl = new URL(url2); - const signature = parsedUrl.searchParams.get("sig"); - if (signature) { - (0, core_1.setSecret)(signature); - (0, core_1.setSecret)(encodeURIComponent(signature)); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - } catch (error4) { - (0, core_1.debug)(`Failed to parse URL: ${url2} ${error4 instanceof Error ? error4.message : String(error4)}`); - } - } - exports2.maskSigUrl = maskSigUrl; - function maskSecretUrls(body) { - if (typeof body !== "object" || body === null) { - (0, core_1.debug)("body is not an object or is null"); - return; + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { - maskSigUrl(body.signed_upload_url); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; } - if ("signed_download_url" in body && typeof body.signed_download_url === "string") { - maskSigUrl(body.signed_download_url); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - } - exports2.maskSecretUrls = maskSecretUrls; - } -}); - -// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js -var require_cacheTwirpClient = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.internalCacheTwirpClient = void 0; - var core_1 = require_core(); - var user_agent_1 = require_user_agent(); - var errors_1 = require_errors2(); - var config_1 = require_config(); - var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); - var cache_twirp_client_1 = require_cache_twirp_client(); - var util_1 = require_util10(); - var CacheServiceClient = class { - constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { - this.maxAttempts = 5; - this.baseRetryIntervalMilliseconds = 3e3; - this.retryMultiplier = 1.5; - const token = (0, cacheUtils_1.getRuntimeToken)(); - this.baseUrl = (0, config_1.getCacheServiceURL)(); - if (maxAttempts) { - this.maxAttempts = maxAttempts; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } - if (baseRetryIntervalMilliseconds) { - this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (retryMultiplier) { - this.retryMultiplier = retryMultiplier; + if (proxyAgent) { + return proxyAgent; } - this.httpClient = new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(token) - ]); + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - // This function satisfies the Rpc interface. It is compatible with the JSON - // JSON generated client. - request(service, method, contentType, data) { + _performExponentialBackoff(retryNumber) { return __awaiter4(this, void 0, void 0, function* () { - const url2 = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; - (0, core_1.debug)(`[Request] ${method} ${url2}`); - const headers = { - "Content-Type": contentType - }; - try { - const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { - return this.httpClient.post(url2, JSON.stringify(data), headers); - })); - return body; - } catch (error4) { - throw new Error(`Failed to ${method}: ${error4.message}`); - } + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); }); } - retryableRequest(operation) { + _processResponse(res, options) { return __awaiter4(this, void 0, void 0, function* () { - let attempt = 0; - let errorMessage = ""; - let rawBody = ""; - while (attempt < this.maxAttempts) { - let isRetryable = false; - try { - const response = yield operation(); - const statusCode = response.message.statusCode; - rawBody = yield response.readBody(); - (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); - (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); - const body = JSON.parse(rawBody); - (0, util_1.maskSecretUrls)(body); - (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); - if (this.isSuccessStatusCode(statusCode)) { - return { response, body }; - } - isRetryable = this.isRetryableHttpStatusCode(statusCode); - errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; - if (body.msg) { - if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { - throw new errors_1.UsageError(); + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; } - errorMessage = `${errorMessage}: ${body.msg}`; - } - } catch (error4) { - if (error4 instanceof SyntaxError) { - (0, core_1.debug)(`Raw Body: ${rawBody}`); - } - if (error4 instanceof errors_1.UsageError) { - throw error4; - } - if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { - throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); } - isRetryable = true; - errorMessage = error4.message; + return value; } - if (!isRetryable) { - throw new Error(`Received non-retryable error: ${errorMessage}`); + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { } - if (attempt + 1 === this.maxAttempts) { - throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); } - const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); - (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); - yield this.sleep(retryTimeMilliseconds); - attempt++; - } - throw new Error(`Request failed`); - }); - } - isSuccessStatusCode(statusCode) { - if (!statusCode) - return false; - return statusCode >= 200 && statusCode < 300; - } - isRetryableHttpStatusCode(statusCode) { - if (!statusCode) - return false; - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.GatewayTimeout, - http_client_1.HttpCodes.InternalServerError, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.TooManyRequests - ]; - return retryableStatusCodes.includes(statusCode); - } - sleep(milliseconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve8) => setTimeout(resolve8, milliseconds)); + })); }); } - getExponentialRetryTimeMilliseconds(attempt) { - if (attempt < 0) { - throw new Error("attempt should be a positive integer"); - } - if (attempt === 0) { - return this.baseRetryIntervalMilliseconds; - } - const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); - const maxTime = minTime * this.retryMultiplier; - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); - } }; - function internalCacheTwirpClient(options) { - const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); - return new cache_twirp_client_1.CacheServiceClientJSON(client); - } - exports2.internalCacheTwirpClient = internalCacheTwirpClient; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/cache/lib/internal/tar.js -var require_tar = __commonJS({ - "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74096,193 +77113,56 @@ var require_tar = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTar = exports2.extractTar = exports2.listTar = void 0; - var exec_1 = require_exec(); - var io7 = __importStar4(require_io()); - var fs_1 = require("fs"); - var path15 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var constants_1 = require_constants7(); - var IS_WINDOWS = process.platform === "win32"; - function getTarPath() { - return __awaiter4(this, void 0, void 0, function* () { - switch (process.platform) { - case "win32": { - const gnuTar = yield utils.getGnuTarPathOnWindows(); - const systemTar = constants_1.SystemTarPathOnWindows; - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else if ((0, fs_1.existsSync)(systemTar)) { - return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; - } - break; - } - case "darwin": { - const gnuTar = yield io7.which("gtar", false); - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else { - return { - path: yield io7.which("tar", true), - type: constants_1.ArchiveToolType.BSD - }; - } - } - default: - break; - } - return { - path: yield io7.which("tar", true), - type: constants_1.ArchiveToolType.GNU - }; - }); - } - function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - const args = [`"${tarPath.path}"`]; - const cacheFileName = utils.getCacheFileName(compressionMethod); - const tarFile = "cache.tar"; - const workingDirectory = getWorkingDirectory(); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (type2) { - case "create": - args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); - break; - case "extract": - args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path15.sep}`, "g"), "/")); - break; - case "list": - args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), "-P"); - break; - } - if (tarPath.type === constants_1.ArchiveToolType.GNU) { - switch (process.platform) { - case "win32": - args.push("--force-local"); - break; - case "darwin": - args.push("--delay-directory-restore"); - break; - } - } - return args; - }); - } - function getCommands(compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - let args; - const tarPath = yield getTarPath(); - const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); - const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - if (BSD_TAR_ZSTD && type2 !== "create") { - args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; - } else { - args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; - } - if (BSD_TAR_ZSTD) { - return args; - } - return [args.join(" ")]; - }); - } - function getWorkingDirectory() { - var _a; - return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); - } - function getDecompressionProgram(tarPath, compressionMethod, archivePath) { - return __awaiter4(this, void 0, void 0, function* () { - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -d --long=30 --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path15.sep}`, "g"), "/") - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -d --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path15.sep}`, "g"), "/") - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; - default: - return ["-z"]; - } - }); - } - function getCompressionProgram(tarPath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const cacheFileName = utils.getCacheFileName(compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --long=30 --force -o", - cacheFileName.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), - constants_1.TarFilename - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --force -o", - cacheFileName.replace(new RegExp(`\\${path15.sep}`, "g"), "/"), - constants_1.TarFilename - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; - default: - return ["-z"]; - } - }); - } - function execCommands(commands, cwd) { - return __awaiter4(this, void 0, void 0, function* () { - for (const command of commands) { - try { - yield (0, exec_1.exec)(command, void 0, { - cwd, - env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) - }); - } catch (error4) { - throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); - } - } - }); - } - function listTar(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const commands = yield getCommands(compressionMethod, "list", archivePath); - yield execCommands(commands); - }); - } - exports2.listTar = listTar; - function extractTar2(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const workingDirectory = getWorkingDirectory(); - yield io7.mkdirP(workingDirectory); - const commands = yield getCommands(compressionMethod, "extract", archivePath); - yield execCommands(commands); - }); - } - exports2.extractTar = extractTar2; - function createTar(archiveFolder, sourceDirectories, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - (0, fs_1.writeFileSync)(path15.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); - const commands = yield getCommands(compressionMethod, "create"); - yield execCommands(commands, archiveFolder); - }); - } - exports2.createTar = createTar; + exports2.RetryHelper = void 0; + var core18 = __importStar4(require_core()); + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); + } + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); + } + } + execute(action, isRetryable) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 1; + while (attempt < this.maxAttempts) { + try { + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; + } + core18.info(err.message); + } + const seconds = this.getSleepAmount(); + core18.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); + attempt++; + } + return yield action(); + }); + } + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + } + sleep(seconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => setTimeout(resolve8, seconds * 1e3)); + }); + } + }; + exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/cache/lib/cache.js -var require_cache3 = __commonJS({ - "node_modules/@actions/cache/lib/cache.js"(exports2) { +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74339,517 +77219,610 @@ var require_cache3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; var core18 = __importStar4(require_core()); + var io7 = __importStar4(require_io()); + var crypto = __importStar4(require("crypto")); + var fs17 = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os3 = __importStar4(require("os")); var path15 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var cacheHttpClient = __importStar4(require_cacheHttpClient()); - var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); - var config_1 = require_config(); - var tar_1 = require_tar(); - var http_client_1 = require_lib(); - var ValidationError = class _ValidationError extends Error { - constructor(message) { - super(message); - this.name = "ValidationError"; - Object.setPrototypeOf(this, _ValidationError.prototype); - } - }; - exports2.ValidationError = ValidationError; - var ReserveCacheError2 = class _ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = "ReserveCacheError"; - Object.setPrototypeOf(this, _ReserveCacheError.prototype); - } - }; - exports2.ReserveCacheError = ReserveCacheError2; - var FinalizeCacheError = class _FinalizeCacheError extends Error { - constructor(message) { - super(message); - this.name = "FinalizeCacheError"; - Object.setPrototypeOf(this, _FinalizeCacheError.prototype); + var httpm = __importStar4(require_lib5()); + var semver8 = __importStar4(require_semver2()); + var stream2 = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError2 = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); } }; - exports2.FinalizeCacheError = FinalizeCacheError; - function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } - } - function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); - } - } - function isFeatureAvailable() { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - switch (cacheServiceVersion) { - case "v2": - return !!process.env["ACTIONS_RESULTS_URL"]; - case "v1": - default: - return !!process.env["ACTIONS_CACHE_URL"]; - } - } - exports2.isFeatureAvailable = isFeatureAvailable; - function restoreCache4(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.HTTPError = HTTPError2; + var IS_WINDOWS = process.platform === "win32"; + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url2, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core18.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - switch (cacheServiceVersion) { - case "v2": - return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - case "v1": - default: - return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - } + dest = dest || path15.join(_getTempDirectory(), crypto.randomUUID()); + yield io7.mkdirP(path15.dirname(dest)); + core18.debug(`Downloading ${url2}`); + core18.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url2, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError2 && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; + } + } + return true; + }); }); } - exports2.restoreCache = restoreCache4; - function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url2, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core18.debug("Resolved Keys:"); - core18.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + if (fs17.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); } - for (const key of keys) { - checkKey(key); + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core18.debug("set auth"); + if (headers === void 0) { + headers = {}; + } + headers.authorization = auth; } - const compressionMethod = yield utils.getCompressionMethod(); - let archivePath = ""; + const response = yield http.get(url2, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError2(response.message.statusCode); + core18.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; + } + const pipeline = util.promisify(stream2.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; try { - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod, - enableCrossOsArchive - }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - return void 0; - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core18.info("Lookup only - skipping download"); - return cacheEntry.cacheKey; - } - archivePath = path15.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core18.debug(`Archive Path: ${archivePath}`); - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core18.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core18.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core18.info("Cache restored successfully"); - return cacheEntry.cacheKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core18.error(`Failed to restore: ${error4.message}`); - } else { - core18.warning(`Failed to restore: ${error4.message}`); + yield pipeline(readStream, fs17.createWriteStream(dest)); + core18.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core18.debug("download failed"); + try { + yield io7.rmRF(dest); + } catch (err) { + core18.debug(`Failed to delete '${dest}'. ${err.message}`); } } - } finally { + } + }); + } + function extract7z(file, dest, _7zPath) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core18.debug(`Failed to delete archive: ${error4}`); + const logLevel = core18.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file + ]; + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } else { + const escapedScript = path15.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true + }; + try { + const powershellPath = yield io7.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); } } - return void 0; + return dest; }); } - function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core18.debug("Resolved Keys:"); - core18.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + core18.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + core18.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + if (core18.isDebug() && !flags.includes("v")) { + args.push("-v"); + } + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); + } + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); + } + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; + }); + } + exports2.extractTar = extractTar2; + function extractXar(file, dest, flags = []) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + args.push("-x", "-C", dest, "-f", file); + if (core18.isDebug()) { + args.push("-v"); + } + const xarPath = yield io7.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; + }); + } + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } else { + yield extractZipNix(file, dest); + } + return dest; + }); + } + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io7.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core18.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io7.which("powershell", true); + core18.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); + } + }); + } + function extractZipNix(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const unzipPath = yield io7.which("unzip", true); + const args = [file]; + if (!core18.isDebug()) { + args.unshift("-q"); + } + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); + }); + } + function cacheDir(sourceDir, tool, version, arch2) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver8.clean(version) || version; + arch2 = arch2 || os3.arch(); + core18.debug(`Caching tool ${tool} ${version} ${arch2}`); + core18.debug(`source dir: ${sourceDir}`); + if (!fs17.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); + } + const destPath = yield _createToolPath(tool, version, arch2); + for (const itemName of fs17.readdirSync(sourceDir)) { + const s = path15.join(sourceDir, itemName); + yield io7.cp(s, destPath, { recursive: true }); + } + _completeToolPath(tool, version, arch2); + return destPath; + }); + } + exports2.cacheDir = cacheDir; + function cacheFile(sourceFile, targetFile, tool, version, arch2) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver8.clean(version) || version; + arch2 = arch2 || os3.arch(); + core18.debug(`Caching tool ${tool} ${version} ${arch2}`); + core18.debug(`source file: ${sourceFile}`); + if (!fs17.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); + } + const destFolder = yield _createToolPath(tool, version, arch2); + const destPath = path15.join(destFolder, targetFile); + core18.debug(`destination file ${destPath}`); + yield io7.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch2); + return destFolder; + }); + } + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch2) { + if (!toolName) { + throw new Error("toolName parameter is required"); + } + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); + } + arch2 = arch2 || os3.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions2(toolName, arch2); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; + } + let toolPath = ""; + if (versionSpec) { + versionSpec = semver8.clean(versionSpec) || ""; + const cachePath = path15.join(_getCacheDirectory(), toolName, versionSpec, arch2); + core18.debug(`checking cache: ${cachePath}`); + if (fs17.existsSync(cachePath) && fs17.existsSync(`${cachePath}.complete`)) { + core18.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); + toolPath = cachePath; + } else { + core18.debug("not found"); + } + } + return toolPath; + } + exports2.find = find2; + function findAllVersions2(toolName, arch2) { + const versions = []; + arch2 = arch2 || os3.arch(); + const toolPath = path15.join(_getCacheDirectory(), toolName); + if (fs17.existsSync(toolPath)) { + const children = fs17.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path15.join(toolPath, child, arch2 || ""); + if (fs17.existsSync(fullPath) && fs17.existsSync(`${fullPath}.complete`)) { + versions.push(child); + } + } + } + } + return versions; + } + exports2.findAllVersions = findAllVersions2; + function getManifestFromRepo(owner, repo, auth, branch = "master") { + return __awaiter4(this, void 0, void 0, function* () { + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core18.debug("set auth"); + headers.authorization = auth; } - for (const key of keys) { - checkKey(key); + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; } - let archivePath = ""; - try { - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - const compressionMethod = yield utils.getCompressionMethod(); - const request = { - key: primaryKey, - restoreKeys, - version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) - }; - const response = yield twirpClient.GetCacheEntryDownloadURL(request); - if (!response.ok) { - core18.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); - return void 0; - } - const isRestoreKeyMatch = request.key !== response.matchedKey; - if (isRestoreKeyMatch) { - core18.info(`Cache hit for restore-key: ${response.matchedKey}`); - } else { - core18.info(`Cache hit for: ${response.matchedKey}`); - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core18.info("Lookup only - skipping download"); - return response.matchedKey; - } - archivePath = path15.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core18.debug(`Archive path: ${archivePath}`); - core18.debug(`Starting download of archive to: ${archivePath}`); - yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core18.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - if (core18.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core18.info("Cache restored successfully"); - return response.matchedKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core18.error(`Failed to restore: ${error4.message}`); - } else { - core18.warning(`Failed to restore: ${error4.message}`); - } + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; } - } finally { + } + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); try { - if (archivePath) { - yield utils.unlinkFile(archivePath); - } - } catch (error4) { - core18.debug(`Failed to delete archive: ${error4}`); + releases = JSON.parse(versionsRaw); + } catch (_a) { + core18.debug("Invalid json"); } } - return void 0; + return releases; }); } - function saveCache4(paths, key, options, enableCrossOsArchive = false) { + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os3.arch()) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core18.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - checkKey(key); - switch (cacheServiceVersion) { - case "v2": - return yield saveCacheV2(paths, key, options, enableCrossOsArchive); - case "v1": - default: - return yield saveCacheV1(paths, key, options, enableCrossOsArchive); - } + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; }); } - exports2.saveCache = saveCache4; - function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { - var _a, _b, _c, _d, _e; + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { return __awaiter4(this, void 0, void 0, function* () { - const compressionMethod = yield utils.getCompressionMethod(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core18.debug("Cache Paths:"); - core18.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); - } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path15.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core18.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core18.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const fileSizeLimit = 10 * 1024 * 1024 * 1024; - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core18.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); - } - core18.debug("Reserving Cache"); - const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod, - enableCrossOsArchive, - cacheSize: archiveFileSize - }); - if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { - cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; - } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { - throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); - } else { - throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); - } - core18.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError2.name) { - core18.info(`Failed to save: ${typedError.message}`); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core18.error(`Failed to save: ${typedError.message}`); - } else { - core18.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core18.debug(`Failed to delete archive: ${error4}`); - } + if (!dest) { + dest = path15.join(_getTempDirectory(), crypto.randomUUID()); } - return cacheId; + yield io7.mkdirP(dest); + return dest; }); } - function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + function _createToolPath(tool, version, arch2) { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); - const compressionMethod = yield utils.getCompressionMethod(); - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core18.debug("Cache Paths:"); - core18.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); - } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path15.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core18.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core18.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core18.debug(`File Size: ${archiveFileSize}`); - options.archiveSizeBytes = archiveFileSize; - core18.debug("Reserving Cache"); - const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); - const request = { - key, - version - }; - let signedUploadUrl; - try { - const response = yield twirpClient.CreateCacheEntry(request); - if (!response.ok) { - if (response.message) { - core18.warning(`Cache reservation failed: ${response.message}`); - } - throw new Error(response.message || "Response was not ok"); - } - signedUploadUrl = response.signedUploadUrl; - } catch (error4) { - core18.debug(`Failed to reserve cache: ${error4}`); - throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); - } - core18.debug(`Attempting to upload cache located at: ${archivePath}`); - yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); - const finalizeRequest = { - key, - version, - sizeBytes: `${archiveFileSize}` - }; - const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); - core18.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); - if (!finalizeResponse.ok) { - if (finalizeResponse.message) { - throw new FinalizeCacheError(finalizeResponse.message); - } - throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); - } - cacheId = parseInt(finalizeResponse.entryId); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError2.name) { - core18.info(`Failed to save: ${typedError.message}`); - } else if (typedError.name === FinalizeCacheError.name) { - core18.warning(typedError.message); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core18.error(`Failed to save: ${typedError.message}`); - } else { - core18.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core18.debug(`Failed to delete archive: ${error4}`); - } + const folderPath = path15.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); + core18.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io7.rmRF(folderPath); + yield io7.rmRF(markerPath); + yield io7.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch2) { + const folderPath = path15.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); + const markerPath = `${folderPath}.complete`; + fs17.writeFileSync(markerPath, ""); + core18.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver8.clean(versionSpec) || ""; + core18.debug(`isExplicit: ${c}`); + const valid3 = semver8.valid(c) != null; + core18.debug(`explicit? ${valid3}`); + return valid3; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { + let version = ""; + core18.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver8.gt(a, b)) { + return 1; } - return cacheId; + return -1; }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver8.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; + } + } + if (version) { + core18.debug(`matched: ${version}`); + } else { + core18.debug("match not found"); + } + return version; + } + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); } } }); -// node_modules/@actions/tool-cache/lib/manifest.js -var require_manifest = __commonJS({ - "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + module2.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return true; + } + return a !== a && b !== b; }; + } +}); + +// node_modules/@actions/http-client/lib/proxy.js +var require_proxy5 = __commonJS({ + "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver8 = __importStar4(require_semver2()); - var core_1 = require_core(); - var os3 = require("os"); - var cp = require("child_process"); - var fs17 = require("fs"); - function _findMatch(versionSpec, stable, candidates, archFilter) { - return __awaiter4(this, void 0, void 0, function* () { - const platFilter = os3.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { - file = candidate.files.find((item) => { - (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module2.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } else { - chk = semver8.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - (0, core_1.debug)(`matched ${candidate.version}`); - match = candidate; - break; - } - } + exports2.getProxyUrl = getProxyUrl; + exports2.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (match && file) { - result = Object.assign({}, match); - result.files = [file]; + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - return result; - }); + } else { + return void 0; + } } - exports2._findMatch = _findMatch; - function _getOsVersion() { - const plat = os3.platform(); - let version = ""; - if (plat === "darwin") { - version = cp.execSync("sw_vers -productVersion").toString(); - } else if (plat === "linux") { - const lsbContents = module2.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split("\n"); - for (const line of lines) { - const parts = line.split("="); - if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { - version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); - break; - } - } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - return version; - } - exports2._getOsVersion = _getOsVersion; - function _readLinuxVersionFile() { - const lsbReleaseFile = "/etc/lsb-release"; - const osReleaseFile = "/etc/os-release"; - let contents = ""; - if (fs17.existsSync(lsbReleaseFile)) { - contents = fs17.readFileSync(lsbReleaseFile).toString(); - } else if (fs17.existsSync(osReleaseFile)) { - contents = fs17.readFileSync(osReleaseFile).toString(); + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; } - return contents; - } - exports2._readLinuxVersionFile = _readLinuxVersionFile; + }; } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib6 = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74869,15 +77842,25 @@ var require_retry_helper = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve8) { @@ -74906,629 +77889,616 @@ var require_retry_helper = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core18 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); - } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); - } + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy5()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - execute(action, isRetryable) { + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core18.info(err.message); - } - const seconds = this.getSleepAmount(); - core18.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); + }); + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - return yield action(); + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); }); } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - sleep(seconds) { + del(requestUrl, additionalHeaders) { return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve8) => setTimeout(resolve8, seconds * 1e3)); + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); }); } - }; - exports2.RetryHelper = RetryHelper; - } -}); - -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); }); } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core18 = __importStar4(require_core()); - var io7 = __importStar4(require_io()); - var crypto = __importStar4(require("crypto")); - var fs17 = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os3 = __importStar4(require("os")); - var path15 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver8 = __importStar4(require_semver2()); - var stream2 = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError2 = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.HTTPError = HTTPError2; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url2, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path15.join(_getTempDirectory(), crypto.randomUUID()); - yield io7.mkdirP(path15.dirname(dest)); - core18.debug(`Downloading ${url2}`); - core18.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url2, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError2 && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url2, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs17.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - if (auth) { - core18.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + postJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - headers.authorization = auth; - } - const response = yield http.get(url2, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError2(response.message.statusCode); - core18.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - const pipeline = util.promisify(stream2.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs17.createWriteStream(dest)); - core18.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core18.debug("download failed"); - try { - yield io7.rmRF(dest); - } catch (err) { - core18.debug(`Failed to delete '${dest}'. ${err.message}`); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); + } } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core18.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); - } - } else { - const escapedScript = path15.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io7.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core18.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); }); - core18.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core18.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - args.push("-x", "-C", dest, "-f", file); - if (core18.isDebug()) { - args.push("-v"); - } - const xarPath = yield io7.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io7.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core18.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io7.which("powershell", true); - core18.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); - } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io7.which("unzip", true); - const args = [file]; - if (!core18.isDebug()) { - args.unshift("-q"); + req.end(); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir(sourceDir, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch2 = arch2 || os3.arch(); - core18.debug(`Caching tool ${tool} ${version} ${arch2}`); - core18.debug(`source dir: ${sourceDir}`); - if (!fs17.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const destPath = yield _createToolPath(tool, version, arch2); - for (const itemName of fs17.readdirSync(sourceDir)) { - const s = path15.join(sourceDir, itemName); - yield io7.cp(s, destPath, { recursive: true }); + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; } - _completeToolPath(tool, version, arch2); - return destPath; - }); - } - exports2.cacheDir = cacheDir; - function cacheFile(sourceFile, targetFile, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch2 = arch2 || os3.arch(); - core18.debug(`Caching tool ${tool} ${version} ${arch2}`); - core18.debug(`source file: ${sourceFile}`); - if (!fs17.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } } - const destFolder = yield _createToolPath(tool, version, arch2); - const destPath = path15.join(destFolder, targetFile); - core18.debug(`destination file ${destPath}`); - yield io7.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch2); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch2) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); - } - arch2 = arch2 || os3.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions2(toolName, arch2); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + return info7; } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver8.clean(versionSpec) || ""; - const cachePath = path15.join(_getCacheDirectory(), toolName, versionSpec, arch2); - core18.debug(`checking cache: ${cachePath}`); - if (fs17.existsSync(cachePath) && fs17.existsSync(`${cachePath}.complete`)) { - core18.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); - toolPath = cachePath; - } else { - core18.debug("not found"); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - return toolPath; - } - exports2.find = find2; - function findAllVersions2(toolName, arch2) { - const versions = []; - arch2 = arch2 || os3.arch(); - const toolPath = path15.join(_getCacheDirectory(), toolName); - if (fs17.existsSync(toolPath)) { - const children = fs17.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path15.join(toolPath, child, arch2 || ""); - if (fs17.existsSync(fullPath) && fs17.existsSync(`${fullPath}.complete`)) { - versions.push(child); - } + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; } } - } - return versions; - } - exports2.findAllVersions = findAllVersions2; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core18.debug("set auth"); - headers.authorization = auth; + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + if (clientHeader !== void 0) { + return clientHeader; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; + return _default2; + } + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; + } } } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core18.debug("Invalid json"); + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; } } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os3.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path15.join(_getTempDirectory(), crypto.randomUUID()); + if (clientHeader !== void 0) { + return clientHeader; } - yield io7.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path15.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); - core18.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io7.rmRF(folderPath); - yield io7.rmRF(markerPath); - yield io7.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch2) { - const folderPath = path15.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); - const markerPath = `${folderPath}.complete`; - fs17.writeFileSync(markerPath, ""); - core18.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver8.clean(versionSpec) || ""; - core18.debug(`isExplicit: ${c}`); - const valid3 = semver8.valid(c) != null; - core18.debug(`explicit? ${valid3}`); - return valid3; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core18.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver8.gt(a, b)) { - return 1; + return _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver8.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (!useProxy) { + agent = this._agent; } - } - if (version) { - core18.debug(`matched: ${version}`); - } else { - core18.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - return true; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); + } + })); + }); } - return a !== a && b !== b; }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -76096,78 +79066,476 @@ var require_config2 = __commonJS({ if (!ghWorkspaceDir) { throw new Error("Unable to get the GITHUB_WORKSPACE env variable"); } - return ghWorkspaceDir; - } - function getConcurrency() { - const numCPUs = os_1.default.cpus().length; - let concurrencyCap = 32; - if (numCPUs > 4) { - const concurrency = 16 * numCPUs; - concurrencyCap = concurrency > 300 ? 300 : concurrency; + return ghWorkspaceDir; + } + function getConcurrency() { + const numCPUs = os_1.default.cpus().length; + let concurrencyCap = 32; + if (numCPUs > 4) { + const concurrency = 16 * numCPUs; + concurrencyCap = concurrency > 300 ? 300 : concurrency; + } + const concurrencyOverride = process.env["ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY"]; + if (concurrencyOverride) { + const concurrency = parseInt(concurrencyOverride); + if (isNaN(concurrency) || concurrency < 1) { + throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY env variable"); + } + if (concurrency < concurrencyCap) { + (0, core_1.info)(`Set concurrency based on the value set in ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY.`); + return concurrency; + } + (0, core_1.info)(`ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY is higher than the cap of ${concurrencyCap} based on the number of cpus. Set it to the maximum value allowed.`); + return concurrencyCap; + } + return 5; + } + function getUploadChunkTimeout() { + const timeoutVar = process.env["ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS"]; + if (!timeoutVar) { + return 3e5; + } + const timeout = parseInt(timeoutVar); + if (isNaN(timeout)) { + throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS env variable"); + } + return timeout; + } + function getMaxArtifactListCount() { + const maxCountVar = process.env["ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT"] || "1000"; + const maxCount = parseInt(maxCountVar); + if (isNaN(maxCount) || maxCount < 1) { + throw new Error("Invalid value set for ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT env variable"); + } + return maxCount; + } + } +}); + +// node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js +var require_timestamp = __commonJS({ + "node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Timestamp = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var runtime_6 = require_commonjs11(); + var runtime_7 = require_commonjs11(); + var Timestamp$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.Timestamp", [ + { + no: 1, + name: "seconds", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 2, + name: "nanos", + kind: "scalar", + T: 5 + /*ScalarType.INT32*/ + } + ]); + } + /** + * Creates a new `Timestamp` for the current time. + */ + now() { + const msg = this.create(); + const ms = Date.now(); + msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); + msg.nanos = ms % 1e3 * 1e6; + return msg; + } + /** + * Converts a `Timestamp` to a JavaScript Date. + */ + toDate(message) { + return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1e3 + Math.ceil(message.nanos / 1e6)); + } + /** + * Converts a JavaScript Date to a `Timestamp`. + */ + fromDate(date) { + const msg = this.create(); + const ms = date.getTime(); + msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); + msg.nanos = ms % 1e3 * 1e6; + return msg; + } + /** + * In JSON format, the `Timestamp` type is encoded as a string + * in the RFC 3339 format. + */ + internalJsonWrite(message, options) { + let ms = runtime_6.PbLong.from(message.seconds).toNumber() * 1e3; + if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) + throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); + if (message.nanos < 0) + throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative."); + let z = "Z"; + if (message.nanos > 0) { + let nanosStr = (message.nanos + 1e9).toString().substring(1); + if (nanosStr.substring(3) === "000000") + z = "." + nanosStr.substring(0, 3) + "Z"; + else if (nanosStr.substring(6) === "000") + z = "." + nanosStr.substring(0, 6) + "Z"; + else + z = "." + nanosStr + "Z"; + } + return new Date(ms).toISOString().replace(".000Z", z); + } + /** + * In JSON format, the `Timestamp` type is encoded as a string + * in the RFC 3339 format. + */ + internalJsonRead(json2, options, target) { + if (typeof json2 !== "string") + throw new Error("Unable to parse Timestamp from JSON " + (0, runtime_5.typeofJsonValue)(json2) + "."); + let matches = json2.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/); + if (!matches) + throw new Error("Unable to parse Timestamp from JSON. Invalid format."); + let ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z")); + if (Number.isNaN(ms)) + throw new Error("Unable to parse Timestamp from JSON. Invalid value."); + if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) + throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); + if (!target) + target = this.create(); + target.seconds = runtime_6.PbLong.from(ms / 1e3).toString(); + target.nanos = 0; + if (matches[7]) + target.nanos = parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1e9; + return target; + } + create(value) { + const message = { seconds: "0", nanos: 0 }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 seconds */ + 1: + message.seconds = reader.int64().toString(); + break; + case /* int32 nanos */ + 2: + message.nanos = reader.int32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.seconds !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.seconds); + if (message.nanos !== 0) + writer.tag(2, runtime_1.WireType.Varint).int32(message.nanos); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.Timestamp = new Timestamp$Type(); + } +}); + +// node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js +var require_wrappers = __commonJS({ + "node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BytesValue = exports2.StringValue = exports2.BoolValue = exports2.UInt32Value = exports2.Int32Value = exports2.UInt64Value = exports2.Int64Value = exports2.FloatValue = exports2.DoubleValue = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var runtime_6 = require_commonjs11(); + var runtime_7 = require_commonjs11(); + var DoubleValue$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.DoubleValue", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 1 + /*ScalarType.DOUBLE*/ + } + ]); + } + /** + * Encode `DoubleValue` to JSON number. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(2, message.value, "value", false, true); + } + /** + * Decode `DoubleValue` from JSON number. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + return target; + } + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* double value */ + 1: + message.value = reader.double(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Bit64).double(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.DoubleValue = new DoubleValue$Type(); + var FloatValue$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.FloatValue", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 2 + /*ScalarType.FLOAT*/ + } + ]); + } + /** + * Encode `FloatValue` to JSON number. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(1, message.value, "value", false, true); + } + /** + * Decode `FloatValue` from JSON number. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + return target; + } + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* float value */ + 1: + message.value = reader.float(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Bit32).float(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FloatValue = new FloatValue$Type(); + var Int64Value$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.Int64Value", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + /** + * Encode `Int64Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true); + } + /** + * Decode `Int64Value` from JSON string. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.INT64, runtime_2.LongType.STRING, "value"); + return target; + } + create(value) { + const message = { value: "0" }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 value */ + 1: + message.value = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== "0") + writer.tag(1, runtime_3.WireType.Varint).int64(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.Int64Value = new Int64Value$Type(); + var UInt64Value$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.UInt64Value", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 4 + /*ScalarType.UINT64*/ + } + ]); + } + /** + * Encode `UInt64Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true); } - const concurrencyOverride = process.env["ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY"]; - if (concurrencyOverride) { - const concurrency = parseInt(concurrencyOverride); - if (isNaN(concurrency) || concurrency < 1) { - throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY env variable"); - } - if (concurrency < concurrencyCap) { - (0, core_1.info)(`Set concurrency based on the value set in ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY.`); - return concurrency; - } - (0, core_1.info)(`ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY is higher than the cap of ${concurrencyCap} based on the number of cpus. Set it to the maximum value allowed.`); - return concurrencyCap; + /** + * Decode `UInt64Value` from JSON string. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.UINT64, runtime_2.LongType.STRING, "value"); + return target; } - return 5; - } - function getUploadChunkTimeout() { - const timeoutVar = process.env["ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS"]; - if (!timeoutVar) { - return 3e5; + create(value) { + const message = { value: "0" }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; } - const timeout = parseInt(timeoutVar); - if (isNaN(timeout)) { - throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS env variable"); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* uint64 value */ + 1: + message.value = reader.uint64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - return timeout; - } - function getMaxArtifactListCount() { - const maxCountVar = process.env["ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT"] || "1000"; - const maxCount = parseInt(maxCountVar); - if (isNaN(maxCount) || maxCount < 1) { - throw new Error("Invalid value set for ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT env variable"); + internalBinaryWrite(message, writer, options) { + if (message.value !== "0") + writer.tag(1, runtime_3.WireType.Varint).uint64(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - return maxCount; - } - } -}); - -// node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js -var require_timestamp = __commonJS({ - "node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Timestamp = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var runtime_6 = require_commonjs11(); - var runtime_7 = require_commonjs11(); - var Timestamp$Type = class extends runtime_7.MessageType { + }; + exports2.UInt64Value = new UInt64Value$Type(); + var Int32Value$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.Timestamp", [ + super("google.protobuf.Int32Value", [ { no: 1, - name: "seconds", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 2, - name: "nanos", + name: "value", kind: "scalar", T: 5 /*ScalarType.INT32*/ @@ -76175,81 +79543,89 @@ var require_timestamp = __commonJS({ ]); } /** - * Creates a new `Timestamp` for the current time. + * Encode `Int32Value` to JSON string. */ - now() { - const msg = this.create(); - const ms = Date.now(); - msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); - msg.nanos = ms % 1e3 * 1e6; - return msg; + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(5, message.value, "value", false, true); } /** - * Converts a `Timestamp` to a JavaScript Date. + * Decode `Int32Value` from JSON string. */ - toDate(message) { - return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1e3 + Math.ceil(message.nanos / 1e6)); + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, 5, void 0, "value"); + return target; } - /** - * Converts a JavaScript Date to a `Timestamp`. - */ - fromDate(date) { - const msg = this.create(); - const ms = date.getTime(); - msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); - msg.nanos = ms % 1e3 * 1e6; - return msg; + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int32 value */ + 1: + message.value = reader.int32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Varint).int32(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.Int32Value = new Int32Value$Type(); + var UInt32Value$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.UInt32Value", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 13 + /*ScalarType.UINT32*/ + } + ]); } /** - * In JSON format, the `Timestamp` type is encoded as a string - * in the RFC 3339 format. + * Encode `UInt32Value` to JSON string. */ internalJsonWrite(message, options) { - let ms = runtime_6.PbLong.from(message.seconds).toNumber() * 1e3; - if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) - throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); - if (message.nanos < 0) - throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative."); - let z = "Z"; - if (message.nanos > 0) { - let nanosStr = (message.nanos + 1e9).toString().substring(1); - if (nanosStr.substring(3) === "000000") - z = "." + nanosStr.substring(0, 3) + "Z"; - else if (nanosStr.substring(6) === "000") - z = "." + nanosStr.substring(0, 6) + "Z"; - else - z = "." + nanosStr + "Z"; - } - return new Date(ms).toISOString().replace(".000Z", z); + return this.refJsonWriter.scalar(13, message.value, "value", false, true); } /** - * In JSON format, the `Timestamp` type is encoded as a string - * in the RFC 3339 format. + * Decode `UInt32Value` from JSON string. */ internalJsonRead(json2, options, target) { - if (typeof json2 !== "string") - throw new Error("Unable to parse Timestamp from JSON " + (0, runtime_5.typeofJsonValue)(json2) + "."); - let matches = json2.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/); - if (!matches) - throw new Error("Unable to parse Timestamp from JSON. Invalid format."); - let ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z")); - if (Number.isNaN(ms)) - throw new Error("Unable to parse Timestamp from JSON. Invalid value."); - if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) - throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); if (!target) target = this.create(); - target.seconds = runtime_6.PbLong.from(ms / 1e3).toString(); - target.nanos = 0; - if (matches[7]) - target.nanos = parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1e9; + target.value = this.refJsonReader.scalar(json2, 13, void 0, "value"); return target; } create(value) { - const message = { seconds: "0", nanos: 0 }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); + (0, runtime_5.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76257,13 +79633,9 @@ var require_timestamp = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* int64 seconds */ + case /* uint32 value */ 1: - message.seconds = reader.int64().toString(); - break; - case /* int32 nanos */ - 2: - message.nanos = reader.int32(); + message.value = reader.uint32(); break; default: let u = options.readUnknownField; @@ -76271,68 +79643,50 @@ var require_timestamp = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.seconds !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.seconds); - if (message.nanos !== 0) - writer.tag(2, runtime_1.WireType.Varint).int32(message.nanos); + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Varint).uint32(message.value); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.Timestamp = new Timestamp$Type(); - } -}); - -// node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js -var require_wrappers = __commonJS({ - "node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BytesValue = exports2.StringValue = exports2.BoolValue = exports2.UInt32Value = exports2.Int32Value = exports2.UInt64Value = exports2.Int64Value = exports2.FloatValue = exports2.DoubleValue = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var runtime_6 = require_commonjs11(); - var runtime_7 = require_commonjs11(); - var DoubleValue$Type = class extends runtime_7.MessageType { + exports2.UInt32Value = new UInt32Value$Type(); + var BoolValue$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.DoubleValue", [ + super("google.protobuf.BoolValue", [ { no: 1, name: "value", kind: "scalar", - T: 1 - /*ScalarType.DOUBLE*/ + T: 8 + /*ScalarType.BOOL*/ } ]); } /** - * Encode `DoubleValue` to JSON number. + * Encode `BoolValue` to JSON bool. */ internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(2, message.value, "value", false, true); + return message.value; } /** - * Decode `DoubleValue` from JSON number. + * Decode `BoolValue` from JSON bool. */ internalJsonRead(json2, options, target) { if (!target) target = this.create(); - target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + target.value = this.refJsonReader.scalar(json2, 8, void 0, "value"); return target; } create(value) { - const message = { value: 0 }; + const message = { value: false }; globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_5.reflectionMergePartial)(this, message, value); @@ -76343,9 +79697,9 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* double value */ + case /* bool value */ 1: - message.value = reader.double(); + message.value = reader.bool(); break; default: let u = options.readUnknownField; @@ -76359,44 +79713,44 @@ var require_wrappers = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Bit64).double(message.value); + if (message.value !== false) + writer.tag(1, runtime_3.WireType.Varint).bool(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.DoubleValue = new DoubleValue$Type(); - var FloatValue$Type = class extends runtime_7.MessageType { + exports2.BoolValue = new BoolValue$Type(); + var StringValue$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.FloatValue", [ + super("google.protobuf.StringValue", [ { no: 1, name: "value", kind: "scalar", - T: 2 - /*ScalarType.FLOAT*/ + T: 9 + /*ScalarType.STRING*/ } ]); } /** - * Encode `FloatValue` to JSON number. + * Encode `StringValue` to JSON string. */ internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(1, message.value, "value", false, true); + return message.value; } /** - * Decode `FloatValue` from JSON number. + * Decode `StringValue` from JSON string. */ internalJsonRead(json2, options, target) { if (!target) target = this.create(); - target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + target.value = this.refJsonReader.scalar(json2, 9, void 0, "value"); return target; } create(value) { - const message = { value: 0 }; + const message = { value: "" }; globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_5.reflectionMergePartial)(this, message, value); @@ -76407,9 +79761,9 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* float value */ + case /* string value */ 1: - message.value = reader.float(); + message.value = reader.string(); break; default: let u = options.readUnknownField; @@ -76423,44 +79777,44 @@ var require_wrappers = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Bit32).float(message.value); + if (message.value !== "") + writer.tag(1, runtime_3.WireType.LengthDelimited).string(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.FloatValue = new FloatValue$Type(); - var Int64Value$Type = class extends runtime_7.MessageType { + exports2.StringValue = new StringValue$Type(); + var BytesValue$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.Int64Value", [ + super("google.protobuf.BytesValue", [ { no: 1, name: "value", kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + T: 12 + /*ScalarType.BYTES*/ } ]); } /** - * Encode `Int64Value` to JSON string. + * Encode `BytesValue` to JSON string. */ internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true); + return this.refJsonWriter.scalar(12, message.value, "value", false, true); } /** - * Decode `Int64Value` from JSON string. + * Decode `BytesValue` from JSON string. */ internalJsonRead(json2, options, target) { if (!target) target = this.create(); - target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.INT64, runtime_2.LongType.STRING, "value"); + target.value = this.refJsonReader.scalar(json2, 12, void 0, "value"); return target; } create(value) { - const message = { value: "0" }; + const message = { value: new Uint8Array(0) }; globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_5.reflectionMergePartial)(this, message, value); @@ -76471,9 +79825,9 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* int64 value */ + case /* bytes value */ 1: - message.value = reader.int64().toString(); + message.value = reader.bytes(); break; default: let u = options.readUnknownField; @@ -76487,47 +79841,195 @@ var require_wrappers = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== "0") - writer.tag(1, runtime_3.WireType.Varint).int64(message.value); + if (message.value.length) + writer.tag(1, runtime_3.WireType.LengthDelimited).bytes(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.Int64Value = new Int64Value$Type(); - var UInt64Value$Type = class extends runtime_7.MessageType { + exports2.BytesValue = new BytesValue$Type(); + } +}); + +// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js +var require_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArtifactService = exports2.DeleteArtifactResponse = exports2.DeleteArtifactRequest = exports2.GetSignedArtifactURLResponse = exports2.GetSignedArtifactURLRequest = exports2.ListArtifactsResponse_MonolithArtifact = exports2.ListArtifactsResponse = exports2.ListArtifactsRequest = exports2.FinalizeArtifactResponse = exports2.FinalizeArtifactRequest = exports2.CreateArtifactResponse = exports2.CreateArtifactRequest = exports2.FinalizeMigratedArtifactResponse = exports2.FinalizeMigratedArtifactRequest = exports2.MigrateArtifactResponse = exports2.MigrateArtifactRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var wrappers_1 = require_wrappers(); + var wrappers_2 = require_wrappers(); + var timestamp_1 = require_timestamp(); + var MigrateArtifactRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.MigrateArtifactRequest", [ + { + no: 1, + name: "workflow_run_backend_id", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { no: 3, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp } + ]); + } + create(value) { + const message = { workflowRunBackendId: "", name: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string workflow_run_backend_id */ + 1: + message.workflowRunBackendId = reader.string(); + break; + case /* string name */ + 2: + message.name = reader.string(); + break; + case /* google.protobuf.Timestamp expires_at */ + 3: + message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.name !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.expiresAt) + timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.MigrateArtifactRequest = new MigrateArtifactRequest$Type(); + var MigrateArtifactResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.MigrateArtifactResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedUploadUrl: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.MigrateArtifactResponse = new MigrateArtifactResponse$Type(); + var FinalizeMigratedArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.UInt64Value", [ + super("github.actions.results.api.v1.FinalizeMigratedArtifactRequest", [ { no: 1, - name: "value", + name: "workflow_run_backend_id", kind: "scalar", - T: 4 - /*ScalarType.UINT64*/ + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ } ]); } - /** - * Encode `UInt64Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true); - } - /** - * Decode `UInt64Value` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.UINT64, runtime_2.LongType.STRING, "value"); - return target; - } create(value) { - const message = { value: "0" }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { workflowRunBackendId: "", name: "", size: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76535,9 +80037,17 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* uint64 value */ + case /* string workflow_run_backend_id */ 1: - message.value = reader.uint64().toString(); + message.workflowRunBackendId = reader.string(); + break; + case /* string name */ + 2: + message.name = reader.string(); + break; + case /* int64 size */ + 3: + message.size = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -76545,53 +80055,49 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== "0") - writer.tag(1, runtime_3.WireType.Varint).uint64(message.value); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.name !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.size !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.size); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.UInt64Value = new UInt64Value$Type(); - var Int32Value$Type = class extends runtime_7.MessageType { + exports2.FinalizeMigratedArtifactRequest = new FinalizeMigratedArtifactRequest$Type(); + var FinalizeMigratedArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.Int32Value", [ + super("github.actions.results.api.v1.FinalizeMigratedArtifactResponse", [ { no: 1, - name: "value", + name: "ok", kind: "scalar", - T: 5 - /*ScalarType.INT32*/ + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "artifact_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ } ]); } - /** - * Encode `Int32Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(5, message.value, "value", false, true); - } - /** - * Decode `Int32Value` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 5, void 0, "value"); - return target; - } create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { ok: false, artifactId: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76599,9 +80105,13 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* int32 value */ + case /* bool ok */ 1: - message.value = reader.int32(); + message.ok = reader.bool(); + break; + case /* int64 artifact_id */ + 2: + message.artifactId = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -76609,53 +80119,62 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Varint).int32(message.value); + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.Int32Value = new Int32Value$Type(); - var UInt32Value$Type = class extends runtime_7.MessageType { + exports2.FinalizeMigratedArtifactResponse = new FinalizeMigratedArtifactResponse$Type(); + var CreateArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.UInt32Value", [ + super("github.actions.results.api.v1.CreateArtifactRequest", [ { no: 1, - name: "value", + name: "workflow_run_backend_id", kind: "scalar", - T: 13 - /*ScalarType.UINT32*/ + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "workflow_job_run_backend_id", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { no: 4, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp }, + { + no: 5, + name: "version", + kind: "scalar", + T: 5 + /*ScalarType.INT32*/ } ]); } - /** - * Encode `UInt32Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(13, message.value, "value", false, true); - } - /** - * Decode `UInt32Value` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 13, void 0, "value"); - return target; - } create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", version: 0 }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76663,9 +80182,25 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* uint32 value */ + case /* string workflow_run_backend_id */ 1: - message.value = reader.uint32(); + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ + 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* string name */ + 3: + message.name = reader.string(); + break; + case /* google.protobuf.Timestamp expires_at */ + 4: + message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + break; + case /* int32 version */ + 5: + message.version = reader.int32(); break; default: let u = options.readUnknownField; @@ -76673,53 +80208,53 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Varint).uint32(message.value); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.name !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.expiresAt) + timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.version !== 0) + writer.tag(5, runtime_1.WireType.Varint).int32(message.version); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.UInt32Value = new UInt32Value$Type(); - var BoolValue$Type = class extends runtime_7.MessageType { + exports2.CreateArtifactRequest = new CreateArtifactRequest$Type(); + var CreateArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.BoolValue", [ + super("github.actions.results.api.v1.CreateArtifactResponse", [ { no: 1, - name: "value", + name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ } ]); } - /** - * Encode `BoolValue` to JSON bool. - */ - internalJsonWrite(message, options) { - return message.value; - } - /** - * Decode `BoolValue` from JSON bool. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 8, void 0, "value"); - return target; - } create(value) { - const message = { value: false }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { ok: false, signedUploadUrl: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76727,9 +80262,13 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bool value */ + case /* bool ok */ 1: - message.value = reader.bool(); + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); break; default: let u = options.readUnknownField; @@ -76737,53 +80276,62 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== false) - writer.tag(1, runtime_3.WireType.Varint).bool(message.value); + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.BoolValue = new BoolValue$Type(); - var StringValue$Type = class extends runtime_7.MessageType { + exports2.CreateArtifactResponse = new CreateArtifactResponse$Type(); + var FinalizeArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.StringValue", [ + super("github.actions.results.api.v1.FinalizeArtifactRequest", [ { no: 1, - name: "value", + name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ - } + }, + { + no: 2, + name: "workflow_job_run_backend_id", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "size", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 5, name: "hash", kind: "message", T: () => wrappers_2.StringValue } ]); } - /** - * Encode `StringValue` to JSON string. - */ - internalJsonWrite(message, options) { - return message.value; - } - /** - * Decode `StringValue` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 9, void 0, "value"); - return target; - } create(value) { - const message = { value: "" }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", size: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76791,9 +80339,25 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* string value */ + case /* string workflow_run_backend_id */ 1: - message.value = reader.string(); + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ + 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* string name */ + 3: + message.name = reader.string(); + break; + case /* int64 size */ + 4: + message.size = reader.int64().toString(); + break; + case /* google.protobuf.StringValue hash */ + 5: + message.hash = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.hash); break; default: let u = options.readUnknownField; @@ -76801,53 +80365,53 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== "") - writer.tag(1, runtime_3.WireType.LengthDelimited).string(message.value); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.name !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.size !== "0") + writer.tag(4, runtime_1.WireType.Varint).int64(message.size); + if (message.hash) + wrappers_2.StringValue.internalBinaryWrite(message.hash, writer.tag(5, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.StringValue = new StringValue$Type(); - var BytesValue$Type = class extends runtime_7.MessageType { + exports2.FinalizeArtifactRequest = new FinalizeArtifactRequest$Type(); + var FinalizeArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.BytesValue", [ + super("github.actions.results.api.v1.FinalizeArtifactResponse", [ { no: 1, - name: "value", + name: "ok", kind: "scalar", - T: 12 - /*ScalarType.BYTES*/ + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "artifact_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ } ]); } - /** - * Encode `BytesValue` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(12, message.value, "value", false, true); - } - /** - * Decode `BytesValue` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 12, void 0, "value"); - return target; - } create(value) { - const message = { value: new Uint8Array(0) }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { ok: false, artifactId: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -76855,9 +80419,13 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bytes value */ + case /* bool ok */ 1: - message.value = reader.bytes(); + message.ok = reader.bool(); + break; + case /* int64 artifact_id */ + 2: + message.artifactId = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -76865,42 +80433,26 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value.length) - writer.tag(1, runtime_3.WireType.LengthDelimited).bytes(message.value); + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.BytesValue = new BytesValue$Type(); - } -}); - -// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js -var require_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArtifactService = exports2.DeleteArtifactResponse = exports2.DeleteArtifactRequest = exports2.GetSignedArtifactURLResponse = exports2.GetSignedArtifactURLRequest = exports2.ListArtifactsResponse_MonolithArtifact = exports2.ListArtifactsResponse = exports2.ListArtifactsRequest = exports2.FinalizeArtifactResponse = exports2.FinalizeArtifactRequest = exports2.CreateArtifactResponse = exports2.CreateArtifactRequest = exports2.FinalizeMigratedArtifactResponse = exports2.FinalizeMigratedArtifactRequest = exports2.MigrateArtifactResponse = exports2.MigrateArtifactRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var wrappers_1 = require_wrappers(); - var wrappers_2 = require_wrappers(); - var timestamp_1 = require_timestamp(); - var MigrateArtifactRequest$Type = class extends runtime_5.MessageType { + exports2.FinalizeArtifactResponse = new FinalizeArtifactResponse$Type(); + var ListArtifactsRequest$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.MigrateArtifactRequest", [ + super("github.actions.results.api.v1.ListArtifactsRequest", [ { no: 1, name: "workflow_run_backend_id", @@ -76910,16 +80462,17 @@ var require_artifact = __commonJS({ }, { no: 2, - name: "name", + name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 3, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp } + { no: 3, name: "name_filter", kind: "message", T: () => wrappers_2.StringValue }, + { no: 4, name: "id_filter", kind: "message", T: () => wrappers_1.Int64Value } ]); } create(value) { - const message = { workflowRunBackendId: "", name: "" }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -76934,13 +80487,17 @@ var require_artifact = __commonJS({ 1: message.workflowRunBackendId = reader.string(); break; - case /* string name */ + case /* string workflow_job_run_backend_id */ 2: - message.name = reader.string(); + message.workflowJobRunBackendId = reader.string(); break; - case /* google.protobuf.Timestamp expires_at */ + case /* google.protobuf.StringValue name_filter */ 3: - message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + message.nameFilter = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.nameFilter); + break; + case /* google.protobuf.Int64Value id_filter */ + 4: + message.idFilter = wrappers_1.Int64Value.internalBinaryRead(reader, reader.uint32(), options, message.idFilter); break; default: let u = options.readUnknownField; @@ -76956,38 +80513,106 @@ var require_artifact = __commonJS({ internalBinaryWrite(message, writer, options) { if (message.workflowRunBackendId !== "") writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.name !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.expiresAt) - timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.nameFilter) + wrappers_2.StringValue.internalBinaryWrite(message.nameFilter, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.idFilter) + wrappers_1.Int64Value.internalBinaryWrite(message.idFilter, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.ListArtifactsRequest = new ListArtifactsRequest$Type(); + var ListArtifactsResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.ListArtifactsResponse", [ + { no: 1, name: "artifacts", kind: "message", repeat: 1, T: () => exports2.ListArtifactsResponse_MonolithArtifact } + ]); + } + create(value) { + const message = { artifacts: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts */ + 1: + message.artifacts.push(exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + for (let i = 0; i < message.artifacts.length; i++) + exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryWrite(message.artifacts[i], writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.MigrateArtifactRequest = new MigrateArtifactRequest$Type(); - var MigrateArtifactResponse$Type = class extends runtime_5.MessageType { + exports2.ListArtifactsResponse = new ListArtifactsResponse$Type(); + var ListArtifactsResponse_MonolithArtifact$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.MigrateArtifactResponse", [ + super("github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact", [ { no: 1, - name: "ok", + name: "workflow_run_backend_id", kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ + T: 9 + /*ScalarType.STRING*/ }, { no: 2, - name: "signed_upload_url", + name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ - } + }, + { + no: 3, + name: "database_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 5, + name: "size", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 6, name: "created_at", kind: "message", T: () => timestamp_1.Timestamp }, + { no: 7, name: "digest", kind: "message", T: () => wrappers_2.StringValue } ]); } create(value) { - const message = { ok: false, signedUploadUrl: "" }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", databaseId: "0", name: "", size: "0" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -76998,13 +80623,33 @@ var require_artifact = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bool ok */ + case /* string workflow_run_backend_id */ 1: - message.ok = reader.bool(); + message.workflowRunBackendId = reader.string(); break; - case /* string signed_upload_url */ + case /* string workflow_job_run_backend_id */ 2: - message.signedUploadUrl = reader.string(); + message.workflowJobRunBackendId = reader.string(); + break; + case /* int64 database_id */ + 3: + message.databaseId = reader.int64().toString(); + break; + case /* string name */ + 4: + message.name = reader.string(); + break; + case /* int64 size */ + 5: + message.size = reader.int64().toString(); + break; + case /* google.protobuf.Timestamp created_at */ + 6: + message.createdAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.createdAt); + break; + case /* google.protobuf.StringValue digest */ + 7: + message.digest = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.digest); break; default: let u = options.readUnknownField; @@ -77018,20 +80663,30 @@ var require_artifact = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.databaseId !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.databaseId); + if (message.name !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.size !== "0") + writer.tag(5, runtime_1.WireType.Varint).int64(message.size); + if (message.createdAt) + timestamp_1.Timestamp.internalBinaryWrite(message.createdAt, writer.tag(6, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.digest) + wrappers_2.StringValue.internalBinaryWrite(message.digest, writer.tag(7, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.MigrateArtifactResponse = new MigrateArtifactResponse$Type(); - var FinalizeMigratedArtifactRequest$Type = class extends runtime_5.MessageType { + exports2.ListArtifactsResponse_MonolithArtifact = new ListArtifactsResponse_MonolithArtifact$Type(); + var GetSignedArtifactURLRequest$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.FinalizeMigratedArtifactRequest", [ + super("github.actions.results.api.v1.GetSignedArtifactURLRequest", [ { no: 1, name: "workflow_run_backend_id", @@ -77041,22 +80696,22 @@ var require_artifact = __commonJS({ }, { no: 2, - name: "name", + name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, - name: "size", + name: "name", kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + T: 9 + /*ScalarType.STRING*/ } ]); } create(value) { - const message = { workflowRunBackendId: "", name: "", size: "0" }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -77071,13 +80726,13 @@ var require_artifact = __commonJS({ 1: message.workflowRunBackendId = reader.string(); break; - case /* string name */ + case /* string workflow_job_run_backend_id */ 2: - message.name = reader.string(); + message.workflowJobRunBackendId = reader.string(); break; - case /* int64 size */ + case /* string name */ 3: - message.size = reader.int64().toString(); + message.name = reader.string(); break; default: let u = options.readUnknownField; @@ -77093,38 +80748,31 @@ var require_artifact = __commonJS({ internalBinaryWrite(message, writer, options) { if (message.workflowRunBackendId !== "") writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); if (message.name !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.size !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.size); + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.FinalizeMigratedArtifactRequest = new FinalizeMigratedArtifactRequest$Type(); - var FinalizeMigratedArtifactResponse$Type = class extends runtime_5.MessageType { + exports2.GetSignedArtifactURLRequest = new GetSignedArtifactURLRequest$Type(); + var GetSignedArtifactURLResponse$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.FinalizeMigratedArtifactResponse", [ + super("github.actions.results.api.v1.GetSignedArtifactURLResponse", [ { no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "artifact_id", + name: "signed_url", kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + T: 9 + /*ScalarType.STRING*/ } ]); } create(value) { - const message = { ok: false, artifactId: "0" }; + const message = { signedUrl: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -77135,13 +80783,9 @@ var require_artifact = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bool ok */ + case /* string signed_url */ 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ - 2: - message.artifactId = reader.int64().toString(); + message.signedUrl = reader.string(); break; default: let u = options.readUnknownField; @@ -77155,20 +80799,18 @@ var require_artifact = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); + if (message.signedUrl !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.signedUrl); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.FinalizeMigratedArtifactResponse = new FinalizeMigratedArtifactResponse$Type(); - var CreateArtifactRequest$Type = class extends runtime_5.MessageType { + exports2.GetSignedArtifactURLResponse = new GetSignedArtifactURLResponse$Type(); + var DeleteArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.CreateArtifactRequest", [ + super("github.actions.results.api.v1.DeleteArtifactRequest", [ { no: 1, name: "workflow_run_backend_id", @@ -77189,19 +80831,11 @@ var require_artifact = __commonJS({ kind: "scalar", T: 9 /*ScalarType.STRING*/ - }, - { no: 4, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp }, - { - no: 5, - name: "version", - kind: "scalar", - T: 5 - /*ScalarType.INT32*/ } ]); } create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", version: 0 }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -77224,14 +80858,6 @@ var require_artifact = __commonJS({ 3: message.name = reader.string(); break; - case /* google.protobuf.Timestamp expires_at */ - 4: - message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); - break; - case /* int32 version */ - 5: - message.version = reader.int32(); - break; default: let u = options.readUnknownField; if (u === "throw") @@ -77250,20 +80876,16 @@ var require_artifact = __commonJS({ writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); if (message.name !== "") writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.expiresAt) - timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.version !== 0) - writer.tag(5, runtime_1.WireType.Varint).int32(message.version); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.CreateArtifactRequest = new CreateArtifactRequest$Type(); - var CreateArtifactResponse$Type = class extends runtime_5.MessageType { + exports2.DeleteArtifactRequest = new DeleteArtifactRequest$Type(); + var DeleteArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.CreateArtifactResponse", [ + super("github.actions.results.api.v1.DeleteArtifactResponse", [ { no: 1, name: "ok", @@ -77273,15 +80895,15 @@ var require_artifact = __commonJS({ }, { no: 2, - name: "signed_upload_url", + name: "artifact_id", kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + T: 3 + /*ScalarType.INT64*/ } ]); } create(value) { - const message = { ok: false, signedUploadUrl: "" }; + const message = { ok: false, artifactId: "0" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -77296,9 +80918,9 @@ var require_artifact = __commonJS({ 1: message.ok = reader.bool(); break; - case /* string signed_upload_url */ + case /* int64 artifact_id */ 2: - message.signedUploadUrl = reader.string(); + message.artifactId = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -77314,938 +80936,1091 @@ var require_artifact = __commonJS({ internalBinaryWrite(message, writer, options) { if (message.ok !== false) writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.CreateArtifactResponse = new CreateArtifactResponse$Type(); - var FinalizeArtifactRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeArtifactRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "size", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 5, name: "hash", kind: "message", T: () => wrappers_2.StringValue } - ]); + exports2.DeleteArtifactResponse = new DeleteArtifactResponse$Type(); + exports2.ArtifactService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.ArtifactService", [ + { name: "CreateArtifact", options: {}, I: exports2.CreateArtifactRequest, O: exports2.CreateArtifactResponse }, + { name: "FinalizeArtifact", options: {}, I: exports2.FinalizeArtifactRequest, O: exports2.FinalizeArtifactResponse }, + { name: "ListArtifacts", options: {}, I: exports2.ListArtifactsRequest, O: exports2.ListArtifactsResponse }, + { name: "GetSignedArtifactURL", options: {}, I: exports2.GetSignedArtifactURLRequest, O: exports2.GetSignedArtifactURLResponse }, + { name: "DeleteArtifact", options: {}, I: exports2.DeleteArtifactRequest, O: exports2.DeleteArtifactResponse }, + { name: "MigrateArtifact", options: {}, I: exports2.MigrateArtifactRequest, O: exports2.MigrateArtifactResponse }, + { name: "FinalizeMigratedArtifact", options: {}, I: exports2.FinalizeMigratedArtifactRequest, O: exports2.FinalizeMigratedArtifactResponse } + ]); + } +}); + +// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js +var require_artifact_twirp_client = __commonJS({ + "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArtifactServiceClientProtobuf = exports2.ArtifactServiceClientJSON = void 0; + var artifact_1 = require_artifact(); + var ArtifactServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateArtifact.bind(this); + this.FinalizeArtifact.bind(this); + this.ListArtifacts.bind(this); + this.GetSignedArtifactURL.bind(this); + this.DeleteArtifact.bind(this); } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", size: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + CreateArtifact(request) { + const data = artifact_1.CreateArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/json", data); + return promise.then((data2) => artifact_1.CreateArtifactResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ - 3: - message.name = reader.string(); - break; - case /* int64 size */ - 4: - message.size = reader.int64().toString(); - break; - case /* google.protobuf.StringValue hash */ - 5: - message.hash = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.hash); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + FinalizeArtifact(request) { + const data = artifact_1.FinalizeArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/json", data); + return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + ListArtifacts(request) { + const data = artifact_1.ListArtifactsRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/json", data); + return promise.then((data2) => artifact_1.ListArtifactsResponse.fromJson(data2, { ignoreUnknownFields: true })); + } + GetSignedArtifactURL(request) { + const data = artifact_1.GetSignedArtifactURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/json", data); + return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + DeleteArtifact(request) { + const data = artifact_1.DeleteArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/json", data); + return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + }; + exports2.ArtifactServiceClientJSON = ArtifactServiceClientJSON; + var ArtifactServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateArtifact.bind(this); + this.FinalizeArtifact.bind(this); + this.ListArtifacts.bind(this); + this.GetSignedArtifactURL.bind(this); + this.DeleteArtifact.bind(this); + } + CreateArtifact(request) { + const data = artifact_1.CreateArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/protobuf", data); + return promise.then((data2) => artifact_1.CreateArtifactResponse.fromBinary(data2)); + } + FinalizeArtifact(request) { + const data = artifact_1.FinalizeArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/protobuf", data); + return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromBinary(data2)); + } + ListArtifacts(request) { + const data = artifact_1.ListArtifactsRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/protobuf", data); + return promise.then((data2) => artifact_1.ListArtifactsResponse.fromBinary(data2)); + } + GetSignedArtifactURL(request) { + const data = artifact_1.GetSignedArtifactURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/protobuf", data); + return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromBinary(data2)); + } + DeleteArtifact(request) { + const data = artifact_1.DeleteArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/protobuf", data); + return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromBinary(data2)); + } + }; + exports2.ArtifactServiceClientProtobuf = ArtifactServiceClientProtobuf; + } +}); + +// node_modules/@actions/artifact/lib/generated/index.js +var require_generated = __commonJS({ + "node_modules/@actions/artifact/lib/generated/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar4(require_timestamp(), exports2); + __exportStar4(require_wrappers(), exports2); + __exportStar4(require_artifact(), exports2); + __exportStar4(require_artifact_twirp_client(), exports2); + } +}); + +// node_modules/@actions/artifact/lib/internal/upload/retention.js +var require_retention = __commonJS({ + "node_modules/@actions/artifact/lib/internal/upload/retention.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getExpiration = getExpiration; + var generated_1 = require_generated(); + var core18 = __importStar4(require_core()); + function getExpiration(retentionDays) { + if (!retentionDays) { + return void 0; + } + const maxRetentionDays = getRetentionDays(); + if (maxRetentionDays && maxRetentionDays < retentionDays) { + core18.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); + retentionDays = maxRetentionDays; + } + const expirationDate = /* @__PURE__ */ new Date(); + expirationDate.setDate(expirationDate.getDate() + retentionDays); + return generated_1.Timestamp.fromDate(expirationDate); + } + function getRetentionDays() { + const retentionDays = process.env["GITHUB_RETENTION_DAYS"]; + if (!retentionDays) { + return void 0; + } + const days = parseInt(retentionDays); + if (isNaN(days)) { + return void 0; + } + return days; + } + } +}); + +// node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js +var require_path_and_artifact_name_validation = __commonJS({ + "node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.validateArtifactName = validateArtifactName; + exports2.validateFilePath = validateFilePath; + var core_1 = require_core(); + var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ + ['"', ' Double quote "'], + [":", " Colon :"], + ["<", " Less than <"], + [">", " Greater than >"], + ["|", " Vertical bar |"], + ["*", " Asterisk *"], + ["?", " Question mark ?"], + ["\r", " Carriage return \\r"], + ["\n", " Line feed \\n"] + ]); + var invalidArtifactNameCharacters = new Map([ + ...invalidArtifactFilePathCharacters, + ["\\", " Backslash \\"], + ["/", " Forward slash /"] + ]); + function validateArtifactName(name) { + if (!name) { + throw new Error(`Provided artifact name input during validation is empty`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { + if (name.includes(invalidCharacterKey)) { + throw new Error(`The artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} + +These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.size !== "0") - writer.tag(4, runtime_1.WireType.Varint).int64(message.size); - if (message.hash) - wrappers_2.StringValue.internalBinaryWrite(message.hash, writer.tag(5, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + (0, core_1.info)(`Artifact name is valid!`); + } + function validateFilePath(path15) { + if (!path15) { + throw new Error(`Provided file path input during validation is empty`); } - }; - exports2.FinalizeArtifactRequest = new FinalizeArtifactRequest$Type(); - var FinalizeArtifactResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeArtifactResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "artifact_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - } - ]); + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { + if (path15.includes(invalidCharacterKey)) { + throw new Error(`The path for one of the files in artifact is not valid: ${path15}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} + +The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. + `); + } } - create(value) { - const message = { ok: false, artifactId: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + } + } +}); + +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/proxy.js +var require_proxy6 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ - 2: - message.artifactId = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - return message; + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - }; - exports2.FinalizeArtifactResponse = new FinalizeArtifactResponse$Type(); - var ListArtifactsRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { no: 3, name: "name_filter", kind: "message", T: () => wrappers_2.StringValue }, - { no: 4, name: "id_filter", kind: "message", T: () => wrappers_1.Int64Value } - ]); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* google.protobuf.StringValue name_filter */ - 3: - message.nameFilter = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.nameFilter); - break; - case /* google.protobuf.Int64Value id_filter */ - 4: - message.idFilter = wrappers_1.Int64Value.internalBinaryRead(reader, reader.uint32(), options, message.idFilter); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.nameFilter) - wrappers_2.StringValue.internalBinaryWrite(message.nameFilter, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.idFilter) - wrappers_1.Int64Value.internalBinaryWrite(message.idFilter, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - }; - exports2.ListArtifactsRequest = new ListArtifactsRequest$Type(); - var ListArtifactsResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsResponse", [ - { no: 1, name: "artifacts", kind: "message", repeat: 1, T: () => exports2.ListArtifactsResponse_MonolithArtifact } - ]); + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } } - create(value) { - const message = { artifacts: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts */ - 1: - message.artifacts.push(exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryRead(reader, reader.uint32(), options)); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + get username() { + return this._decodedUsername; } - internalBinaryWrite(message, writer, options) { - for (let i = 0; i < message.artifacts.length; i++) - exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryWrite(message.artifacts[i], writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + get password() { + return this._decodedPassword; } }; - exports2.ListArtifactsResponse = new ListArtifactsResponse$Type(); - var ListArtifactsResponse_MonolithArtifact$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "database_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 5, - name: "size", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 6, name: "created_at", kind: "message", T: () => timestamp_1.Timestamp }, - { no: 7, name: "digest", kind: "message", T: () => wrappers_2.StringValue } - ]); + } +}); + +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/index.js +var require_lib7 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", databaseId: "0", name: "", size: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* int64 database_id */ - 3: - message.databaseId = reader.int64().toString(); - break; - case /* string name */ - 4: - message.name = reader.string(); - break; - case /* int64 size */ - 5: - message.size = reader.int64().toString(); - break; - case /* google.protobuf.Timestamp created_at */ - 6: - message.createdAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.createdAt); - break; - case /* google.protobuf.StringValue digest */ - 7: - message.digest = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.digest); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.databaseId !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.databaseId); - if (message.name !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.size !== "0") - writer.tag(5, runtime_1.WireType.Varint).int64(message.size); - if (message.createdAt) - timestamp_1.Timestamp.internalBinaryWrite(message.createdAt, writer.tag(6, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.digest) - wrappers_2.StringValue.internalBinaryWrite(message.digest, writer.tag(7, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy6()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.ListArtifactsResponse_MonolithArtifact = new ListArtifactsResponse_MonolithArtifact$Type(); - var GetSignedArtifactURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetSignedArtifactURLRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); - } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ - 3: - message.name = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); + }); } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); + }); } }; - exports2.GetSignedArtifactURLRequest = new GetSignedArtifactURLRequest$Type(); - var GetSignedArtifactURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetSignedArtifactURLResponse", [ - { - no: 1, - name: "signed_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - ]); - } - create(value) { - const message = { signedUrl: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string signed_url */ - 1: - message.signedUrl = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.signedUrl !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.signedUrl); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.GetSignedArtifactURLResponse = new GetSignedArtifactURLResponse$Type(); - var DeleteArtifactRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.DeleteArtifactRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ - 3: - message.name = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - }; - exports2.DeleteArtifactRequest = new DeleteArtifactRequest$Type(); - var DeleteArtifactResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.DeleteArtifactResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "artifact_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - } - ]); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - create(value) { - const message = { ok: false, artifactId: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ - 2: - message.artifactId = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - }; - exports2.DeleteArtifactResponse = new DeleteArtifactResponse$Type(); - exports2.ArtifactService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.ArtifactService", [ - { name: "CreateArtifact", options: {}, I: exports2.CreateArtifactRequest, O: exports2.CreateArtifactResponse }, - { name: "FinalizeArtifact", options: {}, I: exports2.FinalizeArtifactRequest, O: exports2.FinalizeArtifactResponse }, - { name: "ListArtifacts", options: {}, I: exports2.ListArtifactsRequest, O: exports2.ListArtifactsResponse }, - { name: "GetSignedArtifactURL", options: {}, I: exports2.GetSignedArtifactURLRequest, O: exports2.GetSignedArtifactURLResponse }, - { name: "DeleteArtifact", options: {}, I: exports2.DeleteArtifactRequest, O: exports2.DeleteArtifactResponse }, - { name: "MigrateArtifact", options: {}, I: exports2.MigrateArtifactRequest, O: exports2.MigrateArtifactResponse }, - { name: "FinalizeMigratedArtifact", options: {}, I: exports2.FinalizeMigratedArtifactRequest, O: exports2.FinalizeMigratedArtifactResponse } - ]); - } -}); - -// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js -var require_artifact_twirp_client = __commonJS({ - "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArtifactServiceClientProtobuf = exports2.ArtifactServiceClientJSON = void 0; - var artifact_1 = require_artifact(); - var ArtifactServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateArtifact.bind(this); - this.FinalizeArtifact.bind(this); - this.ListArtifacts.bind(this); - this.GetSignedArtifactURL.bind(this); - this.DeleteArtifact.bind(this); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - CreateArtifact(request) { - const data = artifact_1.CreateArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/json", data); - return promise.then((data2) => artifact_1.CreateArtifactResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - FinalizeArtifact(request) { - const data = artifact_1.FinalizeArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/json", data); - return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - ListArtifacts(request) { - const data = artifact_1.ListArtifactsRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/json", data); - return promise.then((data2) => artifact_1.ListArtifactsResponse.fromJson(data2, { ignoreUnknownFields: true })); - } - GetSignedArtifactURL(request) { - const data = artifact_1.GetSignedArtifactURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + let socket; + req.on("socket", (sock) => { + socket = sock; }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/json", data); - return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); - } - DeleteArtifact(request) { - const data = artifact_1.DeleteArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/json", data); - return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromJson(data2, { - ignoreUnknownFields: true - })); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } - }; - exports2.ArtifactServiceClientJSON = ArtifactServiceClientJSON; - var ArtifactServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateArtifact.bind(this); - this.FinalizeArtifact.bind(this); - this.ListArtifacts.bind(this); - this.GetSignedArtifactURL.bind(this); - this.DeleteArtifact.bind(this); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - CreateArtifact(request) { - const data = artifact_1.CreateArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/protobuf", data); - return promise.then((data2) => artifact_1.CreateArtifactResponse.fromBinary(data2)); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - FinalizeArtifact(request) { - const data = artifact_1.FinalizeArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/protobuf", data); - return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromBinary(data2)); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; } - ListArtifacts(request) { - const data = artifact_1.ListArtifactsRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/protobuf", data); - return promise.then((data2) => artifact_1.ListArtifactsResponse.fromBinary(data2)); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - GetSignedArtifactURL(request) { - const data = artifact_1.GetSignedArtifactURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/protobuf", data); - return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromBinary(data2)); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - DeleteArtifact(request) { - const data = artifact_1.DeleteArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/protobuf", data); - return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromBinary(data2)); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - }; - exports2.ArtifactServiceClientProtobuf = ArtifactServiceClientProtobuf; - } -}); - -// node_modules/@actions/artifact/lib/generated/index.js -var require_generated = __commonJS({ - "node_modules/@actions/artifact/lib/generated/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); + } + })); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar4(require_timestamp(), exports2); - __exportStar4(require_wrappers(), exports2); - __exportStar4(require_artifact(), exports2); - __exportStar4(require_artifact_twirp_client(), exports2); + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/artifact/lib/internal/upload/retention.js -var require_retention = __commonJS({ - "node_modules/@actions/artifact/lib/internal/upload/retention.js"(exports2) { +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/auth.js +var require_auth3 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - __setModuleDefault4(result, mod); - return result; - }; - })(); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getExpiration = getExpiration; - var generated_1 = require_generated(); - var core18 = __importStar4(require_core()); - function getExpiration(retentionDays) { - if (!retentionDays) { - return void 0; + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - const maxRetentionDays = getRetentionDays(); - if (maxRetentionDays && maxRetentionDays < retentionDays) { - core18.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); - retentionDays = maxRetentionDays; + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; } - const expirationDate = /* @__PURE__ */ new Date(); - expirationDate.setDate(expirationDate.getDate() + retentionDays); - return generated_1.Timestamp.fromDate(expirationDate); - } - function getRetentionDays() { - const retentionDays = process.env["GITHUB_RETENTION_DAYS"]; - if (!retentionDays) { - return void 0; + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - const days = parseInt(retentionDays); - if (isNaN(days)) { - return void 0; + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - return days; - } - } -}); - -// node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js -var require_path_and_artifact_name_validation = __commonJS({ - "node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.validateArtifactName = validateArtifactName; - exports2.validateFilePath = validateFilePath; - var core_1 = require_core(); - var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ - ['"', ' Double quote "'], - [":", " Colon :"], - ["<", " Less than <"], - [">", " Greater than >"], - ["|", " Vertical bar |"], - ["*", " Asterisk *"], - ["?", " Question mark ?"], - ["\r", " Carriage return \\r"], - ["\n", " Line feed \\n"] - ]); - var invalidArtifactNameCharacters = new Map([ - ...invalidArtifactFilePathCharacters, - ["\\", " Backslash \\"], - ["/", " Forward slash /"] - ]); - function validateArtifactName(name) { - if (!name) { - throw new Error(`Provided artifact name input during validation is empty`); + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { - if (name.includes(invalidCharacterKey)) { - throw new Error(`The artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} - -These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } + options.headers["Authorization"] = `Bearer ${this.token}`; } - (0, core_1.info)(`Artifact name is valid!`); - } - function validateFilePath(path15) { - if (!path15) { - throw new Error(`Provided file path input during validation is empty`); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path15.includes(invalidCharacterKey)) { - throw new Error(`The path for one of the files in artifact is not valid: ${path15}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} - -The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. - `); + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; } - } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); @@ -78614,8 +82389,8 @@ var require_artifact_twirp_client2 = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.internalArtifactTwirpClient = internalArtifactTwirpClient; - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib7(); + var auth_1 = require_auth3(); var core_1 = require_core(); var generated_1 = require_generated(); var config_1 = require_config2(); @@ -100635,7 +104410,7 @@ var require_deflate_crc32_stream = __commonJS({ }); // node_modules/crc32-stream/lib/index.js -var require_lib3 = __commonJS({ +var require_lib8 = __commonJS({ "node_modules/crc32-stream/lib/index.js"(exports2, module2) { "use strict"; module2.exports = { @@ -100650,8 +104425,8 @@ var require_zip_archive_output_stream = __commonJS({ "node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js"(exports2, module2) { var inherits = require("util").inherits; var crc32 = require_crc32(); - var { CRC32Stream } = require_lib3(); - var { DeflateCRC32Stream } = require_lib3(); + var { CRC32Stream } = require_lib8(); + var { DeflateCRC32Stream } = require_lib8(); var ArchiveOutputStream = require_archive_output_stream(); var ZipArchiveEntry = require_zip_archive_entry(); var GeneralPurposeBit = require_general_purpose_bit(); @@ -105380,580 +109155,1578 @@ var require_unzip_stream = __commonJS({ return chunk.length; } }; - UnzipStream.prototype._prepareOutStream = function(vars, entry) { + UnzipStream.prototype._prepareOutStream = function(vars, entry) { + var self2 = this; + var isDirectory = vars.uncompressedSize === 0 && /[\/\\]$/.test(entry.path); + entry.path = entry.path.replace(/(?<=^|[/\\]+)[.][.]+(?=[/\\]+|$)/g, "."); + entry.type = isDirectory ? "Directory" : "File"; + entry.isDirectory = isDirectory; + var fileSizeKnown = !(vars.flags & 8); + if (fileSizeKnown) { + entry.size = vars.uncompressedSize; + } + var isVersionSupported = vars.versionsNeededToExtract <= 45; + this.outStreamInfo = { + stream: null, + limit: fileSizeKnown ? vars.compressedSize : -1, + written: 0 + }; + if (!fileSizeKnown) { + var pattern = new Buffer(4); + pattern.writeUInt32LE(SIG_DATA_DESCRIPTOR, 0); + var zip64Mode = vars.extra.zip64Mode; + var extraSize = zip64Mode ? 20 : 12; + var searchPattern = { + pattern, + requiredExtraSize: extraSize + }; + var matcherStream = new MatcherStream(searchPattern, function(matchedChunk, sizeSoFar) { + var vars2 = self2._readDataDescriptor(matchedChunk, zip64Mode); + var compressedSizeMatches = vars2.compressedSize === sizeSoFar; + if (!zip64Mode && !compressedSizeMatches && sizeSoFar >= FOUR_GIGS) { + var overflown = sizeSoFar - FOUR_GIGS; + while (overflown >= 0) { + compressedSizeMatches = vars2.compressedSize === overflown; + if (compressedSizeMatches) break; + overflown -= FOUR_GIGS; + } + } + if (!compressedSizeMatches) { + return; + } + self2.state = states.FILE_DATA_END; + var sliceOffset = zip64Mode ? 24 : 16; + if (self2.data.length > 0) { + self2.data = Buffer.concat([matchedChunk.slice(sliceOffset), self2.data]); + } else { + self2.data = matchedChunk.slice(sliceOffset); + } + return true; + }); + this.outStreamInfo.stream = matcherStream; + } else { + this.outStreamInfo.stream = new stream2.PassThrough(); + } + var isEncrypted = vars.flags & 1 || vars.flags & 64; + if (isEncrypted || !isVersionSupported) { + var message = isEncrypted ? "Encrypted files are not supported!" : "Zip version " + Math.floor(vars.versionsNeededToExtract / 10) + "." + vars.versionsNeededToExtract % 10 + " is not supported"; + entry.skip = true; + setImmediate(() => { + self2.emit("error", new Error(message)); + }); + this.outStreamInfo.stream.pipe(new Entry().autodrain()); + return; + } + var isCompressed = vars.compressionMethod > 0; + if (isCompressed) { + var inflater = zlib3.createInflateRaw(); + inflater.on("error", function(err) { + self2.state = states.ERROR; + self2.emit("error", err); + }); + this.outStreamInfo.stream.pipe(inflater).pipe(entry); + } else { + this.outStreamInfo.stream.pipe(entry); + } + if (this._drainAllEntries) { + entry.autodrain(); + } + }; + UnzipStream.prototype._readFile = function(data) { + var vars = binary2.parse(data).word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars; + return vars; + }; + UnzipStream.prototype._readExtraFields = function(data) { + var extra = {}; + var result = { parsed: extra }; + if (this.options.debug) { + result.debug = []; + } + var index = 0; + while (index < data.length) { + var vars = binary2.parse(data).skip(index).word16lu("extraId").word16lu("extraSize").vars; + index += 4; + var fieldType = void 0; + switch (vars.extraId) { + case 1: + fieldType = "Zip64 extended information extra field"; + var z64vars = binary2.parse(data.slice(index, index + vars.extraSize)).word64lu("uncompressedSize").word64lu("compressedSize").word64lu("offsetToLocalHeader").word32lu("diskStartNumber").vars; + if (z64vars.uncompressedSize !== null) { + extra.uncompressedSize = z64vars.uncompressedSize; + } + if (z64vars.compressedSize !== null) { + extra.compressedSize = z64vars.compressedSize; + } + extra.zip64Mode = true; + break; + case 10: + fieldType = "NTFS extra field"; + break; + case 21589: + fieldType = "extended timestamp"; + var timestampFields = data.readUInt8(index); + var offset = 1; + if (vars.extraSize >= offset + 4 && timestampFields & 1) { + extra.mtime = new Date(data.readUInt32LE(index + offset) * 1e3); + offset += 4; + } + if (vars.extraSize >= offset + 4 && timestampFields & 2) { + extra.atime = new Date(data.readUInt32LE(index + offset) * 1e3); + offset += 4; + } + if (vars.extraSize >= offset + 4 && timestampFields & 4) { + extra.ctime = new Date(data.readUInt32LE(index + offset) * 1e3); + } + break; + case 28789: + fieldType = "Info-ZIP Unicode Path Extra Field"; + var fieldVer = data.readUInt8(index); + if (fieldVer === 1) { + var offset = 1; + var nameCrc32 = data.readUInt32LE(index + offset); + offset += 4; + var pathBuffer = data.slice(index + offset); + extra.path = pathBuffer.toString(); + } + break; + case 13: + case 22613: + fieldType = vars.extraId === 13 ? "PKWARE Unix" : "Info-ZIP UNIX (type 1)"; + var offset = 0; + if (vars.extraSize >= 8) { + var atime = new Date(data.readUInt32LE(index + offset) * 1e3); + offset += 4; + var mtime = new Date(data.readUInt32LE(index + offset) * 1e3); + offset += 4; + extra.atime = atime; + extra.mtime = mtime; + if (vars.extraSize >= 12) { + var uid = data.readUInt16LE(index + offset); + offset += 2; + var gid = data.readUInt16LE(index + offset); + offset += 2; + extra.uid = uid; + extra.gid = gid; + } + } + break; + case 30805: + fieldType = "Info-ZIP UNIX (type 2)"; + var offset = 0; + if (vars.extraSize >= 4) { + var uid = data.readUInt16LE(index + offset); + offset += 2; + var gid = data.readUInt16LE(index + offset); + offset += 2; + extra.uid = uid; + extra.gid = gid; + } + break; + case 30837: + fieldType = "Info-ZIP New Unix"; + var offset = 0; + var extraVer = data.readUInt8(index); + offset += 1; + if (extraVer === 1) { + var uidSize = data.readUInt8(index + offset); + offset += 1; + if (uidSize <= 6) { + extra.uid = data.readUIntLE(index + offset, uidSize); + } + offset += uidSize; + var gidSize = data.readUInt8(index + offset); + offset += 1; + if (gidSize <= 6) { + extra.gid = data.readUIntLE(index + offset, gidSize); + } + } + break; + case 30062: + fieldType = "ASi Unix"; + var offset = 0; + if (vars.extraSize >= 14) { + var crc = data.readUInt32LE(index + offset); + offset += 4; + var mode = data.readUInt16LE(index + offset); + offset += 2; + var sizdev = data.readUInt32LE(index + offset); + offset += 4; + var uid = data.readUInt16LE(index + offset); + offset += 2; + var gid = data.readUInt16LE(index + offset); + offset += 2; + extra.mode = mode; + extra.uid = uid; + extra.gid = gid; + if (vars.extraSize > 14) { + var start = index + offset; + var end = index + vars.extraSize - 14; + var symlinkName = this._decodeString(data.slice(start, end)); + extra.symlink = symlinkName; + } + } + break; + } + if (this.options.debug) { + result.debug.push({ + extraId: "0x" + vars.extraId.toString(16), + description: fieldType, + data: data.slice(index, index + vars.extraSize).inspect() + }); + } + index += vars.extraSize; + } + return result; + }; + UnzipStream.prototype._readDataDescriptor = function(data, zip64Mode) { + if (zip64Mode) { + var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word64lu("compressedSize").word64lu("uncompressedSize").vars; + return vars; + } + var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").vars; + return vars; + }; + UnzipStream.prototype._readCentralDirectoryEntry = function(data) { + var vars = binary2.parse(data).word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars; + return vars; + }; + UnzipStream.prototype._readEndOfCentralDirectory64 = function(data) { + var vars = binary2.parse(data).word64lu("centralDirectoryRecordSize").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskNumberWithCentralDirectoryStart").word64lu("centralDirectoryEntries").word64lu("totalCentralDirectoryEntries").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars; + return vars; + }; + UnzipStream.prototype._readEndOfCentralDirectory = function(data) { + var vars = binary2.parse(data).word16lu("diskNumber").word16lu("diskStart").word16lu("centralDirectoryEntries").word16lu("totalCentralDirectoryEntries").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars; + return vars; + }; + var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 "; + UnzipStream.prototype._decodeString = function(buffer, isUtf8) { + if (isUtf8) { + return buffer.toString("utf8"); + } + if (this.options.decodeString) { + return this.options.decodeString(buffer); + } + let result = ""; + for (var i = 0; i < buffer.length; i++) { + result += cp437[buffer[i]]; + } + return result; + }; + UnzipStream.prototype._parseOrOutput = function(encoding, cb) { + var consume; + while ((consume = this.processDataChunk(this.data)) > 0) { + this.data = this.data.slice(consume); + if (this.data.length === 0) break; + } + if (this.state === states.FILE_DATA) { + if (this.outStreamInfo.limit >= 0) { + var remaining = this.outStreamInfo.limit - this.outStreamInfo.written; + var packet; + if (remaining < this.data.length) { + packet = this.data.slice(0, remaining); + this.data = this.data.slice(remaining); + } else { + packet = this.data; + this.data = new Buffer(""); + } + this.outStreamInfo.written += packet.length; + if (this.outStreamInfo.limit === this.outStreamInfo.written) { + this.state = states.START; + this.outStreamInfo.stream.end(packet, encoding, cb); + } else { + this.outStreamInfo.stream.write(packet, encoding, cb); + } + } else { + var packet = this.data; + this.data = new Buffer(""); + this.outStreamInfo.written += packet.length; + var outputStream = this.outStreamInfo.stream; + outputStream.write(packet, encoding, () => { + if (this.state === states.FILE_DATA_END) { + this.state = states.START; + return outputStream.end(cb); + } + cb(); + }); + } + return; + } + cb(); + }; + UnzipStream.prototype.drainAll = function() { + this._drainAllEntries = true; + }; + UnzipStream.prototype._transform = function(chunk, encoding, cb) { + var self2 = this; + if (self2.data.length > 0) { + self2.data = Buffer.concat([self2.data, chunk]); + } else { + self2.data = chunk; + } + var startDataLength = self2.data.length; + var done = function() { + if (self2.data.length > 0 && self2.data.length < startDataLength) { + startDataLength = self2.data.length; + self2._parseOrOutput(encoding, done); + return; + } + cb(); + }; + self2._parseOrOutput(encoding, done); + }; + UnzipStream.prototype._flush = function(cb) { + var self2 = this; + if (self2.data.length > 0) { + self2._parseOrOutput("buffer", function() { + if (self2.data.length > 0) return setImmediate(function() { + self2._flush(cb); + }); + cb(); + }); + return; + } + if (self2.state === states.FILE_DATA) { + return cb(new Error("Stream finished in an invalid state, uncompression failed")); + } + setImmediate(cb); + }; + module2.exports = UnzipStream; + } +}); + +// node_modules/unzip-stream/lib/parser-stream.js +var require_parser_stream = __commonJS({ + "node_modules/unzip-stream/lib/parser-stream.js"(exports2, module2) { + var Transform = require("stream").Transform; + var util = require("util"); + var UnzipStream = require_unzip_stream(); + function ParserStream(opts) { + if (!(this instanceof ParserStream)) { + return new ParserStream(opts); + } + var transformOpts = opts || {}; + Transform.call(this, { readableObjectMode: true }); + this.opts = opts || {}; + this.unzipStream = new UnzipStream(this.opts); + var self2 = this; + this.unzipStream.on("entry", function(entry) { + self2.push(entry); + }); + this.unzipStream.on("error", function(error4) { + self2.emit("error", error4); + }); + } + util.inherits(ParserStream, Transform); + ParserStream.prototype._transform = function(chunk, encoding, cb) { + this.unzipStream.write(chunk, encoding, cb); + }; + ParserStream.prototype._flush = function(cb) { + var self2 = this; + this.unzipStream.end(function() { + process.nextTick(function() { + self2.emit("close"); + }); + cb(); + }); + }; + ParserStream.prototype.on = function(eventName, fn) { + if (eventName === "entry") { + return Transform.prototype.on.call(this, "data", fn); + } + return Transform.prototype.on.call(this, eventName, fn); + }; + ParserStream.prototype.drainAll = function() { + this.unzipStream.drainAll(); + return this.pipe(new Transform({ objectMode: true, transform: function(d, e, cb) { + cb(); + } })); + }; + module2.exports = ParserStream; + } +}); + +// node_modules/mkdirp/index.js +var require_mkdirp = __commonJS({ + "node_modules/mkdirp/index.js"(exports2, module2) { + var path15 = require("path"); + var fs17 = require("fs"); + var _0777 = parseInt("0777", 8); + module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + function mkdirP(p, opts, f, made) { + if (typeof opts === "function") { + f = opts; + opts = {}; + } else if (!opts || typeof opts !== "object") { + opts = { mode: opts }; + } + var mode = opts.mode; + var xfs = opts.fs || fs17; + if (mode === void 0) { + mode = _0777; + } + if (!made) made = null; + var cb = f || /* istanbul ignore next */ + function() { + }; + p = path15.resolve(p); + xfs.mkdir(p, mode, function(er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case "ENOENT": + if (path15.dirname(p) === p) return cb(er); + mkdirP(path15.dirname(p), opts, function(er2, made2) { + if (er2) cb(er2, made2); + else mkdirP(p, opts, cb, made2); + }); + break; + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function(er2, stat) { + if (er2 || !stat.isDirectory()) cb(er, made); + else cb(null, made); + }); + break; + } + }); + } + mkdirP.sync = function sync(p, opts, made) { + if (!opts || typeof opts !== "object") { + opts = { mode: opts }; + } + var mode = opts.mode; + var xfs = opts.fs || fs17; + if (mode === void 0) { + mode = _0777; + } + if (!made) made = null; + p = path15.resolve(p); + try { + xfs.mkdirSync(p, mode); + made = made || p; + } catch (err0) { + switch (err0.code) { + case "ENOENT": + made = sync(path15.dirname(p), opts, made); + sync(p, opts, made); + break; + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + return made; + }; + } +}); + +// node_modules/unzip-stream/lib/extract.js +var require_extract2 = __commonJS({ + "node_modules/unzip-stream/lib/extract.js"(exports2, module2) { + var fs17 = require("fs"); + var path15 = require("path"); + var util = require("util"); + var mkdirp = require_mkdirp(); + var Transform = require("stream").Transform; + var UnzipStream = require_unzip_stream(); + function Extract(opts) { + if (!(this instanceof Extract)) + return new Extract(opts); + Transform.call(this); + this.opts = opts || {}; + this.unzipStream = new UnzipStream(this.opts); + this.unfinishedEntries = 0; + this.afterFlushWait = false; + this.createdDirectories = {}; var self2 = this; - var isDirectory = vars.uncompressedSize === 0 && /[\/\\]$/.test(entry.path); - entry.path = entry.path.replace(/(?<=^|[/\\]+)[.][.]+(?=[/\\]+|$)/g, "."); - entry.type = isDirectory ? "Directory" : "File"; - entry.isDirectory = isDirectory; - var fileSizeKnown = !(vars.flags & 8); - if (fileSizeKnown) { - entry.size = vars.uncompressedSize; - } - var isVersionSupported = vars.versionsNeededToExtract <= 45; - this.outStreamInfo = { - stream: null, - limit: fileSizeKnown ? vars.compressedSize : -1, - written: 0 + this.unzipStream.on("entry", this._processEntry.bind(this)); + this.unzipStream.on("error", function(error4) { + self2.emit("error", error4); + }); + } + util.inherits(Extract, Transform); + Extract.prototype._transform = function(chunk, encoding, cb) { + this.unzipStream.write(chunk, encoding, cb); + }; + Extract.prototype._flush = function(cb) { + var self2 = this; + var allDone = function() { + process.nextTick(function() { + self2.emit("close"); + }); + cb(); }; - if (!fileSizeKnown) { - var pattern = new Buffer(4); - pattern.writeUInt32LE(SIG_DATA_DESCRIPTOR, 0); - var zip64Mode = vars.extra.zip64Mode; - var extraSize = zip64Mode ? 20 : 12; - var searchPattern = { - pattern, - requiredExtraSize: extraSize - }; - var matcherStream = new MatcherStream(searchPattern, function(matchedChunk, sizeSoFar) { - var vars2 = self2._readDataDescriptor(matchedChunk, zip64Mode); - var compressedSizeMatches = vars2.compressedSize === sizeSoFar; - if (!zip64Mode && !compressedSizeMatches && sizeSoFar >= FOUR_GIGS) { - var overflown = sizeSoFar - FOUR_GIGS; - while (overflown >= 0) { - compressedSizeMatches = vars2.compressedSize === overflown; - if (compressedSizeMatches) break; - overflown -= FOUR_GIGS; - } - } - if (!compressedSizeMatches) { - return; - } - self2.state = states.FILE_DATA_END; - var sliceOffset = zip64Mode ? 24 : 16; - if (self2.data.length > 0) { - self2.data = Buffer.concat([matchedChunk.slice(sliceOffset), self2.data]); - } else { - self2.data = matchedChunk.slice(sliceOffset); - } - return true; + this.unzipStream.end(function() { + if (self2.unfinishedEntries > 0) { + self2.afterFlushWait = true; + return self2.on("await-finished", allDone); + } + allDone(); + }); + }; + Extract.prototype._processEntry = function(entry) { + var self2 = this; + var destPath = path15.join(this.opts.path, entry.path); + var directory = entry.isDirectory ? destPath : path15.dirname(destPath); + this.unfinishedEntries++; + var writeFileFn = function() { + var pipedStream = fs17.createWriteStream(destPath); + pipedStream.on("close", function() { + self2.unfinishedEntries--; + self2._notifyAwaiter(); }); - this.outStreamInfo.stream = matcherStream; - } else { - this.outStreamInfo.stream = new stream2.PassThrough(); - } - var isEncrypted = vars.flags & 1 || vars.flags & 64; - if (isEncrypted || !isVersionSupported) { - var message = isEncrypted ? "Encrypted files are not supported!" : "Zip version " + Math.floor(vars.versionsNeededToExtract / 10) + "." + vars.versionsNeededToExtract % 10 + " is not supported"; - entry.skip = true; - setImmediate(() => { - self2.emit("error", new Error(message)); + pipedStream.on("error", function(error4) { + self2.emit("error", error4); }); - this.outStreamInfo.stream.pipe(new Entry().autodrain()); - return; + entry.pipe(pipedStream); + }; + if (this.createdDirectories[directory] || directory === ".") { + return writeFileFn(); } - var isCompressed = vars.compressionMethod > 0; - if (isCompressed) { - var inflater = zlib3.createInflateRaw(); - inflater.on("error", function(err) { - self2.state = states.ERROR; - self2.emit("error", err); - }); - this.outStreamInfo.stream.pipe(inflater).pipe(entry); - } else { - this.outStreamInfo.stream.pipe(entry); + mkdirp(directory, function(err) { + if (err) return self2.emit("error", err); + self2.createdDirectories[directory] = true; + if (entry.isDirectory) { + self2.unfinishedEntries--; + self2._notifyAwaiter(); + return; + } + writeFileFn(); + }); + }; + Extract.prototype._notifyAwaiter = function() { + if (this.afterFlushWait && this.unfinishedEntries === 0) { + this.emit("await-finished"); + this.afterFlushWait = false; } - if (this._drainAllEntries) { - entry.autodrain(); + }; + module2.exports = Extract; + } +}); + +// node_modules/unzip-stream/unzip.js +var require_unzip = __commonJS({ + "node_modules/unzip-stream/unzip.js"(exports2) { + "use strict"; + exports2.Parse = require_parser_stream(); + exports2.Extract = require_extract2(); + } +}); + +// node_modules/@actions/artifact/lib/internal/download/download-artifact.js +var require_download_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/internal/download/download-artifact.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - UnzipStream.prototype._readFile = function(data) { - var vars = binary2.parse(data).word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars; - return vars; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; }; - UnzipStream.prototype._readExtraFields = function(data) { - var extra = {}; - var result = { parsed: extra }; - if (this.options.debug) { - result.debug = []; - } - var index = 0; - while (index < data.length) { - var vars = binary2.parse(data).skip(index).word16lu("extraId").word16lu("extraSize").vars; - index += 4; - var fieldType = void 0; - switch (vars.extraId) { - case 1: - fieldType = "Zip64 extended information extra field"; - var z64vars = binary2.parse(data.slice(index, index + vars.extraSize)).word64lu("uncompressedSize").word64lu("compressedSize").word64lu("offsetToLocalHeader").word32lu("diskStartNumber").vars; - if (z64vars.uncompressedSize !== null) { - extra.uncompressedSize = z64vars.uncompressedSize; - } - if (z64vars.compressedSize !== null) { - extra.compressedSize = z64vars.compressedSize; - } - extra.zip64Mode = true; - break; - case 10: - fieldType = "NTFS extra field"; - break; - case 21589: - fieldType = "extended timestamp"; - var timestampFields = data.readUInt8(index); - var offset = 1; - if (vars.extraSize >= offset + 4 && timestampFields & 1) { - extra.mtime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - } - if (vars.extraSize >= offset + 4 && timestampFields & 2) { - extra.atime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - } - if (vars.extraSize >= offset + 4 && timestampFields & 4) { - extra.ctime = new Date(data.readUInt32LE(index + offset) * 1e3); - } - break; - case 28789: - fieldType = "Info-ZIP Unicode Path Extra Field"; - var fieldVer = data.readUInt8(index); - if (fieldVer === 1) { - var offset = 1; - var nameCrc32 = data.readUInt32LE(index + offset); - offset += 4; - var pathBuffer = data.slice(index + offset); - extra.path = pathBuffer.toString(); - } - break; - case 13: - case 22613: - fieldType = vars.extraId === 13 ? "PKWARE Unix" : "Info-ZIP UNIX (type 1)"; - var offset = 0; - if (vars.extraSize >= 8) { - var atime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - var mtime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - extra.atime = atime; - extra.mtime = mtime; - if (vars.extraSize >= 12) { - var uid = data.readUInt16LE(index + offset); - offset += 2; - var gid = data.readUInt16LE(index + offset); - offset += 2; - extra.uid = uid; - extra.gid = gid; - } - } - break; - case 30805: - fieldType = "Info-ZIP UNIX (type 2)"; - var offset = 0; - if (vars.extraSize >= 4) { - var uid = data.readUInt16LE(index + offset); - offset += 2; - var gid = data.readUInt16LE(index + offset); - offset += 2; - extra.uid = uid; - extra.gid = gid; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.streamExtractExternal = streamExtractExternal; + exports2.downloadArtifactPublic = downloadArtifactPublic; + exports2.downloadArtifactInternal = downloadArtifactInternal; + var promises_1 = __importDefault4(require("fs/promises")); + var crypto = __importStar4(require("crypto")); + var stream2 = __importStar4(require("stream")); + var github3 = __importStar4(require_github()); + var core18 = __importStar4(require_core()); + var httpClient = __importStar4(require_lib7()); + var unzip_stream_1 = __importDefault4(require_unzip()); + var user_agent_1 = require_user_agent2(); + var config_1 = require_config2(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var generated_1 = require_generated(); + var util_1 = require_util11(); + var errors_1 = require_errors3(); + var scrubQueryParameters = (url2) => { + const parsed = new URL(url2); + parsed.search = ""; + return parsed.toString(); + }; + function exists(path15) { + return __awaiter4(this, void 0, void 0, function* () { + try { + yield promises_1.default.access(path15); + return true; + } catch (error4) { + if (error4.code === "ENOENT") { + return false; + } else { + throw error4; + } + } + }); + } + function streamExtract(url2, directory) { + return __awaiter4(this, void 0, void 0, function* () { + let retryCount = 0; + while (retryCount < 5) { + try { + return yield streamExtractExternal(url2, directory); + } catch (error4) { + retryCount++; + core18.debug(`Failed to download artifact after ${retryCount} retries due to ${error4.message}. Retrying in 5 seconds...`); + yield new Promise((resolve8) => setTimeout(resolve8, 5e3)); + } + } + throw new Error(`Artifact download failed after ${retryCount} retries.`); + }); + } + function streamExtractExternal(url_1, directory_1) { + return __awaiter4(this, arguments, void 0, function* (url2, directory, opts = { timeout: 30 * 1e3 }) { + const client = new httpClient.HttpClient((0, user_agent_1.getUserAgentString)()); + const response = yield client.get(url2); + if (response.message.statusCode !== 200) { + throw new Error(`Unexpected HTTP response from blob storage: ${response.message.statusCode} ${response.message.statusMessage}`); + } + let sha256Digest = void 0; + return new Promise((resolve8, reject) => { + const timerFn = () => { + const timeoutError = new Error(`Blob storage chunk did not respond in ${opts.timeout}ms`); + response.message.destroy(timeoutError); + reject(timeoutError); + }; + const timer = setTimeout(timerFn, opts.timeout); + const hashStream = crypto.createHash("sha256").setEncoding("hex"); + const passThrough = new stream2.PassThrough(); + response.message.pipe(passThrough); + passThrough.pipe(hashStream); + const extractStream = passThrough; + extractStream.on("data", () => { + timer.refresh(); + }).on("error", (error4) => { + core18.debug(`response.message: Artifact download failed: ${error4.message}`); + clearTimeout(timer); + reject(error4); + }).pipe(unzip_stream_1.default.Extract({ path: directory })).on("close", () => { + clearTimeout(timer); + if (hashStream) { + hashStream.end(); + sha256Digest = hashStream.read(); + core18.info(`SHA256 digest of downloaded artifact is ${sha256Digest}`); } - break; - case 30837: - fieldType = "Info-ZIP New Unix"; - var offset = 0; - var extraVer = data.readUInt8(index); - offset += 1; - if (extraVer === 1) { - var uidSize = data.readUInt8(index + offset); - offset += 1; - if (uidSize <= 6) { - extra.uid = data.readUIntLE(index + offset, uidSize); - } - offset += uidSize; - var gidSize = data.readUInt8(index + offset); - offset += 1; - if (gidSize <= 6) { - extra.gid = data.readUIntLE(index + offset, gidSize); - } + resolve8({ sha256Digest: `sha256:${sha256Digest}` }); + }).on("error", (error4) => { + reject(error4); + }); + }); + }); + } + function downloadArtifactPublic(artifactId, repositoryOwner, repositoryName, token, options) { + return __awaiter4(this, void 0, void 0, function* () { + const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); + const api = github3.getOctokit(token); + let digestMismatch = false; + core18.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`); + const { headers, status } = yield api.rest.actions.downloadArtifact({ + owner: repositoryOwner, + repo: repositoryName, + artifact_id: artifactId, + archive_format: "zip", + request: { + redirect: "manual" + } + }); + if (status !== 302) { + throw new Error(`Unable to download artifact. Unexpected status: ${status}`); + } + const { location } = headers; + if (!location) { + throw new Error(`Unable to redirect to artifact download url`); + } + core18.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`); + try { + core18.info(`Starting download of artifact to: ${downloadPath}`); + const extractResponse = yield streamExtract(location, downloadPath); + core18.info(`Artifact download completed successfully.`); + if (options === null || options === void 0 ? void 0 : options.expectedHash) { + if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { + digestMismatch = true; + core18.debug(`Computed digest: ${extractResponse.sha256Digest}`); + core18.debug(`Expected digest: ${options.expectedHash}`); } - break; - case 30062: - fieldType = "ASi Unix"; - var offset = 0; - if (vars.extraSize >= 14) { - var crc = data.readUInt32LE(index + offset); - offset += 4; - var mode = data.readUInt16LE(index + offset); - offset += 2; - var sizdev = data.readUInt32LE(index + offset); - offset += 4; - var uid = data.readUInt16LE(index + offset); - offset += 2; - var gid = data.readUInt16LE(index + offset); - offset += 2; - extra.mode = mode; - extra.uid = uid; - extra.gid = gid; - if (vars.extraSize > 14) { - var start = index + offset; - var end = index + vars.extraSize - 14; - var symlinkName = this._decodeString(data.slice(start, end)); - extra.symlink = symlinkName; - } + } + } catch (error4) { + throw new Error(`Unable to download and extract artifact: ${error4.message}`); + } + return { downloadPath, digestMismatch }; + }); + } + function downloadArtifactInternal(artifactId, options) { + return __awaiter4(this, void 0, void 0, function* () { + const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + let digestMismatch = false; + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const listReq = { + workflowRunBackendId, + workflowJobRunBackendId, + idFilter: generated_1.Int64Value.create({ value: artifactId.toString() }) + }; + const { artifacts } = yield artifactClient.ListArtifacts(listReq); + if (artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`No artifacts found for ID: ${artifactId} +Are you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`); + } + if (artifacts.length > 1) { + core18.warning("Multiple artifacts found, defaulting to first."); + } + const signedReq = { + workflowRunBackendId: artifacts[0].workflowRunBackendId, + workflowJobRunBackendId: artifacts[0].workflowJobRunBackendId, + name: artifacts[0].name + }; + const { signedUrl } = yield artifactClient.GetSignedArtifactURL(signedReq); + core18.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`); + try { + core18.info(`Starting download of artifact to: ${downloadPath}`); + const extractResponse = yield streamExtract(signedUrl, downloadPath); + core18.info(`Artifact download completed successfully.`); + if (options === null || options === void 0 ? void 0 : options.expectedHash) { + if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { + digestMismatch = true; + core18.debug(`Computed digest: ${extractResponse.sha256Digest}`); + core18.debug(`Expected digest: ${options.expectedHash}`); } - break; + } + } catch (error4) { + throw new Error(`Unable to download and extract artifact: ${error4.message}`); } - if (this.options.debug) { - result.debug.push({ - extraId: "0x" + vars.extraId.toString(16), - description: fieldType, - data: data.slice(index, index + vars.extraSize).inspect() - }); + return { downloadPath, digestMismatch }; + }); + } + function resolveOrCreateDirectory() { + return __awaiter4(this, arguments, void 0, function* (downloadPath = (0, config_1.getGitHubWorkspaceDir)()) { + if (!(yield exists(downloadPath))) { + core18.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`); + yield promises_1.default.mkdir(downloadPath, { recursive: true }); + } else { + core18.debug(`Artifact destination folder already exists: ${downloadPath}`); } - index += vars.extraSize; + return downloadPath; + }); + } + } +}); + +// node_modules/@actions/artifact/lib/internal/find/retry-options.js +var require_retry_options = __commonJS({ + "node_modules/@actions/artifact/lib/internal/find/retry-options.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - return result; - }; - UnzipStream.prototype._readDataDescriptor = function(data, zip64Mode) { - if (zip64Mode) { - var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word64lu("compressedSize").word64lu("uncompressedSize").vars; - return vars; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRetryOptions = getRetryOptions; + var core18 = __importStar4(require_core()); + var defaultMaxRetryNumber = 5; + var defaultExemptStatusCodes = [400, 401, 403, 404, 422]; + function getRetryOptions(defaultOptions, retries = defaultMaxRetryNumber, exemptStatusCodes = defaultExemptStatusCodes) { + var _a; + if (retries <= 0) { + return [{ enabled: false }, defaultOptions.request]; } - var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").vars; - return vars; - }; - UnzipStream.prototype._readCentralDirectoryEntry = function(data) { - var vars = binary2.parse(data).word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars; - return vars; - }; - UnzipStream.prototype._readEndOfCentralDirectory64 = function(data) { - var vars = binary2.parse(data).word64lu("centralDirectoryRecordSize").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskNumberWithCentralDirectoryStart").word64lu("centralDirectoryEntries").word64lu("totalCentralDirectoryEntries").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars; - return vars; - }; - UnzipStream.prototype._readEndOfCentralDirectory = function(data) { - var vars = binary2.parse(data).word16lu("diskNumber").word16lu("diskStart").word16lu("centralDirectoryEntries").word16lu("totalCentralDirectoryEntries").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars; - return vars; - }; - var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 "; - UnzipStream.prototype._decodeString = function(buffer, isUtf8) { - if (isUtf8) { - return buffer.toString("utf8"); + const retryOptions = { + enabled: true + }; + if (exemptStatusCodes.length > 0) { + retryOptions.doNotRetry = exemptStatusCodes; } - if (this.options.decodeString) { - return this.options.decodeString(buffer); + const requestOptions = Object.assign(Object.assign({}, defaultOptions.request), { retries }); + core18.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a = retryOptions.doNotRetry) !== null && _a !== void 0 ? _a : "octokit default: [400, 401, 403, 404, 422]"})`); + return [retryOptions, requestOptions]; + } + } +}); + +// node_modules/@octokit/plugin-request-log/dist-node/index.js +var require_dist_node16 = __commonJS({ + "node_modules/@octokit/plugin-request-log/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var VERSION = "1.0.4"; + function requestLog(octokit) { + octokit.hook.wrap("request", (request, options) => { + octokit.log.debug("request", options); + const start = Date.now(); + const requestOptions = octokit.request.endpoint.parse(options); + const path15 = requestOptions.url.replace(options.baseUrl, ""); + return request(options).then((response) => { + octokit.log.info(`${requestOptions.method} ${path15} - ${response.status} in ${Date.now() - start}ms`); + return response; + }).catch((error4) => { + octokit.log.info(`${requestOptions.method} ${path15} - ${error4.status} in ${Date.now() - start}ms`); + throw error4; + }); + }); + } + requestLog.VERSION = VERSION; + exports2.requestLog = requestLog; + } +}); + +// node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js +var require_dist_node17 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + function _interopDefault(ex) { + return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex; + } + var Bottleneck = _interopDefault(require_light()); + async function errorRequest(octokit, state, error4, options) { + if (!error4.request || !error4.request.request) { + throw error4; } - let result = ""; - for (var i = 0; i < buffer.length; i++) { - result += cp437[buffer[i]]; + if (error4.status >= 400 && !state.doNotRetry.includes(error4.status)) { + const retries = options.request.retries != null ? options.request.retries : state.retries; + const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); + throw octokit.retry.retryRequest(error4, retries, retryAfter); } - return result; - }; - UnzipStream.prototype._parseOrOutput = function(encoding, cb) { - var consume; - while ((consume = this.processDataChunk(this.data)) > 0) { - this.data = this.data.slice(consume); - if (this.data.length === 0) break; + throw error4; + } + async function wrapRequest(state, request, options) { + const limiter = new Bottleneck(); + limiter.on("failed", function(error4, info7) { + const maxRetries = ~~error4.request.request.retries; + const after = ~~error4.request.request.retryAfter; + options.request.retryCount = info7.retryCount + 1; + if (maxRetries > info7.retryCount) { + return after * state.retryAfterBaseValue; + } + }); + return limiter.schedule(request, options); + } + var VERSION = "3.0.9"; + function retry3(octokit, octokitOptions) { + const state = Object.assign({ + enabled: true, + retryAfterBaseValue: 1e3, + doNotRetry: [400, 401, 403, 404, 422], + retries: 3 + }, octokitOptions.retry); + if (state.enabled) { + octokit.hook.error("request", errorRequest.bind(null, octokit, state)); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); } - if (this.state === states.FILE_DATA) { - if (this.outStreamInfo.limit >= 0) { - var remaining = this.outStreamInfo.limit - this.outStreamInfo.written; - var packet; - if (remaining < this.data.length) { - packet = this.data.slice(0, remaining); - this.data = this.data.slice(remaining); - } else { - packet = this.data; - this.data = new Buffer(""); - } - this.outStreamInfo.written += packet.length; - if (this.outStreamInfo.limit === this.outStreamInfo.written) { - this.state = states.START; - this.outStreamInfo.stream.end(packet, encoding, cb); - } else { - this.outStreamInfo.stream.write(packet, encoding, cb); + return { + retry: { + retryRequest: (error4, retries, retryAfter) => { + error4.request.request = Object.assign({}, error4.request.request, { + retries, + retryAfter + }); + return error4; } - } else { - var packet = this.data; - this.data = new Buffer(""); - this.outStreamInfo.written += packet.length; - var outputStream = this.outStreamInfo.stream; - outputStream.write(packet, encoding, () => { - if (this.state === states.FILE_DATA_END) { - this.state = states.START; - return outputStream.end(cb); - } - cb(); - }); } - return; - } - cb(); - }; - UnzipStream.prototype.drainAll = function() { - this._drainAllEntries = true; - }; - UnzipStream.prototype._transform = function(chunk, encoding, cb) { - var self2 = this; - if (self2.data.length > 0) { - self2.data = Buffer.concat([self2.data, chunk]); - } else { - self2.data = chunk; + }; + } + retry3.VERSION = VERSION; + exports2.VERSION = VERSION; + exports2.retry = retry3; + } +}); + +// node_modules/@actions/artifact/lib/internal/find/get-artifact.js +var require_get_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/internal/find/get-artifact.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - var startDataLength = self2.data.length; - var done = function() { - if (self2.data.length > 0 && self2.data.length < startDataLength) { - startDataLength = self2.data.length; - self2._parseOrOutput(encoding, done); - return; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); } - cb(); + __setModuleDefault4(result, mod); + return result; }; - self2._parseOrOutput(encoding, done); - }; - UnzipStream.prototype._flush = function(cb) { - var self2 = this; - if (self2.data.length > 0) { - self2._parseOrOutput("buffer", function() { - if (self2.data.length > 0) return setImmediate(function() { - self2._flush(cb); - }); - cb(); + })(); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); }); - return; } - if (self2.state === states.FILE_DATA) { - return cb(new Error("Stream finished in an invalid state, uncompression failed")); - } - setImmediate(cb); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - module2.exports = UnzipStream; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getArtifactPublic = getArtifactPublic; + exports2.getArtifactInternal = getArtifactInternal; + var github_1 = require_github(); + var plugin_retry_1 = require_dist_node17(); + var core18 = __importStar4(require_core()); + var utils_1 = require_utils4(); + var retry_options_1 = require_retry_options(); + var plugin_request_log_1 = require_dist_node16(); + var util_1 = require_util11(); + var user_agent_1 = require_user_agent2(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var generated_1 = require_generated(); + var errors_1 = require_errors3(); + function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { + return __awaiter4(this, void 0, void 0, function* () { + var _a; + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: void 0, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: void 0, + retry: retryOpts, + request: requestOpts + }; + const github3 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + const getArtifactResp = yield github3.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}", { + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + name: artifactName + }); + if (getArtifactResp.status !== 200) { + throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); + } + if (getArtifactResp.data.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} + Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. + For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); + } + let artifact2 = getArtifactResp.data.artifacts[0]; + if (getArtifactResp.data.artifacts.length > 1) { + artifact2 = getArtifactResp.data.artifacts.sort((a, b) => b.id - a.id)[0]; + core18.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.id})`); + } + return { + artifact: { + name: artifact2.name, + id: artifact2.id, + size: artifact2.size_in_bytes, + createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, + digest: artifact2.digest + } + }; + }); + } + function getArtifactInternal(artifactName) { + return __awaiter4(this, void 0, void 0, function* () { + var _a; + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const req = { + workflowRunBackendId, + workflowJobRunBackendId, + nameFilter: generated_1.StringValue.create({ value: artifactName }) + }; + const res = yield artifactClient.ListArtifacts(req); + if (res.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} + Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. + For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); + } + let artifact2 = res.artifacts[0]; + if (res.artifacts.length > 1) { + artifact2 = res.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; + core18.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); + } + return { + artifact: { + name: artifact2.name, + id: Number(artifact2.databaseId), + size: Number(artifact2.size), + createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, + digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value + } + }; + }); + } } }); -// node_modules/unzip-stream/lib/parser-stream.js -var require_parser_stream = __commonJS({ - "node_modules/unzip-stream/lib/parser-stream.js"(exports2, module2) { - var Transform = require("stream").Transform; - var util = require("util"); - var UnzipStream = require_unzip_stream(); - function ParserStream(opts) { - if (!(this instanceof ParserStream)) { - return new ParserStream(opts); +// node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js +var require_delete_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - var transformOpts = opts || {}; - Transform.call(this, { readableObjectMode: true }); - this.opts = opts || {}; - this.unzipStream = new UnzipStream(this.opts); - var self2 = this; - this.unzipStream.on("entry", function(entry) { - self2.push(entry); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - this.unzipStream.on("error", function(error4) { - self2.emit("error", error4); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.deleteArtifactPublic = deleteArtifactPublic; + exports2.deleteArtifactInternal = deleteArtifactInternal; + var core_1 = require_core(); + var github_1 = require_github(); + var user_agent_1 = require_user_agent2(); + var retry_options_1 = require_retry_options(); + var utils_1 = require_utils4(); + var plugin_request_log_1 = require_dist_node16(); + var plugin_retry_1 = require_dist_node17(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var util_1 = require_util11(); + var generated_1 = require_generated(); + var get_artifact_1 = require_get_artifact(); + var errors_1 = require_errors3(); + function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { + return __awaiter4(this, void 0, void 0, function* () { + var _a; + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: void 0, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: void 0, + retry: retryOpts, + request: requestOpts + }; + const github3 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + const getArtifactResp = yield (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + const deleteArtifactResp = yield github3.rest.actions.deleteArtifact({ + owner: repositoryOwner, + repo: repositoryName, + artifact_id: getArtifactResp.artifact.id + }); + if (deleteArtifactResp.status !== 204) { + throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); + } + return { + id: getArtifactResp.artifact.id + }; }); } - util.inherits(ParserStream, Transform); - ParserStream.prototype._transform = function(chunk, encoding, cb) { - this.unzipStream.write(chunk, encoding, cb); - }; - ParserStream.prototype._flush = function(cb) { - var self2 = this; - this.unzipStream.end(function() { - process.nextTick(function() { - self2.emit("close"); - }); - cb(); + function deleteArtifactInternal(artifactName) { + return __awaiter4(this, void 0, void 0, function* () { + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const listReq = { + workflowRunBackendId, + workflowJobRunBackendId, + nameFilter: generated_1.StringValue.create({ value: artifactName }) + }; + const listRes = yield artifactClient.ListArtifacts(listReq); + if (listRes.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); + } + let artifact2 = listRes.artifacts[0]; + if (listRes.artifacts.length > 1) { + artifact2 = listRes.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; + (0, core_1.debug)(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); + } + const req = { + workflowRunBackendId: artifact2.workflowRunBackendId, + workflowJobRunBackendId: artifact2.workflowJobRunBackendId, + name: artifact2.name + }; + const res = yield artifactClient.DeleteArtifact(req); + (0, core_1.info)(`Artifact '${artifactName}' (ID: ${res.artifactId}) deleted`); + return { + id: Number(res.artifactId) + }; }); - }; - ParserStream.prototype.on = function(eventName, fn) { - if (eventName === "entry") { - return Transform.prototype.on.call(this, "data", fn); - } - return Transform.prototype.on.call(this, eventName, fn); - }; - ParserStream.prototype.drainAll = function() { - this.unzipStream.drainAll(); - return this.pipe(new Transform({ objectMode: true, transform: function(d, e, cb) { - cb(); - } })); - }; - module2.exports = ParserStream; + } } }); -// node_modules/mkdirp/index.js -var require_mkdirp = __commonJS({ - "node_modules/mkdirp/index.js"(exports2, module2) { - var path15 = require("path"); - var fs17 = require("fs"); - var _0777 = parseInt("0777", 8); - module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - function mkdirP(p, opts, f, made) { - if (typeof opts === "function") { - f = opts; - opts = {}; - } else if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - var mode = opts.mode; - var xfs = opts.fs || fs17; - if (mode === void 0) { - mode = _0777; +// node_modules/@actions/artifact/lib/internal/find/list-artifacts.js +var require_list_artifacts = __commonJS({ + "node_modules/@actions/artifact/lib/internal/find/list-artifacts.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - if (!made) made = null; - var cb = f || /* istanbul ignore next */ - function() { - }; - p = path15.resolve(p); - xfs.mkdir(p, mode, function(er) { - if (!er) { - made = made || p; - return cb(null, made); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - switch (er.code) { - case "ENOENT": - if (path15.dirname(p) === p) return cb(er); - mkdirP(path15.dirname(p), opts, function(er2, made2) { - if (er2) cb(er2, made2); - else mkdirP(p, opts, cb, made2); - }); - break; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function(er2, stat) { - if (er2 || !stat.isDirectory()) cb(er, made); - else cb(null, made); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.listArtifactsPublic = listArtifactsPublic; + exports2.listArtifactsInternal = listArtifactsInternal; + var core_1 = require_core(); + var github_1 = require_github(); + var user_agent_1 = require_user_agent2(); + var retry_options_1 = require_retry_options(); + var utils_1 = require_utils4(); + var plugin_request_log_1 = require_dist_node16(); + var plugin_retry_1 = require_dist_node17(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var util_1 = require_util11(); + var config_1 = require_config2(); + var generated_1 = require_generated(); + var maximumArtifactCount = (0, config_1.getMaxArtifactListCount)(); + var paginationCount = 100; + var maxNumberOfPages = Math.ceil(maximumArtifactCount / paginationCount); + function listArtifactsPublic(workflowRunId_1, repositoryOwner_1, repositoryName_1, token_1) { + return __awaiter4(this, arguments, void 0, function* (workflowRunId, repositoryOwner, repositoryName, token, latest = false) { + (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`); + let artifacts = []; + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: void 0, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: void 0, + retry: retryOpts, + request: requestOpts + }; + const github3 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + let currentPageNumber = 1; + const { data: listArtifactResponse } = yield github3.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + per_page: paginationCount, + page: currentPageNumber + }); + let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount); + const totalArtifactCount = listArtifactResponse.total_count; + if (totalArtifactCount > maximumArtifactCount) { + (0, core_1.warning)(`Workflow run ${workflowRunId} has ${totalArtifactCount} artifacts, exceeding the limit of ${maximumArtifactCount}. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`); + numberOfPages = maxNumberOfPages; + } + for (const artifact2 of listArtifactResponse.artifacts) { + artifacts.push({ + name: artifact2.name, + id: artifact2.id, + size: artifact2.size_in_bytes, + createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, + digest: artifact2.digest + }); + } + currentPageNumber++; + for (currentPageNumber; currentPageNumber <= numberOfPages; currentPageNumber++) { + (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`); + const { data: listArtifactResponse2 } = yield github3.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + per_page: paginationCount, + page: currentPageNumber + }); + for (const artifact2 of listArtifactResponse2.artifacts) { + artifacts.push({ + name: artifact2.name, + id: artifact2.id, + size: artifact2.size_in_bytes, + createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, + digest: artifact2.digest }); - break; + } } + if (latest) { + artifacts = filterLatest(artifacts); + } + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; }); } - mkdirP.sync = function sync(p, opts, made) { - if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - var mode = opts.mode; - var xfs = opts.fs || fs17; - if (mode === void 0) { - mode = _0777; - } - if (!made) made = null; - p = path15.resolve(p); - try { - xfs.mkdirSync(p, mode); - made = made || p; - } catch (err0) { - switch (err0.code) { - case "ENOENT": - made = sync(path15.dirname(p), opts, made); - sync(p, opts, made); - break; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; + function listArtifactsInternal() { + return __awaiter4(this, arguments, void 0, function* (latest = false) { + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const req = { + workflowRunBackendId, + workflowJobRunBackendId + }; + const res = yield artifactClient.ListArtifacts(req); + let artifacts = res.artifacts.map((artifact2) => { + var _a; + return { + name: artifact2.name, + id: Number(artifact2.databaseId), + size: Number(artifact2.size), + createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, + digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value + }; + }); + if (latest) { + artifacts = filterLatest(artifacts); + } + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; + }); + } + function filterLatest(artifacts) { + artifacts.sort((a, b) => b.id - a.id); + const latestArtifacts = []; + const seenArtifactNames = /* @__PURE__ */ new Set(); + for (const artifact2 of artifacts) { + if (!seenArtifactNames.has(artifact2.name)) { + latestArtifacts.push(artifact2); + seenArtifactNames.add(artifact2.name); } } - return made; - }; + return latestArtifacts; + } } }); -// node_modules/unzip-stream/lib/extract.js -var require_extract2 = __commonJS({ - "node_modules/unzip-stream/lib/extract.js"(exports2, module2) { - var fs17 = require("fs"); - var path15 = require("path"); - var util = require("util"); - var mkdirp = require_mkdirp(); - var Transform = require("stream").Transform; - var UnzipStream = require_unzip_stream(); - function Extract(opts) { - if (!(this instanceof Extract)) - return new Extract(opts); - Transform.call(this); - this.opts = opts || {}; - this.unzipStream = new UnzipStream(this.opts); - this.unfinishedEntries = 0; - this.afterFlushWait = false; - this.createdDirectories = {}; - var self2 = this; - this.unzipStream.on("entry", this._processEntry.bind(this)); - this.unzipStream.on("error", function(error4) { - self2.emit("error", error4); - }); - } - util.inherits(Extract, Transform); - Extract.prototype._transform = function(chunk, encoding, cb) { - this.unzipStream.write(chunk, encoding, cb); - }; - Extract.prototype._flush = function(cb) { - var self2 = this; - var allDone = function() { - process.nextTick(function() { - self2.emit("close"); +// node_modules/@actions/artifact/lib/internal/client.js +var require_client2 = __commonJS({ + "node_modules/@actions/artifact/lib/internal/client.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); }); - cb(); - }; - this.unzipStream.end(function() { - if (self2.unfinishedEntries > 0) { - self2.afterFlushWait = true; - return self2.on("await-finished", allDone); + } + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - allDone(); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - Extract.prototype._processEntry = function(entry) { - var self2 = this; - var destPath = path15.join(this.opts.path, entry.path); - var directory = entry.isDirectory ? destPath : path15.dirname(destPath); - this.unfinishedEntries++; - var writeFileFn = function() { - var pipedStream = fs17.createWriteStream(destPath); - pipedStream.on("close", function() { - self2.unfinishedEntries--; - self2._notifyAwaiter(); + var __rest4 = exports2 && exports2.__rest || function(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DefaultArtifactClient = void 0; + var core_1 = require_core(); + var config_1 = require_config2(); + var upload_artifact_1 = require_upload_artifact(); + var download_artifact_1 = require_download_artifact(); + var delete_artifact_1 = require_delete_artifact(); + var get_artifact_1 = require_get_artifact(); + var list_artifacts_1 = require_list_artifacts(); + var errors_1 = require_errors3(); + var DefaultArtifactClient2 = class { + uploadArtifact(name, files, rootDirectory, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options); + } catch (error4) { + (0, core_1.warning)(`Artifact upload failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } }); - pipedStream.on("error", function(error4) { - self2.emit("error", error4); + } + downloadArtifact(artifactId, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest4(options, ["findBy"]); + return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions); + } + return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options); + } catch (error4) { + (0, core_1.warning)(`Download Artifact failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } }); - entry.pipe(pipedStream); - }; - if (this.createdDirectories[directory] || directory === ".") { - return writeFileFn(); } - mkdirp(directory, function(err) { - if (err) return self2.emit("error", err); - self2.createdDirectories[directory] = true; - if (entry.isDirectory) { - self2.unfinishedEntries--; - self2._notifyAwaiter(); - return; - } - writeFileFn(); - }); - }; - Extract.prototype._notifyAwaiter = function() { - if (this.afterFlushWait && this.unfinishedEntries === 0) { - this.emit("await-finished"); - this.afterFlushWait = false; + listArtifacts(options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; + return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest); + } + return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest); + } catch (error4) { + (0, core_1.warning)(`Listing Artifacts failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); + } + getArtifact(artifactName, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; + return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + } + return (0, get_artifact_1.getArtifactInternal)(artifactName); + } catch (error4) { + (0, core_1.warning)(`Get Artifact failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); + } + deleteArtifact(artifactName, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { repositoryOwner, repositoryName, workflowRunId, token } } = options; + return (0, delete_artifact_1.deleteArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + } + return (0, delete_artifact_1.deleteArtifactInternal)(artifactName); + } catch (error4) { + (0, core_1.warning)(`Delete Artifact failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); } }; - module2.exports = Extract; + exports2.DefaultArtifactClient = DefaultArtifactClient2; } }); -// node_modules/unzip-stream/unzip.js -var require_unzip = __commonJS({ - "node_modules/unzip-stream/unzip.js"(exports2) { +// node_modules/@actions/artifact/lib/internal/shared/interfaces.js +var require_interfaces2 = __commonJS({ + "node_modules/@actions/artifact/lib/internal/shared/interfaces.js"(exports2) { "use strict"; - exports2.Parse = require_parser_stream(); - exports2.Extract = require_extract2(); + Object.defineProperty(exports2, "__esModule", { value: true }); } }); -// node_modules/@actions/artifact/lib/internal/download/download-artifact.js -var require_download_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/internal/download/download-artifact.js"(exports2) { +// node_modules/@actions/artifact/lib/artifact.js +var require_artifact2 = __commonJS({ + "node_modules/@actions/artifact/lib/artifact.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -105968,251 +110741,80 @@ var require_download_artifact = __commonJS({ if (k2 === void 0) k2 = k; o[k2] = m[k]; })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); - } - __setModuleDefault4(result, mod); - return result; - }; - })(); - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.streamExtractExternal = streamExtractExternal; - exports2.downloadArtifactPublic = downloadArtifactPublic; - exports2.downloadArtifactInternal = downloadArtifactInternal; - var promises_1 = __importDefault4(require("fs/promises")); - var crypto = __importStar4(require("crypto")); - var stream2 = __importStar4(require("stream")); - var github3 = __importStar4(require_github()); - var core18 = __importStar4(require_core()); - var httpClient = __importStar4(require_lib()); - var unzip_stream_1 = __importDefault4(require_unzip()); - var user_agent_1 = require_user_agent2(); - var config_1 = require_config2(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var generated_1 = require_generated(); - var util_1 = require_util11(); - var errors_1 = require_errors3(); - var scrubQueryParameters = (url2) => { - const parsed = new URL(url2); - parsed.search = ""; - return parsed.toString(); - }; - function exists(path15) { - return __awaiter4(this, void 0, void 0, function* () { - try { - yield promises_1.default.access(path15); - return true; - } catch (error4) { - if (error4.code === "ENOENT") { - return false; - } else { - throw error4; - } - } - }); - } - function streamExtract(url2, directory) { - return __awaiter4(this, void 0, void 0, function* () { - let retryCount = 0; - while (retryCount < 5) { - try { - return yield streamExtractExternal(url2, directory); - } catch (error4) { - retryCount++; - core18.debug(`Failed to download artifact after ${retryCount} retries due to ${error4.message}. Retrying in 5 seconds...`); - yield new Promise((resolve8) => setTimeout(resolve8, 5e3)); - } - } - throw new Error(`Artifact download failed after ${retryCount} retries.`); - }); - } - function streamExtractExternal(url_1, directory_1) { - return __awaiter4(this, arguments, void 0, function* (url2, directory, opts = { timeout: 30 * 1e3 }) { - const client = new httpClient.HttpClient((0, user_agent_1.getUserAgentString)()); - const response = yield client.get(url2); - if (response.message.statusCode !== 200) { - throw new Error(`Unexpected HTTP response from blob storage: ${response.message.statusCode} ${response.message.statusMessage}`); - } - let sha256Digest = void 0; - return new Promise((resolve8, reject) => { - const timerFn = () => { - const timeoutError = new Error(`Blob storage chunk did not respond in ${opts.timeout}ms`); - response.message.destroy(timeoutError); - reject(timeoutError); - }; - const timer = setTimeout(timerFn, opts.timeout); - const hashStream = crypto.createHash("sha256").setEncoding("hex"); - const passThrough = new stream2.PassThrough(); - response.message.pipe(passThrough); - passThrough.pipe(hashStream); - const extractStream = passThrough; - extractStream.on("data", () => { - timer.refresh(); - }).on("error", (error4) => { - core18.debug(`response.message: Artifact download failed: ${error4.message}`); - clearTimeout(timer); - reject(error4); - }).pipe(unzip_stream_1.default.Extract({ path: directory })).on("close", () => { - clearTimeout(timer); - if (hashStream) { - hashStream.end(); - sha256Digest = hashStream.read(); - core18.info(`SHA256 digest of downloaded artifact is ${sha256Digest}`); - } - resolve8({ sha256Digest: `sha256:${sha256Digest}` }); - }).on("error", (error4) => { - reject(error4); - }); - }); - }); - } - function downloadArtifactPublic(artifactId, repositoryOwner, repositoryName, token, options) { - return __awaiter4(this, void 0, void 0, function* () { - const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); - const api = github3.getOctokit(token); - let digestMismatch = false; - core18.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`); - const { headers, status } = yield api.rest.actions.downloadArtifact({ - owner: repositoryOwner, - repo: repositoryName, - artifact_id: artifactId, - archive_format: "zip", - request: { - redirect: "manual" - } - }); - if (status !== 302) { - throw new Error(`Unable to download artifact. Unexpected status: ${status}`); - } - const { location } = headers; - if (!location) { - throw new Error(`Unable to redirect to artifact download url`); - } - core18.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`); - try { - core18.info(`Starting download of artifact to: ${downloadPath}`); - const extractResponse = yield streamExtract(location, downloadPath); - core18.info(`Artifact download completed successfully.`); - if (options === null || options === void 0 ? void 0 : options.expectedHash) { - if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { - digestMismatch = true; - core18.debug(`Computed digest: ${extractResponse.sha256Digest}`); - core18.debug(`Expected digest: ${options.expectedHash}`); - } - } - } catch (error4) { - throw new Error(`Unable to download and extract artifact: ${error4.message}`); - } - return { downloadPath, digestMismatch }; - }); - } - function downloadArtifactInternal(artifactId, options) { - return __awaiter4(this, void 0, void 0, function* () { - const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - let digestMismatch = false; - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const listReq = { - workflowRunBackendId, - workflowJobRunBackendId, - idFilter: generated_1.Int64Value.create({ value: artifactId.toString() }) - }; - const { artifacts } = yield artifactClient.ListArtifacts(listReq); - if (artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`No artifacts found for ID: ${artifactId} -Are you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`); - } - if (artifacts.length > 1) { - core18.warning("Multiple artifacts found, defaulting to first."); - } - const signedReq = { - workflowRunBackendId: artifacts[0].workflowRunBackendId, - workflowJobRunBackendId: artifacts[0].workflowJobRunBackendId, - name: artifacts[0].name - }; - const { signedUrl } = yield artifactClient.GetSignedArtifactURL(signedReq); - core18.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`); - try { - core18.info(`Starting download of artifact to: ${downloadPath}`); - const extractResponse = yield streamExtract(signedUrl, downloadPath); - core18.info(`Artifact download completed successfully.`); - if (options === null || options === void 0 ? void 0 : options.expectedHash) { - if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) { - digestMismatch = true; - core18.debug(`Computed digest: ${extractResponse.sha256Digest}`); - core18.debug(`Expected digest: ${options.expectedHash}`); - } - } - } catch (error4) { - throw new Error(`Unable to download and extract artifact: ${error4.message}`); + var client_1 = require_client2(); + __exportStar4(require_interfaces2(), exports2); + __exportStar4(require_errors3(), exports2); + __exportStar4(require_client2(), exports2); + var client = new client_1.DefaultArtifactClient(); + exports2.default = client; + } +}); + +// node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js +var require_path_and_artifact_name_validation2 = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkArtifactFilePath = exports2.checkArtifactName = void 0; + var core_1 = require_core(); + var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ + ['"', ' Double quote "'], + [":", " Colon :"], + ["<", " Less than <"], + [">", " Greater than >"], + ["|", " Vertical bar |"], + ["*", " Asterisk *"], + ["?", " Question mark ?"], + ["\r", " Carriage return \\r"], + ["\n", " Line feed \\n"] + ]); + var invalidArtifactNameCharacters = new Map([ + ...invalidArtifactFilePathCharacters, + ["\\", " Backslash \\"], + ["/", " Forward slash /"] + ]); + function checkArtifactName(name) { + if (!name) { + throw new Error(`Artifact name: ${name}, is incorrectly provided`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { + if (name.includes(invalidCharacterKey)) { + throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} + +These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); } - return { downloadPath, digestMismatch }; - }); + } + (0, core_1.info)(`Artifact name is valid!`); } - function resolveOrCreateDirectory() { - return __awaiter4(this, arguments, void 0, function* (downloadPath = (0, config_1.getGitHubWorkspaceDir)()) { - if (!(yield exists(downloadPath))) { - core18.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`); - yield promises_1.default.mkdir(downloadPath, { recursive: true }); - } else { - core18.debug(`Artifact destination folder already exists: ${downloadPath}`); + exports2.checkArtifactName = checkArtifactName; + function checkArtifactFilePath(path15) { + if (!path15) { + throw new Error(`Artifact path: ${path15}, is incorrectly provided`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { + if (path15.includes(invalidCharacterKey)) { + throw new Error(`Artifact path is not valid: ${path15}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} + +The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. + `); } - return downloadPath; - }); + } } + exports2.checkArtifactFilePath = checkArtifactFilePath; } }); -// node_modules/@actions/artifact/lib/internal/find/retry-options.js -var require_retry_options = __commonJS({ - "node_modules/@actions/artifact/lib/internal/find/retry-options.js"(exports2) { +// node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js +var require_upload_specification = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -106232,560 +110834,573 @@ var require_retry_options = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); - } - __setModuleDefault4(result, mod); - return result; - }; - })(); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRetryOptions = getRetryOptions; - var core18 = __importStar4(require_core()); - var defaultMaxRetryNumber = 5; - var defaultExemptStatusCodes = [400, 401, 403, 404, 422]; - function getRetryOptions(defaultOptions, retries = defaultMaxRetryNumber, exemptStatusCodes = defaultExemptStatusCodes) { - var _a; - if (retries <= 0) { - return [{ enabled: false }, defaultOptions.request]; + exports2.getUploadSpecification = void 0; + var fs17 = __importStar4(require("fs")); + var core_1 = require_core(); + var path_1 = require("path"); + var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); + function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { + const specifications = []; + if (!fs17.existsSync(rootDirectory)) { + throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); } - const retryOptions = { - enabled: true - }; - if (exemptStatusCodes.length > 0) { - retryOptions.doNotRetry = exemptStatusCodes; + if (!fs17.statSync(rootDirectory).isDirectory()) { + throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); } - const requestOptions = Object.assign(Object.assign({}, defaultOptions.request), { retries }); - core18.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a = retryOptions.doNotRetry) !== null && _a !== void 0 ? _a : "octokit default: [400, 401, 403, 404, 422]"})`); - return [retryOptions, requestOptions]; + rootDirectory = (0, path_1.normalize)(rootDirectory); + rootDirectory = (0, path_1.resolve)(rootDirectory); + for (let file of artifactFiles) { + if (!fs17.existsSync(file)) { + throw new Error(`File ${file} does not exist`); + } + if (!fs17.statSync(file).isDirectory()) { + file = (0, path_1.normalize)(file); + file = (0, path_1.resolve)(file); + if (!file.startsWith(rootDirectory)) { + throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); + } + const uploadPath = file.replace(rootDirectory, ""); + (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath); + specifications.push({ + absoluteFilePath: file, + uploadFilePath: (0, path_1.join)(artifactName, uploadPath) + }); + } else { + (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`); + } + } + return specifications; } + exports2.getUploadSpecification = getUploadSpecification; } }); -// node_modules/@octokit/plugin-request-log/dist-node/index.js -var require_dist_node16 = __commonJS({ - "node_modules/@octokit/plugin-request-log/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var VERSION = "1.0.4"; - function requestLog(octokit) { - octokit.hook.wrap("request", (request, options) => { - octokit.log.debug("request", options); - const start = Date.now(); - const requestOptions = octokit.request.endpoint.parse(options); - const path15 = requestOptions.url.replace(options.baseUrl, ""); - return request(options).then((response) => { - octokit.log.info(`${requestOptions.method} ${path15} - ${response.status} in ${Date.now() - start}ms`); - return response; - }).catch((error4) => { - octokit.log.info(`${requestOptions.method} ${path15} - ${error4.status} in ${Date.now() - start}ms`); - throw error4; - }); - }); +// node_modules/tmp/lib/tmp.js +var require_tmp = __commonJS({ + "node_modules/tmp/lib/tmp.js"(exports2, module2) { + var fs17 = require("fs"); + var os3 = require("os"); + var path15 = require("path"); + var crypto = require("crypto"); + var _c = { fs: fs17.constants, os: os3.constants }; + var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + var TEMPLATE_PATTERN = /XXXXXX/; + var DEFAULT_TRIES = 3; + var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR); + var IS_WIN32 = os3.platform() === "win32"; + var EBADF = _c.EBADF || _c.os.errno.EBADF; + var ENOENT = _c.ENOENT || _c.os.errno.ENOENT; + var DIR_MODE = 448; + var FILE_MODE = 384; + var EXIT = "exit"; + var _removeObjects = []; + var FN_RMDIR_SYNC = fs17.rmdirSync.bind(fs17); + var _gracefulCleanup = false; + function rimraf(dirPath, callback) { + return fs17.rm(dirPath, { recursive: true }, callback); } - requestLog.VERSION = VERSION; - exports2.requestLog = requestLog; - } -}); - -// node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js -var require_dist_node17 = __commonJS({ - "node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function _interopDefault(ex) { - return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex; + function FN_RIMRAF_SYNC(dirPath) { + return fs17.rmSync(dirPath, { recursive: true }); } - var Bottleneck = _interopDefault(require_light()); - async function errorRequest(octokit, state, error4, options) { - if (!error4.request || !error4.request.request) { - throw error4; - } - if (error4.status >= 400 && !state.doNotRetry.includes(error4.status)) { - const retries = options.request.retries != null ? options.request.retries : state.retries; - const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); - throw octokit.retry.retryRequest(error4, retries, retryAfter); - } - throw error4; + function tmpName(options, callback) { + const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; + _assertAndSanitizeOptions(opts, function(err, sanitizedOptions) { + if (err) return cb(err); + let tries = sanitizedOptions.tries; + (function _getUniqueName() { + try { + const name = _generateTmpName(sanitizedOptions); + fs17.stat(name, function(err2) { + if (!err2) { + if (tries-- > 0) return _getUniqueName(); + return cb(new Error("Could not get a unique tmp filename, max tries reached " + name)); + } + cb(null, name); + }); + } catch (err2) { + cb(err2); + } + })(); + }); } - async function wrapRequest(state, request, options) { - const limiter = new Bottleneck(); - limiter.on("failed", function(error4, info7) { - const maxRetries = ~~error4.request.request.retries; - const after = ~~error4.request.request.retryAfter; - options.request.retryCount = info7.retryCount + 1; - if (maxRetries > info7.retryCount) { - return after * state.retryAfterBaseValue; + function tmpNameSync(options) { + const args = _parseArguments(options), opts = args[0]; + const sanitizedOptions = _assertAndSanitizeOptionsSync(opts); + let tries = sanitizedOptions.tries; + do { + const name = _generateTmpName(sanitizedOptions); + try { + fs17.statSync(name); + } catch (e) { + return name; } + } while (tries-- > 0); + throw new Error("Could not get a unique tmp filename, max tries reached"); + } + function file(options, callback) { + const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; + tmpName(opts, function _tmpNameCreated(err, name) { + if (err) return cb(err); + fs17.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { + if (err2) return cb(err2); + if (opts.discardDescriptor) { + return fs17.close(fd, function _discardCallback(possibleErr) { + return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false)); + }); + } else { + const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; + cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); + } + }); }); - return limiter.schedule(request, options); } - var VERSION = "3.0.9"; - function retry3(octokit, octokitOptions) { - const state = Object.assign({ - enabled: true, - retryAfterBaseValue: 1e3, - doNotRetry: [400, 401, 403, 404, 422], - retries: 3 - }, octokitOptions.retry); - if (state.enabled) { - octokit.hook.error("request", errorRequest.bind(null, octokit, state)); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); + function fileSync(options) { + const args = _parseArguments(options), opts = args[0]; + const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; + const name = tmpNameSync(opts); + let fd = fs17.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); + if (opts.discardDescriptor) { + fs17.closeSync(fd); + fd = void 0; } return { - retry: { - retryRequest: (error4, retries, retryAfter) => { - error4.request.request = Object.assign({}, error4.request.request, { - retries, - retryAfter - }); - return error4; - } - } + name, + fd, + removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) }; } - retry3.VERSION = VERSION; - exports2.VERSION = VERSION; - exports2.retry = retry3; - } -}); - -// node_modules/@actions/artifact/lib/internal/find/get-artifact.js -var require_get_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/internal/find/get-artifact.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); + function dir(options, callback) { + const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; + tmpName(opts, function _tmpNameCreated(err, name) { + if (err) return cb(err); + fs17.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { + if (err2) return cb(err2); + cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); + }); + }); + } + function dirSync(options) { + const args = _parseArguments(options), opts = args[0]; + const name = tmpNameSync(opts); + fs17.mkdirSync(name, opts.mode || DIR_MODE); + return { + name, + removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + function _removeFileAsync(fdPath, next) { + const _handler = function(err) { + if (err && !_isENOENT(err)) { + return next(err); } - __setModuleDefault4(result, mod); - return result; + next(); }; - })(); - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); + if (0 <= fdPath[0]) + fs17.close(fdPath[0], function() { + fs17.unlink(fdPath[1], _handler); }); - } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + else fs17.unlink(fdPath[1], _handler); + } + function _removeFileSync(fdPath) { + let rethrownException = null; + try { + if (0 <= fdPath[0]) fs17.closeSync(fdPath[0]); + } catch (e) { + if (!_isEBADF(e) && !_isENOENT(e)) throw e; + } finally { + try { + fs17.unlinkSync(fdPath[1]); + } catch (e) { + if (!_isENOENT(e)) rethrownException = e; } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + } + if (rethrownException !== null) { + throw rethrownException; + } + } + function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { + const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); + const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + return sync ? removeCallbackSync : removeCallback; + } + function _prepareTmpDirRemoveCallback(name, opts, sync) { + const removeFunction = opts.unsafeCleanup ? rimraf : fs17.rmdir.bind(fs17); + const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; + const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); + const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + return sync ? removeCallbackSync : removeCallback; + } + function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { + let called = false; + return function _cleanupCallback(next) { + if (!called) { + const toRemove = cleanupCallbackSync || _cleanupCallback; + const index = _removeObjects.indexOf(toRemove); + if (index >= 0) _removeObjects.splice(index, 1); + called = true; + if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { + return removeFunction(fileOrDirName); + } else { + return removeFunction(fileOrDirName, next || function() { + }); } } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getArtifactPublic = getArtifactPublic; - exports2.getArtifactInternal = getArtifactInternal; - var github_1 = require_github(); - var plugin_retry_1 = require_dist_node17(); - var core18 = __importStar4(require_core()); - var utils_1 = require_utils4(); - var retry_options_1 = require_retry_options(); - var plugin_request_log_1 = require_dist_node16(); - var util_1 = require_util11(); - var user_agent_1 = require_user_agent2(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var generated_1 = require_generated(); - var errors_1 = require_errors3(); - function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { - return __awaiter4(this, void 0, void 0, function* () { - var _a; - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: void 0, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: void 0, - retry: retryOpts, - request: requestOpts - }; - const github3 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - const getArtifactResp = yield github3.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}", { - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - name: artifactName - }); - if (getArtifactResp.status !== 200) { - throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); - } - if (getArtifactResp.data.artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} - Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. - For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); + }; + } + function _garbageCollector() { + if (!_gracefulCleanup) return; + while (_removeObjects.length) { + try { + _removeObjects[0](); + } catch (e) { } - let artifact2 = getArtifactResp.data.artifacts[0]; - if (getArtifactResp.data.artifacts.length > 1) { - artifact2 = getArtifactResp.data.artifacts.sort((a, b) => b.id - a.id)[0]; - core18.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.id})`); + } + } + function _randomChars(howMany) { + let value = [], rnd = null; + try { + rnd = crypto.randomBytes(howMany); + } catch (e) { + rnd = crypto.pseudoRandomBytes(howMany); + } + for (let i = 0; i < howMany; i++) { + value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); + } + return value.join(""); + } + function _isUndefined(obj) { + return typeof obj === "undefined"; + } + function _parseArguments(options, callback) { + if (typeof options === "function") { + return [{}, options]; + } + if (_isUndefined(options)) { + return [{}, callback]; + } + const actualOptions = {}; + for (const key of Object.getOwnPropertyNames(options)) { + actualOptions[key] = options[key]; + } + return [actualOptions, callback]; + } + function _resolvePath(name, tmpDir, cb) { + const pathToResolve = path15.isAbsolute(name) ? name : path15.join(tmpDir, name); + fs17.stat(pathToResolve, function(err) { + if (err) { + fs17.realpath(path15.dirname(pathToResolve), function(err2, parentDir) { + if (err2) return cb(err2); + cb(null, path15.join(parentDir, path15.basename(pathToResolve))); + }); + } else { + fs17.realpath(path15, cb); } - return { - artifact: { - name: artifact2.name, - id: artifact2.id, - size: artifact2.size_in_bytes, - createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, - digest: artifact2.digest - } - }; }); } - function getArtifactInternal(artifactName) { - return __awaiter4(this, void 0, void 0, function* () { - var _a; - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const req = { - workflowRunBackendId, - workflowJobRunBackendId, - nameFilter: generated_1.StringValue.create({ value: artifactName }) - }; - const res = yield artifactClient.ListArtifacts(req); - if (res.artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} - Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. - For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); - } - let artifact2 = res.artifacts[0]; - if (res.artifacts.length > 1) { - artifact2 = res.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; - core18.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); + function _resolvePathSync(name, tmpDir) { + const pathToResolve = path15.isAbsolute(name) ? name : path15.join(tmpDir, name); + try { + fs17.statSync(pathToResolve); + return fs17.realpathSync(pathToResolve); + } catch (_err) { + const parentDir = fs17.realpathSync(path15.dirname(pathToResolve)); + return path15.join(parentDir, path15.basename(pathToResolve)); + } + } + function _generateTmpName(opts) { + const tmpDir = opts.tmpdir; + if (!_isUndefined(opts.name)) { + return path15.join(tmpDir, opts.dir, opts.name); + } + if (!_isUndefined(opts.template)) { + return path15.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); + } + const name = [ + opts.prefix ? opts.prefix : "tmp", + "-", + process.pid, + "-", + _randomChars(12), + opts.postfix ? "-" + opts.postfix : "" + ].join(""); + return path15.join(tmpDir, opts.dir, name); + } + function _assertOptionsBase(options) { + if (!_isUndefined(options.name)) { + const name = options.name; + if (path15.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`); + const basename = path15.basename(name); + if (basename === ".." || basename === "." || basename !== name) + throw new Error(`name option must not contain a path, found "${name}".`); + } + if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) { + throw new Error(`Invalid template, found "${options.template}".`); + } + if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) { + throw new Error(`Invalid tries, found "${options.tries}".`); + } + options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; + options.keep = !!options.keep; + options.detachDescriptor = !!options.detachDescriptor; + options.discardDescriptor = !!options.discardDescriptor; + options.unsafeCleanup = !!options.unsafeCleanup; + options.prefix = _isUndefined(options.prefix) ? "" : options.prefix; + options.postfix = _isUndefined(options.postfix) ? "" : options.postfix; + } + function _getRelativePath(option, name, tmpDir, cb) { + if (_isUndefined(name)) return cb(null); + _resolvePath(name, tmpDir, function(err, resolvedPath) { + if (err) return cb(err); + const relativePath = path15.relative(tmpDir, resolvedPath); + if (!resolvedPath.startsWith(tmpDir)) { + return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`)); } - return { - artifact: { - name: artifact2.name, - id: Number(artifact2.databaseId), - size: Number(artifact2.size), - createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, - digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value - } - }; + cb(null, relativePath); }); } - } -}); - -// node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js -var require_delete_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); + function _getRelativePathSync(option, name, tmpDir) { + if (_isUndefined(name)) return; + const resolvedPath = _resolvePathSync(name, tmpDir); + const relativePath = path15.relative(tmpDir, resolvedPath); + if (!resolvedPath.startsWith(tmpDir)) { + throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`); } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); + return relativePath; + } + function _assertAndSanitizeOptions(options, cb) { + _getTmpDir(options, function(err, tmpDir) { + if (err) return cb(err); + options.tmpdir = tmpDir; + try { + _assertOptionsBase(options, tmpDir); + } catch (err2) { + return cb(err2); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.deleteArtifactPublic = deleteArtifactPublic; - exports2.deleteArtifactInternal = deleteArtifactInternal; - var core_1 = require_core(); - var github_1 = require_github(); - var user_agent_1 = require_user_agent2(); - var retry_options_1 = require_retry_options(); - var utils_1 = require_utils4(); - var plugin_request_log_1 = require_dist_node16(); - var plugin_retry_1 = require_dist_node17(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var util_1 = require_util11(); - var generated_1 = require_generated(); - var get_artifact_1 = require_get_artifact(); - var errors_1 = require_errors3(); - function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { - return __awaiter4(this, void 0, void 0, function* () { - var _a; - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: void 0, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: void 0, - retry: retryOpts, - request: requestOpts - }; - const github3 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - const getArtifactResp = yield (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - const deleteArtifactResp = yield github3.rest.actions.deleteArtifact({ - owner: repositoryOwner, - repo: repositoryName, - artifact_id: getArtifactResp.artifact.id + _getRelativePath("dir", options.dir, tmpDir, function(err2, dir2) { + if (err2) return cb(err2); + options.dir = _isUndefined(dir2) ? "" : dir2; + _getRelativePath("template", options.template, tmpDir, function(err3, template) { + if (err3) return cb(err3); + options.template = template; + cb(null, options); + }); }); - if (deleteArtifactResp.status !== 204) { - throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); - } - return { - id: getArtifactResp.artifact.id - }; }); } - function deleteArtifactInternal(artifactName) { - return __awaiter4(this, void 0, void 0, function* () { - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const listReq = { - workflowRunBackendId, - workflowJobRunBackendId, - nameFilter: generated_1.StringValue.create({ value: artifactName }) - }; - const listRes = yield artifactClient.ListArtifacts(listReq); - if (listRes.artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); - } - let artifact2 = listRes.artifacts[0]; - if (listRes.artifacts.length > 1) { - artifact2 = listRes.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; - (0, core_1.debug)(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); - } - const req = { - workflowRunBackendId: artifact2.workflowRunBackendId, - workflowJobRunBackendId: artifact2.workflowJobRunBackendId, - name: artifact2.name - }; - const res = yield artifactClient.DeleteArtifact(req); - (0, core_1.info)(`Artifact '${artifactName}' (ID: ${res.artifactId}) deleted`); - return { - id: Number(res.artifactId) - }; - }); + function _assertAndSanitizeOptionsSync(options) { + const tmpDir = options.tmpdir = _getTmpDirSync(options); + _assertOptionsBase(options, tmpDir); + const dir2 = _getRelativePathSync("dir", options.dir, tmpDir); + options.dir = _isUndefined(dir2) ? "" : dir2; + options.template = _getRelativePathSync("template", options.template, tmpDir); + return options; + } + function _isEBADF(error4) { + return _isExpectedError(error4, -EBADF, "EBADF"); + } + function _isENOENT(error4) { + return _isExpectedError(error4, -ENOENT, "ENOENT"); + } + function _isExpectedError(error4, errno, code) { + return IS_WIN32 ? error4.code === code : error4.code === code && error4.errno === errno; + } + function setGracefulCleanup() { + _gracefulCleanup = true; + } + function _getTmpDir(options, cb) { + return fs17.realpath(options && options.tmpdir || os3.tmpdir(), cb); + } + function _getTmpDirSync(options) { + return fs17.realpathSync(options && options.tmpdir || os3.tmpdir()); } + process.addListener(EXIT, _garbageCollector); + Object.defineProperty(module2.exports, "tmpdir", { + enumerable: true, + configurable: false, + get: function() { + return _getTmpDirSync(); + } + }); + module2.exports.dir = dir; + module2.exports.dirSync = dirSync; + module2.exports.file = file; + module2.exports.fileSync = fileSync; + module2.exports.tmpName = tmpName; + module2.exports.tmpNameSync = tmpNameSync; + module2.exports.setGracefulCleanup = setGracefulCleanup; } }); -// node_modules/@actions/artifact/lib/internal/find/list-artifacts.js -var require_list_artifacts = __commonJS({ - "node_modules/@actions/artifact/lib/internal/find/list-artifacts.js"(exports2) { +// node_modules/tmp-promise/index.js +var require_tmp_promise = __commonJS({ + "node_modules/tmp-promise/index.js"(exports2, module2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve8) { - resolve8(value); - }); + var { promisify } = require("util"); + var tmp = require_tmp(); + module2.exports.fileSync = tmp.fileSync; + var fileWithOptions = promisify( + (options, cb) => tmp.file( + options, + (err, path15, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path15, fd, cleanup: promisify(cleanup) }) + ) + ); + module2.exports.file = async (options) => fileWithOptions(options); + module2.exports.withFile = async function withFile(fn, options) { + const { path: path15, fd, cleanup } = await module2.exports.file(options); + try { + return await fn({ path: path15, fd }); + } finally { + await cleanup(); + } + }; + module2.exports.dirSync = tmp.dirSync; + var dirWithOptions = promisify( + (options, cb) => tmp.dir( + options, + (err, path15, cleanup) => err ? cb(err) : cb(void 0, { path: path15, cleanup: promisify(cleanup) }) + ) + ); + module2.exports.dir = async (options) => dirWithOptions(options); + module2.exports.withDir = async function withDir(fn, options) { + const { path: path15, cleanup } = await module2.exports.dir(options); + try { + return await fn({ path: path15 }); + } finally { + await cleanup(); } - return new (P || (P = Promise))(function(resolve8, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); }; + module2.exports.tmpNameSync = tmp.tmpNameSync; + module2.exports.tmpName = promisify(tmp.tmpName); + module2.exports.tmpdir = tmp.tmpdir; + module2.exports.setGracefulCleanup = tmp.setGracefulCleanup; + } +}); + +// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/proxy.js +var require_proxy7 = __commonJS({ + "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listArtifactsPublic = listArtifactsPublic; - exports2.listArtifactsInternal = listArtifactsInternal; - var core_1 = require_core(); - var github_1 = require_github(); - var user_agent_1 = require_user_agent2(); - var retry_options_1 = require_retry_options(); - var utils_1 = require_utils4(); - var plugin_request_log_1 = require_dist_node16(); - var plugin_retry_1 = require_dist_node17(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var util_1 = require_util11(); - var config_1 = require_config2(); - var generated_1 = require_generated(); - var maximumArtifactCount = (0, config_1.getMaxArtifactListCount)(); - var paginationCount = 100; - var maxNumberOfPages = Math.ceil(maximumArtifactCount / paginationCount); - function listArtifactsPublic(workflowRunId_1, repositoryOwner_1, repositoryName_1, token_1) { - return __awaiter4(this, arguments, void 0, function* (workflowRunId, repositoryOwner, repositoryName, token, latest = false) { - (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`); - let artifacts = []; - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: void 0, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: void 0, - retry: retryOpts, - request: requestOpts - }; - const github3 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - let currentPageNumber = 1; - const { data: listArtifactResponse } = yield github3.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - per_page: paginationCount, - page: currentPageNumber - }); - let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount); - const totalArtifactCount = listArtifactResponse.total_count; - if (totalArtifactCount > maximumArtifactCount) { - (0, core_1.warning)(`Workflow run ${workflowRunId} has ${totalArtifactCount} artifacts, exceeding the limit of ${maximumArtifactCount}. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`); - numberOfPages = maxNumberOfPages; - } - for (const artifact2 of listArtifactResponse.artifacts) { - artifacts.push({ - name: artifact2.name, - id: artifact2.id, - size: artifact2.size_in_bytes, - createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, - digest: artifact2.digest - }); - } - currentPageNumber++; - for (currentPageNumber; currentPageNumber <= numberOfPages; currentPageNumber++) { - (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`); - const { data: listArtifactResponse2 } = yield github3.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - per_page: paginationCount, - page: currentPageNumber - }); - for (const artifact2 of listArtifactResponse2.artifacts) { - artifacts.push({ - name: artifact2.name, - id: artifact2.id, - size: artifact2.size_in_bytes, - createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, - digest: artifact2.digest - }); - } - } - if (latest) { - artifacts = filterLatest(artifacts); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); - return { - artifacts - }; - }); - } - function listArtifactsInternal() { - return __awaiter4(this, arguments, void 0, function* (latest = false) { - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const req = { - workflowRunBackendId, - workflowJobRunBackendId - }; - const res = yield artifactClient.ListArtifacts(req); - let artifacts = res.artifacts.map((artifact2) => { - var _a; - return { - name: artifact2.name, - id: Number(artifact2.databaseId), - size: Number(artifact2.size), - createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, - digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value - }; - }); - if (latest) { - artifacts = filterLatest(artifacts); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); - return { - artifacts - }; - }); + } else { + return void 0; + } } - function filterLatest(artifacts) { - artifacts.sort((a, b) => b.id - a.id); - const latestArtifacts = []; - const seenArtifactNames = /* @__PURE__ */ new Set(); - for (const artifact2 of artifacts) { - if (!seenArtifactNames.has(artifact2.name)) { - latestArtifacts.push(artifact2); - seenArtifactNames.add(artifact2.name); + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - return latestArtifacts; + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@actions/artifact/lib/internal/client.js -var require_client2 = __commonJS({ - "node_modules/@actions/artifact/lib/internal/client.js"(exports2) { +// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/index.js +var require_lib9 = __commonJS({ + "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve8) { @@ -106813,703 +111428,668 @@ var require_client2 = __commonJS({ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __rest4 = exports2 && exports2.__rest || function(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DefaultArtifactClient = void 0; - var core_1 = require_core(); - var config_1 = require_config2(); - var upload_artifact_1 = require_upload_artifact(); - var download_artifact_1 = require_download_artifact(); - var delete_artifact_1 = require_delete_artifact(); - var get_artifact_1 = require_get_artifact(); - var list_artifacts_1 = require_list_artifacts(); - var errors_1 = require_errors3(); - var DefaultArtifactClient2 = class { - uploadArtifact(name, files, rootDirectory, options) { + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy7()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); + } + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options); - } catch (error4) { - (0, core_1.warning)(`Artifact upload failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve8(output.toString()); + }); + })); }); } - downloadArtifact(artifactId, options) { + readBodyBuffer() { return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest4(options, ["findBy"]); - return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions); - } - return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options); - } catch (error4) { - (0, core_1.warning)(`Download Artifact failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } + return new Promise((resolve8) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve8(Buffer.concat(chunks)); + }); + })); }); } - listArtifacts(options) { - return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; - return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest); - } - return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest); - } catch (error4) { - (0, core_1.warning)(`Listing Artifacts failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); }); } - getArtifact(artifactName, options) { + get(requestUrl, additionalHeaders) { return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; - return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - } - return (0, get_artifact_1.getArtifactInternal)(artifactName); - } catch (error4) { - (0, core_1.warning)(`Get Artifact failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } + return this.request("GET", requestUrl, null, additionalHeaders || {}); }); } - deleteArtifact(artifactName, options) { + del(requestUrl, additionalHeaders) { return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { repositoryOwner, repositoryName, workflowRunId, token } } = options; - return (0, delete_artifact_1.deleteArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - } - return (0, delete_artifact_1.deleteArtifactInternal)(artifactName); - } catch (error4) { - (0, core_1.warning)(`Delete Artifact failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); }); } - }; - exports2.DefaultArtifactClient = DefaultArtifactClient2; - } -}); - -// node_modules/@actions/artifact/lib/internal/shared/interfaces.js -var require_interfaces2 = __commonJS({ - "node_modules/@actions/artifact/lib/internal/shared/interfaces.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@actions/artifact/lib/artifact.js -var require_artifact2 = __commonJS({ - "node_modules/@actions/artifact/lib/artifact.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - var client_1 = require_client2(); - __exportStar4(require_interfaces2(), exports2); - __exportStar4(require_errors3(), exports2); - __exportStar4(require_client2(), exports2); - var client = new client_1.DefaultArtifactClient(); - exports2.default = client; - } -}); - -// node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js -var require_path_and_artifact_name_validation2 = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.checkArtifactFilePath = exports2.checkArtifactName = void 0; - var core_1 = require_core(); - var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ - ['"', ' Double quote "'], - [":", " Colon :"], - ["<", " Less than <"], - [">", " Greater than >"], - ["|", " Vertical bar |"], - ["*", " Asterisk *"], - ["?", " Question mark ?"], - ["\r", " Carriage return \\r"], - ["\n", " Line feed \\n"] - ]); - var invalidArtifactNameCharacters = new Map([ - ...invalidArtifactFilePathCharacters, - ["\\", " Backslash \\"], - ["/", " Forward slash /"] - ]); - function checkArtifactName(name) { - if (!name) { - throw new Error(`Artifact name: ${name}, is incorrectly provided`); + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { - if (name.includes(invalidCharacterKey)) { - throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} - -These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); - } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - (0, core_1.info)(`Artifact name is valid!`); - } - exports2.checkArtifactName = checkArtifactName; - function checkArtifactFilePath(path15) { - if (!path15) { - throw new Error(`Artifact path: ${path15}, is incorrectly provided`); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path15.includes(invalidCharacterKey)) { - throw new Error(`Artifact path is not valid: ${path15}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} - -The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. - `); - } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - } - exports2.checkArtifactFilePath = checkArtifactFilePath; - } -}); - -// node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js -var require_upload_specification = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - __setModuleDefault4(result, mod); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUploadSpecification = void 0; - var fs17 = __importStar4(require("fs")); - var core_1 = require_core(); - var path_1 = require("path"); - var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); - function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { - const specifications = []; - if (!fs17.existsSync(rootDirectory)) { - throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - if (!fs17.statSync(rootDirectory).isDirectory()) { - throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - rootDirectory = (0, path_1.normalize)(rootDirectory); - rootDirectory = (0, path_1.resolve)(rootDirectory); - for (let file of artifactFiles) { - if (!fs17.existsSync(file)) { - throw new Error(`File ${file} does not exist`); - } - if (!fs17.statSync(file).isDirectory()) { - file = (0, path_1.normalize)(file); - file = (0, path_1.resolve)(file); - if (!file.startsWith(rootDirectory)) { - throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - const uploadPath = file.replace(rootDirectory, ""); - (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath); - specifications.push({ - absoluteFilePath: file, - uploadFilePath: (0, path_1.join)(artifactName, uploadPath) - }); - } else { - (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`); + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return specifications; - } - exports2.getUploadSpecification = getUploadSpecification; - } -}); - -// node_modules/tmp/lib/tmp.js -var require_tmp = __commonJS({ - "node_modules/tmp/lib/tmp.js"(exports2, module2) { - var fs17 = require("fs"); - var os3 = require("os"); - var path15 = require("path"); - var crypto = require("crypto"); - var _c = { fs: fs17.constants, os: os3.constants }; - var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - var TEMPLATE_PATTERN = /XXXXXX/; - var DEFAULT_TRIES = 3; - var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR); - var IS_WIN32 = os3.platform() === "win32"; - var EBADF = _c.EBADF || _c.os.errno.EBADF; - var ENOENT = _c.ENOENT || _c.os.errno.ENOENT; - var DIR_MODE = 448; - var FILE_MODE = 384; - var EXIT = "exit"; - var _removeObjects = []; - var FN_RMDIR_SYNC = fs17.rmdirSync.bind(fs17); - var _gracefulCleanup = false; - function rimraf(dirPath, callback) { - return fs17.rm(dirPath, { recursive: true }, callback); - } - function FN_RIMRAF_SYNC(dirPath) { - return fs17.rmSync(dirPath, { recursive: true }); - } - function tmpName(options, callback) { - const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; - _assertAndSanitizeOptions(opts, function(err, sanitizedOptions) { - if (err) return cb(err); - let tries = sanitizedOptions.tries; - (function _getUniqueName() { - try { - const name = _generateTmpName(sanitizedOptions); - fs17.stat(name, function(err2) { - if (!err2) { - if (tries-- > 0) return _getUniqueName(); - return cb(new Error("Could not get a unique tmp filename, max tries reached " + name)); + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve8(res); } - cb(null, name); - }); - } catch (err2) { - cb(err2); + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; } - })(); - }); - } - function tmpNameSync(options) { - const args = _parseArguments(options), opts = args[0]; - const sanitizedOptions = _assertAndSanitizeOptionsSync(opts); - let tries = sanitizedOptions.tries; - do { - const name = _generateTmpName(sanitizedOptions); - try { - fs17.statSync(name); - } catch (e) { - return name; + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - } while (tries-- > 0); - throw new Error("Could not get a unique tmp filename, max tries reached"); - } - function file(options, callback) { - const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; - tmpName(opts, function _tmpNameCreated(err, name) { - if (err) return cb(err); - fs17.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { - if (err2) return cb(err2); - if (opts.discardDescriptor) { - return fs17.close(fd, function _discardCallback(possibleErr) { - return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false)); - }); - } else { - const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; - cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); }); - }); - } - function fileSync(options) { - const args = _parseArguments(options), opts = args[0]; - const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; - const name = tmpNameSync(opts); - let fd = fs17.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); - if (opts.discardDescriptor) { - fs17.closeSync(fd); - fd = void 0; - } - return { - name, - fd, - removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) - }; - } - function dir(options, callback) { - const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; - tmpName(opts, function _tmpNameCreated(err, name) { - if (err) return cb(err); - fs17.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { - if (err2) return cb(err2); - cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); + let socket; + req.on("socket", (sock) => { + socket = sock; }); - }); - } - function dirSync(options) { - const args = _parseArguments(options), opts = args[0]; - const name = tmpNameSync(opts); - fs17.mkdirSync(name, opts.mode || DIR_MODE); - return { - name, - removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) - }; - } - function _removeFileAsync(fdPath, next) { - const _handler = function(err) { - if (err && !_isENOENT(err)) { - return next(err); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - next(); - }; - if (0 <= fdPath[0]) - fs17.close(fdPath[0], function() { - fs17.unlink(fdPath[1], _handler); - }); - else fs17.unlink(fdPath[1], _handler); - } - function _removeFileSync(fdPath) { - let rethrownException = null; - try { - if (0 <= fdPath[0]) fs17.closeSync(fdPath[0]); - } catch (e) { - if (!_isEBADF(e) && !_isENOENT(e)) throw e; - } finally { - try { - fs17.unlinkSync(fdPath[1]); - } catch (e) { - if (!_isENOENT(e)) rethrownException = e; + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } } + return info7; } - if (rethrownException !== null) { - throw rethrownException; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - } - function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { - const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); - const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); - return sync ? removeCallbackSync : removeCallback; - } - function _prepareTmpDirRemoveCallback(name, opts, sync) { - const removeFunction = opts.unsafeCleanup ? rimraf : fs17.rmdir.bind(fs17); - const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; - const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); - const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); - return sync ? removeCallbackSync : removeCallback; - } - function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { - let called = false; - return function _cleanupCallback(next) { - if (!called) { - const toRemove = cleanupCallbackSync || _cleanupCallback; - const index = _removeObjects.indexOf(toRemove); - if (index >= 0) _removeObjects.splice(index, 1); - called = true; - if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { - return removeFunction(fileOrDirName); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - return removeFunction(fileOrDirName, next || function() { - }); + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - }; - } - function _garbageCollector() { - if (!_gracefulCleanup) return; - while (_removeObjects.length) { - try { - _removeObjects[0](); - } catch (e) { + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - } - function _randomChars(howMany) { - let value = [], rnd = null; - try { - rnd = crypto.randomBytes(howMany); - } catch (e) { - rnd = crypto.pseudoRandomBytes(howMany); - } - for (let i = 0; i < howMany; i++) { - value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - return value.join(""); - } - function _isUndefined(obj) { - return typeof obj === "undefined"; - } - function _parseArguments(options, callback) { - if (typeof options === "function") { - return [{}, options]; + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve8) => setTimeout(() => resolve8(), ms)); + }); } - if (_isUndefined(options)) { - return [{}, callback]; + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve8, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve8(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve8(response); + } + })); + }); } - const actualOptions = {}; - for (const key of Object.getOwnPropertyNames(options)) { - actualOptions[key] = options[key]; + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/auth.js +var require_auth4 = __commonJS({ + "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/auth.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve8) { + resolve8(value); + }); } - return [actualOptions, callback]; - } - function _resolvePath(name, tmpDir, cb) { - const pathToResolve = path15.isAbsolute(name) ? name : path15.join(tmpDir, name); - fs17.stat(pathToResolve, function(err) { - if (err) { - fs17.realpath(path15.dirname(pathToResolve), function(err2, parentDir) { - if (err2) return cb(err2); - cb(null, path15.join(parentDir, path15.basename(pathToResolve))); - }); - } else { - fs17.realpath(path15, cb); + return new (P || (P = Promise))(function(resolve8, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve8(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - } - function _resolvePathSync(name, tmpDir) { - const pathToResolve = path15.isAbsolute(name) ? name : path15.join(tmpDir, name); - try { - fs17.statSync(pathToResolve); - return fs17.realpathSync(pathToResolve); - } catch (_err) { - const parentDir = fs17.realpathSync(path15.dirname(pathToResolve)); - return path15.join(parentDir, path15.basename(pathToResolve)); - } - } - function _generateTmpName(opts) { - const tmpDir = opts.tmpdir; - if (!_isUndefined(opts.name)) { - return path15.join(tmpDir, opts.dir, opts.name); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - if (!_isUndefined(opts.template)) { - return path15.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; } - const name = [ - opts.prefix ? opts.prefix : "tmp", - "-", - process.pid, - "-", - _randomChars(12), - opts.postfix ? "-" + opts.postfix : "" - ].join(""); - return path15.join(tmpDir, opts.dir, name); - } - function _assertOptionsBase(options) { - if (!_isUndefined(options.name)) { - const name = options.name; - if (path15.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`); - const basename = path15.basename(name); - if (basename === ".." || basename === "." || basename !== name) - throw new Error(`name option must not contain a path, found "${name}".`); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) { - throw new Error(`Invalid template, found "${options.template}".`); + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) { - throw new Error(`Invalid tries, found "${options.tries}".`); + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; } - options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; - options.keep = !!options.keep; - options.detachDescriptor = !!options.detachDescriptor; - options.discardDescriptor = !!options.discardDescriptor; - options.unsafeCleanup = !!options.unsafeCleanup; - options.prefix = _isUndefined(options.prefix) ? "" : options.prefix; - options.postfix = _isUndefined(options.postfix) ? "" : options.postfix; - } - function _getRelativePath(option, name, tmpDir, cb) { - if (_isUndefined(name)) return cb(null); - _resolvePath(name, tmpDir, function(err, resolvedPath) { - if (err) return cb(err); - const relativePath = path15.relative(tmpDir, resolvedPath); - if (!resolvedPath.startsWith(tmpDir)) { - return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`)); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } - cb(null, relativePath); - }); - } - function _getRelativePathSync(option, name, tmpDir) { - if (_isUndefined(name)) return; - const resolvedPath = _resolvePathSync(name, tmpDir); - const relativePath = path15.relative(tmpDir, resolvedPath); - if (!resolvedPath.startsWith(tmpDir)) { - throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`); + options.headers["Authorization"] = `Bearer ${this.token}`; } - return relativePath; - } - function _assertAndSanitizeOptions(options, cb) { - _getTmpDir(options, function(err, tmpDir) { - if (err) return cb(err); - options.tmpdir = tmpDir; - try { - _assertOptionsBase(options, tmpDir); - } catch (err2) { - return cb(err2); - } - _getRelativePath("dir", options.dir, tmpDir, function(err2, dir2) { - if (err2) return cb(err2); - options.dir = _isUndefined(dir2) ? "" : dir2; - _getRelativePath("template", options.template, tmpDir, function(err3, template) { - if (err3) return cb(err3); - options.template = template; - cb(null, options); - }); - }); - }); - } - function _assertAndSanitizeOptionsSync(options) { - const tmpDir = options.tmpdir = _getTmpDirSync(options); - _assertOptionsBase(options, tmpDir); - const dir2 = _getRelativePathSync("dir", options.dir, tmpDir); - options.dir = _isUndefined(dir2) ? "" : dir2; - options.template = _getRelativePathSync("template", options.template, tmpDir); - return options; - } - function _isEBADF(error4) { - return _isExpectedError(error4, -EBADF, "EBADF"); - } - function _isENOENT(error4) { - return _isExpectedError(error4, -ENOENT, "ENOENT"); - } - function _isExpectedError(error4, errno, code) { - return IS_WIN32 ? error4.code === code : error4.code === code && error4.errno === errno; - } - function setGracefulCleanup() { - _gracefulCleanup = true; - } - function _getTmpDir(options, cb) { - return fs17.realpath(options && options.tmpdir || os3.tmpdir(), cb); - } - function _getTmpDirSync(options) { - return fs17.realpathSync(options && options.tmpdir || os3.tmpdir()); - } - process.addListener(EXIT, _garbageCollector); - Object.defineProperty(module2.exports, "tmpdir", { - enumerable: true, - configurable: false, - get: function() { - return _getTmpDirSync(); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - }); - module2.exports.dir = dir; - module2.exports.dirSync = dirSync; - module2.exports.file = file; - module2.exports.fileSync = fileSync; - module2.exports.tmpName = tmpName; - module2.exports.tmpNameSync = tmpNameSync; - module2.exports.setGracefulCleanup = setGracefulCleanup; - } -}); - -// node_modules/tmp-promise/index.js -var require_tmp_promise = __commonJS({ - "node_modules/tmp-promise/index.js"(exports2, module2) { - "use strict"; - var { promisify } = require("util"); - var tmp = require_tmp(); - module2.exports.fileSync = tmp.fileSync; - var fileWithOptions = promisify( - (options, cb) => tmp.file( - options, - (err, path15, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path15, fd, cleanup: promisify(cleanup) }) - ) - ); - module2.exports.file = async (options) => fileWithOptions(options); - module2.exports.withFile = async function withFile(fn, options) { - const { path: path15, fd, cleanup } = await module2.exports.file(options); - try { - return await fn({ path: path15, fd }); - } finally { - await cleanup(); + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } }; - module2.exports.dirSync = tmp.dirSync; - var dirWithOptions = promisify( - (options, cb) => tmp.dir( - options, - (err, path15, cleanup) => err ? cb(err) : cb(void 0, { path: path15, cleanup: promisify(cleanup) }) - ) - ); - module2.exports.dir = async (options) => dirWithOptions(options); - module2.exports.withDir = async function withDir(fn, options) { - const { path: path15, cleanup } = await module2.exports.dir(options); - try { - return await fn({ path: path15 }); - } finally { - await cleanup(); + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } }; - module2.exports.tmpNameSync = tmp.tmpNameSync; - module2.exports.tmpName = promisify(tmp.tmpName); - module2.exports.tmpdir = tmp.tmpdir; - module2.exports.setGracefulCleanup = tmp.setGracefulCleanup; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); @@ -107923,8 +112503,8 @@ var require_utils7 = __commonJS({ var crypto_1 = __importDefault4(require("crypto")); var fs_1 = require("fs"); var core_1 = require_core(); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib9(); + var auth_1 = require_auth4(); var config_variables_1 = require_config_variables(); var crc64_1 = __importDefault4(require_crc64()); function getExponentialRetryTimeInMilliseconds(retryCount) { @@ -108577,7 +113157,7 @@ var require_upload_http_client = __commonJS({ var url_1 = require("url"); var perf_hooks_1 = require("perf_hooks"); var status_reporter_1 = require_status_reporter(); - var http_client_1 = require_lib(); + var http_client_1 = require_lib9(); var http_manager_1 = require_http_manager(); var upload_gzip_1 = require_upload_gzip(); var requestUtils_1 = require_requestUtils2(); @@ -117074,7 +121654,7 @@ var CodeQuality = { }; // src/config/db-config.ts -var jsonschema = __toESM(require_lib2()); +var jsonschema = __toESM(require_lib3()); var semver2 = __toESM(require_semver2()); var PACK_IDENTIFIER_PATTERN = (function() { const alphaNumeric = "[a-z0-9]"; @@ -118178,7 +122758,7 @@ var os = __toESM(require("os")); var path7 = __toESM(require("path")); var import_perf_hooks = require("perf_hooks"); var core9 = __toESM(require_core()); -var import_http_client = __toESM(require_lib()); +var import_http_client = __toESM(require_lib6()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); var semver6 = __toESM(require_semver2()); @@ -119953,7 +124533,7 @@ var path13 = __toESM(require("path")); var url = __toESM(require("url")); var import_zlib = __toESM(require("zlib")); var core14 = __toESM(require_core()); -var jsonschema2 = __toESM(require_lib2()); +var jsonschema2 = __toESM(require_lib3()); // src/fingerprints.ts var fs13 = __toESM(require("fs")); diff --git a/lib/init-action.js b/lib/init-action.js index fd01bba4c7..0c32cfb369 100644 --- a/lib/init-action.js +++ b/lib/init-action.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -21805,9 +21805,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -21864,267 +21946,886 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve9(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve9(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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) => { + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve9(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve9) => setTimeout(() => resolve9(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve9(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve9(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve9) { + resolve9(value); + }); + } + return new (P || (P = Promise))(function(resolve9, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; + var httpClient = __importStar4(require_lib2()); + var undici_1 = require_undici(); + function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error("Parameter token or opts.auth is required"); + } else if (token && options.auth) { + throw new Error("Parameters token and opts.auth may not both be specified"); + } + return typeof options.auth === "string" ? options.auth : `token ${token}`; + } + exports2.getAuthString = getAuthString; + function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + exports2.getProxyAgent = getProxyAgent; + function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); + } + exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; + function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); + }); + return proxyFetch; + } + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; + } + exports2.getApiBaseUrl = getApiBaseUrl; + } +}); + +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); + } + return state.registry[name].reduce(function(method2, registered) { + return registered.hook.bind(null, method2, options); + }, method)(); + }); + } + } +}); + +// node_modules/before-after-hook/lib/add.js +var require_add = __commonJS({ + "node_modules/before-after-hook/lib/add.js"(exports2, module2) { + module2.exports = addHook; + function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } + if (kind === "before") { + hook = function(method, options) { + return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); + }; + } + if (kind === "after") { + hook = function(method, options) { + var result; + return Promise.resolve().then(method.bind(null, options)).then(function(result_) { + result = result_; + return orig(result, options); + }).then(function() { + return result; + }); + }; + } + if (kind === "error") { + hook = function(method, options) { + return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { + return orig(error4, options); + }); + }; + } + state.registry[name].push({ + hook, + orig + }); + } + } +}); + +// node_modules/before-after-hook/lib/remove.js +var require_remove = __commonJS({ + "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { + module2.exports = removeHook; + function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } + var index = state.registry[name].map(function(registered) { + return registered.orig; + }).indexOf(method); + if (index === -1) { + return; + } + state.registry[name].splice(index, 1); + } + } +}); + +// node_modules/before-after-hook/index.js +var require_before_after_hook = __commonJS({ + "node_modules/before-after-hook/index.js"(exports2, module2) { + var register = require_register(); + var addHook = require_add(); + var removeHook = require_remove(); + var bind = Function.bind; + var bindable = bind.bind(bind); + function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function(kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); + } + function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {} + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; + } + function HookCollection() { + var state = { + registry: {} + }; + var hook = register.bind(null, state); + bindApi(hook, state); + return hook; + } + var collectionHookDeprecationMessageDisplayed = false; + function Hook() { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; + } + return HookCollection(); + } + Hook.Singular = HookSingular.bind(); + Hook.Collection = HookCollection.bind(); + module2.exports = Hook; + module2.exports.Hook = Hook; + module2.exports.Singular = Hook.Singular; + module2.exports.Collection = Hook.Collection; + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node2 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_universal_user_agent = require_dist_node(); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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 isPlainObject(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 (isPlainObject(options[key])) { if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); @@ -26499,7 +27200,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -29372,7 +30073,7 @@ var require_validator = __commonJS({ }); // node_modules/jsonschema/lib/index.js -var require_lib2 = __commonJS({ +var require_lib3 = __commonJS({ "node_modules/jsonschema/lib/index.js"(exports2, module2) { "use strict"; var Validator2 = module2.exports.Validator = require_validator(); @@ -31371,1091 +32072,2002 @@ var require_semver3 = __commonJS({ re[i] = new RegExp(src[i]); safeRe[i] = new RegExp(makeSafeRe(src[i])); } - } - var i; - exports2.parse = parse; - function parse(version, options) { + } + var i; + exports2.parse = parse; + function parse(version, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (version instanceof SemVer) { + return version; + } + if (typeof version !== "string") { + return null; + } + if (version.length > MAX_LENGTH) { + return null; + } + var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]; + if (!r.test(version)) { + return null; + } + try { + return new SemVer(version, options); + } catch (er) { + return null; + } + } + exports2.valid = valid3; + function valid3(version, options) { + var v = parse(version, options); + return v ? v.version : null; + } + exports2.clean = clean3; + function clean3(version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ""), options); + return s ? s.version : null; + } + exports2.SemVer = SemVer; + function SemVer(version, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== "string") { + throw new TypeError("Invalid Version: " + version); + } + if (version.length > MAX_LENGTH) { + throw new TypeError("version is longer than " + MAX_LENGTH + " characters"); + } + if (!(this instanceof SemVer)) { + return new SemVer(version, options); + } + debug5("SemVer", version, options); + this.options = options; + this.loose = !!options.loose; + var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]); + if (!m) { + throw new TypeError("Invalid Version: " + version); + } + this.raw = version; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split(".").map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + return id; + }); + } + this.build = m[5] ? m[5].split(".") : []; + this.format(); + } + SemVer.prototype.format = function() { + this.version = this.major + "." + this.minor + "." + this.patch; + if (this.prerelease.length) { + this.version += "-" + this.prerelease.join("."); + } + return this.version; + }; + SemVer.prototype.toString = function() { + return this.version; + }; + SemVer.prototype.compare = function(other) { + debug5("SemVer.compare", this.version, this.options, other); + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + return this.compareMain(other) || this.comparePre(other); + }; + SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + }; + SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + var i2 = 0; + do { + var a = this.prerelease[i2]; + var b = other.prerelease[i2]; + debug5("prerelease compare", i2, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i2); + }; + SemVer.prototype.compareBuild = function(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + var i2 = 0; + do { + var a = this.build[i2]; + var b = other.build[i2]; + debug5("prerelease compare", i2, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i2); + }; + SemVer.prototype.inc = function(release2, identifier) { + switch (release2) { + case "premajor": + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc("pre", identifier); + break; + case "preminor": + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc("pre", identifier); + break; + case "prepatch": + this.prerelease.length = 0; + this.inc("patch", identifier); + this.inc("pre", identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case "prerelease": + if (this.prerelease.length === 0) { + this.inc("patch", identifier); + } + this.inc("pre", identifier); + break; + case "major": + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case "minor": + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break; + case "patch": + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case "pre": + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + var i2 = this.prerelease.length; + while (--i2 >= 0) { + if (typeof this.prerelease[i2] === "number") { + this.prerelease[i2]++; + i2 = -2; + } + } + if (i2 === -1) { + this.prerelease.push(0); + } + } + if (identifier) { + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + break; + default: + throw new Error("invalid increment argument: " + release2); + } + this.format(); + this.raw = this.version; + return this; + }; + exports2.inc = inc; + function inc(version, release2, loose, identifier) { + if (typeof loose === "string") { + identifier = loose; + loose = void 0; + } + try { + return new SemVer(version, loose).inc(release2, identifier).version; + } catch (er) { + return null; + } + } + exports2.diff = diff; + function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + var prefix = ""; + if (v1.prerelease.length || v2.prerelease.length) { + prefix = "pre"; + var defaultResult = "prerelease"; + } + for (var key in v1) { + if (key === "major" || key === "minor" || key === "patch") { + if (v1[key] !== v2[key]) { + return prefix + key; + } + } + } + return defaultResult; + } + } + exports2.compareIdentifiers = compareIdentifiers; + var numeric = /^[0-9]+$/; + function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + if (anum && bnum) { + a = +a; + b = +b; + } + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + } + exports2.rcompareIdentifiers = rcompareIdentifiers; + function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); + } + exports2.major = major; + function major(a, loose) { + return new SemVer(a, loose).major; + } + exports2.minor = minor; + function minor(a, loose) { + return new SemVer(a, loose).minor; + } + exports2.patch = patch; + function patch(a, loose) { + return new SemVer(a, loose).patch; + } + exports2.compare = compare2; + function compare2(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); + } + exports2.compareLoose = compareLoose; + function compareLoose(a, b) { + return compare2(a, b, true); + } + exports2.compareBuild = compareBuild; + function compareBuild(a, b, loose) { + var versionA = new SemVer(a, loose); + var versionB = new SemVer(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB); + } + exports2.rcompare = rcompare; + function rcompare(a, b, loose) { + return compare2(b, a, loose); + } + exports2.sort = sort; + function sort(list, loose) { + return list.sort(function(a, b) { + return exports2.compareBuild(a, b, loose); + }); + } + exports2.rsort = rsort; + function rsort(list, loose) { + return list.sort(function(a, b) { + return exports2.compareBuild(b, a, loose); + }); + } + exports2.gt = gt; + function gt(a, b, loose) { + return compare2(a, b, loose) > 0; + } + exports2.lt = lt2; + function lt2(a, b, loose) { + return compare2(a, b, loose) < 0; + } + exports2.eq = eq; + function eq(a, b, loose) { + return compare2(a, b, loose) === 0; + } + exports2.neq = neq; + function neq(a, b, loose) { + return compare2(a, b, loose) !== 0; + } + exports2.gte = gte5; + function gte5(a, b, loose) { + return compare2(a, b, loose) >= 0; + } + exports2.lte = lte; + function lte(a, b, loose) { + return compare2(a, b, loose) <= 0; + } + exports2.cmp = cmp; + function cmp(a, op, b, loose) { + switch (op) { + case "===": + if (typeof a === "object") + a = a.version; + if (typeof b === "object") + b = b.version; + return a === b; + case "!==": + if (typeof a === "object") + a = a.version; + if (typeof b === "object") + b = b.version; + return a !== b; + case "": + case "=": + case "==": + return eq(a, b, loose); + case "!=": + return neq(a, b, loose); + case ">": + return gt(a, b, loose); + case ">=": + return gte5(a, b, loose); + case "<": + return lt2(a, b, loose); + case "<=": + return lte(a, b, loose); + default: + throw new TypeError("Invalid operator: " + op); + } + } + exports2.Comparator = Comparator; + function Comparator(comp, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + if (!(this instanceof Comparator)) { + return new Comparator(comp, options); + } + comp = comp.trim().split(/\s+/).join(" "); + debug5("comparator", comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + if (this.semver === ANY) { + this.value = ""; + } else { + this.value = this.operator + this.semver.version; + } + debug5("comp", this); + } + var ANY = {}; + Comparator.prototype.parse = function(comp) { + var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; + var m = comp.match(r); + if (!m) { + throw new TypeError("Invalid comparator: " + comp); + } + this.operator = m[1] !== void 0 ? m[1] : ""; + if (this.operator === "=") { + this.operator = ""; + } + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + }; + Comparator.prototype.toString = function() { + return this.value; + }; + Comparator.prototype.test = function(version) { + debug5("Comparator.test", version, this.options.loose); + if (this.semver === ANY || version === ANY) { + return true; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + return cmp(version, this.operator, this.semver, this.options); + }; + Comparator.prototype.intersects = function(comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError("a Comparator is required"); + } if (!options || typeof options !== "object") { options = { loose: !!options, includePrerelease: false }; } - if (version instanceof SemVer) { - return version; - } - if (typeof version !== "string") { - return null; - } - if (version.length > MAX_LENGTH) { - return null; - } - var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]; - if (!r.test(version)) { - return null; - } - try { - return new SemVer(version, options); - } catch (er) { - return null; + var rangeTmp; + if (this.operator === "") { + if (this.value === "") { + return true; + } + rangeTmp = new Range2(comp.value, options); + return satisfies2(this.value, rangeTmp, options); + } else if (comp.operator === "") { + if (comp.value === "") { + return true; + } + rangeTmp = new Range2(this.value, options); + return satisfies2(comp.semver, rangeTmp, options); } - } - exports2.valid = valid3; - function valid3(version, options) { - var v = parse(version, options); - return v ? v.version : null; - } - exports2.clean = clean3; - function clean3(version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ""), options); - return s ? s.version : null; - } - exports2.SemVer = SemVer; - function SemVer(version, options) { + var sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">"); + var sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<"); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<="); + var oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && ((this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<")); + var oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && ((this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">")); + return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; + }; + exports2.Range = Range2; + function Range2(range, options) { if (!options || typeof options !== "object") { options = { loose: !!options, includePrerelease: false }; } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version; + if (range instanceof Range2) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; } else { - version = version.version; + return new Range2(range.raw, options); } - } else if (typeof version !== "string") { - throw new TypeError("Invalid Version: " + version); } - if (version.length > MAX_LENGTH) { - throw new TypeError("version is longer than " + MAX_LENGTH + " characters"); + if (range instanceof Comparator) { + return new Range2(range.value, options); } - if (!(this instanceof SemVer)) { - return new SemVer(version, options); + if (!(this instanceof Range2)) { + return new Range2(range, options); } - debug5("SemVer", version, options); this.options = options; this.loose = !!options.loose; - var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]); - if (!m) { - throw new TypeError("Invalid Version: " + version); - } - this.raw = version; - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError("Invalid major version"); - } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError("Invalid minor version"); - } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError("Invalid patch version"); - } - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split(".").map(function(id) { - if (/^[0-9]+$/.test(id)) { - var num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num; - } - } - return id; - }); + this.includePrerelease = !!options.includePrerelease; + this.raw = range.trim().split(/\s+/).join(" "); + this.set = this.raw.split("||").map(function(range2) { + return this.parseRange(range2.trim()); + }, this).filter(function(c) { + return c.length; + }); + if (!this.set.length) { + throw new TypeError("Invalid SemVer Range: " + this.raw); } - this.build = m[5] ? m[5].split(".") : []; this.format(); } - SemVer.prototype.format = function() { - this.version = this.major + "." + this.minor + "." + this.patch; - if (this.prerelease.length) { - this.version += "-" + this.prerelease.join("."); - } - return this.version; - }; - SemVer.prototype.toString = function() { - return this.version; + Range2.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(" ").trim(); + }).join("||").trim(); + return this.range; }; - SemVer.prototype.compare = function(other) { - debug5("SemVer.compare", this.version, this.options, other); - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - return this.compareMain(other) || this.comparePre(other); + Range2.prototype.toString = function() { + return this.range; }; - SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); + Range2.prototype.parseRange = function(range) { + var loose = this.options.loose; + var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug5("hyphen replace", range); + range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace); + debug5("comparator trim", range, safeRe[t.COMPARATORTRIM]); + range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace); + range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace); + range = range.split(/\s+/).join(" "); + var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; + var set2 = range.split(" ").map(function(comp) { + return parseComparator(comp, this.options); + }, this).join(" ").split(/\s+/); + if (this.options.loose) { + set2 = set2.filter(function(comp) { + return !!comp.match(compRe); + }); } - return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + set2 = set2.map(function(comp) { + return new Comparator(comp, this.options); + }, this); + return set2; }; - SemVer.prototype.comparePre = function(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - if (this.prerelease.length && !other.prerelease.length) { - return -1; - } else if (!this.prerelease.length && other.prerelease.length) { - return 1; - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0; + Range2.prototype.intersects = function(range, options) { + if (!(range instanceof Range2)) { + throw new TypeError("a Range is required"); } - var i2 = 0; - do { - var a = this.prerelease[i2]; - var b = other.prerelease[i2]; - debug5("prerelease compare", i2, a, b); - if (a === void 0 && b === void 0) { - return 0; - } else if (b === void 0) { - return 1; - } else if (a === void 0) { - return -1; - } else if (a === b) { - continue; - } else { - return compareIdentifiers(a, b); - } - } while (++i2); + return this.set.some(function(thisComparators) { + return isSatisfiable(thisComparators, options) && range.set.some(function(rangeComparators) { + return isSatisfiable(rangeComparators, options) && thisComparators.every(function(thisComparator) { + return rangeComparators.every(function(rangeComparator) { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); }; - SemVer.prototype.compareBuild = function(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); + function isSatisfiable(comparators, options) { + var result = true; + var remainingComparators = comparators.slice(); + var testComparator = remainingComparators.pop(); + while (result && remainingComparators.length) { + result = remainingComparators.every(function(otherComparator) { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); } - var i2 = 0; - do { - var a = this.build[i2]; - var b = other.build[i2]; - debug5("prerelease compare", i2, a, b); - if (a === void 0 && b === void 0) { - return 0; - } else if (b === void 0) { - return 1; - } else if (a === void 0) { - return -1; - } else if (a === b) { - continue; + return result; + } + exports2.toComparators = toComparators; + function toComparators(range, options) { + return new Range2(range, options).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(" ").trim().split(" "); + }); + } + function parseComparator(comp, options) { + debug5("comp", comp, options); + comp = replaceCarets(comp, options); + debug5("caret", comp); + comp = replaceTildes(comp, options); + debug5("tildes", comp); + comp = replaceXRanges(comp, options); + debug5("xrange", comp); + comp = replaceStars(comp, options); + debug5("stars", comp); + return comp; + } + function isX(id) { + return !id || id.toLowerCase() === "x" || id === "*"; + } + function replaceTildes(comp, options) { + return comp.trim().split(/\s+/).map(function(comp2) { + return replaceTilde(comp2, options); + }).join(" "); + } + function replaceTilde(comp, options) { + var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug5("tilde", comp, _, M, m, p, pr); + var ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; + } else if (isX(p)) { + ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; + } else if (pr) { + debug5("replaceTilde pr", pr); + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; } else { - return compareIdentifiers(a, b); + ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; } - } while (++i2); - }; - SemVer.prototype.inc = function(release2, identifier) { - switch (release2) { - case "premajor": - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc("pre", identifier); - break; - case "preminor": - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc("pre", identifier); - break; - case "prepatch": - this.prerelease.length = 0; - this.inc("patch", identifier); - this.inc("pre", identifier); - break; - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case "prerelease": - if (this.prerelease.length === 0) { - this.inc("patch", identifier); - } - this.inc("pre", identifier); - break; - case "major": - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { - this.major++; + debug5("tilde return", ret); + return ret; + }); + } + function replaceCarets(comp, options) { + return comp.trim().split(/\s+/).map(function(comp2) { + return replaceCaret(comp2, options); + }).join(" "); + } + function replaceCaret(comp, options) { + debug5("caret", comp, options); + var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug5("caret", comp, _, M, m, p, pr); + var ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; + } else if (isX(p)) { + if (M === "0") { + ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; + } else { + ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0"; } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case "minor": - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; + } else if (pr) { + debug5("replaceCaret pr", pr); + if (M === "0") { + if (m === "0") { + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1); + } else { + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; + } + } else { + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0"; } - this.patch = 0; - this.prerelease = []; - break; - case "patch": - if (this.prerelease.length === 0) { - this.patch++; + } else { + debug5("no pr"); + if (M === "0") { + if (m === "0") { + ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1); + } else { + ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; + } + } else { + ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0"; } - this.prerelease = []; - break; - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case "pre": - if (this.prerelease.length === 0) { - this.prerelease = [0]; + } + debug5("caret return", ret); + return ret; + }); + } + function replaceXRanges(comp, options) { + debug5("replaceXRanges", comp, options); + return comp.split(/\s+/).map(function(comp2) { + return replaceXRange(comp2, options); + }).join(" "); + } + function replaceXRange(comp, options) { + comp = comp.trim(); + var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug5("xRange", comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret = "<0.0.0-0"; } else { - var i2 = this.prerelease.length; - while (--i2 >= 0) { - if (typeof this.prerelease[i2] === "number") { - this.prerelease[i2]++; - i2 = -2; - } + ret = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + p = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; } - if (i2 === -1) { - this.prerelease.push(0); + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; } } - if (identifier) { - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; + ret = gtlt + M + "." + m + "." + p + pr; + } else if (xm) { + ret = ">=" + M + ".0.0" + pr + " <" + (+M + 1) + ".0.0" + pr; + } else if (xp) { + ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr; + } + debug5("xRange return", ret); + return ret; + }); + } + function replaceStars(comp, options) { + debug5("replaceStars", comp, options); + return comp.trim().replace(safeRe[t.STAR], ""); + } + function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = ">=" + fM + ".0.0"; + } else if (isX(fp)) { + from = ">=" + fM + "." + fm + ".0"; + } else { + from = ">=" + from; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = "<" + (+tM + 1) + ".0.0"; + } else if (isX(tp)) { + to = "<" + tM + "." + (+tm + 1) + ".0"; + } else if (tpr) { + to = "<=" + tM + "." + tm + "." + tp + "-" + tpr; + } else { + to = "<=" + to; + } + return (from + " " + to).trim(); + } + Range2.prototype.test = function(version) { + if (!version) { + return false; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + for (var i2 = 0; i2 < this.set.length; i2++) { + if (testSet(this.set[i2], version, this.options)) { + return true; + } + } + return false; + }; + function testSet(set2, version, options) { + for (var i2 = 0; i2 < set2.length; i2++) { + if (!set2[i2].test(version)) { + return false; + } + } + if (version.prerelease.length && !options.includePrerelease) { + for (i2 = 0; i2 < set2.length; i2++) { + debug5(set2[i2].semver); + if (set2[i2].semver === ANY) { + continue; + } + if (set2[i2].semver.prerelease.length > 0) { + var allowed = set2[i2].semver; + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; } } - break; - default: - throw new Error("invalid increment argument: " + release2); + } + return false; } - this.format(); - this.raw = this.version; - return this; - }; - exports2.inc = inc; - function inc(version, release2, loose, identifier) { - if (typeof loose === "string") { - identifier = loose; - loose = void 0; + return true; + } + exports2.satisfies = satisfies2; + function satisfies2(version, range, options) { + try { + range = new Range2(range, options); + } catch (er) { + return false; } + return range.test(version); + } + exports2.maxSatisfying = maxSatisfying; + function maxSatisfying(versions, range, options) { + var max = null; + var maxSV = null; try { - return new SemVer(version, loose).inc(release2, identifier).version; + var rangeObj = new Range2(range, options); } catch (er) { return null; } + versions.forEach(function(v) { + if (rangeObj.test(v)) { + if (!max || maxSV.compare(v) === -1) { + max = v; + maxSV = new SemVer(max, options); + } + } + }); + return max; } - exports2.diff = diff; - function diff(version1, version2) { - if (eq(version1, version2)) { + exports2.minSatisfying = minSatisfying; + function minSatisfying(versions, range, options) { + var min = null; + var minSV = null; + try { + var rangeObj = new Range2(range, options); + } catch (er) { return null; - } else { - var v1 = parse(version1); - var v2 = parse(version2); - var prefix = ""; - if (v1.prerelease.length || v2.prerelease.length) { - prefix = "pre"; - var defaultResult = "prerelease"; - } - for (var key in v1) { - if (key === "major" || key === "minor" || key === "patch") { - if (v1[key] !== v2[key]) { - return prefix + key; - } + } + versions.forEach(function(v) { + if (rangeObj.test(v)) { + if (!min || minSV.compare(v) === 1) { + min = v; + minSV = new SemVer(min, options); } } - return defaultResult; + }); + return min; + } + exports2.minVersion = minVersion; + function minVersion(range, loose) { + range = new Range2(range, loose); + var minver = new SemVer("0.0.0"); + if (range.test(minver)) { + return minver; + } + minver = new SemVer("0.0.0-0"); + if (range.test(minver)) { + return minver; + } + minver = null; + for (var i2 = 0; i2 < range.set.length; ++i2) { + var comparators = range.set[i2]; + comparators.forEach(function(comparator) { + var compver = new SemVer(comparator.semver.version); + switch (comparator.operator) { + case ">": + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case "": + case ">=": + if (!minver || gt(minver, compver)) { + minver = compver; + } + break; + case "<": + case "<=": + break; + /* istanbul ignore next */ + default: + throw new Error("Unexpected operation: " + comparator.operator); + } + }); } + if (minver && range.test(minver)) { + return minver; + } + return null; } - exports2.compareIdentifiers = compareIdentifiers; - var numeric = /^[0-9]+$/; - function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); - if (anum && bnum) { - a = +a; - b = +b; + exports2.validRange = validRange; + function validRange(range, options) { + try { + return new Range2(range, options).range || "*"; + } catch (er) { + return null; } - return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; } - exports2.rcompareIdentifiers = rcompareIdentifiers; - function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); + exports2.ltr = ltr; + function ltr(version, range, options) { + return outside(version, range, "<", options); } - exports2.major = major; - function major(a, loose) { - return new SemVer(a, loose).major; + exports2.gtr = gtr; + function gtr(version, range, options) { + return outside(version, range, ">", options); } - exports2.minor = minor; - function minor(a, loose) { - return new SemVer(a, loose).minor; + exports2.outside = outside; + function outside(version, range, hilo, options) { + version = new SemVer(version, options); + range = new Range2(range, options); + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case ">": + gtfn = gt; + ltefn = lte; + ltfn = lt2; + comp = ">"; + ecomp = ">="; + break; + case "<": + gtfn = lt2; + ltefn = gte5; + ltfn = gt; + comp = "<"; + ecomp = "<="; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + if (satisfies2(version, range, options)) { + return false; + } + for (var i2 = 0; i2 < range.set.length; ++i2) { + var comparators = range.set[i2]; + var high = null; + var low = null; + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator(">=0.0.0"); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + if (high.operator === comp || high.operator === ecomp) { + return false; + } + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; } - exports2.patch = patch; - function patch(a, loose) { - return new SemVer(a, loose).patch; + exports2.prerelease = prerelease; + function prerelease(version, options) { + var parsed = parse(version, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; } - exports2.compare = compare2; - function compare2(a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)); + exports2.intersects = intersects; + function intersects(r1, r2, options) { + r1 = new Range2(r1, options); + r2 = new Range2(r2, options); + return r1.intersects(r2); } - exports2.compareLoose = compareLoose; - function compareLoose(a, b) { - return compare2(a, b, true); + exports2.coerce = coerce3; + function coerce3(version, options) { + if (version instanceof SemVer) { + return version; + } + if (typeof version === "number") { + version = String(version); + } + if (typeof version !== "string") { + return null; + } + options = options || {}; + var match = null; + if (!options.rtl) { + match = version.match(safeRe[t.COERCE]); + } else { + var next; + while ((next = safeRe[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + safeRe[t.COERCERTL].lastIndex = -1; + } + if (match === null) { + return null; + } + return parse(match[2] + "." + (match[3] || "0") + "." + (match[4] || "0"), options); } - exports2.compareBuild = compareBuild; - function compareBuild(a, b, loose) { - var versionA = new SemVer(a, loose); - var versionB = new SemVer(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB); + } +}); + +// node_modules/@actions/cache/lib/internal/constants.js +var require_constants7 = __commonJS({ + "node_modules/@actions/cache/lib/internal/constants.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheFileSizeLimit = exports2.ManifestFilename = exports2.TarFilename = exports2.SystemTarPathOnWindows = exports2.GnuTarPathOnWindows = exports2.SocketTimeout = exports2.DefaultRetryDelay = exports2.DefaultRetryAttempts = exports2.ArchiveToolType = exports2.CompressionMethod = exports2.CacheFilename = void 0; + var CacheFilename; + (function(CacheFilename2) { + CacheFilename2["Gzip"] = "cache.tgz"; + CacheFilename2["Zstd"] = "cache.tzst"; + })(CacheFilename || (exports2.CacheFilename = CacheFilename = {})); + var CompressionMethod; + (function(CompressionMethod2) { + CompressionMethod2["Gzip"] = "gzip"; + CompressionMethod2["ZstdWithoutLong"] = "zstd-without-long"; + CompressionMethod2["Zstd"] = "zstd"; + })(CompressionMethod || (exports2.CompressionMethod = CompressionMethod = {})); + var ArchiveToolType; + (function(ArchiveToolType2) { + ArchiveToolType2["GNU"] = "gnu"; + ArchiveToolType2["BSD"] = "bsd"; + })(ArchiveToolType || (exports2.ArchiveToolType = ArchiveToolType = {})); + exports2.DefaultRetryAttempts = 2; + exports2.DefaultRetryDelay = 5e3; + exports2.SocketTimeout = 5e3; + exports2.GnuTarPathOnWindows = `${process.env["PROGRAMFILES"]}\\Git\\usr\\bin\\tar.exe`; + exports2.SystemTarPathOnWindows = `${process.env["SYSTEMDRIVE"]}\\Windows\\System32\\tar.exe`; + exports2.TarFilename = "cache.tar"; + exports2.ManifestFilename = "manifest.txt"; + exports2.CacheFileSizeLimit = 10 * Math.pow(1024, 3); + } +}); + +// node_modules/@actions/cache/lib/internal/cacheUtils.js +var require_cacheUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/cacheUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve9) { + resolve9(value); + }); + } + return new (P || (P = Promise))(function(resolve9, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve9, reject) { + v = o[n](v), settle(resolve9, reject, v.done, v.value); + }); + }; + } + function settle(resolve9, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve9({ value: v2, done: d }); + }, reject); + } + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRuntimeToken = exports2.getCacheVersion = exports2.assertDefined = exports2.getGnuTarPathOnWindows = exports2.getCacheFileName = exports2.getCompressionMethod = exports2.unlinkFile = exports2.resolvePaths = exports2.getArchiveFileSizeInBytes = exports2.createTempDirectory = void 0; + var core14 = __importStar4(require_core()); + var exec2 = __importStar4(require_exec()); + var glob2 = __importStar4(require_glob()); + var io7 = __importStar4(require_io()); + var crypto2 = __importStar4(require("crypto")); + var fs15 = __importStar4(require("fs")); + var path16 = __importStar4(require("path")); + var semver9 = __importStar4(require_semver3()); + var util = __importStar4(require("util")); + var constants_1 = require_constants7(); + var versionSalt = "1.0"; + function createTempDirectory() { + return __awaiter4(this, void 0, void 0, function* () { + const IS_WINDOWS = process.platform === "win32"; + let tempDirectory = process.env["RUNNER_TEMP"] || ""; + if (!tempDirectory) { + let baseLocation; + if (IS_WINDOWS) { + baseLocation = process.env["USERPROFILE"] || "C:\\"; + } else { + if (process.platform === "darwin") { + baseLocation = "/Users"; + } else { + baseLocation = "/home"; + } + } + tempDirectory = path16.join(baseLocation, "actions", "temp"); + } + const dest = path16.join(tempDirectory, crypto2.randomUUID()); + yield io7.mkdirP(dest); + return dest; + }); } - exports2.rcompare = rcompare; - function rcompare(a, b, loose) { - return compare2(b, a, loose); + exports2.createTempDirectory = createTempDirectory; + function getArchiveFileSizeInBytes(filePath) { + return fs15.statSync(filePath).size; } - exports2.sort = sort; - function sort(list, loose) { - return list.sort(function(a, b) { - return exports2.compareBuild(a, b, loose); + exports2.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; + function resolvePaths(patterns) { + var _a, e_1, _b, _c; + var _d; + return __awaiter4(this, void 0, void 0, function* () { + const paths = []; + const workspace = (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd(); + const globber = yield glob2.create(patterns.join("\n"), { + implicitDescendants: false + }); + try { + for (var _e = true, _f = __asyncValues4(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { + _c = _g.value; + _e = false; + const file = _c; + const relativeFile = path16.relative(workspace, file).replace(new RegExp(`\\${path16.sep}`, "g"), "/"); + core14.debug(`Matched: ${relativeFile}`); + if (relativeFile === "") { + paths.push("."); + } else { + paths.push(`${relativeFile}`); + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); + } finally { + if (e_1) throw e_1.error; + } + } + return paths; }); } - exports2.rsort = rsort; - function rsort(list, loose) { - return list.sort(function(a, b) { - return exports2.compareBuild(b, a, loose); + exports2.resolvePaths = resolvePaths; + function unlinkFile(filePath) { + return __awaiter4(this, void 0, void 0, function* () { + return util.promisify(fs15.unlink)(filePath); }); } - exports2.gt = gt; - function gt(a, b, loose) { - return compare2(a, b, loose) > 0; + exports2.unlinkFile = unlinkFile; + function getVersion(app, additionalArgs = []) { + return __awaiter4(this, void 0, void 0, function* () { + let versionOutput = ""; + additionalArgs.push("--version"); + core14.debug(`Checking ${app} ${additionalArgs.join(" ")}`); + try { + yield exec2.exec(`${app}`, additionalArgs, { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + } catch (err) { + core14.debug(err.message); + } + versionOutput = versionOutput.trim(); + core14.debug(versionOutput); + return versionOutput; + }); } - exports2.lt = lt2; - function lt2(a, b, loose) { - return compare2(a, b, loose) < 0; + function getCompressionMethod() { + return __awaiter4(this, void 0, void 0, function* () { + const versionOutput = yield getVersion("zstd", ["--quiet"]); + const version = semver9.clean(versionOutput); + core14.debug(`zstd version: ${version}`); + if (versionOutput === "") { + return constants_1.CompressionMethod.Gzip; + } else { + return constants_1.CompressionMethod.ZstdWithoutLong; + } + }); } - exports2.eq = eq; - function eq(a, b, loose) { - return compare2(a, b, loose) === 0; + exports2.getCompressionMethod = getCompressionMethod; + function getCacheFileName(compressionMethod) { + return compressionMethod === constants_1.CompressionMethod.Gzip ? constants_1.CacheFilename.Gzip : constants_1.CacheFilename.Zstd; } - exports2.neq = neq; - function neq(a, b, loose) { - return compare2(a, b, loose) !== 0; + exports2.getCacheFileName = getCacheFileName; + function getGnuTarPathOnWindows() { + return __awaiter4(this, void 0, void 0, function* () { + if (fs15.existsSync(constants_1.GnuTarPathOnWindows)) { + return constants_1.GnuTarPathOnWindows; + } + const versionOutput = yield getVersion("tar"); + return versionOutput.toLowerCase().includes("gnu tar") ? io7.which("tar") : ""; + }); } - exports2.gte = gte5; - function gte5(a, b, loose) { - return compare2(a, b, loose) >= 0; + exports2.getGnuTarPathOnWindows = getGnuTarPathOnWindows; + function assertDefined(name, value) { + if (value === void 0) { + throw Error(`Expected ${name} but value was undefiend`); + } + return value; } - exports2.lte = lte; - function lte(a, b, loose) { - return compare2(a, b, loose) <= 0; + exports2.assertDefined = assertDefined; + function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) { + const components = paths.slice(); + if (compressionMethod) { + components.push(compressionMethod); + } + if (process.platform === "win32" && !enableCrossOsArchive) { + components.push("windows-only"); + } + components.push(versionSalt); + return crypto2.createHash("sha256").update(components.join("|")).digest("hex"); } - exports2.cmp = cmp; - function cmp(a, op, b, loose) { - switch (op) { - case "===": - if (typeof a === "object") - a = a.version; - if (typeof b === "object") - b = b.version; - return a === b; - case "!==": - if (typeof a === "object") - a = a.version; - if (typeof b === "object") - b = b.version; - return a !== b; - case "": - case "=": - case "==": - return eq(a, b, loose); - case "!=": - return neq(a, b, loose); - case ">": - return gt(a, b, loose); - case ">=": - return gte5(a, b, loose); - case "<": - return lt2(a, b, loose); - case "<=": - return lte(a, b, loose); - default: - throw new TypeError("Invalid operator: " + op); + exports2.getCacheVersion = getCacheVersion; + function getRuntimeToken() { + const token = process.env["ACTIONS_RUNTIME_TOKEN"]; + if (!token) { + throw new Error("Unable to get the ACTIONS_RUNTIME_TOKEN env variable"); } + return token; } - exports2.Comparator = Comparator; - function Comparator(comp, options) { - if (!options || typeof options !== "object") { - options = { - loose: !!options, - includePrerelease: false - }; + exports2.getRuntimeToken = getRuntimeToken; + } +}); + +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp; + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; } else { - comp = comp.value; + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - } - if (!(this instanceof Comparator)) { - return new Comparator(comp, options); - } - comp = comp.trim().split(/\s+/).join(" "); - debug5("comparator", comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - if (this.semver === ANY) { - this.value = ""; } else { - this.value = this.operator + this.semver.version; + return void 0; } - debug5("comp", this); } - var ANY = {}; - Comparator.prototype.parse = function(comp) { - var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; - var m = comp.match(r); - if (!m) { - throw new TypeError("Invalid comparator: " + comp); - } - this.operator = m[1] !== void 0 ? m[1] : ""; - if (this.operator === "=") { - this.operator = ""; - } - if (!m[2]) { - this.semver = ANY; - } else { - this.semver = new SemVer(m[2], this.options.loose); + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - }; - Comparator.prototype.toString = function() { - return this.value; - }; - Comparator.prototype.test = function(version) { - debug5("Comparator.test", version, this.options.loose); - if (this.semver === ANY || version === ANY) { + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { return true; } - if (typeof version === "string") { - try { - version = new SemVer(version, this.options); - } catch (er) { - return false; - } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - return cmp(version, this.operator, this.semver, this.options); - }; - Comparator.prototype.intersects = function(comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError("a Comparator is required"); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - if (!options || typeof options !== "object") { - options = { - loose: !!options, - includePrerelease: false - }; + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - var rangeTmp; - if (this.operator === "") { - if (this.value === "") { - return true; - } - rangeTmp = new Range2(comp.value, options); - return satisfies2(this.value, rangeTmp, options); - } else if (comp.operator === "") { - if (comp.value === "") { + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { return true; } - rangeTmp = new Range2(this.value, options); - return satisfies2(comp.semver, rangeTmp, options); } - var sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">"); - var sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<"); - var sameSemVer = this.semver.version === comp.semver.version; - var differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<="); - var oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && ((this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<")); - var oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && ((this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">")); - return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; - }; - exports2.Range = Range2; - function Range2(range, options) { - if (!options || typeof options !== "object") { - options = { - loose: !!options, - includePrerelease: false - }; + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - if (range instanceof Range2) { - if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { - return range; - } else { - return new Range2(range.raw, options); - } + get username() { + return this._decodedUsername; } - if (range instanceof Comparator) { - return new Range2(range.value, options); + get password() { + return this._decodedPassword; } - if (!(this instanceof Range2)) { - return new Range2(range, options); + }; + } +}); + +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - this.raw = range.trim().split(/\s+/).join(" "); - this.set = this.raw.split("||").map(function(range2) { - return this.parseRange(range2.trim()); - }, this).filter(function(c) { - return c.length; - }); - if (!this.set.length) { - throw new TypeError("Invalid SemVer Range: " + this.raw); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - this.format(); - } - Range2.prototype.format = function() { - this.range = this.set.map(function(comps) { - return comps.join(" ").trim(); - }).join("||").trim(); - return this.range; - }; - Range2.prototype.toString = function() { - return this.range; + __setModuleDefault4(result, mod); + return result; }; - Range2.prototype.parseRange = function(range) { - var loose = this.options.loose; - var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - debug5("hyphen replace", range); - range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace); - debug5("comparator trim", range, safeRe[t.COMPARATORTRIM]); - range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace); - range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace); - range = range.split(/\s+/).join(" "); - var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; - var set2 = range.split(" ").map(function(comp) { - return parseComparator(comp, this.options); - }, this).join(" ").split(/\s+/); - if (this.options.loose) { - set2 = set2.filter(function(comp) { - return !!comp.match(compRe); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve9) { + resolve9(value); }); } - set2 = set2.map(function(comp) { - return new Comparator(comp, this.options); - }, this); - return set2; + return new (P || (P = Promise))(function(resolve9, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - Range2.prototype.intersects = function(range, options) { - if (!(range instanceof Range2)) { - throw new TypeError("a Range is required"); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return this.set.some(function(thisComparators) { - return isSatisfiable(thisComparators, options) && range.set.some(function(rangeComparators) { - return isSatisfiable(rangeComparators, options) && thisComparators.every(function(thisComparator) { - return rangeComparators.every(function(rangeComparator) { - return thisComparator.intersects(rangeComparator, options); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); }); - }); + this.message.on("end", () => { + resolve9(output.toString()); + }); + })); }); - }); - }; - function isSatisfiable(comparators, options) { - var result = true; - var remainingComparators = comparators.slice(); - var testComparator = remainingComparators.pop(); - while (result && remainingComparators.length) { - result = remainingComparators.every(function(otherComparator) { - return testComparator.intersects(otherComparator, options); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve9(Buffer.concat(chunks)); + }); + })); }); - testComparator = remainingComparators.pop(); } - return result; - } - exports2.toComparators = toComparators; - function toComparators(range, options) { - return new Range2(range, options).set.map(function(comp) { - return comp.map(function(c) { - return c.value; - }).join(" ").trim().split(" "); - }); - } - function parseComparator(comp, options) { - debug5("comp", comp, options); - comp = replaceCarets(comp, options); - debug5("caret", comp); - comp = replaceTildes(comp, options); - debug5("tildes", comp); - comp = replaceXRanges(comp, options); - debug5("xrange", comp); - comp = replaceStars(comp, options); - debug5("stars", comp); - return comp; - } - function isX(id) { - return !id || id.toLowerCase() === "x" || id === "*"; - } - function replaceTildes(comp, options) { - return comp.trim().split(/\s+/).map(function(comp2) { - return replaceTilde(comp2, options); - }).join(" "); - } - function replaceTilde(comp, options) { - var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - debug5("tilde", comp, _, M, m, p, pr); - var ret; - if (isX(M)) { - ret = ""; - } else if (isX(m)) { - ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; - } else if (isX(p)) { - ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; - } else if (pr) { - debug5("replaceTilde pr", pr); - ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; - } else { - ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; - } - debug5("tilde return", ret); - return ret; - }); - } - function replaceCarets(comp, options) { - return comp.trim().split(/\s+/).map(function(comp2) { - return replaceCaret(comp2, options); - }).join(" "); - } - function replaceCaret(comp, options) { - debug5("caret", comp, options); - var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - debug5("caret", comp, _, M, m, p, pr); - var ret; - if (isX(M)) { - ret = ""; - } else if (isX(m)) { - ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; - } else if (isX(p)) { - if (M === "0") { - ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; - } else { - ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0"; + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - } else if (pr) { - debug5("replaceCaret pr", pr); - if (M === "0") { - if (m === "0") { - ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1); - } else { - ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; - } - } else { - ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0"; + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } else { - debug5("no pr"); - if (M === "0") { - if (m === "0") { - ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1); - } else { - ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; - } - } else { - ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0"; + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } - debug5("caret return", ret); - return ret; - }); - } - function replaceXRanges(comp, options) { - debug5("replaceXRanges", comp, options); - return comp.split(/\s+/).map(function(comp2) { - return replaceXRange(comp2, options); - }).join(" "); - } - function replaceXRange(comp, options) { - comp = comp.trim(); - var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - debug5("xRange", comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; - if (gtlt === "=" && anyX) { - gtlt = ""; - } - pr = options.includePrerelease ? "-0" : ""; - if (xM) { - if (gtlt === ">" || gtlt === "<") { - ret = "<0.0.0-0"; - } else { - ret = "*"; + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } - } else if (gtlt && anyX) { - if (xm) { - m = 0; + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; } - p = 0; - if (gtlt === ">") { - gtlt = ">="; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === "<=") { - gtlt = "<"; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } - ret = gtlt + M + "." + m + "." + p + pr; - } else if (xm) { - ret = ">=" + M + ".0.0" + pr + " <" + (+M + 1) + ".0.0" + pr; - } else if (xp) { - ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr; } - debug5("xRange return", ret); - return ret; - }); - } - function replaceStars(comp, options) { - debug5("replaceStars", comp, options); - return comp.trim().replace(safeRe[t.STAR], ""); - } - function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = ""; - } else if (isX(fm)) { - from = ">=" + fM + ".0.0"; - } else if (isX(fp)) { - from = ">=" + fM + "." + fm + ".0"; - } else { - from = ">=" + from; } - if (isX(tM)) { - to = ""; - } else if (isX(tm)) { - to = "<" + (+tM + 1) + ".0.0"; - } else if (isX(tp)) { - to = "<" + tM + "." + (+tm + 1) + ".0"; - } else if (tpr) { - to = "<=" + tM + "." + tm + "." + tp + "-" + tpr; - } else { - to = "<=" + to; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - return (from + " " + to).trim(); - } - Range2.prototype.test = function(version) { - if (!version) { - return false; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (typeof version === "string") { - try { - version = new SemVer(version, this.options); - } catch (er) { - return false; - } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - for (var i2 = 0; i2 < this.set.length; i2++) { - if (testSet(this.set[i2], version, this.options)) { - return true; - } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - return false; - }; - function testSet(set2, version, options) { - for (var i2 = 0; i2 < set2.length; i2++) { - if (!set2[i2].test(version)) { - return false; - } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - if (version.prerelease.length && !options.includePrerelease) { - for (i2 = 0; i2 < set2.length; i2++) { - debug5(set2[i2].semver); - if (set2[i2].semver === ANY) { - continue; - } - if (set2[i2].semver.prerelease.length > 0) { - var allowed = set2[i2].semver; - if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { - return true; - } - } - } - return false; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return true; - } - exports2.satisfies = satisfies2; - function satisfies2(version, range, options) { - try { - range = new Range2(range, options); - } catch (er) { - return false; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return range.test(version); - } - exports2.maxSatisfying = maxSatisfying; - function maxSatisfying(versions, range, options) { - var max = null; - var maxSV = null; - try { - var rangeObj = new Range2(range, options); - } catch (er) { - return null; + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - versions.forEach(function(v) { - if (rangeObj.test(v)) { - if (!max || maxSV.compare(v) === -1) { - max = v; - maxSV = new SemVer(max, options); - } - } - }); - return max; - } - exports2.minSatisfying = minSatisfying; - function minSatisfying(versions, range, options) { - var min = null; - var minSV = null; - try { - var rangeObj = new Range2(range, options); - } catch (er) { - return null; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - versions.forEach(function(v) { - if (rangeObj.test(v)) { - if (!min || minSV.compare(v) === 1) { - min = v; - minSV = new SemVer(min, options); - } - } - }); - return min; - } - exports2.minVersion = minVersion; - function minVersion(range, loose) { - range = new Range2(range, loose); - var minver = new SemVer("0.0.0"); - if (range.test(minver)) { - return minver; + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - minver = new SemVer("0.0.0-0"); - if (range.test(minver)) { - return minver; + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - minver = null; - for (var i2 = 0; i2 < range.set.length; ++i2) { - var comparators = range.set[i2]; - comparators.forEach(function(comparator) { - var compver = new SemVer(comparator.semver.version); - switch (comparator.operator) { - case ">": - if (compver.prerelease.length === 0) { - compver.patch++; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); } else { - compver.prerelease.push(0); + return response; } - compver.raw = compver.format(); - /* fallthrough */ - case "": - case ">=": - if (!minver || gt(minver, compver)) { - minver = compver; + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; } - break; - case "<": - case "<=": - break; - /* istanbul ignore next */ - default: - throw new Error("Unexpected operation: " + comparator.operator); - } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); } - if (minver && range.test(minver)) { - return minver; - } - return null; - } - exports2.validRange = validRange; - function validRange(range, options) { - try { - return new Range2(range, options).range || "*"; - } catch (er) { - return null; - } - } - exports2.ltr = ltr; - function ltr(version, range, options) { - return outside(version, range, "<", options); - } - exports2.gtr = gtr; - function gtr(version, range, options) { - return outside(version, range, ">", options); - } - exports2.outside = outside; - function outside(version, range, hilo, options) { - version = new SemVer(version, options); - range = new Range2(range, options); - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case ">": - gtfn = gt; - ltefn = lte; - ltfn = lt2; - comp = ">"; - ecomp = ">="; - break; - case "<": - gtfn = lt2; - ltefn = gte5; - ltfn = gt; - comp = "<"; - ecomp = "<="; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; } - if (satisfies2(version, range, options)) { - return false; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve9(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); } - for (var i2 = 0; i2 < range.set.length; ++i2) { - var comparators = range.set[i2]; - var high = null; - var low = null; - comparators.forEach(function(comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator(">=0.0.0"); + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } + } + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); }); - if (high.operator === comp || high.operator === ecomp) { - return false; + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); } } - return true; - } - exports2.prerelease = prerelease; - function prerelease(version, options) { - var parsed = parse(version, options); - return parsed && parsed.prerelease.length ? parsed.prerelease : null; - } - exports2.intersects = intersects; - function intersects(r1, r2, options) { - r1 = new Range2(r1, options); - r2 = new Range2(r2, options); - return r1.intersects(r2); - } - exports2.coerce = coerce3; - function coerce3(version, options) { - if (version instanceof SemVer) { - return version; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (typeof version === "number") { - version = String(version); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - if (typeof version !== "string") { - return null; + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; } - options = options || {}; - var match = null; - if (!options.rtl) { - match = version.match(safeRe[t.COERCE]); - } else { - var next; - while ((next = safeRe[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) { - if (!match || next.index + next[0].length !== match.index + match[0].length) { - match = next; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } - safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - safeRe[t.COERCERTL].lastIndex = -1; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - if (match === null) { - return null; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - return parse(match[2] + "." + (match[3] || "0") + "." + (match[4] || "0"), options); - } - } -}); - -// node_modules/@actions/cache/lib/internal/constants.js -var require_constants7 = __commonJS({ - "node_modules/@actions/cache/lib/internal/constants.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheFileSizeLimit = exports2.ManifestFilename = exports2.TarFilename = exports2.SystemTarPathOnWindows = exports2.GnuTarPathOnWindows = exports2.SocketTimeout = exports2.DefaultRetryDelay = exports2.DefaultRetryAttempts = exports2.ArchiveToolType = exports2.CompressionMethod = exports2.CacheFilename = void 0; - var CacheFilename; - (function(CacheFilename2) { - CacheFilename2["Gzip"] = "cache.tgz"; - CacheFilename2["Zstd"] = "cache.tzst"; - })(CacheFilename || (exports2.CacheFilename = CacheFilename = {})); - var CompressionMethod; - (function(CompressionMethod2) { - CompressionMethod2["Gzip"] = "gzip"; - CompressionMethod2["ZstdWithoutLong"] = "zstd-without-long"; - CompressionMethod2["Zstd"] = "zstd"; - })(CompressionMethod || (exports2.CompressionMethod = CompressionMethod = {})); - var ArchiveToolType; - (function(ArchiveToolType2) { - ArchiveToolType2["GNU"] = "gnu"; - ArchiveToolType2["BSD"] = "bsd"; - })(ArchiveToolType || (exports2.ArchiveToolType = ArchiveToolType = {})); - exports2.DefaultRetryAttempts = 2; - exports2.DefaultRetryDelay = 5e3; - exports2.SocketTimeout = 5e3; - exports2.GnuTarPathOnWindows = `${process.env["PROGRAMFILES"]}\\Git\\usr\\bin\\tar.exe`; - exports2.SystemTarPathOnWindows = `${process.env["SYSTEMDRIVE"]}\\Windows\\System32\\tar.exe`; - exports2.TarFilename = "cache.tar"; - exports2.ManifestFilename = "manifest.txt"; - exports2.CacheFileSizeLimit = 10 * Math.pow(1024, 3); + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve9) => setTimeout(() => resolve9(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve9(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve9(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/cache/lib/internal/cacheUtils.js -var require_cacheUtils = __commonJS({ - "node_modules/@actions/cache/lib/internal/cacheUtils.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve9) { @@ -32483,182 +34095,76 @@ var require_cacheUtils = __commonJS({ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve9, reject) { - v = o[n](v), settle(resolve9, reject, v.done, v.value); - }); - }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - function settle(resolve9, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve9({ value: v2, done: d }); - }, reject); + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRuntimeToken = exports2.getCacheVersion = exports2.assertDefined = exports2.getGnuTarPathOnWindows = exports2.getCacheFileName = exports2.getCompressionMethod = exports2.unlinkFile = exports2.resolvePaths = exports2.getArchiveFileSizeInBytes = exports2.createTempDirectory = void 0; - var core14 = __importStar4(require_core()); - var exec2 = __importStar4(require_exec()); - var glob2 = __importStar4(require_glob()); - var io7 = __importStar4(require_io()); - var crypto2 = __importStar4(require("crypto")); - var fs15 = __importStar4(require("fs")); - var path16 = __importStar4(require("path")); - var semver9 = __importStar4(require_semver3()); - var util = __importStar4(require("util")); - var constants_1 = require_constants7(); - var versionSalt = "1.0"; - function createTempDirectory() { - return __awaiter4(this, void 0, void 0, function* () { - const IS_WINDOWS = process.platform === "win32"; - let tempDirectory = process.env["RUNNER_TEMP"] || ""; - if (!tempDirectory) { - let baseLocation; - if (IS_WINDOWS) { - baseLocation = process.env["USERPROFILE"] || "C:\\"; - } else { - if (process.platform === "darwin") { - baseLocation = "/Users"; - } else { - baseLocation = "/home"; - } - } - tempDirectory = path16.join(baseLocation, "actions", "temp"); + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } - const dest = path16.join(tempDirectory, crypto2.randomUUID()); - yield io7.mkdirP(dest); - return dest; - }); - } - exports2.createTempDirectory = createTempDirectory; - function getArchiveFileSizeInBytes(filePath) { - return fs15.statSync(filePath).size; - } - exports2.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; - function resolvePaths(patterns) { - var _a, e_1, _b, _c; - var _d; - return __awaiter4(this, void 0, void 0, function* () { - const paths = []; - const workspace = (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd(); - const globber = yield glob2.create(patterns.join("\n"), { - implicitDescendants: false + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); }); - try { - for (var _e = true, _f = __asyncValues4(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { - _c = _g.value; - _e = false; - const file = _c; - const relativeFile = path16.relative(workspace, file).replace(new RegExp(`\\${path16.sep}`, "g"), "/"); - core14.debug(`Matched: ${relativeFile}`); - if (relativeFile === "") { - paths.push("."); - } else { - paths.push(`${relativeFile}`); - } - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); - } finally { - if (e_1) throw e_1.error; - } - } - return paths; - }); - } - exports2.resolvePaths = resolvePaths; - function unlinkFile(filePath) { - return __awaiter4(this, void 0, void 0, function* () { - return util.promisify(fs15.unlink)(filePath); - }); - } - exports2.unlinkFile = unlinkFile; - function getVersion(app, additionalArgs = []) { - return __awaiter4(this, void 0, void 0, function* () { - let versionOutput = ""; - additionalArgs.push("--version"); - core14.debug(`Checking ${app} ${additionalArgs.join(" ")}`); - try { - yield exec2.exec(`${app}`, additionalArgs, { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() - } - }); - } catch (err) { - core14.debug(err.message); - } - versionOutput = versionOutput.trim(); - core14.debug(versionOutput); - return versionOutput; - }); - } - function getCompressionMethod() { - return __awaiter4(this, void 0, void 0, function* () { - const versionOutput = yield getVersion("zstd", ["--quiet"]); - const version = semver9.clean(versionOutput); - core14.debug(`zstd version: ${version}`); - if (versionOutput === "") { - return constants_1.CompressionMethod.Gzip; - } else { - return constants_1.CompressionMethod.ZstdWithoutLong; - } - }); - } - exports2.getCompressionMethod = getCompressionMethod; - function getCacheFileName(compressionMethod) { - return compressionMethod === constants_1.CompressionMethod.Gzip ? constants_1.CacheFilename.Gzip : constants_1.CacheFilename.Zstd; - } - exports2.getCacheFileName = getCacheFileName; - function getGnuTarPathOnWindows() { - return __awaiter4(this, void 0, void 0, function* () { - if (fs15.existsSync(constants_1.GnuTarPathOnWindows)) { - return constants_1.GnuTarPathOnWindows; - } - const versionOutput = yield getVersion("tar"); - return versionOutput.toLowerCase().includes("gnu tar") ? io7.which("tar") : ""; - }); - } - exports2.getGnuTarPathOnWindows = getGnuTarPathOnWindows; - function assertDefined(name, value) { - if (value === void 0) { - throw Error(`Expected ${name} but value was undefiend`); } - return value; - } - exports2.assertDefined = assertDefined; - function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) { - const components = paths.slice(); - if (compressionMethod) { - components.push(compressionMethod); + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; } - if (process.platform === "win32" && !enableCrossOsArchive) { - components.push("windows-only"); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; } - components.push(versionSalt); - return crypto2.createHash("sha256").update(components.join("|")).digest("hex"); - } - exports2.getCacheVersion = getCacheVersion; - function getRuntimeToken() { - const token = process.env["ACTIONS_RUNTIME_TOKEN"]; - if (!token) { - throw new Error("Unable to get the ACTIONS_RUNTIME_TOKEN env variable"); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - return token; - } - exports2.getRuntimeToken = getRuntimeToken; + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); @@ -68097,7 +69603,7 @@ var require_requestUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var constants_1 = require_constants7(); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -68265,7 +69771,7 @@ var require_downloadUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var storage_blob_1 = require_dist7(); var buffer = __importStar4(require("buffer")); var fs15 = __importStar4(require("fs")); @@ -68842,8 +70348,8 @@ var require_cacheHttpClient = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib4(); + var auth_1 = require_auth2(); var fs15 = __importStar4(require("fs")); var url_1 = require("url"); var utils = __importStar4(require_cacheUtils()); @@ -74049,8 +75555,8 @@ var require_cacheTwirpClient = __commonJS({ var errors_1 = require_errors2(); var config_1 = require_config(); var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib4(); var cache_twirp_client_1 = require_cache_twirp_client(); var util_1 = require_util10(); var CacheServiceClient = class { @@ -74498,7 +76004,7 @@ var require_cache3 = __commonJS({ var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); var config_1 = require_config(); var tar_1 = require_tar(); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var ValidationError = class _ValidationError extends Error { constructor(message) { super(message); @@ -75055,34 +76561,443 @@ var require_internal_path_helper2 = __commonJS({ if (p === path16.sep) { return p; } - if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { - return p; + if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { + return p; + } + return p.substr(0, p.length - 1); + } + exports2.safeTrimTrailingSeparator = safeTrimTrailingSeparator; + } +}); + +// node_modules/@actions/glob/lib/internal-match-kind.js +var require_internal_match_kind2 = __commonJS({ + "node_modules/@actions/glob/lib/internal-match-kind.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MatchKind = void 0; + var MatchKind; + (function(MatchKind2) { + MatchKind2[MatchKind2["None"] = 0] = "None"; + MatchKind2[MatchKind2["Directory"] = 1] = "Directory"; + MatchKind2[MatchKind2["File"] = 2] = "File"; + MatchKind2[MatchKind2["All"] = 3] = "All"; + })(MatchKind || (exports2.MatchKind = MatchKind = {})); + } +}); + +// node_modules/@actions/glob/lib/internal-pattern-helper.js +var require_internal_pattern_helper2 = __commonJS({ + "node_modules/@actions/glob/lib/internal-pattern-helper.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.partialMatch = exports2.match = exports2.getSearchPaths = void 0; + var pathHelper = __importStar4(require_internal_path_helper2()); + var internal_match_kind_1 = require_internal_match_kind2(); + var IS_WINDOWS = process.platform === "win32"; + function getSearchPaths(patterns) { + patterns = patterns.filter((x) => !x.negate); + const searchPathMap = {}; + for (const pattern of patterns) { + const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; + searchPathMap[key] = "candidate"; + } + const result = []; + for (const pattern of patterns) { + const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; + if (searchPathMap[key] === "included") { + continue; + } + let foundAncestor = false; + let tempKey = key; + let parent = pathHelper.dirname(tempKey); + while (parent !== tempKey) { + if (searchPathMap[parent]) { + foundAncestor = true; + break; + } + tempKey = parent; + parent = pathHelper.dirname(tempKey); + } + if (!foundAncestor) { + result.push(pattern.searchPath); + searchPathMap[key] = "included"; + } + } + return result; + } + exports2.getSearchPaths = getSearchPaths; + function match(patterns, itemPath) { + let result = internal_match_kind_1.MatchKind.None; + for (const pattern of patterns) { + if (pattern.negate) { + result &= ~pattern.match(itemPath); + } else { + result |= pattern.match(itemPath); + } + } + return result; + } + exports2.match = match; + function partialMatch(patterns, itemPath) { + return patterns.some((x) => !x.negate && x.partialMatch(itemPath)); + } + exports2.partialMatch = partialMatch; + } +}); + +// node_modules/@actions/glob/lib/internal-path.js +var require_internal_path2 = __commonJS({ + "node_modules/@actions/glob/lib/internal-path.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Path = void 0; + var path16 = __importStar4(require("path")); + var pathHelper = __importStar4(require_internal_path_helper2()); + var assert_1 = __importDefault4(require("assert")); + var IS_WINDOWS = process.platform === "win32"; + var Path = class { + /** + * Constructs a Path + * @param itemPath Path or array of segments + */ + constructor(itemPath) { + this.segments = []; + if (typeof itemPath === "string") { + (0, assert_1.default)(itemPath, `Parameter 'itemPath' must not be empty`); + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + if (!pathHelper.hasRoot(itemPath)) { + this.segments = itemPath.split(path16.sep); + } else { + let remaining = itemPath; + let dir = pathHelper.dirname(remaining); + while (dir !== remaining) { + const basename = path16.basename(remaining); + this.segments.unshift(basename); + remaining = dir; + dir = pathHelper.dirname(remaining); + } + this.segments.unshift(remaining); + } + } else { + (0, assert_1.default)(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + for (let i = 0; i < itemPath.length; i++) { + let segment = itemPath[i]; + (0, assert_1.default)(segment, `Parameter 'itemPath' must not contain any empty segments`); + segment = pathHelper.normalizeSeparators(itemPath[i]); + if (i === 0 && pathHelper.hasRoot(segment)) { + segment = pathHelper.safeTrimTrailingSeparator(segment); + (0, assert_1.default)(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + this.segments.push(segment); + } else { + (0, assert_1.default)(!segment.includes(path16.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); + } + } + } + } + /** + * Converts the path to it's string representation + */ + toString() { + let result = this.segments[0]; + let skipSlash = result.endsWith(path16.sep) || IS_WINDOWS && /^[A-Z]:$/i.test(result); + for (let i = 1; i < this.segments.length; i++) { + if (skipSlash) { + skipSlash = false; + } else { + result += path16.sep; + } + result += this.segments[i]; + } + return result; + } + }; + exports2.Path = Path; + } +}); + +// node_modules/@actions/glob/lib/internal-pattern.js +var require_internal_pattern2 = __commonJS({ + "node_modules/@actions/glob/lib/internal-pattern.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Pattern = void 0; + var os5 = __importStar4(require("os")); + var path16 = __importStar4(require("path")); + var pathHelper = __importStar4(require_internal_path_helper2()); + var assert_1 = __importDefault4(require("assert")); + var minimatch_1 = require_minimatch(); + var internal_match_kind_1 = require_internal_match_kind2(); + var internal_path_1 = require_internal_path2(); + var IS_WINDOWS = process.platform === "win32"; + var Pattern = class _Pattern { + constructor(patternOrNegate, isImplicitPattern = false, segments, homedir2) { + this.negate = false; + let pattern; + if (typeof patternOrNegate === "string") { + pattern = patternOrNegate.trim(); + } else { + segments = segments || []; + (0, assert_1.default)(segments.length, `Parameter 'segments' must not empty`); + const root = _Pattern.getLiteral(segments[0]); + (0, assert_1.default)(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + pattern = new internal_path_1.Path(segments).toString().trim(); + if (patternOrNegate) { + pattern = `!${pattern}`; + } + } + while (pattern.startsWith("!")) { + this.negate = !this.negate; + pattern = pattern.substr(1).trim(); + } + pattern = _Pattern.fixupPattern(pattern, homedir2); + this.segments = new internal_path_1.Path(pattern).segments; + this.trailingSeparator = pathHelper.normalizeSeparators(pattern).endsWith(path16.sep); + pattern = pathHelper.safeTrimTrailingSeparator(pattern); + let foundGlob = false; + const searchSegments = this.segments.map((x) => _Pattern.getLiteral(x)).filter((x) => !foundGlob && !(foundGlob = x === "")); + this.searchPath = new internal_path_1.Path(searchSegments).toString(); + this.rootRegExp = new RegExp(_Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? "i" : ""); + this.isImplicitPattern = isImplicitPattern; + const minimatchOptions = { + dot: true, + nobrace: true, + nocase: IS_WINDOWS, + nocomment: true, + noext: true, + nonegate: true + }; + pattern = IS_WINDOWS ? pattern.replace(/\\/g, "/") : pattern; + this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); + } + /** + * Matches the pattern against the specified path + */ + match(itemPath) { + if (this.segments[this.segments.length - 1] === "**") { + itemPath = pathHelper.normalizeSeparators(itemPath); + if (!itemPath.endsWith(path16.sep) && this.isImplicitPattern === false) { + itemPath = `${itemPath}${path16.sep}`; + } + } else { + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + } + if (this.minimatch.match(itemPath)) { + return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; + } + return internal_match_kind_1.MatchKind.None; + } + /** + * Indicates whether the pattern may match descendants of the specified path + */ + partialMatch(itemPath) { + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + if (pathHelper.dirname(itemPath) === itemPath) { + return this.rootRegExp.test(itemPath); + } + return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); + } + /** + * Escapes glob patterns within a path + */ + static globEscape(s) { + return (IS_WINDOWS ? s : s.replace(/\\/g, "\\\\")).replace(/(\[)(?=[^/]+\])/g, "[[]").replace(/\?/g, "[?]").replace(/\*/g, "[*]"); + } + /** + * Normalizes slashes and ensures absolute root + */ + static fixupPattern(pattern, homedir2) { + (0, assert_1.default)(pattern, "pattern cannot be empty"); + const literalSegments = new internal_path_1.Path(pattern).segments.map((x) => _Pattern.getLiteral(x)); + (0, assert_1.default)(literalSegments.every((x, i) => (x !== "." || i === 0) && x !== ".."), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + (0, assert_1.default)(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + pattern = pathHelper.normalizeSeparators(pattern); + if (pattern === "." || pattern.startsWith(`.${path16.sep}`)) { + pattern = _Pattern.globEscape(process.cwd()) + pattern.substr(1); + } else if (pattern === "~" || pattern.startsWith(`~${path16.sep}`)) { + homedir2 = homedir2 || os5.homedir(); + (0, assert_1.default)(homedir2, "Unable to determine HOME directory"); + (0, assert_1.default)(pathHelper.hasAbsoluteRoot(homedir2), `Expected HOME directory to be a rooted path. Actual '${homedir2}'`); + pattern = _Pattern.globEscape(homedir2) + pattern.substr(1); + } else if (IS_WINDOWS && (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { + let root = pathHelper.ensureAbsoluteRoot("C:\\dummy-root", pattern.substr(0, 2)); + if (pattern.length > 2 && !root.endsWith("\\")) { + root += "\\"; + } + pattern = _Pattern.globEscape(root) + pattern.substr(2); + } else if (IS_WINDOWS && (pattern === "\\" || pattern.match(/^\\[^\\]/))) { + let root = pathHelper.ensureAbsoluteRoot("C:\\dummy-root", "\\"); + if (!root.endsWith("\\")) { + root += "\\"; + } + pattern = _Pattern.globEscape(root) + pattern.substr(1); + } else { + pattern = pathHelper.ensureAbsoluteRoot(_Pattern.globEscape(process.cwd()), pattern); + } + return pathHelper.normalizeSeparators(pattern); + } + /** + * Attempts to unescape a pattern segment to create a literal path segment. + * Otherwise returns empty string. + */ + static getLiteral(segment) { + let literal = ""; + for (let i = 0; i < segment.length; i++) { + const c = segment[i]; + if (c === "\\" && !IS_WINDOWS && i + 1 < segment.length) { + literal += segment[++i]; + continue; + } else if (c === "*" || c === "?") { + return ""; + } else if (c === "[" && i + 1 < segment.length) { + let set2 = ""; + let closed = -1; + for (let i2 = i + 1; i2 < segment.length; i2++) { + const c2 = segment[i2]; + if (c2 === "\\" && !IS_WINDOWS && i2 + 1 < segment.length) { + set2 += segment[++i2]; + continue; + } else if (c2 === "]") { + closed = i2; + break; + } else { + set2 += c2; + } + } + if (closed >= 0) { + if (set2.length > 1) { + return ""; + } + if (set2) { + literal += set2; + i = closed; + continue; + } + } + } + literal += c; + } + return literal; + } + /** + * Escapes regexp special characters + * https://javascript.info/regexp-escaping + */ + static regExpEscape(s) { + return s.replace(/[[\\^$.|?*+()]/g, "\\$&"); } - return p.substr(0, p.length - 1); - } - exports2.safeTrimTrailingSeparator = safeTrimTrailingSeparator; + }; + exports2.Pattern = Pattern; } }); -// node_modules/@actions/glob/lib/internal-match-kind.js -var require_internal_match_kind2 = __commonJS({ - "node_modules/@actions/glob/lib/internal-match-kind.js"(exports2) { +// node_modules/@actions/glob/lib/internal-search-state.js +var require_internal_search_state2 = __commonJS({ + "node_modules/@actions/glob/lib/internal-search-state.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MatchKind = void 0; - var MatchKind; - (function(MatchKind2) { - MatchKind2[MatchKind2["None"] = 0] = "None"; - MatchKind2[MatchKind2["Directory"] = 1] = "Directory"; - MatchKind2[MatchKind2["File"] = 2] = "File"; - MatchKind2[MatchKind2["All"] = 3] = "All"; - })(MatchKind || (exports2.MatchKind = MatchKind = {})); + exports2.SearchState = void 0; + var SearchState = class { + constructor(path16, level) { + this.path = path16; + this.level = level; + } + }; + exports2.SearchState = SearchState; } }); -// node_modules/@actions/glob/lib/internal-pattern-helper.js -var require_internal_pattern_helper2 = __commonJS({ - "node_modules/@actions/glob/lib/internal-pattern-helper.js"(exports2) { +// node_modules/@actions/glob/lib/internal-globber.js +var require_internal_globber2 = __commonJS({ + "node_modules/@actions/glob/lib/internal-globber.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -75111,65 +77026,250 @@ var require_internal_pattern_helper2 = __commonJS({ __setModuleDefault4(result, mod); return result; }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.partialMatch = exports2.match = exports2.getSearchPaths = void 0; - var pathHelper = __importStar4(require_internal_path_helper2()); - var internal_match_kind_1 = require_internal_match_kind2(); - var IS_WINDOWS = process.platform === "win32"; - function getSearchPaths(patterns) { - patterns = patterns.filter((x) => !x.negate); - const searchPathMap = {}; - for (const pattern of patterns) { - const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; - searchPathMap[key] = "candidate"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve9) { + resolve9(value); + }); } - const result = []; - for (const pattern of patterns) { - const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; - if (searchPathMap[key] === "included") { - continue; + return new (P || (P = Promise))(function(resolve9, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - let foundAncestor = false; - let tempKey = key; - let parent = pathHelper.dirname(tempKey); - while (parent !== tempKey) { - if (searchPathMap[parent]) { - foundAncestor = true; - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - tempKey = parent; - parent = pathHelper.dirname(tempKey); } - if (!foundAncestor) { - result.push(pattern.searchPath); - searchPathMap[key] = "included"; + function step(result) { + result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve9, reject) { + v = o[n](v), settle(resolve9, reject, v.done, v.value); + }); + }; } - return result; - } - exports2.getSearchPaths = getSearchPaths; - function match(patterns, itemPath) { - let result = internal_match_kind_1.MatchKind.None; - for (const pattern of patterns) { - if (pattern.negate) { - result &= ~pattern.match(itemPath); - } else { - result |= pattern.match(itemPath); + function settle(resolve9, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve9({ value: v2, done: d }); + }, reject); + } + }; + var __await4 = exports2 && exports2.__await || function(v) { + return this instanceof __await4 ? (this.v = v, this) : new __await4(v); + }; + var __asyncGenerator4 = exports2 && exports2.__asyncGenerator || function(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function verb(n) { + if (g[n]) i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); } } - return result; - } - exports2.match = match; - function partialMatch(patterns, itemPath) { - return patterns.some((x) => !x.negate && x.partialMatch(itemPath)); - } - exports2.partialMatch = partialMatch; + function step(r) { + r.value instanceof __await4 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DefaultGlobber = void 0; + var core14 = __importStar4(require_core()); + var fs15 = __importStar4(require("fs")); + var globOptionsHelper = __importStar4(require_internal_glob_options_helper2()); + var path16 = __importStar4(require("path")); + var patternHelper = __importStar4(require_internal_pattern_helper2()); + var internal_match_kind_1 = require_internal_match_kind2(); + var internal_pattern_1 = require_internal_pattern2(); + var internal_search_state_1 = require_internal_search_state2(); + var IS_WINDOWS = process.platform === "win32"; + var DefaultGlobber = class _DefaultGlobber { + constructor(options) { + this.patterns = []; + this.searchPaths = []; + this.options = globOptionsHelper.getOptions(options); + } + getSearchPaths() { + return this.searchPaths.slice(); + } + glob() { + var _a, e_1, _b, _c; + return __awaiter4(this, void 0, void 0, function* () { + const result = []; + try { + for (var _d = true, _e = __asyncValues4(this.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const itemPath = _c; + result.push(itemPath); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); + } finally { + if (e_1) throw e_1.error; + } + } + return result; + }); + } + globGenerator() { + return __asyncGenerator4(this, arguments, function* globGenerator_1() { + const options = globOptionsHelper.getOptions(this.options); + const patterns = []; + for (const pattern of this.patterns) { + patterns.push(pattern); + if (options.implicitDescendants && (pattern.trailingSeparator || pattern.segments[pattern.segments.length - 1] !== "**")) { + patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat("**"))); + } + } + const stack = []; + for (const searchPath of patternHelper.getSearchPaths(patterns)) { + core14.debug(`Search path '${searchPath}'`); + try { + yield __await4(fs15.promises.lstat(searchPath)); + } catch (err) { + if (err.code === "ENOENT") { + continue; + } + throw err; + } + stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); + } + const traversalChain = []; + while (stack.length) { + const item = stack.pop(); + const match = patternHelper.match(patterns, item.path); + const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); + if (!match && !partialMatch) { + continue; + } + const stats = yield __await4( + _DefaultGlobber.stat(item, options, traversalChain) + // Broken symlink, or symlink cycle detected, or no longer exists + ); + if (!stats) { + continue; + } + if (options.excludeHiddenFiles && path16.basename(item.path).match(/^\./)) { + continue; + } + if (stats.isDirectory()) { + if (match & internal_match_kind_1.MatchKind.Directory && options.matchDirectories) { + yield yield __await4(item.path); + } else if (!partialMatch) { + continue; + } + const childLevel = item.level + 1; + const childItems = (yield __await4(fs15.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path16.join(item.path, x), childLevel)); + stack.push(...childItems.reverse()); + } else if (match & internal_match_kind_1.MatchKind.File) { + yield yield __await4(item.path); + } + } + }); + } + /** + * Constructs a DefaultGlobber + */ + static create(patterns, options) { + return __awaiter4(this, void 0, void 0, function* () { + const result = new _DefaultGlobber(options); + if (IS_WINDOWS) { + patterns = patterns.replace(/\r\n/g, "\n"); + patterns = patterns.replace(/\r/g, "\n"); + } + const lines = patterns.split("\n").map((x) => x.trim()); + for (const line of lines) { + if (!line || line.startsWith("#")) { + continue; + } else { + result.patterns.push(new internal_pattern_1.Pattern(line)); + } + } + result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); + return result; + }); + } + static stat(item, options, traversalChain) { + return __awaiter4(this, void 0, void 0, function* () { + let stats; + if (options.followSymbolicLinks) { + try { + stats = yield fs15.promises.stat(item.path); + } catch (err) { + if (err.code === "ENOENT") { + if (options.omitBrokenSymbolicLinks) { + core14.debug(`Broken symlink '${item.path}'`); + return void 0; + } + throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); + } + throw err; + } + } else { + stats = yield fs15.promises.lstat(item.path); + } + if (stats.isDirectory() && options.followSymbolicLinks) { + const realPath = yield fs15.promises.realpath(item.path); + while (traversalChain.length >= item.level) { + traversalChain.pop(); + } + if (traversalChain.some((x) => x === realPath)) { + core14.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); + return void 0; + } + traversalChain.push(realPath); + } + return stats; + }); + } + }; + exports2.DefaultGlobber = DefaultGlobber; } }); -// node_modules/@actions/glob/lib/internal-path.js -var require_internal_path2 = __commonJS({ - "node_modules/@actions/glob/lib/internal-path.js"(exports2) { +// node_modules/@actions/glob/lib/internal-hash-files.js +var require_internal_hash_files = __commonJS({ + "node_modules/@actions/glob/lib/internal-hash-files.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -75198,79 +77298,173 @@ var require_internal_path2 = __commonJS({ __setModuleDefault4(result, mod); return result; }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve9) { + resolve9(value); + }); + } + return new (P || (P = Promise))(function(resolve9, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve9, reject) { + v = o[n](v), settle(resolve9, reject, v.done, v.value); + }); + }; + } + function settle(resolve9, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve9({ value: v2, done: d }); + }, reject); + } }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Path = void 0; + exports2.hashFiles = void 0; + var crypto2 = __importStar4(require("crypto")); + var core14 = __importStar4(require_core()); + var fs15 = __importStar4(require("fs")); + var stream2 = __importStar4(require("stream")); + var util = __importStar4(require("util")); var path16 = __importStar4(require("path")); - var pathHelper = __importStar4(require_internal_path_helper2()); - var assert_1 = __importDefault4(require("assert")); - var IS_WINDOWS = process.platform === "win32"; - var Path = class { - /** - * Constructs a Path - * @param itemPath Path or array of segments - */ - constructor(itemPath) { - this.segments = []; - if (typeof itemPath === "string") { - (0, assert_1.default)(itemPath, `Parameter 'itemPath' must not be empty`); - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - if (!pathHelper.hasRoot(itemPath)) { - this.segments = itemPath.split(path16.sep); - } else { - let remaining = itemPath; - let dir = pathHelper.dirname(remaining); - while (dir !== remaining) { - const basename = path16.basename(remaining); - this.segments.unshift(basename); - remaining = dir; - dir = pathHelper.dirname(remaining); + function hashFiles2(globber, currentWorkspace, verbose = false) { + var _a, e_1, _b, _c; + var _d; + return __awaiter4(this, void 0, void 0, function* () { + const writeDelegate = verbose ? core14.info : core14.debug; + let hasMatch = false; + const githubWorkspace = currentWorkspace ? currentWorkspace : (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd(); + const result = crypto2.createHash("sha256"); + let count = 0; + try { + for (var _e = true, _f = __asyncValues4(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { + _c = _g.value; + _e = false; + const file = _c; + writeDelegate(file); + if (!file.startsWith(`${githubWorkspace}${path16.sep}`)) { + writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); + continue; } - this.segments.unshift(remaining); + if (fs15.statSync(file).isDirectory()) { + writeDelegate(`Skip directory '${file}'.`); + continue; + } + const hash = crypto2.createHash("sha256"); + const pipeline = util.promisify(stream2.pipeline); + yield pipeline(fs15.createReadStream(file), hash); + result.write(hash.digest()); + count++; + if (!hasMatch) { + hasMatch = true; + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); + } finally { + if (e_1) throw e_1.error; } + } + result.end(); + if (hasMatch) { + writeDelegate(`Found ${count} files to hash.`); + return result.digest("hex"); } else { - (0, assert_1.default)(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); - for (let i = 0; i < itemPath.length; i++) { - let segment = itemPath[i]; - (0, assert_1.default)(segment, `Parameter 'itemPath' must not contain any empty segments`); - segment = pathHelper.normalizeSeparators(itemPath[i]); - if (i === 0 && pathHelper.hasRoot(segment)) { - segment = pathHelper.safeTrimTrailingSeparator(segment); - (0, assert_1.default)(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); - this.segments.push(segment); - } else { - (0, assert_1.default)(!segment.includes(path16.sep), `Parameter 'itemPath' contains unexpected path separators`); - this.segments.push(segment); - } + writeDelegate(`No matches found for glob`); + return ""; + } + }); + } + exports2.hashFiles = hashFiles2; + } +}); + +// node_modules/@actions/glob/lib/glob.js +var require_glob2 = __commonJS({ + "node_modules/@actions/glob/lib/glob.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve9) { + resolve9(value); + }); + } + return new (P || (P = Promise))(function(resolve9, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - } - /** - * Converts the path to it's string representation - */ - toString() { - let result = this.segments[0]; - let skipSlash = result.endsWith(path16.sep) || IS_WINDOWS && /^[A-Z]:$/i.test(result); - for (let i = 1; i < this.segments.length; i++) { - if (skipSlash) { - skipSlash = false; - } else { - result += path16.sep; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - result += this.segments[i]; } - return result; - } + function step(result) { + result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - exports2.Path = Path; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.hashFiles = exports2.create = void 0; + var internal_globber_1 = require_internal_globber2(); + var internal_hash_files_1 = require_internal_hash_files(); + function create2(patterns, options) { + return __awaiter4(this, void 0, void 0, function* () { + return yield internal_globber_1.DefaultGlobber.create(patterns, options); + }); + } + exports2.create = create2; + function hashFiles2(patterns, currentWorkspace = "", options, verbose = false) { + return __awaiter4(this, void 0, void 0, function* () { + let followSymbolicLinks = true; + if (options && typeof options.followSymbolicLinks === "boolean") { + followSymbolicLinks = options.followSymbolicLinks; + } + const globber = yield create2(patterns, { followSymbolicLinks }); + return (0, internal_hash_files_1.hashFiles)(globber, currentWorkspace, verbose); + }); + } + exports2.hashFiles = hashFiles2; } }); -// node_modules/@actions/glob/lib/internal-pattern.js -var require_internal_pattern2 = __commonJS({ - "node_modules/@actions/glob/lib/internal-pattern.js"(exports2) { +// node_modules/@actions/tool-cache/lib/manifest.js +var require_manifest = __commonJS({ + "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -75299,199 +77493,199 @@ var require_internal_pattern2 = __commonJS({ __setModuleDefault4(result, mod); return result; }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Pattern = void 0; - var os5 = __importStar4(require("os")); - var path16 = __importStar4(require("path")); - var pathHelper = __importStar4(require_internal_path_helper2()); - var assert_1 = __importDefault4(require("assert")); - var minimatch_1 = require_minimatch(); - var internal_match_kind_1 = require_internal_match_kind2(); - var internal_path_1 = require_internal_path2(); - var IS_WINDOWS = process.platform === "win32"; - var Pattern = class _Pattern { - constructor(patternOrNegate, isImplicitPattern = false, segments, homedir2) { - this.negate = false; - let pattern; - if (typeof patternOrNegate === "string") { - pattern = patternOrNegate.trim(); - } else { - segments = segments || []; - (0, assert_1.default)(segments.length, `Parameter 'segments' must not empty`); - const root = _Pattern.getLiteral(segments[0]); - (0, assert_1.default)(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); - pattern = new internal_path_1.Path(segments).toString().trim(); - if (patternOrNegate) { - pattern = `!${pattern}`; - } - } - while (pattern.startsWith("!")) { - this.negate = !this.negate; - pattern = pattern.substr(1).trim(); - } - pattern = _Pattern.fixupPattern(pattern, homedir2); - this.segments = new internal_path_1.Path(pattern).segments; - this.trailingSeparator = pathHelper.normalizeSeparators(pattern).endsWith(path16.sep); - pattern = pathHelper.safeTrimTrailingSeparator(pattern); - let foundGlob = false; - const searchSegments = this.segments.map((x) => _Pattern.getLiteral(x)).filter((x) => !foundGlob && !(foundGlob = x === "")); - this.searchPath = new internal_path_1.Path(searchSegments).toString(); - this.rootRegExp = new RegExp(_Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? "i" : ""); - this.isImplicitPattern = isImplicitPattern; - const minimatchOptions = { - dot: true, - nobrace: true, - nocase: IS_WINDOWS, - nocomment: true, - noext: true, - nonegate: true - }; - pattern = IS_WINDOWS ? pattern.replace(/\\/g, "/") : pattern; - this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve9) { + resolve9(value); + }); } - /** - * Matches the pattern against the specified path - */ - match(itemPath) { - if (this.segments[this.segments.length - 1] === "**") { - itemPath = pathHelper.normalizeSeparators(itemPath); - if (!itemPath.endsWith(path16.sep) && this.isImplicitPattern === false) { - itemPath = `${itemPath}${path16.sep}`; + return new (P || (P = Promise))(function(resolve9, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - } else { - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - } - if (this.minimatch.match(itemPath)) { - return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; - } - return internal_match_kind_1.MatchKind.None; - } - /** - * Indicates whether the pattern may match descendants of the specified path - */ - partialMatch(itemPath) { - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - if (pathHelper.dirname(itemPath) === itemPath) { - return this.rootRegExp.test(itemPath); } - return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); - } - /** - * Escapes glob patterns within a path - */ - static globEscape(s) { - return (IS_WINDOWS ? s : s.replace(/\\/g, "\\\\")).replace(/(\[)(?=[^/]+\])/g, "[[]").replace(/\?/g, "[?]").replace(/\*/g, "[*]"); - } - /** - * Normalizes slashes and ensures absolute root - */ - static fixupPattern(pattern, homedir2) { - (0, assert_1.default)(pattern, "pattern cannot be empty"); - const literalSegments = new internal_path_1.Path(pattern).segments.map((x) => _Pattern.getLiteral(x)); - (0, assert_1.default)(literalSegments.every((x, i) => (x !== "." || i === 0) && x !== ".."), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); - (0, assert_1.default)(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); - pattern = pathHelper.normalizeSeparators(pattern); - if (pattern === "." || pattern.startsWith(`.${path16.sep}`)) { - pattern = _Pattern.globEscape(process.cwd()) + pattern.substr(1); - } else if (pattern === "~" || pattern.startsWith(`~${path16.sep}`)) { - homedir2 = homedir2 || os5.homedir(); - (0, assert_1.default)(homedir2, "Unable to determine HOME directory"); - (0, assert_1.default)(pathHelper.hasAbsoluteRoot(homedir2), `Expected HOME directory to be a rooted path. Actual '${homedir2}'`); - pattern = _Pattern.globEscape(homedir2) + pattern.substr(1); - } else if (IS_WINDOWS && (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { - let root = pathHelper.ensureAbsoluteRoot("C:\\dummy-root", pattern.substr(0, 2)); - if (pattern.length > 2 && !root.endsWith("\\")) { - root += "\\"; - } - pattern = _Pattern.globEscape(root) + pattern.substr(2); - } else if (IS_WINDOWS && (pattern === "\\" || pattern.match(/^\\[^\\]/))) { - let root = pathHelper.ensureAbsoluteRoot("C:\\dummy-root", "\\"); - if (!root.endsWith("\\")) { - root += "\\"; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - pattern = _Pattern.globEscape(root) + pattern.substr(1); - } else { - pattern = pathHelper.ensureAbsoluteRoot(_Pattern.globEscape(process.cwd()), pattern); } - return pathHelper.normalizeSeparators(pattern); - } - /** - * Attempts to unescape a pattern segment to create a literal path segment. - * Otherwise returns empty string. - */ - static getLiteral(segment) { - let literal = ""; - for (let i = 0; i < segment.length; i++) { - const c = segment[i]; - if (c === "\\" && !IS_WINDOWS && i + 1 < segment.length) { - literal += segment[++i]; - continue; - } else if (c === "*" || c === "?") { - return ""; - } else if (c === "[" && i + 1 < segment.length) { - let set2 = ""; - let closed = -1; - for (let i2 = i + 1; i2 < segment.length; i2++) { - const c2 = segment[i2]; - if (c2 === "\\" && !IS_WINDOWS && i2 + 1 < segment.length) { - set2 += segment[++i2]; - continue; - } else if (c2 === "]") { - closed = i2; - break; - } else { - set2 += c2; + function step(result) { + result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; + var semver9 = __importStar4(require_semver2()); + var core_1 = require_core(); + var os5 = require("os"); + var cp = require("child_process"); + var fs15 = require("fs"); + function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os5.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); + if (semver9.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + file = candidate.files.find((item) => { + (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module2.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } else { + chk = semver9.satisfies(osVersion, item.platform_version); + } } + return chk; + }); + if (file) { + (0, core_1.debug)(`matched ${candidate.version}`); + match = candidate; + break; } - if (closed >= 0) { - if (set2.length > 1) { - return ""; - } - if (set2) { - literal += set2; - i = closed; - continue; - } + } + } + if (match && file) { + result = Object.assign({}, match); + result.files = [file]; + } + return result; + }); + } + exports2._findMatch = _findMatch; + function _getOsVersion() { + const plat = os5.platform(); + let version = ""; + if (plat === "darwin") { + version = cp.execSync("sw_vers -productVersion").toString(); + } else if (plat === "linux") { + const lsbContents = module2.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split("\n"); + for (const line of lines) { + const parts = line.split("="); + if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { + version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); + break; } } - literal += c; } - return literal; } - /** - * Escapes regexp special characters - * https://javascript.info/regexp-escaping - */ - static regExpEscape(s) { - return s.replace(/[[\\^$.|?*+()]/g, "\\$&"); + return version; + } + exports2._getOsVersion = _getOsVersion; + function _readLinuxVersionFile() { + const lsbReleaseFile = "/etc/lsb-release"; + const osReleaseFile = "/etc/os-release"; + let contents = ""; + if (fs15.existsSync(lsbReleaseFile)) { + contents = fs15.readFileSync(lsbReleaseFile).toString(); + } else if (fs15.existsSync(osReleaseFile)) { + contents = fs15.readFileSync(osReleaseFile).toString(); } - }; - exports2.Pattern = Pattern; + return contents; + } + exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/glob/lib/internal-search-state.js -var require_internal_search_state2 = __commonJS({ - "node_modules/@actions/glob/lib/internal-search-state.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SearchState = void 0; - var SearchState = class { - constructor(path16, level) { - this.path = path16; - this.level = level; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; } }; - exports2.SearchState = SearchState; } }); -// node_modules/@actions/glob/lib/internal-globber.js -var require_internal_globber2 = __commonJS({ - "node_modules/@actions/glob/lib/internal-globber.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -75533,237 +77727,584 @@ var require_internal_globber2 = __commonJS({ } catch (e) { reject(e); } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); + } + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve9(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve9(Buffer.concat(chunks)); + }); + })); + }); + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - function step(result) { - result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve9, reject) { - v = o[n](v), settle(resolve9, reject, v.done, v.value); - }); - }; } - function settle(resolve9, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve9({ value: v2, done: d }); - }, reject); + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - var __await4 = exports2 && exports2.__await || function(v) { - return this instanceof __await4 ? (this.v = v, this) : new __await4(v); - }; - var __asyncGenerator4 = exports2 && exports2.__asyncGenerator || function(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function verb(n) { - if (g[n]) i[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - function step(r) { - r.value instanceof __await4 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - function fulfill(value) { - resume("next", value); + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - function reject(value) { - resume("throw", value); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DefaultGlobber = void 0; - var core14 = __importStar4(require_core()); - var fs15 = __importStar4(require("fs")); - var globOptionsHelper = __importStar4(require_internal_glob_options_helper2()); - var path16 = __importStar4(require("path")); - var patternHelper = __importStar4(require_internal_pattern_helper2()); - var internal_match_kind_1 = require_internal_match_kind2(); - var internal_pattern_1 = require_internal_pattern2(); - var internal_search_state_1 = require_internal_search_state2(); - var IS_WINDOWS = process.platform === "win32"; - var DefaultGlobber = class _DefaultGlobber { - constructor(options) { - this.patterns = []; - this.searchPaths = []; - this.options = globOptionsHelper.getOptions(options); + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - getSearchPaths() { - return this.searchPaths.slice(); + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - glob() { - var _a, e_1, _b, _c; + postJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter4(this, void 0, void 0, function* () { - const result = []; - try { - for (var _d = true, _e = __asyncValues4(this.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const itemPath = _c; - result.push(itemPath); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); - } finally { - if (e_1) throw e_1.error; - } - } - return result; + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); } - globGenerator() { - return __asyncGenerator4(this, arguments, function* globGenerator_1() { - const options = globOptionsHelper.getOptions(this.options); - const patterns = []; - for (const pattern of this.patterns) { - patterns.push(pattern); - if (options.implicitDescendants && (pattern.trailingSeparator || pattern.segments[pattern.segments.length - 1] !== "**")) { - patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat("**"))); - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - const stack = []; - for (const searchPath of patternHelper.getSearchPaths(patterns)) { - core14.debug(`Search path '${searchPath}'`); - try { - yield __await4(fs15.promises.lstat(searchPath)); - } catch (err) { - if (err.code === "ENOENT") { - continue; + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; } - throw err; } - stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); - } - const traversalChain = []; - while (stack.length) { - const item = stack.pop(); - const match = patternHelper.match(patterns, item.path); - const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); - if (!match && !partialMatch) { - continue; + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; } - const stats = yield __await4( - _DefaultGlobber.stat(item, options, traversalChain) - // Broken symlink, or symlink cycle detected, or no longer exists - ); - if (!stats) { - continue; + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - if (options.excludeHiddenFiles && path16.basename(item.path).match(/^\./)) { - continue; + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); } - if (stats.isDirectory()) { - if (match & internal_match_kind_1.MatchKind.Directory && options.matchDirectories) { - yield yield __await4(item.path); - } else if (!partialMatch) { - continue; + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve9(res); } - const childLevel = item.level + 1; - const childItems = (yield __await4(fs15.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path16.join(item.path, x), childLevel)); - stack.push(...childItems.reverse()); - } else if (match & internal_match_kind_1.MatchKind.File) { - yield yield __await4(item.path); } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } /** - * Constructs a DefaultGlobber + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ - static create(patterns, options) { - return __awaiter4(this, void 0, void 0, function* () { - const result = new _DefaultGlobber(options); - if (IS_WINDOWS) { - patterns = patterns.replace(/\r\n/g, "\n"); - patterns = patterns.replace(/\r/g, "\n"); + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - const lines = patterns.split("\n").map((x) => x.trim()); - for (const line of lines) { - if (!line || line.startsWith("#")) { - continue; - } else { - result.patterns.push(new internal_pattern_1.Pattern(line)); - } + } + return info6; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } - result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); - return result; + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve9) => setTimeout(() => resolve9(), ms)); }); } - static stat(item, options, traversalChain) { + _processResponse(res, options) { return __awaiter4(this, void 0, void 0, function* () { - let stats; - if (options.followSymbolicLinks) { - try { - stats = yield fs15.promises.stat(item.path); - } catch (err) { - if (err.code === "ENOENT") { - if (options.omitBrokenSymbolicLinks) { - core14.debug(`Broken symlink '${item.path}'`); - return void 0; + return new Promise((resolve9, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve9(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; } - throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); } - throw err; + return value; } - } else { - stats = yield fs15.promises.lstat(item.path); - } - if (stats.isDirectory() && options.followSymbolicLinks) { - const realPath = yield fs15.promises.realpath(item.path); - while (traversalChain.length >= item.level) { - traversalChain.pop(); + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { } - if (traversalChain.some((x) => x === realPath)) { - core14.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); - return void 0; + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve9(response); } - traversalChain.push(realPath); - } - return stats; + })); }); } }; - exports2.DefaultGlobber = DefaultGlobber; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/glob/lib/internal-hash-files.js -var require_internal_hash_files = __commonJS({ - "node_modules/@actions/glob/lib/internal-hash-files.js"(exports2) { +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -75819,92 +78360,85 @@ var require_internal_hash_files = __commonJS({ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve9, reject) { - v = o[n](v), settle(resolve9, reject, v.done, v.value); - }); - }; - } - function settle(resolve9, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve9({ value: v2, done: d }); - }, reject); - } - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.hashFiles = void 0; - var crypto2 = __importStar4(require("crypto")); + exports2.RetryHelper = void 0; var core14 = __importStar4(require_core()); - var fs15 = __importStar4(require("fs")); - var stream2 = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var path16 = __importStar4(require("path")); - function hashFiles2(globber, currentWorkspace, verbose = false) { - var _a, e_1, _b, _c; - var _d; - return __awaiter4(this, void 0, void 0, function* () { - const writeDelegate = verbose ? core14.info : core14.debug; - let hasMatch = false; - const githubWorkspace = currentWorkspace ? currentWorkspace : (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd(); - const result = crypto2.createHash("sha256"); - let count = 0; - try { - for (var _e = true, _f = __asyncValues4(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { - _c = _g.value; - _e = false; - const file = _c; - writeDelegate(file); - if (!file.startsWith(`${githubWorkspace}${path16.sep}`)) { - writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); - continue; - } - if (fs15.statSync(file).isDirectory()) { - writeDelegate(`Skip directory '${file}'.`); - continue; - } - const hash = crypto2.createHash("sha256"); - const pipeline = util.promisify(stream2.pipeline); - yield pipeline(fs15.createReadStream(file), hash); - result.write(hash.digest()); - count++; - if (!hasMatch) { - hasMatch = true; - } - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); - } finally { - if (e_1) throw e_1.error; - } + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); } - result.end(); - if (hasMatch) { - writeDelegate(`Found ${count} files to hash.`); - return result.digest("hex"); - } else { - writeDelegate(`No matches found for glob`); - return ""; + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); } - }); - } - exports2.hashFiles = hashFiles2; + } + execute(action, isRetryable) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 1; + while (attempt < this.maxAttempts) { + try { + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; + } + core14.info(err.message); + } + const seconds = this.getSleepAmount(); + core14.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); + attempt++; + } + return yield action(); + }); + } + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + } + sleep(seconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9) => setTimeout(resolve9, seconds * 1e3)); + }); + } + }; + exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/glob/lib/glob.js -var require_glob2 = __commonJS({ - "node_modules/@actions/glob/lib/glob.js"(exports2) { +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve9) { @@ -75926,284 +78460,617 @@ var require_glob2 = __commonJS({ reject(e); } } - function step(result) { - result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + function step(result) { + result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; + var core14 = __importStar4(require_core()); + var io7 = __importStar4(require_io()); + var crypto2 = __importStar4(require("crypto")); + var fs15 = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os5 = __importStar4(require("os")); + var path16 = __importStar4(require("path")); + var httpm = __importStar4(require_lib5()); + var semver9 = __importStar4(require_semver2()); + var stream2 = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError2 = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + exports2.HTTPError = HTTPError2; + var IS_WINDOWS = process.platform === "win32"; + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url, dest, auth, headers) { + return __awaiter4(this, void 0, void 0, function* () { + dest = dest || path16.join(_getTempDirectory(), crypto2.randomUUID()); + yield io7.mkdirP(path16.dirname(dest)); + core14.debug(`Downloading ${url}`); + core14.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError2 && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; + } + } + return true; + }); + }); + } + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url, dest, auth, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (fs15.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); + } + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core14.debug("set auth"); + if (headers === void 0) { + headers = {}; + } + headers.authorization = auth; + } + const response = yield http.get(url, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError2(response.message.statusCode); + core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; + } + const pipeline = util.promisify(stream2.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; + try { + yield pipeline(readStream, fs15.createWriteStream(dest)); + core14.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core14.debug("download failed"); + try { + yield io7.rmRF(dest); + } catch (err) { + core14.debug(`Failed to delete '${dest}'. ${err.message}`); + } + } + } + }); + } + function extract7z(file, dest, _7zPath) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { + try { + const logLevel = core14.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file + ]; + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } else { + const escapedScript = path16.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true + }; + try { + const powershellPath = yield io7.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } + return dest; + }); + } + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + core14.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + core14.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + if (core14.isDebug() && !flags.includes("v")) { + args.push("-v"); + } + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); + } + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); + } + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; + }); + } + exports2.extractTar = extractTar2; + function extractXar(file, dest, flags = []) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + args.push("-x", "-C", dest, "-f", file); + if (core14.isDebug()) { + args.push("-v"); + } + const xarPath = yield io7.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; + }); + } + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } else { + yield extractZipNix(file, dest); + } + return dest; + }); + } + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io7.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core14.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io7.which("powershell", true); + core14.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); + } + }); + } + function extractZipNix(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const unzipPath = yield io7.which("unzip", true); + const args = [file]; + if (!core14.isDebug()) { + args.unshift("-q"); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.hashFiles = exports2.create = void 0; - var internal_globber_1 = require_internal_globber2(); - var internal_hash_files_1 = require_internal_hash_files(); - function create2(patterns, options) { + } + function cacheDir(sourceDir, tool, version, arch2) { return __awaiter4(this, void 0, void 0, function* () { - return yield internal_globber_1.DefaultGlobber.create(patterns, options); + version = semver9.clean(version) || version; + arch2 = arch2 || os5.arch(); + core14.debug(`Caching tool ${tool} ${version} ${arch2}`); + core14.debug(`source dir: ${sourceDir}`); + if (!fs15.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); + } + const destPath = yield _createToolPath(tool, version, arch2); + for (const itemName of fs15.readdirSync(sourceDir)) { + const s = path16.join(sourceDir, itemName); + yield io7.cp(s, destPath, { recursive: true }); + } + _completeToolPath(tool, version, arch2); + return destPath; }); } - exports2.create = create2; - function hashFiles2(patterns, currentWorkspace = "", options, verbose = false) { + exports2.cacheDir = cacheDir; + function cacheFile(sourceFile, targetFile, tool, version, arch2) { return __awaiter4(this, void 0, void 0, function* () { - let followSymbolicLinks = true; - if (options && typeof options.followSymbolicLinks === "boolean") { - followSymbolicLinks = options.followSymbolicLinks; + version = semver9.clean(version) || version; + arch2 = arch2 || os5.arch(); + core14.debug(`Caching tool ${tool} ${version} ${arch2}`); + core14.debug(`source file: ${sourceFile}`); + if (!fs15.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); } - const globber = yield create2(patterns, { followSymbolicLinks }); - return (0, internal_hash_files_1.hashFiles)(globber, currentWorkspace, verbose); + const destFolder = yield _createToolPath(tool, version, arch2); + const destPath = path16.join(destFolder, targetFile); + core14.debug(`destination file ${destPath}`); + yield io7.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch2); + return destFolder; }); } - exports2.hashFiles = hashFiles2; - } -}); - -// node_modules/@actions/tool-cache/lib/manifest.js -var require_manifest = __commonJS({ - "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch2) { + if (!toolName) { + throw new Error("toolName parameter is required"); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve9) { - resolve9(value); - }); + arch2 = arch2 || os5.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions2(toolName, arch2); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; } - return new (P || (P = Promise))(function(resolve9, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + let toolPath = ""; + if (versionSpec) { + versionSpec = semver9.clean(versionSpec) || ""; + const cachePath = path16.join(_getCacheDirectory(), toolName, versionSpec, arch2); + core14.debug(`checking cache: ${cachePath}`); + if (fs15.existsSync(cachePath) && fs15.existsSync(`${cachePath}.complete`)) { + core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); + toolPath = cachePath; + } else { + core14.debug("not found"); + } + } + return toolPath; + } + exports2.find = find2; + function findAllVersions2(toolName, arch2) { + const versions = []; + arch2 = arch2 || os5.arch(); + const toolPath = path16.join(_getCacheDirectory(), toolName); + if (fs15.existsSync(toolPath)) { + const children = fs15.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path16.join(toolPath, child, arch2 || ""); + if (fs15.existsSync(fullPath) && fs15.existsSync(`${fullPath}.complete`)) { + versions.push(child); + } } } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + } + return versions; + } + exports2.findAllVersions = findAllVersions2; + function getManifestFromRepo(owner, repo, auth, branch = "master") { + return __awaiter4(this, void 0, void 0, function* () { + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core14.debug("set auth"); + headers.authorization = auth; + } + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; + } + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; } } - function step(result) { - result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); + try { + releases = JSON.parse(versionsRaw); + } catch (_a) { + core14.debug("Invalid json"); + } } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return releases; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver9 = __importStar4(require_semver2()); - var core_1 = require_core(); - var os5 = require("os"); - var cp = require("child_process"); - var fs15 = require("fs"); - function _findMatch(versionSpec, stable, candidates, archFilter) { + } + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os5.arch()) { return __awaiter4(this, void 0, void 0, function* () { - const platFilter = os5.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver9.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { - file = candidate.files.find((item) => { - (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module2.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } else { - chk = semver9.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - (0, core_1.debug)(`matched ${candidate.version}`); - match = candidate; - break; - } - } - } - if (match && file) { - result = Object.assign({}, match); - result.files = [file]; + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; + }); + } + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!dest) { + dest = path16.join(_getTempDirectory(), crypto2.randomUUID()); } - return result; + yield io7.mkdirP(dest); + return dest; }); } - exports2._findMatch = _findMatch; - function _getOsVersion() { - const plat = os5.platform(); + function _createToolPath(tool, version, arch2) { + return __awaiter4(this, void 0, void 0, function* () { + const folderPath = path16.join(_getCacheDirectory(), tool, semver9.clean(version) || version, arch2 || ""); + core14.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io7.rmRF(folderPath); + yield io7.rmRF(markerPath); + yield io7.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch2) { + const folderPath = path16.join(_getCacheDirectory(), tool, semver9.clean(version) || version, arch2 || ""); + const markerPath = `${folderPath}.complete`; + fs15.writeFileSync(markerPath, ""); + core14.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver9.clean(versionSpec) || ""; + core14.debug(`isExplicit: ${c}`); + const valid3 = semver9.valid(c) != null; + core14.debug(`explicit? ${valid3}`); + return valid3; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { let version = ""; - if (plat === "darwin") { - version = cp.execSync("sw_vers -productVersion").toString(); - } else if (plat === "linux") { - const lsbContents = module2.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split("\n"); - for (const line of lines) { - const parts = line.split("="); - if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { - version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); - break; - } - } + core14.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver9.gt(a, b)) { + return 1; + } + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver9.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; } } + if (version) { + core14.debug(`matched: ${version}`); + } else { + core14.debug("match not found"); + } return version; } - exports2._getOsVersion = _getOsVersion; - function _readLinuxVersionFile() { - const lsbReleaseFile = "/etc/lsb-release"; - const osReleaseFile = "/etc/os-release"; - let contents = ""; - if (fs15.existsSync(lsbReleaseFile)) { - contents = fs15.readFileSync(lsbReleaseFile).toString(); - } else if (fs15.existsSync(osReleaseFile)) { - contents = fs15.readFileSync(osReleaseFile).toString(); - } - return contents; + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); } - exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve9) { - resolve9(value); - }); - } - return new (P || (P = Promise))(function(resolve9, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + module2.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; } - function step(result) { - result.done ? resolve9(result.value) : adopt(result.value).then(fulfilled, rejected); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return true; + } + return a !== a && b !== b; }; + } +}); + +// node_modules/@actions/http-client/lib/proxy.js +var require_proxy5 = __commonJS({ + "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core14 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); + exports2.getProxyUrl = getProxyUrl; + exports2.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - execute(action, isRetryable) { - return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core14.info(err.message); - } - const seconds = this.getSleepAmount(); - core14.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - return yield action(); - }); + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + get username() { + return this._decodedUsername; } - sleep(seconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve9) => setTimeout(resolve9, seconds * 1e3)); - }); + get password() { + return this._decodedPassword; } }; - exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib6 = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -76223,15 +79090,25 @@ var require_tool_cache = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve9) { @@ -76260,523 +79137,616 @@ var require_tool_cache = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core14 = __importStar4(require_core()); - var io7 = __importStar4(require_io()); - var crypto2 = __importStar4(require("crypto")); - var fs15 = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os5 = __importStar4(require("os")); - var path16 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver9 = __importStar4(require_semver2()); - var stream2 = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError2 = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy5()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.HTTPError = HTTPError2; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path16.join(_getTempDirectory(), crypto2.randomUUID()); - yield io7.mkdirP(path16.dirname(dest)); - core14.debug(`Downloading ${url}`); - core14.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError2 && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve9(output.toString()); + }); + })); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs15.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve9(Buffer.concat(chunks)); + }); + })); }); - if (auth) { - core14.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - headers.authorization = auth; - } - const response = yield http.get(url, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError2(response.message.statusCode); - core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; - } - const pipeline = util.promisify(stream2.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs15.createWriteStream(dest)); - core14.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core14.debug("download failed"); - try { - yield io7.rmRF(dest); - } catch (err) { - core14.debug(`Failed to delete '${dest}'. ${err.message}`); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core14.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } else { - const escapedScript = path16.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io7.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core14.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - core14.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core14.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - args.push("-x", "-C", dest, "-f", file); - if (core14.isDebug()) { - args.push("-v"); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve9(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - const xarPath = yield io7.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io7.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core14.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io7.which("powershell", true); - core14.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); - } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io7.which("unzip", true); - const args = [file]; - if (!core14.isDebug()) { - args.unshift("-q"); + req.end(); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir(sourceDir, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver9.clean(version) || version; - arch2 = arch2 || os5.arch(); - core14.debug(`Caching tool ${tool} ${version} ${arch2}`); - core14.debug(`source dir: ${sourceDir}`); - if (!fs15.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const destPath = yield _createToolPath(tool, version, arch2); - for (const itemName of fs15.readdirSync(sourceDir)) { - const s = path16.join(sourceDir, itemName); - yield io7.cp(s, destPath, { recursive: true }); + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - _completeToolPath(tool, version, arch2); - return destPath; - }); - } - exports2.cacheDir = cacheDir; - function cacheFile(sourceFile, targetFile, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver9.clean(version) || version; - arch2 = arch2 || os5.arch(); - core14.debug(`Caching tool ${tool} ${version} ${arch2}`); - core14.debug(`source file: ${sourceFile}`); - if (!fs15.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } } - const destFolder = yield _createToolPath(tool, version, arch2); - const destPath = path16.join(destFolder, targetFile); - core14.debug(`destination file ${destPath}`); - yield io7.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch2); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch2) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); + return info6; } - arch2 = arch2 || os5.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions2(toolName, arch2); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver9.clean(versionSpec) || ""; - const cachePath = path16.join(_getCacheDirectory(), toolName, versionSpec, arch2); - core14.debug(`checking cache: ${cachePath}`); - if (fs15.existsSync(cachePath) && fs15.existsSync(`${cachePath}.complete`)) { - core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); - toolPath = cachePath; - } else { - core14.debug("not found"); + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return toolPath; - } - exports2.find = find2; - function findAllVersions2(toolName, arch2) { - const versions = []; - arch2 = arch2 || os5.arch(); - const toolPath = path16.join(_getCacheDirectory(), toolName); - if (fs15.existsSync(toolPath)) { - const children = fs15.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path16.join(toolPath, child, arch2 || ""); - if (fs15.existsSync(fullPath) && fs15.existsSync(`${fullPath}.complete`)) { - versions.push(child); + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; } } } + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; + } + } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return versions; - } - exports2.findAllVersions = findAllVersions2; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core14.debug("set auth"); - headers.authorization = auth; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + if (!useProxy) { + agent = this._agent; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; - } + if (agent) { + return agent; } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core14.debug("Invalid json"); - } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os5.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path16.join(_getTempDirectory(), crypto2.randomUUID()); + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - yield io7.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path16.join(_getCacheDirectory(), tool, semver9.clean(version) || version, arch2 || ""); - core14.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io7.rmRF(folderPath); - yield io7.rmRF(markerPath); - yield io7.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch2) { - const folderPath = path16.join(_getCacheDirectory(), tool, semver9.clean(version) || version, arch2 || ""); - const markerPath = `${folderPath}.complete`; - fs15.writeFileSync(markerPath, ""); - core14.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver9.clean(versionSpec) || ""; - core14.debug(`isExplicit: ${c}`); - const valid3 = semver9.valid(c) != null; - core14.debug(`explicit? ${valid3}`); - return valid3; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core14.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver9.gt(a, b)) { - return 1; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver9.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } + return agent; } - if (version) { - core14.debug(`matched: ${version}`); - } else { - core14.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; + if (proxyAgent) { + return proxyAgent; } - return true; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve9) => setTimeout(() => resolve9(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve9, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve9(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve9(response); + } + })); + }); } - return a !== a && b !== b; }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -81010,7 +83980,7 @@ var import_perf_hooks = require("perf_hooks"); // src/config/db-config.ts var path3 = __toESM(require("path")); -var jsonschema = __toESM(require_lib2()); +var jsonschema = __toESM(require_lib3()); var semver2 = __toESM(require_semver2()); // src/error-messages.ts @@ -83570,7 +86540,7 @@ var os3 = __toESM(require("os")); var path9 = __toESM(require("path")); var import_perf_hooks2 = require("perf_hooks"); var core9 = __toESM(require_core()); -var import_http_client = __toESM(require_lib()); +var import_http_client = __toESM(require_lib6()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); var semver6 = __toESM(require_semver2()); diff --git a/lib/resolve-environment-action.js b/lib/resolve-environment-action.js index c8cdd52627..2378de271e 100644 --- a/lib/resolve-environment-action.js +++ b/lib/resolve-environment-action.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -19875,9 +19875,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -19934,737 +20016,826 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve4(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve4(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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 (isPlainObject(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+)|(?:(? a.concat(b), []); - } - function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - } - function encodeReserved(str2) { - return str2.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(str2) { - return encodeURIComponent(str2).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; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - function isDefined2(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context2, operator, key, modifier) { - var value = context2[key], result = []; - if (isDefined2(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)); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - result.push(encodeValue(operator, value[k], k)); + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; } - }); + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } } - }); + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - } else { - if (operator === ";") { - if (isDefined2(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; - } - function expand(template, context2) { - 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(context2, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve4(res); } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); } - } else { - return encodeReserved(literal); + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } - } - function parse(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 = omit(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 = omit(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(","); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + req.end(); } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); - } - function endpointWithDefaults(defaults, route, options) { - return parse(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 - }); - } - var endpoint = withDefaults(null, DEFAULTS); - } -}); - -// node_modules/deprecation/dist-node/index.js -var require_dist_node3 = __commonJS({ - "node_modules/deprecation/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var Deprecation = class extends Error { - constructor(message) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - this.name = "Deprecation"; + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; } - }; - exports2.Deprecation = Deprecation; - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - return ret; + return additionalHeaders[header] || clientHeader || _default2; } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve4) => setTimeout(() => resolve4(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve4(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve4(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; + var httpClient = __importStar4(require_lib2()); + var undici_1 = require_undici(); + function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error("Parameter token or opts.auth is required"); + } else if (token && options.auth) { + throw new Error("Parameters token and opts.auth may not both be specified"); + } + return typeof options.auth === "string" ? options.auth : `token ${token}`; + } + exports2.getAuthString = getAuthString; + function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + exports2.getProxyAgent = getProxyAgent; + function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); + } + exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; + function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; + return proxyFetch; } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; } + exports2.getApiBaseUrl = getApiBaseUrl; } }); -// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node4 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { "use strict"; - var __create2 = Object.create; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - RequestError: () => RequestError - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_deprecation = require_dist_node3(); - var import_once = __toESM2(require_once()); - var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - request: () => request - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node2(); - var import_universal_user_agent = require_dist_node(); - var VERSION = "8.4.1"; - function isPlainObject(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); - } - var import_request_error = require_dist_node4(); - function getBufferResponse(response) { - return response.arrayBuffer(); - } - function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - 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" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } - }).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error4; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error4) => { - if (error4 instanceof import_request_error.RequestError) - throw error4; - else if (error4.name === "AbortError") - throw error4; - let message = error4.message; - if (error4.name === "TypeError" && "cause" in error4) { - if (error4.cause instanceof Error) { - message = error4.cause.message; - } else if (typeof error4.cause === "string") { - message = error4.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); - } - 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 getBufferResponse(response); - } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; - } - function withDefaults(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: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - } - var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } - }); - } -}); - -// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node6 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint + endpoint: () => endpoint }); module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); @@ -21218,9 +21179,101 @@ var require_dist_node6 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node7 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/deprecation/dist-node/index.js +var require_dist_node3 = __commonJS({ + "node_modules/deprecation/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var Deprecation = class extends Error { + constructor(message) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "Deprecation"; + } + }; + exports2.Deprecation = Deprecation; + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node4 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; var __create2 = Object.create; var __defProp2 = Object.defineProperty; @@ -21310,9 +21363,9 @@ var require_dist_node7 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js -var require_dist_node8 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js +var require_dist_node5 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21336,7 +21389,7 @@ var require_dist_node8 = __commonJS({ request: () => request }); module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node6(); + var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; function isPlainObject(value) { @@ -21350,7 +21403,7 @@ var require_dist_node8 = __commonJS({ 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); } - var import_request_error = require_dist_node7(); + var import_request_error = require_dist_node4(); function getBufferResponse(response) { return response.arrayBuffer(); } @@ -21520,9 +21573,9 @@ var require_dist_node8 = __commonJS({ } }); -// node_modules/@octokit/graphql/dist-node/index.js -var require_dist_node9 = __commonJS({ - "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node6 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21541,129 +21594,340 @@ var require_dist_node9 = __commonJS({ return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export2(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint }); - module2.exports = __toCommonJS2(index_exports); - var import_request3 = require_dist_node8(); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); - var VERSION = "7.1.1"; - var import_request2 = require_dist_node8(); - var import_request = require_dist_node8(); - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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; + }, {}); } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + function isPlainObject(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 (isPlainObject(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]; } } - }; - 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`) - ); + 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); } - 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` - ) - ); + 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+)|(?:(? { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } + function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; } - if (!result.variables) { - result.variables = {}; + } + return result; + } + function encodeReserved(str2) { + return str2.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, "]"); } - 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 part; + }).join(""); + } + function encodeUnreserved(str2) { + return encodeURIComponent(str2).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; } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; + } + function isDefined2(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context2, operator, key, modifier) { + var value = context2[key], result = []; + if (isDefined2(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)); } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(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(",")); + } + } } - return response.data.data; - }); + } else { + if (operator === ";") { + if (isDefined2(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; } - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); + function parseUrl(template) { + return { + expand: expand.bind(null, template) }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); } - var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" - }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" + function expand(template, context2) { + 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(context2, 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 parse(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 = omit(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 = omit(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(/(? { + 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 parse(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 }); } + var endpoint = withDefaults(null, DEFAULTS); } }); -// node_modules/@octokit/auth-token/dist-node/index.js -var require_dist_node10 = __commonJS({ - "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node7 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; + var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) @@ -21677,53 +21941,490 @@ var require_dist_node10 = __commonJS({ } return to; }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - createTokenAuth: () => createTokenAuth + RequestError: () => RequestError }); module2.exports = __toCommonJS2(dist_src_exports); - 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, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); - } - 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" - ); + var import_deprecation = require_dist_node3(); + var import_once = __toESM2(require_once()); + var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + request: () => request + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_endpoint = require_dist_node6(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "8.4.1"; + function isPlainObject(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); + } + var import_request_error = require_dist_node7(); + function getBufferResponse(response) { + return response.arrayBuffer(); + } + function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + 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" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error4; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error4) => { + if (error4 instanceof import_request_error.RequestError) + throw error4; + else if (error4.name === "AbortError") + throw error4; + let message = error4.message; + if (error4.name === "TypeError" && "cause" in error4) { + if (error4.cause instanceof Error) { + message = error4.cause.message; + } else if (typeof error4.cause === "string") { + message = error4.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); + } + 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 getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; + } + function withDefaults(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: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + } + var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }); + } +}); + +// node_modules/@octokit/graphql/dist-node/index.js +var require_dist_node9 = __commonJS({ + "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export2(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest + }); + module2.exports = __toCommonJS2(index_exports); + var import_request3 = require_dist_node8(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "7.1.1"; + var import_request2 = require_dist_node8(); + var import_request = require_dist_node8(); + 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.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + }; + 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 withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); + } + } +}); + +// node_modules/@octokit/auth-token/dist-node/index.js +var require_dist_node10 = __commonJS({ + "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + createTokenAuth: () => createTokenAuth + }); + module2.exports = __toCommonJS2(dist_src_exports); + 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, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + 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) + }); }; } }); @@ -26499,7 +27200,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -29372,7 +30073,7 @@ var require_validator = __commonJS({ }); // node_modules/jsonschema/lib/index.js -var require_lib2 = __commonJS({ +var require_lib3 = __commonJS({ "node_modules/jsonschema/lib/index.js"(exports2, module2) { "use strict"; var Validator2 = module2.exports.Validator = require_validator(); @@ -32511,958 +33212,1763 @@ var require_cacheUtils = __commonJS({ } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); - var HttpPipeline = class _HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = void 0; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - this._policies.push({ - policy, - options - }); - this._orderedPolicies = void 0; + } else { + return void 0; } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { - removedPolicies.push(policyDescriptor.policy); - return false; - } else { - return true; - } - }); - this._orderedPolicies = void 0; - return removedPolicies; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - clone() { - return new _HttpPipeline(this._policies); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - static create() { - return new _HttpPipeline(); + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - orderPolicies() { - const result = []; - const policyMap = /* @__PURE__ */ new Map(); - function createPhase(name) { - return { - name, - policies: /* @__PURE__ */ new Set(), - hasRun: false, - hasAfterPolicies: false - }; - } - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } else if (phase === "Serialize") { - return serializePhase; - } else if (phase === "Deserialize") { - return deserializePhase; - } else if (phase === "Sign") { - return signPhase; - } else { - return noPhase; - } - } - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: /* @__PURE__ */ new Set(), - dependants: /* @__PURE__ */ new Set() - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); - } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); - } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); - } - } - } - } - function walkPhase(phase) { - phase.hasRun = true; - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - continue; - } - if (node.dependsOn.size === 0) { - result.push(node.policy); - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); - } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - walkPhase(noPhase); - } - return; - } - if (phase.hasAfterPolicies) { - walkPhase(noPhase); - } - } - } - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - walkPhases(); - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return result; } - }; - function createEmptyPipeline() { - return HttpPipeline.create(); + return false; } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@azure/logger/dist/index.js -var require_dist = __commonJS({ - "node_modules/@azure/logger/dist/index.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var os2 = require("os"); - var util = require("util"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); - function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os2.EOL}`); - } - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; - var enabledString; - var enabledNamespaces = []; - var skippedNamespaces = []; - var debuggers = []; - if (debugEnvVariable) { - enable(debugEnvVariable); - } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log - }); - function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); - } else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); - } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - } - function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - } - return false; - } - function disable() { - const result = enabledString || ""; - enable(""); - return result; - } - function createDebugger(namespace) { - const newDebugger = Object.assign(debug6, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend: extend3 - }); - function debug6(...args) { - if (!newDebugger.enabled) { - return; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); } - newDebugger.log(...args); - } - debuggers.push(newDebugger); - return newDebugger; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return false; - } - function extend3(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; - } - var debug5 = debugObj; - var registeredLoggers = /* @__PURE__ */ new Set(); - var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; - var azureLogLevel; - var AzureLogger = debug5("azure"); - AzureLogger.log = (...args) => { - debug5.log(...args); }; - var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; - if (logLevelFromEnv) { - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); - } else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - } - function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve4(output.toString()); + }); + })); + }); } - azureLogLevel = level; - const enabledNamespaces2 = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces2.push(logger.namespace); - } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve4(Buffer.concat(chunks)); + }); + })); + }); } - debug5.enable(enabledNamespaces2.join(",")); - } - function getLogLevel() { - return azureLogLevel; - } - var levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 }; - function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") - }; - } - function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); - }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces2 = debug5.disable(); - debug5.enable(enabledNamespaces2 + "," + logger.namespace); + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - registeredLoggers.add(logger); - return logger; - } - function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); - } - function isAzureLogLevel(logLevel) { - return AZURE_LOG_LEVELS.includes(logLevel); - } - exports2.AzureLogger = AzureLogger; - exports2.createClientLogger = createClientLogger; - exports2.getLogLevel = getLogLevel; - exports2.setLogLevel = setLogLevel; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js -var require_log = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_dist(); - exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - } -}); - -// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js -var require_createAbortablePromise = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createAbortablePromise = createAbortablePromise; - var abort_controller_1 = require_commonjs(); - function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve4, reject) => { - function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - function removeListeners() { - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve4(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - function onAbort() { - cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); - removeListeners(); - rejectOnAbort(); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { - return rejectOnAbort(); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - try { - buildPromise((x) => { - removeListeners(); - resolve4(x); - }, (x) => { - removeListeners(); - reject(x); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); }); - } catch (err) { - reject(err); + data.pipe(req); + } else { + req.end(); } - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); - }); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/random.js -var require_random = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - function getRandomIntegerInclusive(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - const offset = Math.floor(Math.random() * (max - min + 1)); - return offset + min; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/delay.js -var require_delay = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay2; - exports2.calculateRetryDelay = calculateRetryDelay; - var createAbortablePromise_js_1 = require_createAbortablePromise(); - var random_js_1 = require_random(); - var StandardAbortMessage = "The delay was aborted."; - function delay2(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve4) => { - token = setTimeout(resolve4, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage - }); - } - function calculateRetryDelay(retryAttempt, config) { - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); - return { retryAfterInMs }; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js -var require_aborterUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cancelablePromiseRace = cancelablePromiseRace; - async function cancelablePromiseRace(abortablePromiseBuilders, options) { - var _a, _b; - const aborter = new AbortController(); - function abortHandler() { - aborter.abort(); } - (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); - try { - return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); - } finally { - aborter.abort(); - (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/object.js -var require_object = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isObject = isObject2; - function isObject2(input) { - return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/error.js -var require_error = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isError = isError; - exports2.getErrorMessage = getErrorMessage2; - var object_js_1 = require_object(); - function isError(e) { - if ((0, object_js_1.isObject)(e)) { - const hasName = typeof e.name === "string"; - const hasMessage = typeof e.message === "string"; - return hasName && hasMessage; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return false; - } - function getErrorMessage2(e) { - if (isError(e)) { - return e.message; - } else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } else { - stringified = String(e); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - } catch (err) { - stringified = "[unable to stringify input]"; } - return `Unknown error ${stringified}`; + return info6; } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.computeSha256Hash = computeSha256Hash; - var crypto_1 = require("crypto"); - async function computeSha256Hmac(key, stringToSign, encoding) { - const decodedKey = Buffer.from(key, "base64"); - return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); - } - async function computeSha256Hash(content, encoding) { - return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/typeGuards.js -var require_typeGuards = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isDefined = isDefined2; - exports2.isObjectWithProperties = isObjectWithProperties; - exports2.objectHasProperty = objectHasProperty; - function isDefined2(thing) { - return typeof thing !== "undefined" && thing !== null; - } - function isObjectWithProperties(thing, properties) { - if (!isDefined2(thing) || typeof thing !== "object") { - return false; - } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - return true; - } - function objectHasProperty(thing, property) { - return isDefined2(thing) && typeof thing === "object" && property in thing; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js -var require_uuidUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomUUID = randomUUID; - var crypto_1 = require("crypto"); - var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; - function randomUUID() { - return uuidFunction(); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js -var require_checkEnvironment = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { - "use strict"; - var _a; - var _b; - var _c; - var _d; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; - exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; - exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); - exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; - exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; - exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); - exports2.isNode = exports2.isNodeLike; - exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; - exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; - } -}); - -// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js -var require_bytesEncoding = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - function uint8ArrayToString(bytes, format) { - return Buffer.from(bytes).toString(format); - } - function stringToUint8Array(value, format) { - return Buffer.from(value, format); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/index.js -var require_commonjs2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; - var delay_js_1 = require_delay(); - Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { - return delay_js_1.delay; - } }); - Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { - return delay_js_1.calculateRetryDelay; - } }); - var aborterUtils_js_1 = require_aborterUtils(); - Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { - return aborterUtils_js_1.cancelablePromiseRace; - } }); - var createAbortablePromise_js_1 = require_createAbortablePromise(); - Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { - return createAbortablePromise_js_1.createAbortablePromise; - } }); - var random_js_1 = require_random(); - Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { - return random_js_1.getRandomIntegerInclusive; - } }); - var object_js_1 = require_object(); - Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { - return object_js_1.isObject; - } }); - var error_js_1 = require_error(); - Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { - return error_js_1.isError; - } }); - Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { - return error_js_1.getErrorMessage; - } }); - var sha256_js_1 = require_sha256(); - Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hash; - } }); - Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hmac; - } }); - var typeGuards_js_1 = require_typeGuards(); - Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { - return typeGuards_js_1.isDefined; - } }); - Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { - return typeGuards_js_1.isObjectWithProperties; - } }); - Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { - return typeGuards_js_1.objectHasProperty; - } }); - var uuidUtils_js_1 = require_uuidUtils(); - Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { - return uuidUtils_js_1.randomUUID; - } }); - var checkEnvironment_js_1 = require_checkEnvironment(); - Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBrowser; - } }); - Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBun; - } }); - Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNode; - } }); - Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeLike; - } }); - Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeRuntime; - } }); - Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { - return checkEnvironment_js_1.isDeno; - } }); - Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { - return checkEnvironment_js_1.isReactNative; - } }); - Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { - return checkEnvironment_js_1.isWebWorker; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js -var require_sanitizer = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = void 0; - var core_util_1 = require_commonjs2(); - var RedactedString = "REDACTED"; - var defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate" - ]; - var defaultAllowedQueryParameters = ["api-version"]; - var Sanitizer = class { - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { - allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); - allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); - } - sanitize(obj) { - const seen = /* @__PURE__ */ new Set(); - return JSON.stringify(obj, (key, value) => { - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); - } - if (key === "headers") { - return this.sanitizeHeaders(value); - } else if (key === "url") { - return this.sanitizeUrl(value); - } else if (key === "query") { - return this.sanitizeQuery(value); - } else if (key === "body") { - return void 0; - } else if (key === "response") { - return void 0; - } else if (key === "operationSpec") { - return void 0; - } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - } - return value; - }, 2); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - sanitizeUrl(value) { - if (typeof value !== "string" || value === null || value === "") { - return value; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const url = new URL(value); - if (!url.search) { - return value; + if (!useProxy) { + agent = this._agent; } - for (const [key] of url.searchParams) { - if (!this.allowedQueryParameters.has(key.toLowerCase())) { - url.searchParams.set(key, RedactedString); - } + if (agent) { + return agent; } - return url.toString(); - } - sanitizeHeaders(obj) { - const sanitized = {}; - for (const key of Object.keys(obj)) { - if (this.allowedHeaderNames.has(key.toLowerCase())) { - sanitized[key] = obj[key]; + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - sanitized[key] = RedactedString; + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - return sanitized; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - sanitizeQuery(value) { - if (typeof value !== "object" || value === null) { - return value; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (this.allowedQueryParameters.has(k.toLowerCase())) { - sanitized[k] = value[k]; - } else { - sanitized[k] = RedactedString; - } + if (proxyAgent) { + return proxyAgent; } - return sanitized; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve4) => setTimeout(() => resolve4(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve4(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve4(response); + } + })); + }); } }; - exports2.Sanitizer = Sanitizer; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js -var require_logPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log(); - var sanitizer_js_1 = require_sanitizer(); - exports2.logPolicyName = "logPolicy"; - function logPolicy(options = {}) { - var _a; - const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - return { - name: exports2.logPolicyName, - async sendRequest(request, next) { - if (!logger.enabled) { - return next(request); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - logger(`Request: ${sanitizer.sanitize(request)}`); - const response = await next(request); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); - return response; } - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js -var require_redirectPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - exports2.redirectPolicyName = "redirectPolicy"; - var allowedRedirect = ["GET", "HEAD"]; - function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: exports2.redirectPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return handleRedirect(next, response, maxRetries); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - }; - } - async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { - const url = new URL(locationHeader, request.url); - request.url = url.toString(); - if (status === 303) { - request.method = "GET"; - request.headers.delete("Content-Length"); - delete request.body; + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); } - request.headers.delete("Authorization"); - const res = await next(request); - return handleRedirect(next, res, maxRetries, currentRetries + 1); - } - return response; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; + } + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; + } + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } + }; + function createEmptyPipeline() { + return HttpPipeline.create(); + } + } +}); + +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os2 = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; + } + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os2.EOL}`); + } + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); + } + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log + }); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } + } + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; + } + function disable() { + const result = enabledString || ""; + enable(""); + return result; + } + function createDebugger(namespace) { + const newDebugger = Object.assign(debug6, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug6(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; + } + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; + } + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; + } + var debug5 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug5("azure"); + AzureLogger.log = (...args) => { + debug5.log(...args); + }; + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + } + } + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); + } + } + debug5.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 + }; + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; + } + function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; + } + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces2 = debug5.disable(); + debug5.enable(enabledNamespaces2 + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; + } + function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + } + function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); + } + exports2.AzureLogger = AzureLogger; + exports2.createClientLogger = createClientLogger; + exports2.getLogLevel = getLogLevel; + exports2.setLogLevel = setLogLevel; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js +var require_log = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError; + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve4, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve4(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/random.js +var require_random = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; + function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay2; + exports2.calculateRetryDelay = calculateRetryDelay; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var random_js_1 = require_random(); + var StandardAbortMessage = "The delay was aborted."; + function delay2(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve4) => { + token = setTimeout(resolve4, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage + }); + } + function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); + } + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/object.js +var require_object = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isObject = isObject2; + function isObject2(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isError = isError; + exports2.getErrorMessage = getErrorMessage2; + var object_js_1 = require_object(); + function isError(e) { + if ((0, object_js_1.isObject)(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; + } + function getErrorMessage2(e) { + if (isError(e)) { + return e.message; + } else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } else { + stringified = String(e); + } + } catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.computeSha256Hmac = computeSha256Hmac; + exports2.computeSha256Hash = computeSha256Hash; + var crypto_1 = require("crypto"); + async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); + } + async function computeSha256Hash(content, encoding) { + return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isDefined = isDefined2; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined2(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined2(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined2(thing) && typeof thing === "object" && property in thing; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js +var require_uuidUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { + "use strict"; + var _a; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.randomUUID = randomUUID; + var crypto_1 = require("crypto"); + var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; + function randomUUID() { + return uuidFunction(); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js +var require_checkEnvironment = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { + "use strict"; + var _a; + var _b; + var _c; + var _d; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; + exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; + exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); + exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; + exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; + exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); + exports2.isNode = exports2.isNodeLike; + exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; + exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js +var require_bytesEncoding = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.uint8ArrayToString = uint8ArrayToString; + exports2.stringToUint8Array = stringToUint8Array; + function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); + } + function stringToUint8Array(value, format) { + return Buffer.from(value, format); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; + var delay_js_1 = require_delay(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { + return delay_js_1.calculateRetryDelay; + } }); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var random_js_1 = require_random(); + Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { + return random_js_1.getRandomIntegerInclusive; + } }); + var object_js_1 = require_object(); + Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { + return object_js_1.isObject; + } }); + var error_js_1 = require_error(); + Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { + return error_js_1.isError; + } }); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var sha256_js_1 = require_sha256(); + Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hash; + } }); + Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hmac; + } }); + var typeGuards_js_1 = require_typeGuards(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + var uuidUtils_js_1 = require_uuidUtils(); + Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { + return uuidUtils_js_1.randomUUID; + } }); + var checkEnvironment_js_1 = require_checkEnvironment(); + Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBrowser; + } }); + Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBun; + } }); + Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNode; + } }); + Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeLike; + } }); + Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeRuntime; + } }); + Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { + return checkEnvironment_js_1.isDeno; + } }); + Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { + return checkEnvironment_js_1.isReactNative; + } }); + Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { + return checkEnvironment_js_1.isWebWorker; + } }); + var bytesEncoding_js_1 = require_bytesEncoding(); + Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { + return bytesEncoding_js_1.uint8ArrayToString; + } }); + Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { + return bytesEncoding_js_1.stringToUint8Array; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js +var require_sanitizer = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Sanitizer = void 0; + var core_util_1 = require_commonjs2(); + var RedactedString = "REDACTED"; + var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" + ]; + var defaultAllowedQueryParameters = ["api-version"]; + var Sanitizer = class { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); + } + if (key === "headers") { + return this.sanitizeHeaders(value); + } else if (key === "url") { + return this.sanitizeUrl(value); + } else if (key === "query") { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }, 2); + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; + } + const url = new URL(value); + if (!url.search) { + return value; + } + for (const [key] of url.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url.searchParams.set(key, RedactedString); + } + } + return url.toString(); + } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } + }; + exports2.Sanitizer = Sanitizer; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js +var require_logPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logPolicyName = void 0; + exports2.logPolicy = logPolicy; + var log_js_1 = require_log(); + var sanitizer_js_1 = require_sanitizer(); + exports2.logPolicyName = "logPolicy"; + function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + return { + name: exports2.logPolicyName, + async sendRequest(request, next) { + if (!logger.enabled) { + return next(request); + } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.redirectPolicyName = void 0; + exports2.redirectPolicy = redirectPolicy; + exports2.redirectPolicyName = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; + return { + name: exports2.redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + } + }; + } + async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url = new URL(locationHeader, request.url); + request.url = url.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; + } + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); + } + return response; } } }); @@ -67946,7 +69452,7 @@ var require_requestUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; var core13 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var constants_1 = require_constants7(); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -68114,7 +69620,7 @@ var require_downloadUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; var core13 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var storage_blob_1 = require_dist7(); var buffer = __importStar4(require("buffer")); var fs5 = __importStar4(require("fs")); @@ -68691,8 +70197,8 @@ var require_cacheHttpClient = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; var core13 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib4(); + var auth_1 = require_auth2(); var fs5 = __importStar4(require("fs")); var url_1 = require("url"); var utils = __importStar4(require_cacheUtils()); @@ -69668,2706 +71174,4406 @@ var require_binary_reader = __commonJS({ return this.buf.subarray(start, start + len); } /** - * Read a `string` field, length-delimited data converted to UTF-8 text. + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); + } + }; + exports2.BinaryReader = BinaryReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js +var require_assert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; + function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } + } + exports2.assert = assert; + function assertNever2(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + } + exports2.assertNever = assertNever2; + var FLOAT32_MAX = 34028234663852886e22; + var FLOAT32_MIN = -34028234663852886e22; + var UINT32_MAX = 4294967295; + var INT32_MAX = 2147483647; + var INT32_MIN = -2147483648; + function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid int 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error("invalid int 32: " + arg); + } + exports2.assertInt32 = assertInt32; + function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid uint 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error("invalid uint 32: " + arg); + } + exports2.assertUInt32 = assertUInt32; + function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error("invalid float 32: " + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error("invalid float 32: " + arg); + } + exports2.assertFloat32 = assertFloat32; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js +var require_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var assert_1 = require_assert(); + var defaultsWrite = { + writeUnknownFields: true, + writerFactory: () => new BinaryWriter() + }; + function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.binaryWriteOptions = binaryWriteOptions; + var BinaryWriter = class { + constructor(textEncoder) { + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; + } + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; + } + this.chunks = []; + return bytes; + } + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; + } + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + let chunk = this.finish(); + let prev = this.stack.pop(); + if (!prev) + throw new Error("invalid state, fork stack empty"); + this.chunks = prev.chunks; + this.buf = prev.buf; + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type2) { + return this.uint32((fieldNo << 3 | type2) >>> 0); + } + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; + } + this.chunks.push(chunk); + return this; + } + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); + while (value > 127) { + this.buf.push(value & 127 | 128); + value = value >>> 7; + } + this.buf.push(value); + return this; + } + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; + } + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); + return this.raw(value); + } + /** + * Write a `string` value, length-delimited data converted to UTF-8 text. + */ + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Write a `float` value, 32-bit floating point number. + */ + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `double` value, a 64-bit floating point number. + */ + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); + } + /** + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + */ + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + */ + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + */ + sint32(value) { + assert_1.assertInt32(value); + value = (value << 1 ^ value >> 31) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + */ + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + */ + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `int64` value, a signed 64-bit varint. + */ + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + /** + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. */ - string() { - return this.textDecoder.decode(this.bytes()); + sint64(value) { + let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; + } + /** + * Write a `uint64` value, an unsigned 64-bit varint. + */ + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; } }; - exports2.BinaryReader = BinaryReader; + exports2.BinaryWriter = BinaryWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js -var require_assert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js +var require_json_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; - function assert(condition, msg) { - if (!condition) { - throw new Error(msg); + exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; + var defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0 + }; + var defaultsRead = { + ignoreUnknownFields: false + }; + function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; + } + exports2.jsonReadOptions = jsonReadOptions; + function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.jsonWriteOptions = jsonWriteOptions; + function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; + return c; + } + exports2.mergeJsonOptions = mergeJsonOptions; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js +var require_message_type_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MESSAGE_TYPE = void 0; + exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js +var require_lower_camel_case = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.lowerCamelCase = void 0; + function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == "_") { + capNext = true; + } else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } else if (i == 0) { + sb.push(next.toLowerCase()); + } else { + sb.push(next); + } } + return sb.join(""); } - exports2.assert = assert; - function assertNever2(value, msg) { - throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + exports2.lowerCamelCase = lowerCamelCase; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js +var require_reflection_info = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; + var lower_camel_case_1 = require_lower_camel_case(); + var ScalarType; + (function(ScalarType2) { + ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; + ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; + ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; + ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; + ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; + ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; + ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; + ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; + ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; + ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; + ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; + ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; + ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; + ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; + ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; + })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); + var LongType; + (function(LongType2) { + LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; + LongType2[LongType2["STRING"] = 1] = "STRING"; + LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; + })(LongType = exports2.LongType || (exports2.LongType = {})); + var RepeatType; + (function(RepeatType2) { + RepeatType2[RepeatType2["NO"] = 0] = "NO"; + RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; + RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; + })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); + function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; + return field; } - exports2.assertNever = assertNever2; - var FLOAT32_MAX = 34028234663852886e22; - var FLOAT32_MIN = -34028234663852886e22; - var UINT32_MAX = 4294967295; - var INT32_MAX = 2147483647; - var INT32_MIN = -2147483648; - function assertInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid int 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) - throw new Error("invalid int 32: " + arg); + exports2.normalizeFieldInfo = normalizeFieldInfo; + function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; } - exports2.assertInt32 = assertInt32; - function assertUInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid uint 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) - throw new Error("invalid uint 32: " + arg); + exports2.readFieldOptions = readFieldOptions; + function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.assertUInt32 = assertUInt32; - function assertFloat32(arg) { - if (typeof arg !== "number") - throw new Error("invalid float 32: " + typeof arg); - if (!Number.isFinite(arg)) - return; - if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) - throw new Error("invalid float 32: " + arg); + exports2.readFieldOption = readFieldOption; + function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.assertFloat32 = assertFloat32; + exports2.readMessageOption = readMessageOption; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js -var require_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js +var require_oneof = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; - var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); - var assert_1 = require_assert(); - var defaultsWrite = { - writeUnknownFields: true, - writerFactory: () => new BinaryWriter() - }; - function binaryWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; + function isOneofGroup(any) { + if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === void 0) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; + } } - exports2.binaryWriteOptions = binaryWriteOptions; - var BinaryWriter = class { - constructor(textEncoder) { - this.stack = []; - this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); - this.chunks = []; - this.buf = []; + exports2.isOneofGroup = isOneofGroup; + function getOneofValue(oneof, kind) { + return oneof[kind]; + } + exports2.getOneofValue = getOneofValue; + function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; } - /** - * Return all bytes written and reset this writer. - */ - finish() { - this.chunks.push(new Uint8Array(this.buf)); - let len = 0; - for (let i = 0; i < this.chunks.length; i++) - len += this.chunks[i].length; - let bytes = new Uint8Array(len); - let offset = 0; - for (let i = 0; i < this.chunks.length; i++) { - bytes.set(this.chunks[i], offset); - offset += this.chunks[i].length; - } - this.chunks = []; - return bytes; + oneof.oneofKind = kind; + if (value !== void 0) { + oneof[kind] = value; } - /** - * Start a new fork for length-delimited data like a message - * or a packed repeated field. - * - * Must be joined later with `join()`. - */ - fork() { - this.stack.push({ chunks: this.chunks, buf: this.buf }); - this.chunks = []; - this.buf = []; - return this; + } + exports2.setOneofValue = setOneofValue; + function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; } - /** - * Join the last fork. Write its length and bytes, then - * return to the previous state. - */ - join() { - let chunk = this.finish(); - let prev = this.stack.pop(); - if (!prev) - throw new Error("invalid state, fork stack empty"); - this.chunks = prev.chunks; - this.buf = prev.buf; - this.uint32(chunk.byteLength); - return this.raw(chunk); + oneof.oneofKind = kind; + if (value !== void 0 && kind !== void 0) { + oneof[kind] = value; + } + } + exports2.setUnknownOneofValue = setUnknownOneofValue; + function clearOneofValue(oneof) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = void 0; + } + exports2.clearOneofValue = clearOneofValue; + function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === void 0) { + return void 0; + } + return oneof[oneof.oneofKind]; + } + exports2.getSelectedOneofValue = getSelectedOneofValue; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js +var require_reflection_type_check = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionTypeCheck = void 0; + var reflection_info_1 = require_reflection_info(); + var oneof_1 = require_oneof(); + var ReflectionTypeCheck = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + } + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); + } + } else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; + } + } + } + this.data = { req, known, oneofs: Object.values(oneofs) }; } /** - * Writes a tag (field number and wire type). + * Is the argument a valid message as specified by the + * reflection information? * - * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. * - * Generated code should compute the tag ahead of time and call `uint32()`. + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. */ - tag(fieldNo, type2) { - return this.uint32((fieldNo << 3 | type2) >>> 0); + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === void 0 || typeof message != "object") + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + if (keys.some((k) => !data.known.includes(k))) + return false; + } + if (depth < 1) { + return true; + } + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === void 0) + continue; + const field = this.fields.find((f) => f.localName === group.oneofKind); + if (!field) + return false; + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + for (const field of this.fields) { + if (field.oneof !== void 0) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; + } + return true; } - /** - * Write a chunk of raw bytes. - */ - raw(chunk) { - if (this.buf.length) { - this.chunks.push(new Uint8Array(this.buf)); - this.buf = []; + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === void 0) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != "object" || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } + break; } - this.chunks.push(chunk); - return this; + return true; } - /** - * Write a `uint32` value, an unsigned 32 bit varint. - */ - uint32(value) { - assert_1.assertUInt32(value); - while (value > 127) { - this.buf.push(value & 127 | 128); - value = value >>> 7; + message(arg, type2, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type2.isAssignable(arg, depth); + } + return type2.is(arg, depth); + } + messages(arg, type2, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.isAssignable(arg[i], depth - 1)) + return false; + } else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.is(arg[i], depth - 1)) + return false; + } + return true; + } + scalar(arg, type2, longType) { + let argType = typeof arg; + switch (type2) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == "boolean"; + case reflection_info_1.ScalarType.STRING: + return argType == "string"; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == "number" && !isNaN(arg); + default: + return argType == "number" && Number.isInteger(arg); } - this.buf.push(value); - return this; } - /** - * Write a `int32` value, a signed 32 bit varint. - */ - int32(value) { - assert_1.assertInt32(value); - goog_varint_1.varint32write(value, this.buf); - return this; + scalars(arg, type2, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type2, longType)) + return false; + } + return true; } - /** - * Write a `bool` value, a variant. - */ - bool(value) { - this.buf.push(value ? 1 : 0); - return this; + mapKeys(map2, type2, depth) { + let keys = Object.keys(map2); + switch (type2) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); + default: + return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + } } - /** - * Write a `bytes` value, length-delimited arbitrary data. - */ - bytes(value) { - this.uint32(value.byteLength); - return this.raw(value); + }; + exports2.ReflectionTypeCheck = ReflectionTypeCheck; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js +var require_reflection_long_convert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionLongConvert = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionLongConvert(long, type2) { + switch (type2) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + return long.toString(); } - /** - * Write a `string` value, length-delimited data converted to UTF-8 text. - */ - string(value) { - let chunk = this.textEncoder.encode(value); - this.uint32(chunk.byteLength); - return this.raw(chunk); + } + exports2.reflectionLongConvert = reflectionLongConvert; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js +var require_reflection_json_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonReader = void 0; + var json_typings_1 = require_json_typings(); + var base64_1 = require_base642(); + var reflection_info_1 = require_reflection_info(); + var pb_long_1 = require_pb_long(); + var assert_1 = require_assert(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var ReflectionJsonReader = class { + constructor(info6) { + this.info = info6; } - /** - * Write a `float` value, 32-bit floating point number. - */ - float(value) { - assert_1.assertFloat32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setFloat32(0, value, true); - return this.raw(chunk); + prepare() { + var _a; + if (this.fMap === void 0) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } + } } - /** - * Write a `double` value, a 64-bit floating point number. - */ - double(value) { - let chunk = new Uint8Array(8); - new DataView(chunk.buffer).setFloat64(0, value, true); - return this.raw(chunk); + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + } } /** - * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. */ - fixed32(value) { - assert_1.assertUInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setUint32(0, value, true); - return this.raw(chunk); + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + let target; + if (field.oneof) { + if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { + continue; + } + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } else { + target = message; + } + if (field.kind == "map") { + if (jsonValue === null) { + continue; + } + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + const fieldObj = target[localName]; + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + let val2; + switch (field.V.kind) { + case "message": + val2 = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val2; + } + } else if (field.repeat) { + if (jsonValue === null) + continue; + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + const fieldArr = target[localName]; + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val2; + switch (field.kind) { + case "message": + val2 = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name, jsonValue); + fieldArr.push(val2); + } + } else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { + this.assert(field.oneof === void 0, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + if (jsonValue === null) + continue; + let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + target[localName] = val2; + break; + case "scalar": + if (jsonValue === null) + continue; + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } + } } /** - * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). */ - sfixed32(value) { - assert_1.assertInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setInt32(0, value, true); - return this.raw(chunk); + enum(type2, json2, fieldName, ignoreUnknownFields) { + if (type2[0] == "google.protobuf.NullValue") + assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); + if (json2 === null) + return 0; + switch (typeof json2) { + case "number": + assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); + return json2; + case "string": + let localEnumName = json2; + if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) + localEnumName = json2.substring(type2[2].length); + let enumNumber = type2[1][localEnumName]; + if (typeof enumNumber === "undefined" && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); + return enumNumber; + } + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); } - /** - * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. - */ - sint32(value) { - assert_1.assertInt32(value); - value = (value << 1 ^ value >> 31) >>> 0; - goog_varint_1.varint32write(value, this.buf); - return this; + scalar(json2, type2, longType, fieldName) { + let e; + try { + switch (type2) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json2 === null) + return 0; + if (json2 === "NaN") + return Number.NaN; + if (json2 === "Infinity") + return Number.POSITIVE_INFINITY; + if (json2 === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json2 === "") { + e = "empty string"; + break; + } + if (typeof json2 == "string" && json2.trim().length !== json2.length) { + e = "extra whitespace"; + break; + } + if (typeof json2 != "string" && typeof json2 != "number") { + break; + } + let float2 = Number(json2); + if (Number.isNaN(float2)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float2)) { + e = "too large or small"; + break; + } + if (type2 == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float2); + return float2; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json2 === null) + return 0; + let int32; + if (typeof json2 == "number") + int32 = json2; + else if (json2 === "") + e = "empty string"; + else if (typeof json2 == "string") { + if (json2.trim().length !== json2.length) + e = "extra whitespace"; + else + int32 = Number(json2); + } + if (int32 === void 0) + break; + if (type2 == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json2 === null) + return false; + if (typeof json2 !== "boolean") + break; + return json2; + // string: + case reflection_info_1.ScalarType.STRING: + if (json2 === null) + return ""; + if (typeof json2 !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json2); + } catch (e2) { + e2 = "invalid UTF8"; + break; + } + return json2; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json2 === null || json2 === "") + return new Uint8Array(0); + if (typeof json2 !== "string") + break; + return base64_1.base64decode(json2); + } + } catch (error4) { + e = error4.message; + } + this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - /** - * Write a `fixed64` value, a signed, fixed-length 64-bit integer. - */ - sfixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbLong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + }; + exports2.ReflectionJsonReader = ReflectionJsonReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js +var require_reflection_json_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonWriter = void 0; + var base64_1 = require_base642(); + var pb_long_1 = require_pb_long(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); + var ReflectionJsonWriter = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; } /** - * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + * Converts the message to a JSON object, based on the field descriptors. */ - fixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbULong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + write(message, options) { + const json2 = {}, source = message; + for (const field of this.fields) { + if (!field.oneof) { + let jsonValue2 = this.field(field, source[field.localName], options); + if (jsonValue2 !== void 0) + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; + continue; + } + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; + const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== void 0); + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + } + return json2; } - /** - * Write a `int64` value, a signed 64-bit varint. - */ - int64(value) { - let long = pb_long_1.PbLong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + field(field, value, options) { + let jsonValue = void 0; + if (field.kind == "map") { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); + const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + } + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); + const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val2 = this.message(messageType, value[i], field.name, options); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + } + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } + } + return jsonValue; } /** - * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + * Returns `null` as the default for google.protobuf.NullValue. */ - sint64(value) { - let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; - goog_varint_1.varint64write(lo, hi, this.buf); - return this; + enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type2[0] == "google.protobuf.NullValue") + return !emitDefaultValues && !optional ? void 0 : null; + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + if (value === 0 && !emitDefaultValues && !optional) + return void 0; + assert_1.assert(typeof value == "number"); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type2[1].hasOwnProperty(value)) + return value; + if (type2[2]) + return type2[2] + type2[1][value]; + return type2[1][value]; } - /** - * Write a `uint64` value, an unsigned 64-bit varint. - */ - uint64(value) { - let long = pb_long_1.PbULong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + message(type2, value, fieldName, options) { + if (value === void 0) + return options.emitDefaultValues ? null : void 0; + return type2.internalJsonWrite(value, options); } - }; - exports2.BinaryWriter = BinaryWriter; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js -var require_json_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; - var defaultsWrite = { - emitDefaultValues: false, - enumAsInteger: false, - useProtoFieldName: false, - prettySpaces: 0 - }; - var defaultsRead = { - ignoreUnknownFields: false - }; - function jsonReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.jsonReadOptions = jsonReadOptions; - function jsonWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.jsonWriteOptions = jsonWriteOptions; - function mergeJsonOptions(a, b) { - var _a, _b; - let c = Object.assign(Object.assign({}, a), b); - c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; - return c; - } - exports2.mergeJsonOptions = mergeJsonOptions; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js -var require_message_type_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MESSAGE_TYPE = void 0; - exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js -var require_lower_camel_case = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.lowerCamelCase = void 0; - function lowerCamelCase(snakeCase) { - let capNext = false; - const sb = []; - for (let i = 0; i < snakeCase.length; i++) { - let next = snakeCase.charAt(i); - if (next == "_") { - capNext = true; - } else if (/\d/.test(next)) { - sb.push(next); - capNext = true; - } else if (capNext) { - sb.push(next.toUpperCase()); - capNext = false; - } else if (i == 0) { - sb.push(next.toLowerCase()); - } else { - sb.push(next); + scalar(type2, value, fieldName, optional, emitDefaultValues) { + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + const ed = emitDefaultValues || optional; + switch (type2) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assert(typeof value == "number"); + if (Number.isNaN(value)) + return "NaN"; + if (value === Number.POSITIVE_INFINITY) + return "Infinity"; + if (value === Number.NEGATIVE_INFINITY) + return "-Infinity"; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? "" : void 0; + assert_1.assert(typeof value == "string"); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : void 0; + assert_1.assert(typeof value == "boolean"); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return void 0; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return void 0; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : void 0; + return base64_1.base64encode(value); } } - return sb.join(""); - } - exports2.lowerCamelCase = lowerCamelCase; + }; + exports2.ReflectionJsonWriter = ReflectionJsonWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js -var require_reflection_info = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js +var require_reflection_scalar_default = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; - var lower_camel_case_1 = require_lower_camel_case(); - var ScalarType; - (function(ScalarType2) { - ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; - ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; - ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; - ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; - ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; - ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; - ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; - ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; - ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; - ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; - ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; - ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; - ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; - ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; - ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; - })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); - var LongType; - (function(LongType2) { - LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; - LongType2[LongType2["STRING"] = 1] = "STRING"; - LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; - })(LongType = exports2.LongType || (exports2.LongType = {})); - var RepeatType; - (function(RepeatType2) { - RepeatType2[RepeatType2["NO"] = 0] = "NO"; - RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; - RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; - })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); - function normalizeFieldInfo(field) { - var _a, _b, _c, _d; - field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); - field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); - field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; - field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; - return field; - } - exports2.normalizeFieldInfo = normalizeFieldInfo; - function readFieldOptions(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readFieldOptions = readFieldOptions; - function readFieldOption(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readFieldOption = readFieldOption; - function readMessageOption(messageType, extensionName, extensionType) { - const options = messageType.options; - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + exports2.reflectionScalarDefault = void 0; + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var pb_long_1 = require_pb_long(); + function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { + switch (type2) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + return 0; } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.readMessageOption = readMessageOption; + exports2.reflectionScalarDefault = reflectionScalarDefault; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js -var require_oneof = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js +var require_reflection_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; - function isOneofGroup(any) { - if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { - return false; - } - switch (typeof any.oneofKind) { - case "string": - if (any[any.oneofKind] === void 0) - return false; - return Object.keys(any).length == 2; - case "undefined": - return Object.keys(any).length == 1; - default: - return false; - } - } - exports2.isOneofGroup = isOneofGroup; - function getOneofValue(oneof, kind) { - return oneof[kind]; - } - exports2.getOneofValue = getOneofValue; - function setOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== void 0) { - oneof[kind] = value; + exports2.ReflectionBinaryReader = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var ReflectionBinaryReader = class { + constructor(info6) { + this.info = info6; } - } - exports2.setOneofValue = setOneofValue; - function setUnknownOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + } } - oneof.oneofKind = kind; - if (value !== void 0 && kind !== void 0) { - oneof[kind] = value; + /** + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(reader, message, options, length) { + this.prepare(); + const end = length === void 0 ? reader.len : reader.pos + length; + while (reader.pos < end) { + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; + } + let target = message, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + target = target[field.oneof]; + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : void 0; + if (repeated) { + let arr = target[localName]; + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } else + arr.push(this.scalar(reader, T, L)); + } else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + target[localName][mapKey] = mapVal; + break; + } + } } - } - exports2.setUnknownOneofValue = setUnknownOneofValue; - function clearOneofValue(oneof) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + /** + * Read a map field, expecting key field = 1, value field = 2 + */ + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = void 0; + let val2 = void 0; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val2 = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val2 = reader.int32(); + break; + case "message": + val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } + } + if (key === void 0) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val2 === void 0) + switch (field.V.kind) { + case "scalar": + val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val2 = 0; + break; + case "message": + val2 = field.V.T().create(); + break; + } + return [key, val2]; } - oneof.oneofKind = void 0; - } - exports2.clearOneofValue = clearOneofValue; - function getSelectedOneofValue(oneof) { - if (oneof.oneofKind === void 0) { - return void 0; + scalar(reader, type2, longType) { + switch (type2) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } } - return oneof[oneof.oneofKind]; - } - exports2.getSelectedOneofValue = getSelectedOneofValue; + }; + exports2.ReflectionBinaryReader = ReflectionBinaryReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js -var require_reflection_type_check = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js +var require_reflection_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionTypeCheck = void 0; + exports2.ReflectionBinaryWriter = void 0; + var binary_format_contract_1 = require_binary_format_contract(); var reflection_info_1 = require_reflection_info(); - var oneof_1 = require_oneof(); - var ReflectionTypeCheck = class { + var assert_1 = require_assert(); + var pb_long_1 = require_pb_long(); + var ReflectionBinaryWriter = class { constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + this.info = info6; } prepare() { - if (this.data) - return; - const req = [], known = [], oneofs = []; - for (let field of this.fields) { - if (field.oneof) { - if (!oneofs.includes(field.oneof)) { - oneofs.push(field.oneof); - req.push(field.oneof); - known.push(field.oneof); - } - } else { - known.push(field.localName); - switch (field.kind) { - case "scalar": - case "enum": - if (!field.opt || field.repeat) - req.push(field.localName); - break; - case "message": - if (field.repeat) - req.push(field.localName); - break; - case "map": - req.push(field.localName); - break; - } - } + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); } - this.data = { req, known, oneofs: Object.values(oneofs) }; } /** - * Is the argument a valid message as specified by the - * reflection information? - * - * Checks all field types recursively. The `depth` - * specifies how deep into the structure the check will be. - * - * With a depth of 0, only the presence of fields - * is checked. - * - * With a depth of 1 or more, the field types are checked. - * - * With a depth of 2 or more, the members of map, repeated - * and message fields are checked. - * - * Message fields will be checked recursively with depth - 1. - * - * The number of map entries / repeated values being checked - * is < depth. + * Writes the message to binary format. */ - is(message, depth, allowExcessProperties = false) { - if (depth < 0) - return true; - if (message === null || message === void 0 || typeof message != "object") - return false; + write(message, writer, options) { this.prepare(); - let keys = Object.keys(message), data = this.data; - if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) - return false; - if (!allowExcessProperties) { - if (keys.some((k) => !data.known.includes(k))) - return false; - } - if (depth < 1) { - return true; - } - for (const name of data.oneofs) { - const group = message[name]; - if (!oneof_1.isOneofGroup(group)) - return false; - if (group.oneofKind === void 0) - continue; - const field = this.fields.find((f) => f.localName === group.oneofKind); - if (!field) - return false; - if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) - return false; - } for (const field of this.fields) { - if (field.oneof !== void 0) - continue; - if (!this.field(message[field.localName], field, allowExcessProperties, depth)) - return false; + let value, emitDefault, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; + value = group[localName]; + emitDefault = true; + } else { + value = message[localName]; + emitDefault = false; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } else if (value === void 0) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == "object" && value !== null); + for (const [key, val2] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val2); + break; + } } - return true; + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); } - field(arg, field, allowExcessProperties, depth) { - let repeated = field.repeat; - switch (field.kind) { + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); + break; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == "true" || key == "false"); + keyValue = key == "true"; + break; + } + this.scalar(writer, field.K, 1, keyValue, true); + switch (field.V.kind) { case "scalar": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, field.T, depth, field.L); - return this.scalar(arg, field.T, field.L); + this.scalar(writer, field.V.T, 2, value, true); + break; case "enum": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); - return this.scalar(arg, reflection_info_1.ScalarType.INT32); + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; case "message": - if (arg === void 0) - return true; - if (repeated) - return this.messages(arg, field.T(), allowExcessProperties, depth); - return this.message(arg, field.T(), allowExcessProperties, depth); - case "map": - if (typeof arg != "object" || arg === null) - return false; - if (depth < 2) - return true; - if (!this.mapKeys(arg, field.K, depth)) - return false; - switch (field.V.kind) { - case "scalar": - return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); - case "enum": - return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); - case "message": - return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); - } + this.message(writer, options, field.V.T(), 2, value); break; } - return true; + writer.join(); } - message(arg, type2, allowExcessProperties, depth) { - if (allowExcessProperties) { - return type2.isAssignable(arg, depth); - } - return type2.is(arg, depth); + message(writer, options, handler, fieldNo, value) { + if (value === void 0) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); } - messages(arg, type2, allowExcessProperties, depth) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (allowExcessProperties) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.isAssignable(arg[i], depth - 1)) - return false; - } else { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.is(arg[i], depth - 1)) - return false; + /** + * Write a single scalar value. + */ + scalar(writer, type2, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type2, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); } - return true; } - scalar(arg, type2, longType) { - let argType = typeof arg; + /** + * Write an array of scalar values in packed format. + */ + packed(writer, type2, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let [, method] = this.scalarInfo(type2); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + writer.join(); + } + /** + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. + */ + scalarInfo(type2, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === void 0; + let d = value === 0; switch (type2) { - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - switch (longType) { - case reflection_info_1.LongType.BIGINT: - return argType == "bigint"; - case reflection_info_1.LongType.NUMBER: - return argType == "number" && !isNaN(arg); - default: - return argType == "string"; - } - case reflection_info_1.ScalarType.BOOL: - return argType == "boolean"; + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; case reflection_info_1.ScalarType.STRING: - return argType == "string"; - case reflection_info_1.ScalarType.BYTES: - return arg instanceof Uint8Array; + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; case reflection_info_1.ScalarType.FLOAT: - return argType == "number" && !isNaN(arg); - default: - return argType == "number" && Number.isInteger(arg); - } - } - scalars(arg, type2, depth, longType) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (Array.isArray(arg)) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!this.scalar(arg[i], type2, longType)) - return false; - } - return true; - } - mapKeys(map2, type2, depth) { - let keys = Object.keys(map2); - switch (type2) { - case reflection_info_1.ScalarType.INT32: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); - case reflection_info_1.ScalarType.BOOL: - return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); - default: - return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; } + return [t, m, i || d]; } }; - exports2.ReflectionTypeCheck = ReflectionTypeCheck; + exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js -var require_reflection_long_convert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js +var require_reflection_create = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionLongConvert = void 0; + exports2.reflectionCreate = void 0; + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var message_type_contract_1 = require_message_type_contract(); + function reflectionCreate(type2) { + const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); + for (let field of type2.fields) { + let name = field.localName; + if (field.opt) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: void 0 }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } + } + return msg; + } + exports2.reflectionCreate = reflectionCreate; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js +var require_reflection_merge_partial = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionMergePartial = void 0; + function reflectionMergePartial(info6, target, source) { + let fieldValue, input = source, output; + for (let field of info6.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { + continue; + } + fieldValue = group[name]; + output = target[field.oneof]; + output.oneofKind = group.oneofKind; + if (fieldValue == void 0) { + delete output[name]; + continue; + } + } else { + fieldValue = input[name]; + output = target; + if (fieldValue == void 0) { + continue; + } + } + if (field.repeat) + output[name].length = fieldValue.length; + switch (field.kind) { + case "scalar": + case "enum": + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; + else + output[name] = fieldValue; + break; + case "message": + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === void 0) + output[name] = T.create(fieldValue); + else + T.mergePartial(output[name], fieldValue); + break; + case "map": + switch (field.V.kind) { + case "scalar": + case "enum": + Object.assign(output[name], fieldValue); + break; + case "message": + let T2 = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T2.create(fieldValue[k]); + break; + } + break; + } + } + } + exports2.reflectionMergePartial = reflectionMergePartial; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js +var require_reflection_equals = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionEquals = void 0; var reflection_info_1 = require_reflection_info(); - function reflectionLongConvert(long, type2) { - switch (type2) { - case reflection_info_1.LongType.BIGINT: - return long.toBigInt(); - case reflection_info_1.LongType.NUMBER: - return long.toNumber(); - default: - return long.toString(); + function reflectionEquals(info6, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info6.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) + return false; + break; + } } + return true; + } + exports2.reflectionEquals = reflectionEquals; + var objectValues = Object.values; + function primitiveEq(type2, a, b) { + if (a === b) + return true; + if (type2 !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; + } + function repeatedPrimitiveEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type2, a[i], b[i])) + return false; + return true; + } + function repeatedMsgEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type2.equals(a[i], b[i])) + return false; + return true; } - exports2.reflectionLongConvert = reflectionLongConvert; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js -var require_reflection_json_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js +var require_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonReader = void 0; - var json_typings_1 = require_json_typings(); - var base64_1 = require_base642(); + exports2.MessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); var reflection_info_1 = require_reflection_info(); - var pb_long_1 = require_pb_long(); - var assert_1 = require_assert(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var ReflectionJsonReader = class { - constructor(info6) { - this.info = info6; + var reflection_type_check_1 = require_reflection_type_check(); + var reflection_json_reader_1 = require_reflection_json_reader(); + var reflection_json_writer_1 = require_reflection_json_writer(); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + var reflection_create_1 = require_reflection_create(); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + var json_typings_1 = require_json_typings(); + var json_format_contract_1 = require_json_format_contract(); + var reflection_equals_1 = require_reflection_equals(); + var binary_writer_1 = require_binary_writer(); + var binary_reader_1 = require_binary_reader(); + var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); + var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; + var MessageType = class { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + messageTypeDescriptor.value = this; + this.messagePrototype = Object.create(null, baseDescriptors); + this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); + this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); + this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } - prepare() { - var _a; - if (this.fMap === void 0) { - this.fMap = {}; - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - for (const field of fieldsInput) { - this.fMap[field.name] = field; - this.fMap[field.jsonName] = field; - this.fMap[field.localName] = field; - } + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== void 0) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); } + return message; } - // Cannot parse JSON for #. - assert(condition, fieldName, jsonValue) { - if (!condition) { - let what = json_typings_1.typeofJsonValue(jsonValue); - if (what == "number" || what == "boolean") - what = jsonValue.toString(); - throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + /** + * Clone the message. + * + * Unknown fields are discarded. + */ + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; + } + /** + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. + */ + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); + } + /** + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); + } + /** + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); + } + /** + * Copy partial data into the target message. + */ + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); + } + /** + * Create a new message from binary format. + */ + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + } + /** + * Read a new message from a JSON value. + */ + fromJson(json2, options) { + return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + } + /** + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. + */ + fromJsonString(json2, options) { + let value = JSON.parse(json2); + return this.fromJson(value, options); + } + /** + * Write the message to canonical JSON value. + */ + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + } + /** + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` + */ + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + } + /** + * Write the message to binary format. + */ + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + } + /** + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. + */ + internalJsonRead(json2, options, target) { + if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json2, message, options); + return message; } + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); } /** - * Reads a message from canonical JSON format into the target message. + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); + } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. * - * If a message field is already present, it will be merged with the - * new data. + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. */ - read(input, message, options) { - this.prepare(); - const oneofsHandled = []; - for (const [jsonKey, jsonValue] of Object.entries(input)) { - const field = this.fMap[jsonKey]; - if (!field) { - if (!options.ignoreUnknownFields) - throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); - continue; - } - const localName = field.localName; - let target; - if (field.oneof) { - if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { - continue; - } - if (oneofsHandled.includes(field.oneof)) - throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); - oneofsHandled.push(field.oneof); - target = message[field.oneof] = { - oneofKind: localName - }; - } else { - target = message; - } - if (field.kind == "map") { - if (jsonValue === null) { - continue; - } - this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); - const fieldObj = target[localName]; - for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { - this.assert(jsonObjValue !== null, field.name + " map value", null); - let val2; - switch (field.V.kind) { - case "message": - val2 = field.V.T().internalJsonRead(jsonObjValue, options); - break; - case "enum": - val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); - let key = jsonObjKey; - if (field.K == reflection_info_1.ScalarType.BOOL) - key = key == "true" ? true : key == "false" ? false : key; - key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); - fieldObj[key] = val2; - } - } else if (field.repeat) { - if (jsonValue === null) - continue; - this.assert(Array.isArray(jsonValue), field.name, jsonValue); - const fieldArr = target[localName]; - for (const jsonItem of jsonValue) { - this.assert(jsonItem !== null, field.name, null); - let val2; - switch (field.kind) { - case "message": - val2 = field.T().internalJsonRead(jsonItem, options); - break; - case "enum": - val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonItem, field.T, field.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name, jsonValue); - fieldArr.push(val2); - } - } else { - switch (field.kind) { - case "message": - if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { - this.assert(field.oneof === void 0, field.name + " (oneof member)", null); - continue; - } - target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); - break; - case "enum": - if (jsonValue === null) - continue; - let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - target[localName] = val2; - break; - case "scalar": - if (jsonValue === null) - continue; - target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); - break; - } - } - } + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; } /** - * Returns `false` for unrecognized string representations. + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. * - * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. */ - enum(type2, json2, fieldName, ignoreUnknownFields) { - if (type2[0] == "google.protobuf.NullValue") - assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); - if (json2 === null) - return 0; - switch (typeof json2) { - case "number": - assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); - return json2; - case "string": - let localEnumName = json2; - if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) - localEnumName = json2.substring(type2[2].length); - let enumNumber = type2[1][localEnumName]; - if (typeof enumNumber === "undefined" && ignoreUnknownFields) { - return false; - } - assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); - return enumNumber; - } - assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; } - scalar(json2, type2, longType, fieldName) { - let e; - try { - switch (type2) { - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - if (json2 === null) - return 0; - if (json2 === "NaN") - return Number.NaN; - if (json2 === "Infinity") - return Number.POSITIVE_INFINITY; - if (json2 === "-Infinity") - return Number.NEGATIVE_INFINITY; - if (json2 === "") { - e = "empty string"; - break; - } - if (typeof json2 == "string" && json2.trim().length !== json2.length) { - e = "extra whitespace"; - break; - } - if (typeof json2 != "string" && typeof json2 != "number") { - break; - } - let float2 = Number(json2); - if (Number.isNaN(float2)) { - e = "not a number"; - break; - } - if (!Number.isFinite(float2)) { - e = "too large or small"; - break; - } - if (type2 == reflection_info_1.ScalarType.FLOAT) - assert_1.assertFloat32(float2); - return float2; - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - if (json2 === null) - return 0; - let int32; - if (typeof json2 == "number") - int32 = json2; - else if (json2 === "") - e = "empty string"; - else if (typeof json2 == "string") { - if (json2.trim().length !== json2.length) - e = "extra whitespace"; - else - int32 = Number(json2); - } - if (int32 === void 0) - break; - if (type2 == reflection_info_1.ScalarType.UINT32) - assert_1.assertUInt32(int32); - else - assert_1.assertInt32(int32); - return int32; - // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.UINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); - // bool: - case reflection_info_1.ScalarType.BOOL: - if (json2 === null) - return false; - if (typeof json2 !== "boolean") - break; - return json2; - // string: - case reflection_info_1.ScalarType.STRING: - if (json2 === null) - return ""; - if (typeof json2 !== "string") { - e = "extra whitespace"; - break; - } - try { - encodeURIComponent(json2); - } catch (e2) { - e2 = "invalid UTF8"; - break; - } - return json2; - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - if (json2 === null || json2 === "") - return new Uint8Array(0); - if (typeof json2 !== "string") - break; - return base64_1.base64decode(json2); - } - } catch (error4) { - e = error4.message; + }; + exports2.MessageType = MessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js +var require_reflection_contains_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.containsMessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; + } + exports2.containsMessageType = containsMessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js +var require_enum_object = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; + function isEnumObject(arg) { + if (typeof arg != "object" || arg === null) { + return false; + } + if (!arg.hasOwnProperty(0)) { + return false; + } + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + let nam = arg[num]; + if (nam === void 0) + return false; + if (arg[nam] !== num) + return false; + } else { + let num2 = arg[k]; + if (num2 === void 0) + return false; + if (typeof num2 !== "number") + return false; + if (arg[num2] === void 0) + return false; } - this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - }; - exports2.ReflectionJsonReader = ReflectionJsonReader; + return true; + } + exports2.isEnumObject = isEnumObject; + function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; + } + exports2.listEnumValues = listEnumValues; + function listEnumNames(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.name); + } + exports2.listEnumNames = listEnumNames; + function listEnumNumbers(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + } + exports2.listEnumNumbers = listEnumNumbers; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js -var require_reflection_json_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonWriter = void 0; + var json_typings_1 = require_json_typings(); + Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { + return json_typings_1.typeofJsonValue; + } }); + Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { + return json_typings_1.isJsonObject; + } }); var base64_1 = require_base642(); + Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { + return base64_1.base64decode; + } }); + Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { + return base64_1.base64encode; + } }); + var protobufjs_utf8_1 = require_protobufjs_utf8(); + Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { + return protobufjs_utf8_1.utf8read; + } }); + var binary_format_contract_1 = require_binary_format_contract(); + Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { + return binary_format_contract_1.WireType; + } }); + Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { + return binary_format_contract_1.mergeBinaryOptions; + } }); + Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { + return binary_format_contract_1.UnknownFieldHandler; + } }); + var binary_reader_1 = require_binary_reader(); + Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { + return binary_reader_1.BinaryReader; + } }); + Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { + return binary_reader_1.binaryReadOptions; + } }); + var binary_writer_1 = require_binary_writer(); + Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { + return binary_writer_1.BinaryWriter; + } }); + Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { + return binary_writer_1.binaryWriteOptions; + } }); var pb_long_1 = require_pb_long(); + Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { + return pb_long_1.PbLong; + } }); + Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { + return pb_long_1.PbULong; + } }); + var json_format_contract_1 = require_json_format_contract(); + Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonReadOptions; + } }); + Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonWriteOptions; + } }); + Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { + return json_format_contract_1.mergeJsonOptions; + } }); + var message_type_contract_1 = require_message_type_contract(); + Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { + return message_type_contract_1.MESSAGE_TYPE; + } }); + var message_type_1 = require_message_type(); + Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { + return message_type_1.MessageType; + } }); var reflection_info_1 = require_reflection_info(); + Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { + return reflection_info_1.ScalarType; + } }); + Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { + return reflection_info_1.LongType; + } }); + Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { + return reflection_info_1.RepeatType; + } }); + Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { + return reflection_info_1.normalizeFieldInfo; + } }); + Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { + return reflection_info_1.readFieldOptions; + } }); + Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { + return reflection_info_1.readFieldOption; + } }); + Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { + return reflection_info_1.readMessageOption; + } }); + var reflection_type_check_1 = require_reflection_type_check(); + Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { + return reflection_type_check_1.ReflectionTypeCheck; + } }); + var reflection_create_1 = require_reflection_create(); + Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { + return reflection_create_1.reflectionCreate; + } }); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { + return reflection_scalar_default_1.reflectionScalarDefault; + } }); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { + return reflection_merge_partial_1.reflectionMergePartial; + } }); + var reflection_equals_1 = require_reflection_equals(); + Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { + return reflection_equals_1.reflectionEquals; + } }); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { + return reflection_binary_reader_1.ReflectionBinaryReader; + } }); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { + return reflection_binary_writer_1.ReflectionBinaryWriter; + } }); + var reflection_json_reader_1 = require_reflection_json_reader(); + Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { + return reflection_json_reader_1.ReflectionJsonReader; + } }); + var reflection_json_writer_1 = require_reflection_json_writer(); + Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { + return reflection_json_writer_1.ReflectionJsonWriter; + } }); + var reflection_contains_message_type_1 = require_reflection_contains_message_type(); + Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { + return reflection_contains_message_type_1.containsMessageType; + } }); + var oneof_1 = require_oneof(); + Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { + return oneof_1.isOneofGroup; + } }); + Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { + return oneof_1.setOneofValue; + } }); + Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { + return oneof_1.getOneofValue; + } }); + Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { + return oneof_1.clearOneofValue; + } }); + Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { + return oneof_1.getSelectedOneofValue; + } }); + var enum_object_1 = require_enum_object(); + Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { + return enum_object_1.listEnumValues; + } }); + Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { + return enum_object_1.listEnumNames; + } }); + Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { + return enum_object_1.listEnumNumbers; + } }); + Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { + return enum_object_1.isEnumObject; + } }); + var lower_camel_case_1 = require_lower_camel_case(); + Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { + return lower_camel_case_1.lowerCamelCase; + } }); var assert_1 = require_assert(); - var ReflectionJsonWriter = class { - constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { + return assert_1.assert; + } }); + Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { + return assert_1.assertNever; + } }); + Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { + return assert_1.assertInt32; + } }); + Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { + return assert_1.assertUInt32; + } }); + Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { + return assert_1.assertFloat32; + } }); + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js +var require_reflection_info2 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + var runtime_1 = require_commonjs11(); + function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + m.serverStreaming = !!m.serverStreaming; + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; + return m; + } + exports2.normalizeMethodInfo = normalizeMethodInfo; + function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readMethodOptions = readMethodOptions; + function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; } - /** - * Converts the message to a JSON object, based on the field descriptors. - */ - write(message, options) { - const json2 = {}, source = message; - for (const field of this.fields) { - if (!field.oneof) { - let jsonValue2 = this.field(field, source[field.localName], options); - if (jsonValue2 !== void 0) - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; - continue; - } - const group = source[field.oneof]; - if (group.oneofKind !== field.localName) - continue; - const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; - let jsonValue = this.field(field, group[field.localName], opt); - assert_1.assert(jsonValue !== void 0); - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; - } - return json2; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - field(field, value, options) { - let jsonValue = void 0; - if (field.kind == "map") { - assert_1.assert(typeof value == "object" && value !== null); - const jsonObj = {}; - switch (field.V.kind) { - case "scalar": - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "message": - const messageType = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.message(messageType, entryValue, field.name, options); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "enum": - const enumInfo = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); - const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - } - if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) - jsonValue = jsonObj; - } else if (field.repeat) { - assert_1.assert(Array.isArray(value)); - const jsonArr = []; - switch (field.kind) { - case "scalar": - for (let i = 0; i < value.length; i++) { - const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "enum": - const enumInfo = field.T(); - for (let i = 0; i < value.length; i++) { - assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); - const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "message": - const messageType = field.T(); - for (let i = 0; i < value.length; i++) { - const val2 = this.message(messageType, value[i], field.name, options); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - } - if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) - jsonValue = jsonArr; - } else { - switch (field.kind) { - case "scalar": - jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); - break; - case "enum": - jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); - break; - case "message": - jsonValue = this.message(field.T(), value, field.name, options); - break; - } - } - return jsonValue; + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMethodOption = readMethodOption; + function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return void 0; } - /** - * Returns `null` as the default for google.protobuf.NullValue. - */ - enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { - if (type2[0] == "google.protobuf.NullValue") - return !emitDefaultValues && !optional ? void 0 : null; - if (value === void 0) { - assert_1.assert(optional); - return void 0; - } - if (value === 0 && !emitDefaultValues && !optional) - return void 0; - assert_1.assert(typeof value == "number"); - assert_1.assert(Number.isInteger(value)); - if (enumAsInteger || !type2[1].hasOwnProperty(value)) - return value; - if (type2[2]) - return type2[2] + type2[1][value]; - return type2[1][value]; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - message(type2, value, fieldName, options) { - if (value === void 0) - return options.emitDefaultValues ? null : void 0; - return type2.internalJsonWrite(value, options); + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readServiceOption = readServiceOption; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js +var require_service_type = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServiceType = void 0; + var reflection_info_1 = require_reflection_info2(); + var ServiceType = class { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; } - scalar(type2, value, fieldName, optional, emitDefaultValues) { - if (value === void 0) { - assert_1.assert(optional); - return void 0; + }; + exports2.ServiceType = ServiceType; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js +var require_rpc_error = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcError = void 0; + var RpcError = class extends Error { + constructor(message, code = "UNKNOWN", meta) { + super(message); + this.name = "RpcError"; + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; + } + toString() { + const l = [this.name + ": " + this.message]; + if (this.code) { + l.push(""); + l.push("Code: " + this.code); } - const ed = emitDefaultValues || optional; - switch (type2) { - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertInt32(value); - return value; - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertUInt32(value); - return value; - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.FLOAT: - assert_1.assertFloat32(value); - case reflection_info_1.ScalarType.DOUBLE: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assert(typeof value == "number"); - if (Number.isNaN(value)) - return "NaN"; - if (value === Number.POSITIVE_INFINITY) - return "Infinity"; - if (value === Number.NEGATIVE_INFINITY) - return "-Infinity"; - return value; - // string: - case reflection_info_1.ScalarType.STRING: - if (value === "") - return ed ? "" : void 0; - assert_1.assert(typeof value == "string"); - return value; - // bool: - case reflection_info_1.ScalarType.BOOL: - if (value === false) - return ed ? false : void 0; - assert_1.assert(typeof value == "boolean"); - return value; - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let ulong = pb_long_1.PbULong.from(value); - if (ulong.isZero() && !ed) - return void 0; - return ulong.toString(); - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let long = pb_long_1.PbLong.from(value); - if (long.isZero() && !ed) - return void 0; - return long.toString(); - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - assert_1.assert(value instanceof Uint8Array); - if (!value.byteLength) - return ed ? "" : void 0; - return base64_1.base64encode(value); + if (this.serviceName && this.methodName) { + l.push("Method: " + this.serviceName + "/" + this.methodName); + } + let m = Object.entries(this.meta); + if (m.length) { + l.push(""); + l.push("Meta:"); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); + } } + return l.join("\n"); } }; - exports2.ReflectionJsonWriter = ReflectionJsonWriter; + exports2.RpcError = RpcError; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js -var require_reflection_scalar_default = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js +var require_rpc_options = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionScalarDefault = void 0; - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var pb_long_1 = require_pb_long(); - function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { - switch (type2) { - case reflection_info_1.ScalarType.BOOL: - return false; - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return 0; - case reflection_info_1.ScalarType.BYTES: - return new Uint8Array(0); - case reflection_info_1.ScalarType.STRING: - return ""; - default: - return 0; + exports2.mergeRpcOptions = void 0; + var runtime_1 = require_commonjs11(); + function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val2 = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); + break; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); + break; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); + break; + } + } + return o; + } + exports2.mergeRpcOptions = mergeRpcOptions; + function copy(a, into) { + if (!a) + return; + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; } } - exports2.reflectionScalarDefault = reflectionScalarDefault; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js -var require_reflection_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js +var require_deferred = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryReader = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var ReflectionBinaryReader = class { - constructor(info6) { - this.info = info6; - } - prepare() { - var _a; - if (!this.fieldNoToField) { - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + exports2.Deferred = exports2.DeferredState = void 0; + var DeferredState; + (function(DeferredState2) { + DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; + DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; + DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; + })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); + var Deferred = class { + /** + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. + */ + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve4, reject) => { + this._resolve = resolve4; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch((_) => { + }); } } /** - * Reads a message from binary format into the target message. + * Get the current state of the promise. + */ + get state() { + return this._state; + } + /** + * Get the deferred promise. + */ + get promise() { + return this._promise; + } + /** + * Resolve the promise. Throws if the promise is already resolved or rejected. + */ + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; + } + /** + * Reject the promise. Throws if the promise is already resolved or rejected. + */ + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; + } + /** + * Resolve the promise. Ignore if not pending. + */ + resolvePending(val2) { + if (this._state === DeferredState.PENDING) + this.resolve(val2); + } + /** + * Reject the promise. Ignore if not pending. + */ + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); + } + }; + exports2.Deferred = Deferred; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js +var require_rpc_output_stream = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcOutputStreamController = void 0; + var deferred_1 = require_deferred(); + var runtime_1 = require_commonjs11(); + var RpcOutputStreamController = class { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [] + }; + this._closed = false; + this._itState = { q: [] }; + } + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); + } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); + } + // --- Controller API + /** + * Is this stream already closed by a completion or error? + */ + get closed() { + return this._closed !== false; + } + /** + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. + */ + notifyNext(message, error4, complete) { + runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); + if (message) + this.notifyMessage(message); + if (error4) + this.notifyError(error4); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, "stream is closed"); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach((l) => l(message)); + this._lis.nxt.forEach((l) => l(message, void 0, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. * - * If a message field is already present, it will be merged with the - * new data. + * Triggers onNext and onError callbacks. */ - read(reader, message, options, length) { - this.prepare(); - const end = length === void 0 ? reader.len : reader.pos + length; - while (reader.pos < end) { - const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); - if (!field) { - let u = options.readUnknownField; - if (u == "throw") - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); - continue; - } - let target = message, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - target = target[field.oneof]; - if (target.oneofKind !== localName) - target = message[field.oneof] = { - oneofKind: localName - }; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - let L = field.kind == "scalar" ? field.L : void 0; - if (repeated) { - let arr = target[localName]; - if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { - let e = reader.uint32() + reader.pos; - while (reader.pos < e) - arr.push(this.scalar(reader, T, L)); - } else - arr.push(this.scalar(reader, T, L)); - } else - target[localName] = this.scalar(reader, T, L); - break; - case "message": - if (repeated) { - let arr = target[localName]; - let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); - arr.push(msg); - } else - target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); - break; - case "map": - let [mapKey, mapVal] = this.mapEntry(field, reader, options); - target[localName][mapKey] = mapVal; - break; - } - } + notifyError(error4) { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = error4; + this.pushIt(error4); + this._lis.err.forEach((l) => l(error4)); + this._lis.nxt.forEach((l) => l(void 0, error4, false)); + this.clearLis(); } /** - * Read a map field, expecting key field = 1, value field = 2 + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. */ - mapEntry(field, reader, options) { - let length = reader.uint32(); - let end = reader.pos + length; - let key = void 0; - let val2 = void 0; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case 1: - if (field.K == reflection_info_1.ScalarType.BOOL) - key = reader.bool().toString(); - else - key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); - break; - case 2: - switch (field.V.kind) { - case "scalar": - val2 = this.scalar(reader, field.V.T, field.V.L); - break; - case "enum": - val2 = reader.int32(); - break; - case "message": - val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); - break; - } - break; - default: - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + notifyComplete() { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach((l) => l()); + this._lis.nxt.forEach((l) => l(void 0, void 0, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); + runtime_1.assert(!state.p, "iterator contract broken"); + let first = state.q.shift(); + if (first) + return "value" in first ? Promise.resolve(first) : Promise.reject(first); + state.p = new deferred_1.Deferred(); + return state.p.promise; } + }; + } + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (state.p) { + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + "value" in result ? p.resolve(result) : p.reject(result); + delete state.p; + } else { + state.q.push(result); } - if (key === void 0) { - let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); - key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + }; + exports2.RpcOutputStreamController = RpcOutputStreamController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js +var require_unary_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - if (val2 === void 0) - switch (field.V.kind) { - case "scalar": - val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); - break; - case "enum": - val2 = 0; - break; - case "message": - val2 = field.V.T().create(); - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return [key, val2]; - } - scalar(reader, type2, longType) { - switch (type2) { - case reflection_info_1.ScalarType.INT32: - return reader.int32(); - case reflection_info_1.ScalarType.STRING: - return reader.string(); - case reflection_info_1.ScalarType.BOOL: - return reader.bool(); - case reflection_info_1.ScalarType.DOUBLE: - return reader.double(); - case reflection_info_1.ScalarType.FLOAT: - return reader.float(); - case reflection_info_1.ScalarType.INT64: - return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); - case reflection_info_1.ScalarType.UINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); - case reflection_info_1.ScalarType.FIXED32: - return reader.fixed32(); - case reflection_info_1.ScalarType.BYTES: - return reader.bytes(); - case reflection_info_1.ScalarType.UINT32: - return reader.uint32(); - case reflection_info_1.ScalarType.SFIXED32: - return reader.sfixed32(); - case reflection_info_1.ScalarType.SFIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); - case reflection_info_1.ScalarType.SINT32: - return reader.sint32(); - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UnaryCall = void 0; + var UnaryCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryReader = ReflectionBinaryReader; + exports2.UnaryCall = UnaryCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js -var require_reflection_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js +var require_server_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryWriter = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var pb_long_1 = require_pb_long(); - var ReflectionBinaryWriter = class { - constructor(info6) { - this.info = info6; - } - prepare() { - if (!this.fields) { - const fieldsInput = this.info.fields ? this.info.fields.concat() : []; - this.fields = fieldsInput.sort((a, b) => a.no - b.no); - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - /** - * Writes the message to binary format. - */ - write(message, writer, options) { - this.prepare(); - for (const field of this.fields) { - let value, emitDefault, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - const group = message[field.oneof]; - if (group.oneofKind !== localName) - continue; - value = group[localName]; - emitDefault = true; - } else { - value = message[localName]; - emitDefault = false; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (repeated) { - assert_1.assert(Array.isArray(value)); - if (repeated == reflection_info_1.RepeatType.PACKED) - this.packed(writer, T, field.no, value); - else - for (const item of value) - this.scalar(writer, T, field.no, item, true); - } else if (value === void 0) - assert_1.assert(field.opt); - else - this.scalar(writer, T, field.no, value, emitDefault || field.opt); - break; - case "message": - if (repeated) { - assert_1.assert(Array.isArray(value)); - for (const item of value) - this.message(writer, options, field.T(), field.no, item); - } else { - this.message(writer, options, field.T(), field.no, value); - } - break; - case "map": - assert_1.assert(typeof value == "object" && value !== null); - for (const [key, val2] of Object.entries(value)) - this.mapEntry(writer, options, field, key, val2); - break; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - let u = options.writeUnknownFields; - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); - } - mapEntry(writer, options, field, key, value) { - writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let keyValue = key; - switch (field.K) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - keyValue = Number.parseInt(key); - break; - case reflection_info_1.ScalarType.BOOL: - assert_1.assert(key == "true" || key == "false"); - keyValue = key == "true"; - break; - } - this.scalar(writer, field.K, 1, keyValue, true); - switch (field.V.kind) { - case "scalar": - this.scalar(writer, field.V.T, 2, value, true); - break; - case "enum": - this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); - break; - case "message": - this.message(writer, options, field.V.T(), 2, value); - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - writer.join(); - } - message(writer, options, handler, fieldNo, value) { - if (value === void 0) - return; - handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); - writer.join(); - } - /** - * Write a single scalar value. - */ - scalar(writer, type2, fieldNo, value, emitDefault) { - let [wireType, method, isDefault] = this.scalarInfo(type2, value); - if (!isDefault || emitDefault) { - writer.tag(fieldNo, wireType); - writer[method](value); + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerStreamingCall = void 0; + var ServerStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } /** - * Write an array of scalar values in packed format. + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. */ - packed(writer, type2, fieldNo, value) { - if (!value.length) - return; - assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); - writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let [, method] = this.scalarInfo(type2); - for (let i = 0; i < value.length; i++) - writer[method](value[i]); - writer.join(); + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } - /** - * Get information for writing a scalar value. - * - * Returns tuple: - * [0]: appropriate WireType - * [1]: name of the appropriate method of IBinaryWriter - * [2]: whether the given value is a default value - * - * If argument `value` is omitted, [2] is always false. - */ - scalarInfo(type2, value) { - let t = binary_format_contract_1.WireType.Varint; - let m; - let i = value === void 0; - let d = value === 0; - switch (type2) { - case reflection_info_1.ScalarType.INT32: - m = "int32"; - break; - case reflection_info_1.ScalarType.STRING: - d = i || !value.length; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "string"; - break; - case reflection_info_1.ScalarType.BOOL: - d = value === false; - m = "bool"; - break; - case reflection_info_1.ScalarType.UINT32: - m = "uint32"; - break; - case reflection_info_1.ScalarType.DOUBLE: - t = binary_format_contract_1.WireType.Bit64; - m = "double"; - break; - case reflection_info_1.ScalarType.FLOAT: - t = binary_format_contract_1.WireType.Bit32; - m = "float"; - break; - case reflection_info_1.ScalarType.INT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "int64"; - break; - case reflection_info_1.ScalarType.UINT64: - d = i || pb_long_1.PbULong.from(value).isZero(); - m = "uint64"; - break; - case reflection_info_1.ScalarType.FIXED64: - d = i || pb_long_1.PbULong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "fixed64"; - break; - case reflection_info_1.ScalarType.BYTES: - d = i || !value.byteLength; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "bytes"; - break; - case reflection_info_1.ScalarType.FIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "fixed32"; - break; - case reflection_info_1.ScalarType.SFIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "sfixed32"; - break; - case reflection_info_1.ScalarType.SFIXED64: - d = i || pb_long_1.PbLong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "sfixed64"; - break; - case reflection_info_1.ScalarType.SINT32: - m = "sint32"; - break; - case reflection_info_1.ScalarType.SINT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "sint64"; - break; - } - return [t, m, i || d]; + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + exports2.ServerStreamingCall = ServerStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js -var require_reflection_create = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js +var require_client_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionCreate = void 0; - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var message_type_contract_1 = require_message_type_contract(); - function reflectionCreate(type2) { - const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); - for (let field of type2.fields) { - let name = field.localName; - if (field.opt) - continue; - if (field.oneof) - msg[field.oneof] = { oneofKind: void 0 }; - else if (field.repeat) - msg[name] = []; - else - switch (field.kind) { - case "scalar": - msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); - break; - case "enum": - msg[name] = 0; - break; - case "map": - msg[name] = {}; - break; - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - return msg; - } - exports2.reflectionCreate = reflectionCreate; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js -var require_reflection_merge_partial = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionMergePartial = void 0; - function reflectionMergePartial(info6, target, source) { - let fieldValue, input = source, output; - for (let field of info6.fields) { - let name = field.localName; - if (field.oneof) { - const group = input[field.oneof]; - if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { - continue; - } - fieldValue = group[name]; - output = target[field.oneof]; - output.oneofKind = group.oneofKind; - if (fieldValue == void 0) { - delete output[name]; - continue; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - } else { - fieldValue = input[name]; - output = target; - if (fieldValue == void 0) { - continue; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - if (field.repeat) - output[name].length = fieldValue.length; - switch (field.kind) { - case "scalar": - case "enum": - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = fieldValue[i]; - else - output[name] = fieldValue; - break; - case "message": - let T = field.T(); - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = T.create(fieldValue[i]); - else if (output[name] === void 0) - output[name] = T.create(fieldValue); - else - T.mergePartial(output[name], fieldValue); - break; - case "map": - switch (field.V.kind) { - case "scalar": - case "enum": - Object.assign(output[name], fieldValue); - break; - case "message": - let T2 = field.V.T(); - for (let k of Object.keys(fieldValue)) - output[name][k] = T2.create(fieldValue[k]); - break; - } - break; + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ClientStreamingCall = void 0; + var ClientStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; } - } - exports2.reflectionMergePartial = reflectionMergePartial; + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.ClientStreamingCall = ClientStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js -var require_reflection_equals = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js +var require_duplex_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionEquals = void 0; - var reflection_info_1 = require_reflection_info(); - function reflectionEquals(info6, a, b) { - if (a === b) - return true; - if (!a || !b) - return false; - for (let field of info6.fields) { - let localName = field.localName; - let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; - let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; - switch (field.kind) { - case "enum": - case "scalar": - let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) - return false; - break; - case "map": - if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) - return false; - break; - case "message": - let T = field.T(); - if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) - return false; - break; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DuplexStreamingCall = void 0; + var DuplexStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers + }; + }); } - return true; - } - exports2.reflectionEquals = reflectionEquals; - var objectValues = Object.values; - function primitiveEq(type2, a, b) { - if (a === b) - return true; - if (type2 !== reflection_info_1.ScalarType.BYTES) - return false; - let ba = a; - let bb = b; - if (ba.length !== bb.length) - return false; - for (let i = 0; i < ba.length; i++) - if (ba[i] != bb[i]) - return false; - return true; - } - function repeatedPrimitiveEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!primitiveEq(type2, a[i], b[i])) - return false; - return true; - } - function repeatedMsgEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!type2.equals(a[i], b[i])) - return false; - return true; - } + }; + exports2.DuplexStreamingCall = DuplexStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js -var require_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js +var require_test_transport = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_type_check_1 = require_reflection_type_check(); - var reflection_json_reader_1 = require_reflection_json_reader(); - var reflection_json_writer_1 = require_reflection_json_writer(); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - var reflection_create_1 = require_reflection_create(); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - var json_typings_1 = require_json_typings(); - var json_format_contract_1 = require_json_format_contract(); - var reflection_equals_1 = require_reflection_equals(); - var binary_writer_1 = require_binary_writer(); - var binary_reader_1 = require_binary_reader(); - var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); - var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; - var MessageType = class { - constructor(name, fields, options) { - this.defaultCheckDepth = 16; - this.typeName = name; - this.fields = fields.map(reflection_info_1.normalizeFieldInfo); - this.options = options !== null && options !== void 0 ? options : {}; - messageTypeDescriptor.value = this; - this.messagePrototype = Object.create(null, baseDescriptors); - this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); - this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); - this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); - this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); - this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - create(value) { - let message = reflection_create_1.reflectionCreate(this); - if (value !== void 0) { - reflection_merge_partial_1.reflectionMergePartial(this, message, value); + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - return message; - } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TestTransport = void 0; + var rpc_error_1 = require_rpc_error(); + var runtime_1 = require_commonjs11(); + var rpc_output_stream_1 = require_rpc_output_stream(); + var rpc_options_1 = require_rpc_options(); + var unary_call_1 = require_unary_call(); + var server_streaming_call_1 = require_server_streaming_call(); + var client_streaming_call_1 = require_client_streaming_call(); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + var TestTransport = class _TestTransport { /** - * Clone the message. - * - * Unknown fields are discarded. + * Initialize with mock data. Omitted fields have default value. */ - clone(message) { - let copy = this.create(); - reflection_merge_partial_1.reflectionMergePartial(this, copy, message); - return copy; + constructor(data) { + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; } /** - * Determines whether two message of the same type have the same field values. - * Checks for deep equality, traversing repeated fields, oneof groups, maps - * and messages recursively. - * Will also return true if both messages are `undefined`. + * Sent message(s) during the last operation. */ - equals(a, b) { - return reflection_equals_1.reflectionEquals(this, a, b); + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; + } else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; } /** - * Is the given value assignable to our message type - * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + * Sending message(s) completed? */ - is(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, false); + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } else if (typeof this.lastInput == "object") { + return true; + } + return false; } - /** - * Is the given value assignable to our message type, - * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? - */ - isAssignable(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, true); + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); } - /** - * Copy partial data into the target message. - */ - mergePartial(target, source) { - reflection_merge_partial_1.reflectionMergePartial(this, target, source); + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } else if (this.data.response !== void 0) { + r = this.data.response; + } else { + r = method.O.create(); + } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); } /** - * Create a new message from binary format. + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. */ - fromBinary(data, options) { - let opt = binary_reader_1.binaryReadOptions(options); - return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + streamResponses(method, stream, abort) { + return __awaiter4(this, void 0, void 0, function* () { + const messages = []; + if (this.data.response === void 0) { + messages.push(method.O.create()); + } else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + try { + yield delay2(this.responseDelay, abort)(void 0); + } catch (error4) { + stream.notifyError(error4); + return; + } + if (this.data.response instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.response); + return; + } + for (let msg of messages) { + stream.notifyMessage(msg); + try { + yield delay2(this.betweenResponseDelay, abort)(void 0); + } catch (error4) { + stream.notifyError(error4); + return; + } + } + if (this.data.status instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.status); + return; + } + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.trailers); + return; + } + stream.notifyComplete(); + }); } - /** - * Read a new message from a JSON value. - */ - fromJson(json2, options) { - return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); } - /** - * Read a new message from a JSON string. - * This is equivalent to `T.fromJson(JSON.parse(json))`. - */ - fromJsonString(json2, options) { - let value = JSON.parse(json2); - return this.fromJson(value, options); + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); } - /** - * Write the message to canonical JSON value. - */ - toJson(message, options) { - return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } } - /** - * Convert the message to canonical JSON string. - * This is equivalent to `JSON.stringify(T.toJson(t))` - */ - toJsonString(message, options) { + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); + } + unary(method, input, options) { var _a; - let value = this.toJson(message, options); - return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); } - /** - * Write the message to binary format. - */ - toBinary(message, options) { - let opt = binary_writer_1.binaryWriteOptions(options); - return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); } - /** - * This is an internal method. If you just want to read a message from - * JSON, use `fromJson()` or `fromJsonString()`. - * - * Reads JSON value and merges the fields into the target - * according to protobuf rules. If the target is omitted, - * a new instance is created first. - */ - internalJsonRead(json2, options, target) { - if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refJsonReader.read(json2, message, options); - return message; + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + } + }; + exports2.TestTransport = TestTransport; + TestTransport.defaultHeaders = { + responseHeader: "test" + }; + TestTransport.defaultStatus = { + code: "OK", + detail: "all good" + }; + TestTransport.defaultTrailers = { + responseTrailer: "test" + }; + function delay2(ms, abort) { + return (v) => new Promise((resolve4, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } else { + const id = setTimeout(() => resolve4(v), ms); + if (abort) { + abort.addEventListener("abort", (ev) => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } } - throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); + }); + } + var TestInputStream = class { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; } - /** - * This is an internal method. If you just want to write a message - * to JSON, use `toJson()` or `toJsonString(). - * - * Writes JSON value and returns it. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.write(message, options); + get sent() { + return this._sent; } - /** - * This is an internal method. If you just want to write a message - * in binary format, use `toBinary()`. - * - * Serializes the message in binary format and appends it to the given - * writer. Returns passed writer. - */ - internalBinaryWrite(message, writer, options) { - this.refBinWriter.write(message, writer, options); - return writer; + get completed() { + return this._completed; } - /** - * This is an internal method. If you just want to read a message from - * binary data, use `fromBinary()`. - * - * Reads data from binary format and merges the fields into - * the target according to protobuf rules. If the target is - * omitted, a new instance is created first. - */ - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refBinReader.read(reader, message, options, length); - return message; + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); + } + const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; + return Promise.resolve(void 0).then(() => { + this._sent.push(message); + }).then(delay2(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); + } + const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; + return Promise.resolve(void 0).then(() => { + this._completed = true; + }).then(delay2(delayMs, this.abort)); } }; - exports2.MessageType = MessageType; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js -var require_reflection_contains_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.containsMessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - function containsMessageType(msg) { - return msg[message_type_contract_1.MESSAGE_TYPE] != null; - } - exports2.containsMessageType = containsMessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js -var require_enum_object = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js +var require_rpc_interceptor = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; - function isEnumObject(arg) { - if (typeof arg != "object" || arg === null) { - return false; + exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; + var runtime_1 = require_commonjs11(); + function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + } + return tail(method, input, options); } - if (!arg.hasOwnProperty(0)) { - return false; + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); } - for (let k of Object.keys(arg)) { - let num = parseInt(k); - if (!Number.isNaN(num)) { - let nam = arg[num]; - if (nam === void 0) - return false; - if (arg[nam] !== num) - return false; - } else { - let num2 = arg[k]; - if (num2 === void 0) - return false; - if (typeof num2 !== "number") - return false; - if (arg[num2] === void 0) - return false; + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); } + return tail(method, options); } - return true; + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); + } + runtime_1.assertNever(kind); } - exports2.isEnumObject = isEnumObject; - function listEnumValues(enumObject) { - if (!isEnumObject(enumObject)) - throw new Error("not a typescript enum object"); - let values = []; - for (let [name, number] of Object.entries(enumObject)) - if (typeof number == "number") - values.push({ name, number }); - return values; + exports2.stackIntercept = stackIntercept; + function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); } - exports2.listEnumValues = listEnumValues; - function listEnumNames(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.name); + exports2.stackUnaryInterceptors = stackUnaryInterceptors; + function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); } - exports2.listEnumNames = listEnumNames; - function listEnumNumbers(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; + function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); } - exports2.listEnumNumbers = listEnumNumbers; + exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; + function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); + } + exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/index.js -var require_commonjs11 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js +var require_server_call_context = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var json_typings_1 = require_json_typings(); - Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { - return json_typings_1.typeofJsonValue; - } }); - Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { - return json_typings_1.isJsonObject; - } }); - var base64_1 = require_base642(); - Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { - return base64_1.base64decode; - } }); - Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { - return base64_1.base64encode; - } }); - var protobufjs_utf8_1 = require_protobufjs_utf8(); - Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { - return protobufjs_utf8_1.utf8read; - } }); - var binary_format_contract_1 = require_binary_format_contract(); - Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { - return binary_format_contract_1.WireType; - } }); - Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { - return binary_format_contract_1.mergeBinaryOptions; - } }); - Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { - return binary_format_contract_1.UnknownFieldHandler; - } }); - var binary_reader_1 = require_binary_reader(); - Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { - return binary_reader_1.BinaryReader; - } }); - Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { - return binary_reader_1.binaryReadOptions; - } }); - var binary_writer_1 = require_binary_writer(); - Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { - return binary_writer_1.BinaryWriter; - } }); - Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { - return binary_writer_1.binaryWriteOptions; - } }); - var pb_long_1 = require_pb_long(); - Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { - return pb_long_1.PbLong; - } }); - Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { - return pb_long_1.PbULong; - } }); - var json_format_contract_1 = require_json_format_contract(); - Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonReadOptions; - } }); - Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonWriteOptions; - } }); - Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { - return json_format_contract_1.mergeJsonOptions; - } }); - var message_type_contract_1 = require_message_type_contract(); - Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { - return message_type_contract_1.MESSAGE_TYPE; - } }); - var message_type_1 = require_message_type(); - Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { - return message_type_1.MessageType; - } }); - var reflection_info_1 = require_reflection_info(); - Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { - return reflection_info_1.ScalarType; - } }); - Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { - return reflection_info_1.LongType; - } }); - Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { - return reflection_info_1.RepeatType; - } }); - Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { - return reflection_info_1.normalizeFieldInfo; - } }); - Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { - return reflection_info_1.readFieldOptions; - } }); - Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { - return reflection_info_1.readFieldOption; - } }); - Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { - return reflection_info_1.readMessageOption; - } }); - var reflection_type_check_1 = require_reflection_type_check(); - Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { - return reflection_type_check_1.ReflectionTypeCheck; - } }); - var reflection_create_1 = require_reflection_create(); - Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { - return reflection_create_1.reflectionCreate; - } }); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { - return reflection_scalar_default_1.reflectionScalarDefault; - } }); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { - return reflection_merge_partial_1.reflectionMergePartial; - } }); - var reflection_equals_1 = require_reflection_equals(); - Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { - return reflection_equals_1.reflectionEquals; - } }); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { - return reflection_binary_reader_1.ReflectionBinaryReader; + exports2.ServerCallContextController = void 0; + var ServerCallContextController = class { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; + } + /** + * Set the call cancelled. + * + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. + */ + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } + } + } + /** + * Send response headers. + */ + sendResponseHeaders(data) { + this._sendRH(data); + } + /** + * Is the call cancelled? + * + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. + */ + get cancelled() { + return this._cancelled; + } + /** + * Add a callback for cancellation. + */ + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; + } + }; + exports2.ServerCallContextController = ServerCallContextController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var service_type_1 = require_service_type(); + Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { + return service_type_1.ServiceType; } }); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { - return reflection_binary_writer_1.ReflectionBinaryWriter; + var reflection_info_1 = require_reflection_info2(); + Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { + return reflection_info_1.readMethodOptions; } }); - var reflection_json_reader_1 = require_reflection_json_reader(); - Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { - return reflection_json_reader_1.ReflectionJsonReader; + Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { + return reflection_info_1.readMethodOption; } }); - var reflection_json_writer_1 = require_reflection_json_writer(); - Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { - return reflection_json_writer_1.ReflectionJsonWriter; + Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { + return reflection_info_1.readServiceOption; } }); - var reflection_contains_message_type_1 = require_reflection_contains_message_type(); - Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { - return reflection_contains_message_type_1.containsMessageType; + var rpc_error_1 = require_rpc_error(); + Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { + return rpc_error_1.RpcError; } }); - var oneof_1 = require_oneof(); - Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { - return oneof_1.isOneofGroup; + var rpc_options_1 = require_rpc_options(); + Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { + return rpc_options_1.mergeRpcOptions; } }); - Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { - return oneof_1.setOneofValue; + var rpc_output_stream_1 = require_rpc_output_stream(); + Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { + return rpc_output_stream_1.RpcOutputStreamController; } }); - Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { - return oneof_1.getOneofValue; + var test_transport_1 = require_test_transport(); + Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { + return test_transport_1.TestTransport; } }); - Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { - return oneof_1.clearOneofValue; + var deferred_1 = require_deferred(); + Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { + return deferred_1.Deferred; } }); - Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { - return oneof_1.getSelectedOneofValue; + Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { + return deferred_1.DeferredState; } }); - var enum_object_1 = require_enum_object(); - Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { - return enum_object_1.listEnumValues; + var duplex_streaming_call_1 = require_duplex_streaming_call(); + Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { + return duplex_streaming_call_1.DuplexStreamingCall; } }); - Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { - return enum_object_1.listEnumNames; + var client_streaming_call_1 = require_client_streaming_call(); + Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { + return client_streaming_call_1.ClientStreamingCall; } }); - Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { - return enum_object_1.listEnumNumbers; + var server_streaming_call_1 = require_server_streaming_call(); + Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { + return server_streaming_call_1.ServerStreamingCall; } }); - Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { - return enum_object_1.isEnumObject; + var unary_call_1 = require_unary_call(); + Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { + return unary_call_1.UnaryCall; } }); - var lower_camel_case_1 = require_lower_camel_case(); - Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { - return lower_camel_case_1.lowerCamelCase; + var rpc_interceptor_1 = require_rpc_interceptor(); + Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { + return rpc_interceptor_1.stackIntercept; } }); - var assert_1 = require_assert(); - Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { - return assert_1.assert; + Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackDuplexStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { - return assert_1.assertNever; + Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackClientStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { - return assert_1.assertInt32; + Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackServerStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { - return assert_1.assertUInt32; + Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackUnaryInterceptors; } }); - Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { - return assert_1.assertFloat32; + var server_call_context_1 = require_server_call_context(); + Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { + return server_call_context_1.ServerCallContextController; } }); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js -var require_reflection_info2 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js +var require_cachescope = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + exports2.CacheScope = void 0; var runtime_1 = require_commonjs11(); - function normalizeMethodInfo(method, service) { - var _a, _b, _c; - let m = method; - m.service = service; - m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); - m.serverStreaming = !!m.serverStreaming; - m.clientStreaming = !!m.clientStreaming; - m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; - m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; - return m; - } - exports2.normalizeMethodInfo = normalizeMethodInfo; - function readMethodOptions(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readMethodOptions = readMethodOptions; - function readMethodOption(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var CacheScope$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheScope", [ + { + no: 1, + name: "scope", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "permission", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + create(value) { + const message = { scope: "", permission: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string scope */ + 1: + message.scope = reader.string(); + break; + case /* int64 permission */ + 2: + message.permission = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.scope !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); + if (message.permission !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheScope = new CacheScope$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js +var require_cachemetadata = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheMetadata = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachescope_1 = require_cachescope(); + var CacheMetadata$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheMetadata", [ + { + no: 1, + name: "repository_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } + ]); + } + create(value) { + const message = { repositoryId: "0", scope: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 repository_id */ + 1: + message.repositoryId = reader.int64().toString(); + break; + case /* repeated github.actions.results.entities.v1.CacheScope scope */ + 2: + message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.repositoryId !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); + for (let i = 0; i < message.scope.length; i++) + cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheMetadata = new CacheMetadata$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js +var require_cache2 = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachemetadata_1 = require_cachemetadata(); + var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* string version */ + 3: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readMethodOption = readMethodOption; - function readServiceOption(service, extensionName, extensionType) { - const options = service.options; - if (!options) { - return void 0; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.version !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + }; + exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); + var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readServiceOption = readServiceOption; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js -var require_service_type = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceType = void 0; - var reflection_info_1 = require_reflection_info2(); - var ServiceType = class { - constructor(typeName, methods, options) { - this.typeName = typeName; - this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); - this.options = options !== null && options !== void 0 ? options : {}; + create(value) { + const message = { ok: false, signedUploadUrl: "", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.ServiceType = ServiceType; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js -var require_rpc_error = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcError = void 0; - var RpcError = class extends Error { - constructor(message, code = "UNKNOWN", meta) { - super(message); - this.name = "RpcError"; - Object.setPrototypeOf(this, new.target.prototype); - this.code = code; - this.meta = meta !== null && meta !== void 0 ? meta : {}; + exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); + var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size_bytes", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - toString() { - const l = [this.name + ": " + this.message]; - if (this.code) { - l.push(""); - l.push("Code: " + this.code); - } - if (this.serviceName && this.methodName) { - l.push("Method: " + this.serviceName + "/" + this.methodName); + create(value) { + const message = { key: "", sizeBytes: "0", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* int64 size_bytes */ + 3: + message.sizeBytes = reader.int64().toString(); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } - let m = Object.entries(this.meta); - if (m.length) { - l.push(""); - l.push("Meta:"); - for (let [k, v] of m) { - l.push(` ${k}: ${v}`); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.sizeBytes !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); + var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "entry_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, entryId: "0", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* int64 entry_id */ + 2: + message.entryId = reader.int64().toString(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - return l.join("\n"); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.entryId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.RpcError = RpcError; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js -var require_rpc_options = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeRpcOptions = void 0; - var runtime_1 = require_commonjs11(); - function mergeRpcOptions(defaults, options) { - if (!options) - return defaults; - let o = {}; - copy(defaults, o); - copy(options, o); - for (let key of Object.keys(options)) { - let val2 = options[key]; - switch (key) { - case "jsonOptions": - o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); - break; - case "binaryOptions": - o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); - break; - case "meta": - o.meta = {}; - copy(defaults.meta, o.meta); - copy(options.meta, o.meta); - break; - case "interceptors": - o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); - break; + exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); + var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "restore_keys", + kind: "scalar", + repeat: 2, + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", restoreKeys: [], version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* repeated string restore_keys */ + 3: + message.restoreKeys.push(reader.string()); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } + return message; } - return o; - } - exports2.mergeRpcOptions = mergeRpcOptions; - function copy(a, into) { - if (!a) - return; - let c = into; - for (let [k, v] of Object.entries(a)) { - if (v instanceof Date) - c[k] = new Date(v.getTime()); - else if (Array.isArray(v)) - c[k] = v.concat(); - else - c[k] = v; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + for (let i = 0; i < message.restoreKeys.length; i++) + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); + var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_download_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "matched_key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_download_url */ + 2: + message.signedDownloadUrl = reader.string(); + break; + case /* string matched_key */ + 3: + message.matchedKey = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedDownloadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); + if (message.matchedKey !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); + exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ + { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, + { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, + { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } + ]); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js -var require_deferred = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js +var require_cache_twirp_client = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Deferred = exports2.DeferredState = void 0; - var DeferredState; - (function(DeferredState2) { - DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; - DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; - DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; - })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); - var Deferred = class { - /** - * @param preventUnhandledRejectionWarning - prevents the warning - * "Unhandled Promise rejection" by adding a noop rejection handler. - * Working with calls returned from the runtime-rpc package in an - * async function usually means awaiting one call property after - * the other. This means that the "status" is not being awaited when - * an earlier await for the "headers" is rejected. This causes the - * "unhandled promise reject" warning. A more correct behaviour for - * calls might be to become aware whether at least one of the - * promises is handled and swallow the rejection warning for the - * others. - */ - constructor(preventUnhandledRejectionWarning = true) { - this._state = DeferredState.PENDING; - this._promise = new Promise((resolve4, reject) => { - this._resolve = resolve4; - this._reject = reject; + exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; + var cache_1 = require_cache2(); + var CacheServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); + } + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false }); - if (preventUnhandledRejectionWarning) { - this._promise.catch((_) => { - }); - } + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Get the current state of the promise. - */ - get state() { - return this._state; + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Get the deferred promise. - */ - get promise() { - return this._promise; + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Resolve the promise. Throws if the promise is already resolved or rejected. - */ - resolve(value) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); - this._resolve(value); - this._state = DeferredState.RESOLVED; + }; + exports2.CacheServiceClientJSON = CacheServiceClientJSON; + var CacheServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - /** - * Reject the promise. Throws if the promise is already resolved or rejected. - */ - reject(reason) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); - this._reject(reason); - this._state = DeferredState.REJECTED; + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); } - /** - * Resolve the promise. Ignore if not pending. - */ - resolvePending(val2) { - if (this._state === DeferredState.PENDING) - this.resolve(val2); + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); } - /** - * Reject the promise. Ignore if not pending. - */ - rejectPending(reason) { - if (this._state === DeferredState.PENDING) - this.reject(reason); + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.Deferred = Deferred; + exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js -var require_rpc_output_stream = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/util.js +var require_util10 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcOutputStreamController = void 0; - var deferred_1 = require_deferred(); - var runtime_1 = require_commonjs11(); - var RpcOutputStreamController = class { - constructor() { - this._lis = { - nxt: [], - msg: [], - err: [], - cmp: [] - }; - this._closed = false; - this._itState = { q: [] }; + exports2.maskSecretUrls = exports2.maskSigUrl = void 0; + var core_1 = require_core(); + function maskSigUrl(url) { + if (!url) + return; + try { + const parsedUrl = new URL(url); + const signature = parsedUrl.searchParams.get("sig"); + if (signature) { + (0, core_1.setSecret)(signature); + (0, core_1.setSecret)(encodeURIComponent(signature)); + } + } catch (error4) { + (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); } - // --- RpcOutputStream callback API - onNext(callback) { - return this.addLis(callback, this._lis.nxt); + } + exports2.maskSigUrl = maskSigUrl; + function maskSecretUrls(body) { + if (typeof body !== "object" || body === null) { + (0, core_1.debug)("body is not an object or is null"); + return; } - onMessage(callback) { - return this.addLis(callback, this._lis.msg); + if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { + maskSigUrl(body.signed_upload_url); } - onError(callback) { - return this.addLis(callback, this._lis.err); + if ("signed_download_url" in body && typeof body.signed_download_url === "string") { + maskSigUrl(body.signed_download_url); } - onComplete(callback) { - return this.addLis(callback, this._lis.cmp); + } + exports2.maskSecretUrls = maskSecretUrls; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js +var require_cacheTwirpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - addLis(callback, list) { - list.push(callback); - return () => { - let i = list.indexOf(callback); - if (i >= 0) - list.splice(i, 1); - }; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.internalCacheTwirpClient = void 0; + var core_1 = require_core(); + var user_agent_1 = require_user_agent(); + var errors_1 = require_errors2(); + var config_1 = require_config(); + var cacheUtils_1 = require_cacheUtils(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib4(); + var cache_twirp_client_1 = require_cache_twirp_client(); + var util_1 = require_util10(); + var CacheServiceClient = class { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3e3; + this.retryMultiplier = 1.5; + const token = (0, cacheUtils_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getCacheServiceURL)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; + } + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) + ]); } - // remove all listeners - clearLis() { - for (let l of Object.values(this._lis)) - l.splice(0, l.length); + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { + return __awaiter4(this, void 0, void 0, function* () { + const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url}`); + const headers = { + "Content-Type": contentType + }; + try { + const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { + return this.httpClient.post(url, JSON.stringify(data), headers); + })); + return body; + } catch (error4) { + throw new Error(`Failed to ${method}: ${error4.message}`); + } + }); } - // --- Controller API - /** - * Is this stream already closed by a completion or error? - */ - get closed() { - return this._closed !== false; + retryableRequest(operation) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ""; + let rawBody = ""; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, util_1.maskSecretUrls)(body); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } catch (error4) { + if (error4 instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + } + if (error4 instanceof errors_1.UsageError) { + throw error4; + } + if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { + throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + } + isRetryable = true; + errorMessage = error4.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; + } + throw new Error(`Request failed`); + }); } - /** - * Emit message, close with error, or close successfully, but only one - * at a time. - * Can be used to wrap a stream by using the other stream's `onNext`. - */ - notifyNext(message, error4, complete) { - runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); - if (message) - this.notifyMessage(message); - if (error4) - this.notifyError(error4); - if (complete) - this.notifyComplete(); + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; } - /** - * Emits a new message. Throws if stream is closed. - * - * Triggers onNext and onMessage callbacks. - */ - notifyMessage(message) { - runtime_1.assert(!this.closed, "stream is closed"); - this.pushIt({ value: message, done: false }); - this._lis.msg.forEach((l) => l(message)); - this._lis.nxt.forEach((l) => l(message, void 0, false)); + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); } - /** - * Closes the stream with an error. Throws if stream is closed. - * - * Triggers onNext and onError callbacks. - */ - notifyError(error4) { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = error4; - this.pushIt(error4); - this._lis.err.forEach((l) => l(error4)); - this._lis.nxt.forEach((l) => l(void 0, error4, false)); - this.clearLis(); + sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => setTimeout(resolve4, milliseconds)); + }); } - /** - * Closes the stream successfully. Throws if stream is closed. - * - * Triggers onNext and onComplete callbacks. - */ - notifyComplete() { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = true; - this.pushIt({ value: null, done: true }); - this._lis.cmp.forEach((l) => l()); - this._lis.nxt.forEach((l) => l(void 0, void 0, true)); - this.clearLis(); + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error("attempt should be a positive integer"); + } + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } - /** - * Creates an async iterator (that can be used with `for await {...}`) - * to consume the stream. - * - * Some things to note: - * - If an error occurs, the `for await` will throw it. - * - If an error occurred before the `for await` was started, `for await` - * will re-throw it. - * - If the stream is already complete, the `for await` will be empty. - * - If your `for await` consumes slower than the stream produces, - * for example because you are relaying messages in a slow operation, - * messages are queued. - */ - [Symbol.asyncIterator]() { - if (this._closed === true) - this.pushIt({ value: null, done: true }); - else if (this._closed !== false) - this.pushIt(this._closed); - return { - next: () => { - let state = this._itState; - runtime_1.assert(state, "bad state"); - runtime_1.assert(!state.p, "iterator contract broken"); - let first = state.q.shift(); - if (first) - return "value" in first ? Promise.resolve(first) : Promise.reject(first); - state.p = new deferred_1.Deferred(); - return state.p.promise; - } - }; + }; + function internalCacheTwirpClient(options) { + const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new cache_twirp_client_1.CacheServiceClientJSON(client); + } + exports2.internalCacheTwirpClient = internalCacheTwirpClient; + } +}); + +// node_modules/@actions/cache/lib/internal/tar.js +var require_tar = __commonJS({ + "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - // "push" a new iterator result. - // this either resolves a pending promise, or enqueues the result. - pushIt(result) { - let state = this._itState; - if (state.p) { - const p = state.p; - runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); - "value" in result ? p.resolve(result) : p.reject(result); - delete state.p; - } else { - state.q.push(result); - } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.RpcOutputStreamController = RpcOutputStreamController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js -var require_unary_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve4) { @@ -72396,47 +75602,221 @@ var require_unary_call = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UnaryCall = void 0; - var UnaryCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * If you are only interested in the final outcome of this call, - * you can await it to receive a `FinishedUnaryCall`. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - response, - status, - trailers - }; - }); - } - }; - exports2.UnaryCall = UnaryCall; + exports2.createTar = exports2.extractTar = exports2.listTar = void 0; + var exec_1 = require_exec(); + var io5 = __importStar4(require_io()); + var fs_1 = require("fs"); + var path5 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var IS_WINDOWS = process.platform === "win32"; + function getTarPath() { + return __awaiter4(this, void 0, void 0, function* () { + switch (process.platform) { + case "win32": { + const gnuTar = yield utils.getGnuTarPathOnWindows(); + const systemTar = constants_1.SystemTarPathOnWindows; + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else if ((0, fs_1.existsSync)(systemTar)) { + return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; + } + break; + } + case "darwin": { + const gnuTar = yield io5.which("gtar", false); + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else { + return { + path: yield io5.which("tar", true), + type: constants_1.ArchiveToolType.BSD + }; + } + } + default: + break; + } + return { + path: yield io5.which("tar", true), + type: constants_1.ArchiveToolType.GNU + }; + }); + } + function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + const args = [`"${tarPath.path}"`]; + const cacheFileName = utils.getCacheFileName(compressionMethod); + const tarFile = "cache.tar"; + const workingDirectory = getWorkingDirectory(); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (type2) { + case "create": + args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); + break; + case "extract": + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path5.sep}`, "g"), "/")); + break; + case "list": + args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "-P"); + break; + } + if (tarPath.type === constants_1.ArchiveToolType.GNU) { + switch (process.platform) { + case "win32": + args.push("--force-local"); + break; + case "darwin": + args.push("--delay-directory-restore"); + break; + } + } + return args; + }); + } + function getCommands(compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + let args; + const tarPath = yield getTarPath(); + const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); + const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + if (BSD_TAR_ZSTD && type2 !== "create") { + args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; + } else { + args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; + } + if (BSD_TAR_ZSTD) { + return args; + } + return [args.join(" ")]; + }); + } + function getWorkingDirectory() { + var _a; + return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); + } + function getDecompressionProgram(tarPath, compressionMethod, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -d --long=30 --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path5.sep}`, "g"), "/") + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -d --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path5.sep}`, "g"), "/") + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; + default: + return ["-z"]; + } + }); + } + function getCompressionProgram(tarPath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheFileName = utils.getCacheFileName(compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --long=30 --force -o", + cacheFileName.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), + constants_1.TarFilename + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --force -o", + cacheFileName.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), + constants_1.TarFilename + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; + default: + return ["-z"]; + } + }); + } + function execCommands(commands, cwd) { + return __awaiter4(this, void 0, void 0, function* () { + for (const command of commands) { + try { + yield (0, exec_1.exec)(command, void 0, { + cwd, + env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) + }); + } catch (error4) { + throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + } + } + }); + } + function listTar(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const commands = yield getCommands(compressionMethod, "list", archivePath); + yield execCommands(commands); + }); + } + exports2.listTar = listTar; + function extractTar2(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const workingDirectory = getWorkingDirectory(); + yield io5.mkdirP(workingDirectory); + const commands = yield getCommands(compressionMethod, "extract", archivePath); + yield execCommands(commands); + }); + } + exports2.extractTar = extractTar2; + function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + (0, fs_1.writeFileSync)(path5.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); + const commands = yield getCommands(compressionMethod, "create"); + yield execCommands(commands, archiveFolder); + }); + } + exports2.createTar = createTar; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js -var require_server_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { +// node_modules/@actions/cache/lib/cache.js +var require_cache3 = __commonJS({ + "node_modules/@actions/cache/lib/cache.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve4) { @@ -72450,200 +75830,421 @@ var require_server_streaming_call = __commonJS({ } catch (e) { reject(e); } - } - function rejected(value) { + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + var core13 = __importStar4(require_core()); + var path5 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var cacheHttpClient = __importStar4(require_cacheHttpClient()); + var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); + var config_1 = require_config(); + var tar_1 = require_tar(); + var http_client_1 = require_lib4(); + var ValidationError = class _ValidationError extends Error { + constructor(message) { + super(message); + this.name = "ValidationError"; + Object.setPrototypeOf(this, _ValidationError.prototype); + } + }; + exports2.ValidationError = ValidationError; + var ReserveCacheError = class _ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = "ReserveCacheError"; + Object.setPrototypeOf(this, _ReserveCacheError.prototype); + } + }; + exports2.ReserveCacheError = ReserveCacheError; + var FinalizeCacheError = class _FinalizeCacheError extends Error { + constructor(message) { + super(message); + this.name = "FinalizeCacheError"; + Object.setPrototypeOf(this, _FinalizeCacheError.prototype); + } + }; + exports2.FinalizeCacheError = FinalizeCacheError; + function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); + } + } + function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } + } + function isFeatureAvailable() { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + switch (cacheServiceVersion) { + case "v2": + return !!process.env["ACTIONS_RESULTS_URL"]; + case "v1": + default: + return !!process.env["ACTIONS_CACHE_URL"]; + } + } + exports2.isFeatureAvailable = isFeatureAvailable; + function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core13.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + switch (cacheServiceVersion) { + case "v2": + return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + case "v1": + default: + return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + } + }); + } + exports2.restoreCache = restoreCache3; + function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core13.debug("Resolved Keys:"); + core13.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + let archivePath = ""; + try { + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod, + enableCrossOsArchive + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + return void 0; + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core13.info("Lookup only - skipping download"); + return cacheEntry.cacheKey; + } + archivePath = path5.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core13.debug(`Archive Path: ${archivePath}`); + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core13.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core13.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core13.info("Cache restored successfully"); + return cacheEntry.cacheKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core13.error(`Failed to restore: ${error4.message}`); + } else { + core13.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core13.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core13.debug("Resolved Keys:"); + core13.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + let archivePath = ""; + try { + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + const compressionMethod = yield utils.getCompressionMethod(); + const request = { + key: primaryKey, + restoreKeys, + version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) + }; + const response = yield twirpClient.GetCacheEntryDownloadURL(request); + if (!response.ok) { + core13.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); + return void 0; + } + const isRestoreKeyMatch = request.key !== response.matchedKey; + if (isRestoreKeyMatch) { + core13.info(`Cache hit for restore-key: ${response.matchedKey}`); + } else { + core13.info(`Cache hit for: ${response.matchedKey}`); + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core13.info("Lookup only - skipping download"); + return response.matchedKey; + } + archivePath = path5.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core13.debug(`Archive path: ${archivePath}`); + core13.debug(`Starting download of archive to: ${archivePath}`); + yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core13.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + if (core13.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core13.info("Cache restored successfully"); + return response.matchedKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core13.error(`Failed to restore: ${error4.message}`); + } else { + core13.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + if (archivePath) { + yield utils.unlinkFile(archivePath); + } + } catch (error4) { + core13.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function saveCache3(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core13.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + checkKey(key); + switch (cacheServiceVersion) { + case "v2": + return yield saveCacheV2(paths, key, options, enableCrossOsArchive); + case "v1": + default: + return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + } + }); + } + exports2.saveCache = saveCache3; + function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { + var _a, _b, _c, _d, _e; + return __awaiter4(this, void 0, void 0, function* () { + const compressionMethod = yield utils.getCompressionMethod(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core13.debug("Cache Paths:"); + core13.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path5.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core13.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core13.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const fileSizeLimit = 10 * 1024 * 1024 * 1024; + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core13.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core13.debug("Reserving Cache"); + const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod, + enableCrossOsArchive, + cacheSize: archiveFileSize + }); + if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { + cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { + throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); + } else { + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); + } + core13.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError.name) { + core13.info(`Failed to save: ${typedError.message}`); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core13.error(`Failed to save: ${typedError.message}`); + } else { + core13.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + yield utils.unlinkFile(archivePath); + } catch (error4) { + core13.debug(`Failed to delete archive: ${error4}`); } } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return cacheId; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerStreamingCall = void 0; - var ServerStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * You should first setup some listeners to the `request` to - * see the actual messages the server replied with. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - status, - trailers + } + function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); + const compressionMethod = yield utils.getCompressionMethod(); + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core13.debug("Cache Paths:"); + core13.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path5.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core13.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core13.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core13.debug(`File Size: ${archiveFileSize}`); + options.archiveSizeBytes = archiveFileSize; + core13.debug("Reserving Cache"); + const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); + const request = { + key, + version }; - }); - } - }; - exports2.ServerStreamingCall = ServerStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js -var require_client_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { + let signedUploadUrl; try { - step(generator.next(value)); - } catch (e) { - reject(e); + const response = yield twirpClient.CreateCacheEntry(request); + if (!response.ok) { + if (response.message) { + core13.warning(`Cache reservation failed: ${response.message}`); + } + throw new Error(response.message || "Response was not ok"); + } + signedUploadUrl = response.signedUploadUrl; + } catch (error4) { + core13.debug(`Failed to reserve cache: ${error4}`); + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); } - } - function rejected(value) { + core13.debug(`Attempting to upload cache located at: ${archivePath}`); + yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); + const finalizeRequest = { + key, + version, + sizeBytes: `${archiveFileSize}` + }; + const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); + core13.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); + if (!finalizeResponse.ok) { + if (finalizeResponse.message) { + throw new FinalizeCacheError(finalizeResponse.message); + } + throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); + } + cacheId = parseInt(finalizeResponse.entryId); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError.name) { + core13.info(`Failed to save: ${typedError.message}`); + } else if (typedError.name === FinalizeCacheError.name) { + core13.warning(typedError.message); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core13.error(`Failed to save: ${typedError.message}`); + } else { + core13.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + yield utils.unlinkFile(archivePath); + } catch (error4) { + core13.debug(`Failed to delete archive: ${error4}`); } } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return cacheId; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ClientStreamingCall = void 0; - var ClientStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - response, - status, - trailers - }; - }); - } - }; - exports2.ClientStreamingCall = ClientStreamingCall; + } } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js -var require_duplex_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { +// node_modules/@actions/tool-cache/lib/manifest.js +var require_manifest = __commonJS({ + "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DuplexStreamingCall = void 0; - var DuplexStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - status, - trailers - }; - }); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.DuplexStreamingCall = DuplexStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js -var require_test_transport = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve4) { @@ -72666,1204 +76267,824 @@ var require_test_transport = __commonJS({ } } function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TestTransport = void 0; - var rpc_error_1 = require_rpc_error(); - var runtime_1 = require_commonjs11(); - var rpc_output_stream_1 = require_rpc_output_stream(); - var rpc_options_1 = require_rpc_options(); - var unary_call_1 = require_unary_call(); - var server_streaming_call_1 = require_server_streaming_call(); - var client_streaming_call_1 = require_client_streaming_call(); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - var TestTransport = class _TestTransport { - /** - * Initialize with mock data. Omitted fields have default value. - */ - constructor(data) { - this.suppressUncaughtRejections = true; - this.headerDelay = 10; - this.responseDelay = 50; - this.betweenResponseDelay = 10; - this.afterResponseDelay = 10; - this.data = data !== null && data !== void 0 ? data : {}; - } - /** - * Sent message(s) during the last operation. - */ - get sentMessages() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.sent; - } else if (typeof this.lastInput == "object") { - return [this.lastInput.single]; - } - return []; - } - /** - * Sending message(s) completed? - */ - get sendComplete() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.completed; - } else if (typeof this.lastInput == "object") { - return true; - } - return false; - } - // Creates a promise for response headers from the mock data. - promiseHeaders() { - var _a; - const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; - return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); - } - // Creates a promise for a single, valid, message from the mock data. - promiseSingleResponse(method) { - if (this.data.response instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.response); - } - let r; - if (Array.isArray(this.data.response)) { - runtime_1.assert(this.data.response.length > 0); - r = this.data.response[0]; - } else if (this.data.response !== void 0) { - r = this.data.response; - } else { - r = method.O.create(); - } - runtime_1.assert(method.O.is(r)); - return Promise.resolve(r); - } - /** - * Pushes response messages from the mock data to the output stream. - * If an error response, status or trailers are mocked, the stream is - * closed with the respective error. - * Otherwise, stream is completed successfully. - * - * The returned promise resolves when the stream is closed. It should - * not reject. If it does, code is broken. - */ - streamResponses(method, stream, abort) { - return __awaiter4(this, void 0, void 0, function* () { - const messages = []; - if (this.data.response === void 0) { - messages.push(method.O.create()); - } else if (Array.isArray(this.data.response)) { - for (let msg of this.data.response) { - runtime_1.assert(method.O.is(msg)); - messages.push(msg); - } - } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { - runtime_1.assert(method.O.is(this.data.response)); - messages.push(this.data.response); - } - try { - yield delay2(this.responseDelay, abort)(void 0); - } catch (error4) { - stream.notifyError(error4); - return; - } - if (this.data.response instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.response); - return; - } - for (let msg of messages) { - stream.notifyMessage(msg); - try { - yield delay2(this.betweenResponseDelay, abort)(void 0); - } catch (error4) { - stream.notifyError(error4); - return; - } - } - if (this.data.status instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.status); - return; - } - if (this.data.trailers instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.trailers); - return; - } - stream.notifyComplete(); - }); - } - // Creates a promise for response status from the mock data. - promiseStatus() { - var _a; - const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; - return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); - } - // Creates a promise for response trailers from the mock data. - promiseTrailers() { - var _a; - const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; - return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); - } - maybeSuppressUncaught(...promise) { - if (this.suppressUncaughtRejections) { - for (let p of promise) { - p.catch(() => { - }); - } - } - } - mergeOptions(options) { - return rpc_options_1.mergeRpcOptions({}, options); - } - unary(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); - } - serverStreaming(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); - } - clientStreaming(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); - } - duplex(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); - } - }; - exports2.TestTransport = TestTransport; - TestTransport.defaultHeaders = { - responseHeader: "test" - }; - TestTransport.defaultStatus = { - code: "OK", - detail: "all good" - }; - TestTransport.defaultTrailers = { - responseTrailer: "test" + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - function delay2(ms, abort) { - return (v) => new Promise((resolve4, reject) => { - if (abort === null || abort === void 0 ? void 0 : abort.aborted) { - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - } else { - const id = setTimeout(() => resolve4(v), ms); - if (abort) { - abort.addEventListener("abort", (ev) => { - clearTimeout(id); - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; + var semver8 = __importStar4(require_semver2()); + var core_1 = require_core(); + var os2 = require("os"); + var cp = require("child_process"); + var fs5 = require("fs"); + function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os2.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); + if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + file = candidate.files.find((item) => { + (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module2.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } else { + chk = semver8.satisfies(osVersion, item.platform_version); + } + } + return chk; }); + if (file) { + (0, core_1.debug)(`matched ${candidate.version}`); + match = candidate; + break; + } } } + if (match && file) { + result = Object.assign({}, match); + result.files = [file]; + } + return result; }); } - var TestInputStream = class { - constructor(data, abort) { - this._completed = false; - this._sent = []; - this.data = data; - this.abort = abort; - } - get sent() { - return this._sent; - } - get completed() { - return this._completed; - } - send(message) { - if (this.data.inputMessage instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputMessage); + exports2._findMatch = _findMatch; + function _getOsVersion() { + const plat = os2.platform(); + let version = ""; + if (plat === "darwin") { + version = cp.execSync("sw_vers -productVersion").toString(); + } else if (plat === "linux") { + const lsbContents = module2.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split("\n"); + for (const line of lines) { + const parts = line.split("="); + if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { + version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); + break; + } + } } - const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; - return Promise.resolve(void 0).then(() => { - this._sent.push(message); - }).then(delay2(delayMs, this.abort)); } - complete() { - if (this.data.inputComplete instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputComplete); - } - const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; - return Promise.resolve(void 0).then(() => { - this._completed = true; - }).then(delay2(delayMs, this.abort)); + return version; + } + exports2._getOsVersion = _getOsVersion; + function _readLinuxVersionFile() { + const lsbReleaseFile = "/etc/lsb-release"; + const osReleaseFile = "/etc/os-release"; + let contents = ""; + if (fs5.existsSync(lsbReleaseFile)) { + contents = fs5.readFileSync(lsbReleaseFile).toString(); + } else if (fs5.existsSync(osReleaseFile)) { + contents = fs5.readFileSync(osReleaseFile).toString(); } - }; + return contents; + } + exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js -var require_rpc_interceptor = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; - var runtime_1 = require_commonjs11(); - function stackIntercept(kind, transport, method, options, input) { - var _a, _b, _c, _d; - if (kind == "unary") { - let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); - for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); - } - return tail(method, input, options); - } - if (kind == "serverStreaming") { - let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); - for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); - } - return tail(method, input, options); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - if (kind == "clientStreaming") { - let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); - for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - return tail(method, options); - } - if (kind == "duplex") { - let tail = (mtd, opt) => transport.duplex(mtd, opt); - for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - return tail(method, options); + } else { + return void 0; } - runtime_1.assertNever(kind); - } - exports2.stackIntercept = stackIntercept; - function stackUnaryInterceptors(transport, method, input, options) { - return stackIntercept("unary", transport, method, options, input); - } - exports2.stackUnaryInterceptors = stackUnaryInterceptors; - function stackServerStreamingInterceptors(transport, method, input, options) { - return stackIntercept("serverStreaming", transport, method, options, input); } - exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; - function stackClientStreamingInterceptors(transport, method, options) { - return stackIntercept("clientStreaming", transport, method, options); - } - exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; - function stackDuplexStreamingInterceptors(transport, method, options) { - return stackIntercept("duplex", transport, method, options); - } - exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js -var require_server_call_context = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerCallContextController = void 0; - var ServerCallContextController = class { - constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { - this._cancelled = false; - this._listeners = []; - this.method = method; - this.headers = headers; - this.deadline = deadline; - this.trailers = {}; - this._sendRH = sendResponseHeadersFn; - this.status = defaultStatus; + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - /** - * Set the call cancelled. - * - * Invokes all callbacks registered with onCancel() and - * sets `cancelled = true`. - */ - notifyCancelled() { - if (!this._cancelled) { - this._cancelled = true; - for (let l of this._listeners) { - l(); - } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - /** - * Send response headers. - */ - sendResponseHeaders(data) { - this._sendRH(data); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - /** - * Is the call cancelled? - * - * When the client closes the connection before the server - * is done, the call is cancelled. - * - * If you want to cancel a request on the server, throw a - * RpcError with the CANCELLED status code. - */ - get cancelled() { - return this._cancelled; + get username() { + return this._decodedUsername; } - /** - * Add a callback for cancellation. - */ - onCancel(callback) { - const l = this._listeners; - l.push(callback); - return () => { - let i = l.indexOf(callback); - if (i >= 0) - l.splice(i, 1); - }; + get password() { + return this._decodedPassword; } }; - exports2.ServerCallContextController = ServerCallContextController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js -var require_commonjs12 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var service_type_1 = require_service_type(); - Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { - return service_type_1.ServiceType; - } }); - var reflection_info_1 = require_reflection_info2(); - Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { - return reflection_info_1.readMethodOptions; - } }); - Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { - return reflection_info_1.readMethodOption; - } }); - Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { - return reflection_info_1.readServiceOption; - } }); - var rpc_error_1 = require_rpc_error(); - Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { - return rpc_error_1.RpcError; - } }); - var rpc_options_1 = require_rpc_options(); - Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { - return rpc_options_1.mergeRpcOptions; - } }); - var rpc_output_stream_1 = require_rpc_output_stream(); - Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { - return rpc_output_stream_1.RpcOutputStreamController; - } }); - var test_transport_1 = require_test_transport(); - Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { - return test_transport_1.TestTransport; - } }); - var deferred_1 = require_deferred(); - Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { - return deferred_1.Deferred; - } }); - Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { - return deferred_1.DeferredState; - } }); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { - return duplex_streaming_call_1.DuplexStreamingCall; - } }); - var client_streaming_call_1 = require_client_streaming_call(); - Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { - return client_streaming_call_1.ClientStreamingCall; - } }); - var server_streaming_call_1 = require_server_streaming_call(); - Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { - return server_streaming_call_1.ServerStreamingCall; - } }); - var unary_call_1 = require_unary_call(); - Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { - return unary_call_1.UnaryCall; - } }); - var rpc_interceptor_1 = require_rpc_interceptor(); - Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { - return rpc_interceptor_1.stackIntercept; - } }); - Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackDuplexStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackClientStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackServerStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackUnaryInterceptors; - } }); - var server_call_context_1 = require_server_call_context(); - Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { - return server_call_context_1.ServerCallContextController; - } }); } }); -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js -var require_cachescope = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheScope = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var CacheScope$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheScope", [ - { - no: 1, - name: "scope", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "permission", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - ]); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - create(value) { - const message = { scope: "", permission: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string scope */ - 1: - message.scope = reader.string(); - break; - case /* int64 permission */ - 2: - message.permission = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve4(output.toString()); + }); + })); + }); } - internalBinaryWrite(message, writer, options) { - if (message.scope !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); - if (message.permission !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve4(Buffer.concat(chunks)); + }); + })); + }); } }; - exports2.CacheScope = new CacheScope$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js -var require_cachemetadata = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheMetadata = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachescope_1 = require_cachescope(); - var CacheMetadata$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheMetadata", [ - { - no: 1, - name: "repository_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } - ]); - } - create(value) { - const message = { repositoryId: "0", scope: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int64 repository_id */ - 1: - message.repositoryId = reader.int64().toString(); - break; - case /* repeated github.actions.results.entities.v1.CacheScope scope */ - 2: - message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.repositoryId !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); - for (let i = 0; i < message.scope.length; i++) - cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.CacheMetadata = new CacheMetadata$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js -var require_cache2 = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachemetadata_1 = require_cachemetadata(); - var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - create(value) { - const message = { key: "", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* string version */ - 3: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.version !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - }; - exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); - var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_upload_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - create(value) { - const message = { ok: false, signedUploadUrl: "", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_upload_url */ - 2: - message.signedUploadUrl = reader.string(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - }; - exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); - var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "size_bytes", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - create(value) { - const message = { key: "", sizeBytes: "0", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* int64 size_bytes */ - 3: - message.sizeBytes = reader.int64().toString(); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - return message; + this._disposed = true; } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.sizeBytes !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve4(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); } - }; - exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); - var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "entry_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } - ]); - } - create(value) { - const message = { ok: false, entryId: "0", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 entry_id */ - 2: - message.entryId = reader.int64().toString(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.entryId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } - }; - exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); - var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "restore_keys", - kind: "scalar", - repeat: 2, - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } - ]); + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } - create(value) { - const message = { key: "", restoreKeys: [], version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* repeated string restore_keys */ - 3: - message.restoreKeys.push(reader.string()); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - for (let i = 0; i < message.restoreKeys.length; i++) - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - }; - exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); - var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_download_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "matched_key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - ]); - } - create(value) { - const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + } + return info6; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_download_url */ - 2: - message.signedDownloadUrl = reader.string(); - break; - case /* string matched_key */ - 3: - message.matchedKey = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - return message; + return lowercaseKeys(headers || {}); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedDownloadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); - if (message.matchedKey !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - }; - exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); - exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ - { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, - { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, - { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } - ]); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js -var require_cache_twirp_client = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; - var cache_1 = require_cache2(); - var CacheServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false - }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { - ignoreUnknownFields: true + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve4) => setTimeout(() => resolve4(), ms)); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve4(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve4(response); + } + })); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); - } - }; - exports2.CacheServiceClientJSON = CacheServiceClientJSON; - var CacheServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); - } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); - } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); - } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/cache/lib/internal/shared/util.js -var require_util10 = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.maskSecretUrls = exports2.maskSigUrl = void 0; - var core_1 = require_core(); - function maskSigUrl(url) { - if (!url) - return; - try { - const parsedUrl = new URL(url); - const signature = parsedUrl.searchParams.get("sig"); - if (signature) { - (0, core_1.setSecret)(signature); - (0, core_1.setSecret)(encodeURIComponent(signature)); - } - } catch (error4) { - (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); - } - } - exports2.maskSigUrl = maskSigUrl; - function maskSecretUrls(body) { - if (typeof body !== "object" || body === null) { - (0, core_1.debug)("body is not an object or is null"); - return; - } - if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { - maskSigUrl(body.signed_upload_url); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - if ("signed_download_url" in body && typeof body.signed_download_url === "string") { - maskSigUrl(body.signed_download_url); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - } - exports2.maskSecretUrls = maskSecretUrls; - } -}); - -// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js -var require_cacheTwirpClient = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { - "use strict"; + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve4) { @@ -73892,154 +77113,56 @@ var require_cacheTwirpClient = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.internalCacheTwirpClient = void 0; - var core_1 = require_core(); - var user_agent_1 = require_user_agent(); - var errors_1 = require_errors2(); - var config_1 = require_config(); - var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); - var cache_twirp_client_1 = require_cache_twirp_client(); - var util_1 = require_util10(); - var CacheServiceClient = class { - constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { - this.maxAttempts = 5; - this.baseRetryIntervalMilliseconds = 3e3; - this.retryMultiplier = 1.5; - const token = (0, cacheUtils_1.getRuntimeToken)(); - this.baseUrl = (0, config_1.getCacheServiceURL)(); - if (maxAttempts) { - this.maxAttempts = maxAttempts; - } - if (baseRetryIntervalMilliseconds) { - this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + exports2.RetryHelper = void 0; + var core13 = __importStar4(require_core()); + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); } - if (retryMultiplier) { - this.retryMultiplier = retryMultiplier; + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); } - this.httpClient = new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(token) - ]); - } - // This function satisfies the Rpc interface. It is compatible with the JSON - // JSON generated client. - request(service, method, contentType, data) { - return __awaiter4(this, void 0, void 0, function* () { - const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; - (0, core_1.debug)(`[Request] ${method} ${url}`); - const headers = { - "Content-Type": contentType - }; - try { - const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { - return this.httpClient.post(url, JSON.stringify(data), headers); - })); - return body; - } catch (error4) { - throw new Error(`Failed to ${method}: ${error4.message}`); - } - }); } - retryableRequest(operation) { + execute(action, isRetryable) { return __awaiter4(this, void 0, void 0, function* () { - let attempt = 0; - let errorMessage = ""; - let rawBody = ""; + let attempt = 1; while (attempt < this.maxAttempts) { - let isRetryable = false; try { - const response = yield operation(); - const statusCode = response.message.statusCode; - rawBody = yield response.readBody(); - (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); - (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); - const body = JSON.parse(rawBody); - (0, util_1.maskSecretUrls)(body); - (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); - if (this.isSuccessStatusCode(statusCode)) { - return { response, body }; - } - isRetryable = this.isRetryableHttpStatusCode(statusCode); - errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; - if (body.msg) { - if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { - throw new errors_1.UsageError(); - } - errorMessage = `${errorMessage}: ${body.msg}`; - } - } catch (error4) { - if (error4 instanceof SyntaxError) { - (0, core_1.debug)(`Raw Body: ${rawBody}`); - } - if (error4 instanceof errors_1.UsageError) { - throw error4; - } - if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { - throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; } - isRetryable = true; - errorMessage = error4.message; - } - if (!isRetryable) { - throw new Error(`Received non-retryable error: ${errorMessage}`); - } - if (attempt + 1 === this.maxAttempts) { - throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + core13.info(err.message); } - const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); - (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); - yield this.sleep(retryTimeMilliseconds); + const seconds = this.getSleepAmount(); + core13.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); attempt++; } - throw new Error(`Request failed`); + return yield action(); }); } - isSuccessStatusCode(statusCode) { - if (!statusCode) - return false; - return statusCode >= 200 && statusCode < 300; - } - isRetryableHttpStatusCode(statusCode) { - if (!statusCode) - return false; - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.GatewayTimeout, - http_client_1.HttpCodes.InternalServerError, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.TooManyRequests - ]; - return retryableStatusCodes.includes(statusCode); + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; } - sleep(milliseconds) { + sleep(seconds) { return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve4) => setTimeout(resolve4, milliseconds)); + return new Promise((resolve4) => setTimeout(resolve4, seconds * 1e3)); }); } - getExponentialRetryTimeMilliseconds(attempt) { - if (attempt < 0) { - throw new Error("attempt should be a positive integer"); - } - if (attempt === 0) { - return this.baseRetryIntervalMilliseconds; - } - const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); - const maxTime = minTime * this.retryMultiplier; - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); - } }; - function internalCacheTwirpClient(options) { - const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); - return new cache_twirp_client_1.CacheServiceClientJSON(client); - } - exports2.internalCacheTwirpClient = internalCacheTwirpClient; + exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/cache/lib/internal/tar.js -var require_tar = __commonJS({ - "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74096,866 +77219,610 @@ var require_tar = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTar = exports2.extractTar = exports2.listTar = void 0; - var exec_1 = require_exec(); + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; + var core13 = __importStar4(require_core()); var io5 = __importStar4(require_io()); - var fs_1 = require("fs"); + var crypto = __importStar4(require("crypto")); + var fs5 = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os2 = __importStar4(require("os")); var path5 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var constants_1 = require_constants7(); + var httpm = __importStar4(require_lib5()); + var semver8 = __importStar4(require_semver2()); + var stream = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError2 = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + exports2.HTTPError = HTTPError2; var IS_WINDOWS = process.platform === "win32"; - function getTarPath() { + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - switch (process.platform) { - case "win32": { - const gnuTar = yield utils.getGnuTarPathOnWindows(); - const systemTar = constants_1.SystemTarPathOnWindows; - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else if ((0, fs_1.existsSync)(systemTar)) { - return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; - } - break; - } - case "darwin": { - const gnuTar = yield io5.which("gtar", false); - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else { - return { - path: yield io5.which("tar", true), - type: constants_1.ArchiveToolType.BSD - }; + dest = dest || path5.join(_getTempDirectory(), crypto.randomUUID()); + yield io5.mkdirP(path5.dirname(dest)); + core13.debug(`Downloading ${url}`); + core13.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError2 && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; } } - default: - break; - } - return { - path: yield io5.which("tar", true), - type: constants_1.ArchiveToolType.GNU - }; + return true; + }); }); } - function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - const args = [`"${tarPath.path}"`]; - const cacheFileName = utils.getCacheFileName(compressionMethod); - const tarFile = "cache.tar"; - const workingDirectory = getWorkingDirectory(); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (type2) { - case "create": - args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); - break; - case "extract": - args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path5.sep}`, "g"), "/")); - break; - case "list": - args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), "-P"); - break; + if (fs5.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); } - if (tarPath.type === constants_1.ArchiveToolType.GNU) { - switch (process.platform) { - case "win32": - args.push("--force-local"); - break; - case "darwin": - args.push("--delay-directory-restore"); - break; + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core13.debug("set auth"); + if (headers === void 0) { + headers = {}; } + headers.authorization = auth; } - return args; - }); - } - function getCommands(compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - let args; - const tarPath = yield getTarPath(); - const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); - const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - if (BSD_TAR_ZSTD && type2 !== "create") { - args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; - } else { - args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; - } - if (BSD_TAR_ZSTD) { - return args; + const response = yield http.get(url, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError2(response.message.statusCode); + core13.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; } - return [args.join(" ")]; - }); - } - function getWorkingDirectory() { - var _a; - return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); - } - function getDecompressionProgram(tarPath, compressionMethod, archivePath) { - return __awaiter4(this, void 0, void 0, function* () { - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -d --long=30 --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path5.sep}`, "g"), "/") - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -d --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path5.sep}`, "g"), "/") - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; - default: - return ["-z"]; + const pipeline = util.promisify(stream.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; + try { + yield pipeline(readStream, fs5.createWriteStream(dest)); + core13.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core13.debug("download failed"); + try { + yield io5.rmRF(dest); + } catch (err) { + core13.debug(`Failed to delete '${dest}'. ${err.message}`); + } + } } }); } - function getCompressionProgram(tarPath, compressionMethod) { + function extract7z(file, dest, _7zPath) { return __awaiter4(this, void 0, void 0, function* () { - const cacheFileName = utils.getCacheFileName(compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --long=30 --force -o", - cacheFileName.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), - constants_1.TarFilename - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { + try { + const logLevel = core13.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --force -o", - cacheFileName.replace(new RegExp(`\\${path5.sep}`, "g"), "/"), - constants_1.TarFilename - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; - default: - return ["-z"]; - } - }); - } - function execCommands(commands, cwd) { - return __awaiter4(this, void 0, void 0, function* () { - for (const command of commands) { + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } else { + const escapedScript = path5.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true + }; try { - yield (0, exec_1.exec)(command, void 0, { - cwd, - env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) - }); - } catch (error4) { - throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + const powershellPath = yield io5.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); } } + return dest; }); } - function listTar(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const commands = yield getCommands(compressionMethod, "list", archivePath); - yield execCommands(commands); - }); - } - exports2.listTar = listTar; - function extractTar2(archivePath, compressionMethod) { + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { return __awaiter4(this, void 0, void 0, function* () { - const workingDirectory = getWorkingDirectory(); - yield io5.mkdirP(workingDirectory); - const commands = yield getCommands(compressionMethod, "extract", archivePath); - yield execCommands(commands); + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + core13.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + core13.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + if (core13.isDebug() && !flags.includes("v")) { + args.push("-v"); + } + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); + } + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); + } + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; }); } exports2.extractTar = extractTar2; - function createTar(archiveFolder, sourceDirectories, compressionMethod) { + function extractXar(file, dest, flags = []) { return __awaiter4(this, void 0, void 0, function* () { - (0, fs_1.writeFileSync)(path5.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); - const commands = yield getCommands(compressionMethod, "create"); - yield execCommands(commands, archiveFolder); + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + args.push("-x", "-C", dest, "-f", file); + if (core13.isDebug()) { + args.push("-v"); + } + const xarPath = yield io5.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; }); } - exports2.createTar = createTar; - } -}); - -// node_modules/@actions/cache/lib/cache.js -var require_cache3 = __commonJS({ - "node_modules/@actions/cache/lib/cache.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } else { + yield extractZipNix(file, dest); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return dest; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; - var core13 = __importStar4(require_core()); - var path5 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var cacheHttpClient = __importStar4(require_cacheHttpClient()); - var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); - var config_1 = require_config(); - var tar_1 = require_tar(); - var http_client_1 = require_lib(); - var ValidationError = class _ValidationError extends Error { - constructor(message) { - super(message); - this.name = "ValidationError"; - Object.setPrototypeOf(this, _ValidationError.prototype); - } - }; - exports2.ValidationError = ValidationError; - var ReserveCacheError = class _ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = "ReserveCacheError"; - Object.setPrototypeOf(this, _ReserveCacheError.prototype); - } - }; - exports2.ReserveCacheError = ReserveCacheError; - var FinalizeCacheError = class _FinalizeCacheError extends Error { - constructor(message) { - super(message); - this.name = "FinalizeCacheError"; - Object.setPrototypeOf(this, _FinalizeCacheError.prototype); - } - }; - exports2.FinalizeCacheError = FinalizeCacheError; - function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } - } - function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); - } - } - function isFeatureAvailable() { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - switch (cacheServiceVersion) { - case "v2": - return !!process.env["ACTIONS_RESULTS_URL"]; - case "v1": - default: - return !!process.env["ACTIONS_CACHE_URL"]; - } } - exports2.isFeatureAvailable = isFeatureAvailable; - function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core13.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - switch (cacheServiceVersion) { - case "v2": - return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - case "v1": - default: - return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io5.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core13.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io5.which("powershell", true); + core13.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); } }); } - exports2.restoreCache = restoreCache3; - function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + function extractZipNix(file, dest) { return __awaiter4(this, void 0, void 0, function* () { - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core13.debug("Resolved Keys:"); - core13.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); - } - const compressionMethod = yield utils.getCompressionMethod(); - let archivePath = ""; - try { - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod, - enableCrossOsArchive - }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - return void 0; - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core13.info("Lookup only - skipping download"); - return cacheEntry.cacheKey; - } - archivePath = path5.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core13.debug(`Archive Path: ${archivePath}`); - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core13.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core13.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core13.info("Cache restored successfully"); - return cacheEntry.cacheKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core13.error(`Failed to restore: ${error4.message}`); - } else { - core13.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core13.debug(`Failed to delete archive: ${error4}`); - } + const unzipPath = yield io5.which("unzip", true); + const args = [file]; + if (!core13.isDebug()) { + args.unshift("-q"); } - return void 0; + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); }); } - function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + function cacheDir(sourceDir, tool, version, arch) { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core13.debug("Resolved Keys:"); - core13.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); + version = semver8.clean(version) || version; + arch = arch || os2.arch(); + core13.debug(`Caching tool ${tool} ${version} ${arch}`); + core13.debug(`source dir: ${sourceDir}`); + if (!fs5.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); } - let archivePath = ""; - try { - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - const compressionMethod = yield utils.getCompressionMethod(); - const request = { - key: primaryKey, - restoreKeys, - version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) - }; - const response = yield twirpClient.GetCacheEntryDownloadURL(request); - if (!response.ok) { - core13.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); - return void 0; - } - const isRestoreKeyMatch = request.key !== response.matchedKey; - if (isRestoreKeyMatch) { - core13.info(`Cache hit for restore-key: ${response.matchedKey}`); - } else { - core13.info(`Cache hit for: ${response.matchedKey}`); - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core13.info("Lookup only - skipping download"); - return response.matchedKey; - } - archivePath = path5.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core13.debug(`Archive path: ${archivePath}`); - core13.debug(`Starting download of archive to: ${archivePath}`); - yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core13.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - if (core13.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core13.info("Cache restored successfully"); - return response.matchedKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core13.error(`Failed to restore: ${error4.message}`); - } else { - core13.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - if (archivePath) { - yield utils.unlinkFile(archivePath); - } - } catch (error4) { - core13.debug(`Failed to delete archive: ${error4}`); - } + const destPath = yield _createToolPath(tool, version, arch); + for (const itemName of fs5.readdirSync(sourceDir)) { + const s = path5.join(sourceDir, itemName); + yield io5.cp(s, destPath, { recursive: true }); } - return void 0; + _completeToolPath(tool, version, arch); + return destPath; }); } - function saveCache3(paths, key, options, enableCrossOsArchive = false) { + exports2.cacheDir = cacheDir; + function cacheFile(sourceFile, targetFile, tool, version, arch) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core13.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - checkKey(key); - switch (cacheServiceVersion) { - case "v2": - return yield saveCacheV2(paths, key, options, enableCrossOsArchive); - case "v1": - default: - return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + version = semver8.clean(version) || version; + arch = arch || os2.arch(); + core13.debug(`Caching tool ${tool} ${version} ${arch}`); + core13.debug(`source file: ${sourceFile}`); + if (!fs5.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); } + const destFolder = yield _createToolPath(tool, version, arch); + const destPath = path5.join(destFolder, targetFile); + core13.debug(`destination file ${destPath}`); + yield io5.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch); + return destFolder; }); } - exports2.saveCache = saveCache3; - function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { - var _a, _b, _c, _d, _e; - return __awaiter4(this, void 0, void 0, function* () { - const compressionMethod = yield utils.getCompressionMethod(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core13.debug("Cache Paths:"); - core13.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch) { + if (!toolName) { + throw new Error("toolName parameter is required"); + } + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); + } + arch = arch || os2.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions2(toolName, arch); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; + } + let toolPath = ""; + if (versionSpec) { + versionSpec = semver8.clean(versionSpec) || ""; + const cachePath = path5.join(_getCacheDirectory(), toolName, versionSpec, arch); + core13.debug(`checking cache: ${cachePath}`); + if (fs5.existsSync(cachePath) && fs5.existsSync(`${cachePath}.complete`)) { + core13.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); + toolPath = cachePath; + } else { + core13.debug("not found"); } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path5.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core13.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core13.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const fileSizeLimit = 10 * 1024 * 1024 * 1024; - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core13.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); - } - core13.debug("Reserving Cache"); - const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod, - enableCrossOsArchive, - cacheSize: archiveFileSize - }); - if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { - cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; - } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { - throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); - } else { - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); - } - core13.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError.name) { - core13.info(`Failed to save: ${typedError.message}`); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core13.error(`Failed to save: ${typedError.message}`); - } else { - core13.warning(`Failed to save: ${typedError.message}`); + } + return toolPath; + } + exports2.find = find2; + function findAllVersions2(toolName, arch) { + const versions = []; + arch = arch || os2.arch(); + const toolPath = path5.join(_getCacheDirectory(), toolName); + if (fs5.existsSync(toolPath)) { + const children = fs5.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path5.join(toolPath, child, arch || ""); + if (fs5.existsSync(fullPath) && fs5.existsSync(`${fullPath}.complete`)) { + versions.push(child); } } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core13.debug(`Failed to delete archive: ${error4}`); - } } - return cacheId; - }); + } + return versions; } - function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + exports2.findAllVersions = findAllVersions2; + function getManifestFromRepo(owner, repo, auth, branch = "master") { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); - const compressionMethod = yield utils.getCompressionMethod(); - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core13.debug("Cache Paths:"); - core13.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core13.debug("set auth"); + headers.authorization = auth; } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path5.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core13.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core13.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core13.debug(`File Size: ${archiveFileSize}`); - options.archiveSizeBytes = archiveFileSize; - core13.debug("Reserving Cache"); - const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); - const request = { - key, - version - }; - let signedUploadUrl; - try { - const response = yield twirpClient.CreateCacheEntry(request); - if (!response.ok) { - if (response.message) { - core13.warning(`Cache reservation failed: ${response.message}`); - } - throw new Error(response.message || "Response was not ok"); - } - signedUploadUrl = response.signedUploadUrl; - } catch (error4) { - core13.debug(`Failed to reserve cache: ${error4}`); - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); - } - core13.debug(`Attempting to upload cache located at: ${archivePath}`); - yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); - const finalizeRequest = { - key, - version, - sizeBytes: `${archiveFileSize}` - }; - const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); - core13.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); - if (!finalizeResponse.ok) { - if (finalizeResponse.message) { - throw new FinalizeCacheError(finalizeResponse.message); - } - throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); - } - cacheId = parseInt(finalizeResponse.entryId); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError.name) { - core13.info(`Failed to save: ${typedError.message}`); - } else if (typedError.name === FinalizeCacheError.name) { - core13.warning(typedError.message); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core13.error(`Failed to save: ${typedError.message}`); - } else { - core13.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core13.debug(`Failed to delete archive: ${error4}`); - } + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; } - return cacheId; - }); - } - } -}); - -// node_modules/@actions/tool-cache/lib/manifest.js -var require_manifest = __commonJS({ - "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; } } - function rejected(value) { + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + releases = JSON.parse(versionsRaw); + } catch (_a) { + core13.debug("Invalid json"); } } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return releases; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver8 = __importStar4(require_semver2()); - var core_1 = require_core(); - var os2 = require("os"); - var cp = require("child_process"); - var fs5 = require("fs"); - function _findMatch(versionSpec, stable, candidates, archFilter) { + } + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os2.arch()) { return __awaiter4(this, void 0, void 0, function* () { - const platFilter = os2.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { - file = candidate.files.find((item) => { - (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module2.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } else { - chk = semver8.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - (0, core_1.debug)(`matched ${candidate.version}`); - match = candidate; - break; - } - } - } - if (match && file) { - result = Object.assign({}, match); - result.files = [file]; + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; + }); + } + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!dest) { + dest = path5.join(_getTempDirectory(), crypto.randomUUID()); } - return result; + yield io5.mkdirP(dest); + return dest; }); } - exports2._findMatch = _findMatch; - function _getOsVersion() { - const plat = os2.platform(); + function _createToolPath(tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + const folderPath = path5.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); + core13.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io5.rmRF(folderPath); + yield io5.rmRF(markerPath); + yield io5.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch) { + const folderPath = path5.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); + const markerPath = `${folderPath}.complete`; + fs5.writeFileSync(markerPath, ""); + core13.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver8.clean(versionSpec) || ""; + core13.debug(`isExplicit: ${c}`); + const valid3 = semver8.valid(c) != null; + core13.debug(`explicit? ${valid3}`); + return valid3; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { let version = ""; - if (plat === "darwin") { - version = cp.execSync("sw_vers -productVersion").toString(); - } else if (plat === "linux") { - const lsbContents = module2.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split("\n"); - for (const line of lines) { - const parts = line.split("="); - if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { - version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); - break; - } - } + core13.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver8.gt(a, b)) { + return 1; + } + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver8.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; } } + if (version) { + core13.debug(`matched: ${version}`); + } else { + core13.debug("match not found"); + } return version; } - exports2._getOsVersion = _getOsVersion; - function _readLinuxVersionFile() { - const lsbReleaseFile = "/etc/lsb-release"; - const osReleaseFile = "/etc/os-release"; - let contents = ""; - if (fs5.existsSync(lsbReleaseFile)) { - contents = fs5.readFileSync(lsbReleaseFile).toString(); - } else if (fs5.existsSync(osReleaseFile)) { - contents = fs5.readFileSync(osReleaseFile).toString(); - } - return contents; + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); } - exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + module2.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return true; + } + return a !== a && b !== b; }; + } +}); + +// node_modules/@actions/http-client/lib/proxy.js +var require_proxy5 = __commonJS({ + "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core13 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); + exports2.getProxyUrl = getProxyUrl; + exports2.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - execute(action, isRetryable) { - return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core13.info(err.message); - } - const seconds = this.getSleepAmount(); - core13.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - return yield action(); - }); + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + get username() { + return this._decodedUsername; } - sleep(seconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve4) => setTimeout(resolve4, seconds * 1e3)); - }); + get password() { + return this._decodedPassword; } }; - exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib6 = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74975,15 +77842,25 @@ var require_tool_cache = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve4) { @@ -75012,523 +77889,616 @@ var require_tool_cache = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core13 = __importStar4(require_core()); - var io5 = __importStar4(require_io()); - var crypto = __importStar4(require("crypto")); - var fs5 = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os2 = __importStar4(require("os")); - var path5 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver8 = __importStar4(require_semver2()); - var stream = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError2 = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy5()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.HTTPError = HTTPError2; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path5.join(_getTempDirectory(), crypto.randomUUID()); - yield io5.mkdirP(path5.dirname(dest)); - core13.debug(`Downloading ${url}`); - core13.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError2 && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve4(output.toString()); + }); + })); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs5.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve4(Buffer.concat(chunks)); + }); + })); }); - if (auth) { - core13.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - headers.authorization = auth; - } - const response = yield http.get(url, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError2(response.message.statusCode); - core13.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; - } - const pipeline = util.promisify(stream.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs5.createWriteStream(dest)); - core13.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core13.debug("download failed"); - try { - yield io5.rmRF(dest); - } catch (err) { - core13.debug(`Failed to delete '${dest}'. ${err.message}`); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core13.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } else { - const escapedScript = path5.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io5.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core13.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - core13.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core13.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - args.push("-x", "-C", dest, "-f", file); - if (core13.isDebug()) { - args.push("-v"); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve4(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - const xarPath = yield io5.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io5.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core13.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io5.which("powershell", true); - core13.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); - } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io5.which("unzip", true); - const args = [file]; - if (!core13.isDebug()) { - args.unshift("-q"); + req.end(); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir(sourceDir, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch = arch || os2.arch(); - core13.debug(`Caching tool ${tool} ${version} ${arch}`); - core13.debug(`source dir: ${sourceDir}`); - if (!fs5.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const destPath = yield _createToolPath(tool, version, arch); - for (const itemName of fs5.readdirSync(sourceDir)) { - const s = path5.join(sourceDir, itemName); - yield io5.cp(s, destPath, { recursive: true }); + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - _completeToolPath(tool, version, arch); - return destPath; - }); - } - exports2.cacheDir = cacheDir; - function cacheFile(sourceFile, targetFile, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch = arch || os2.arch(); - core13.debug(`Caching tool ${tool} ${version} ${arch}`); - core13.debug(`source file: ${sourceFile}`); - if (!fs5.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } } - const destFolder = yield _createToolPath(tool, version, arch); - const destPath = path5.join(destFolder, targetFile); - core13.debug(`destination file ${destPath}`); - yield io5.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); + return info6; } - arch = arch || os2.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions2(toolName, arch); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver8.clean(versionSpec) || ""; - const cachePath = path5.join(_getCacheDirectory(), toolName, versionSpec, arch); - core13.debug(`checking cache: ${cachePath}`); - if (fs5.existsSync(cachePath) && fs5.existsSync(`${cachePath}.complete`)) { - core13.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); - toolPath = cachePath; - } else { - core13.debug("not found"); + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return toolPath; - } - exports2.find = find2; - function findAllVersions2(toolName, arch) { - const versions = []; - arch = arch || os2.arch(); - const toolPath = path5.join(_getCacheDirectory(), toolName); - if (fs5.existsSync(toolPath)) { - const children = fs5.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path5.join(toolPath, child, arch || ""); - if (fs5.existsSync(fullPath) && fs5.existsSync(`${fullPath}.complete`)) { - versions.push(child); + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; } } } + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; + } + } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return versions; - } - exports2.findAllVersions = findAllVersions2; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core13.debug("set auth"); - headers.authorization = auth; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + if (!useProxy) { + agent = this._agent; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; - } + if (agent) { + return agent; } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core13.debug("Invalid json"); - } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os2.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path5.join(_getTempDirectory(), crypto.randomUUID()); + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - yield io5.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path5.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); - core13.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io5.rmRF(folderPath); - yield io5.rmRF(markerPath); - yield io5.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch) { - const folderPath = path5.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); - const markerPath = `${folderPath}.complete`; - fs5.writeFileSync(markerPath, ""); - core13.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver8.clean(versionSpec) || ""; - core13.debug(`isExplicit: ${c}`); - const valid3 = semver8.valid(c) != null; - core13.debug(`explicit? ${valid3}`); - return valid3; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core13.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver8.gt(a, b)) { - return 1; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver8.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } + return agent; } - if (version) { - core13.debug(`matched: ${version}`); - } else { - core13.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; + if (proxyAgent) { + return proxyAgent; } - return true; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve4) => setTimeout(() => resolve4(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve4(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve4(response); + } + })); + }); } - return a !== a && b !== b; }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -79413,7 +82383,7 @@ var supportedAnalysisKinds = new Set(Object.values(AnalysisKind)); var core6 = __toESM(require_core()); // src/config/db-config.ts -var jsonschema = __toESM(require_lib2()); +var jsonschema = __toESM(require_lib3()); var semver2 = __toESM(require_semver2()); var PACK_IDENTIFIER_PATTERN = (function() { const alphaNumeric = "[a-z0-9]"; @@ -79955,7 +82925,7 @@ var semver5 = __toESM(require_semver2()); // src/tools-download.ts var core9 = __toESM(require_core()); -var import_http_client = __toESM(require_lib()); +var import_http_client = __toESM(require_lib6()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); var semver6 = __toESM(require_semver2()); diff --git a/lib/setup-codeql-action.js b/lib/setup-codeql-action.js index eaca207d9f..c4114f35ee 100644 --- a/lib/setup-codeql-action.js +++ b/lib/setup-codeql-action.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -19875,9 +19875,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -19934,737 +20016,826 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve4(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve4(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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 (isPlainObject(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+)|(?:(? a.concat(b), []); - } - function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - } - function encodeReserved(str2) { - return str2.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(str2) { - return encodeURIComponent(str2).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; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - function isDefined2(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context2, operator, key, modifier) { - var value = context2[key], result = []; - if (isDefined2(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)); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - result.push(encodeValue(operator, value[k], k)); + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; } - }); + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } } - }); + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - } else { - if (operator === ";") { - if (isDefined2(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; - } - function expand(template, context2) { - 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(context2, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve4(res); } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); } - } else { - return encodeReserved(literal); + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } - } - function parse(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 = omit(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 = omit(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(","); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + req.end(); } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); - } - function endpointWithDefaults(defaults, route, options) { - return parse(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 - }); - } - var endpoint = withDefaults(null, DEFAULTS); - } -}); - -// node_modules/deprecation/dist-node/index.js -var require_dist_node3 = __commonJS({ - "node_modules/deprecation/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var Deprecation = class extends Error { - constructor(message) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - this.name = "Deprecation"; + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; } - }; - exports2.Deprecation = Deprecation; - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - return ret; + return additionalHeaders[header] || clientHeader || _default2; } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve4) => setTimeout(() => resolve4(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve4(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve4(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; + var httpClient = __importStar4(require_lib2()); + var undici_1 = require_undici(); + function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error("Parameter token or opts.auth is required"); + } else if (token && options.auth) { + throw new Error("Parameters token and opts.auth may not both be specified"); + } + return typeof options.auth === "string" ? options.auth : `token ${token}`; + } + exports2.getAuthString = getAuthString; + function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + exports2.getProxyAgent = getProxyAgent; + function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); + } + exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; + function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; + return proxyFetch; } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; } + exports2.getApiBaseUrl = getApiBaseUrl; } }); -// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node4 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { "use strict"; - var __create2 = Object.create; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - RequestError: () => RequestError - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_deprecation = require_dist_node3(); - var import_once = __toESM2(require_once()); - var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - request: () => request - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node2(); - var import_universal_user_agent = require_dist_node(); - var VERSION = "8.4.1"; - function isPlainObject(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); - } - var import_request_error = require_dist_node4(); - function getBufferResponse(response) { - return response.arrayBuffer(); - } - function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - 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" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } - }).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error4; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error4) => { - if (error4 instanceof import_request_error.RequestError) - throw error4; - else if (error4.name === "AbortError") - throw error4; - let message = error4.message; - if (error4.name === "TypeError" && "cause" in error4) { - if (error4.cause instanceof Error) { - message = error4.cause.message; - } else if (typeof error4.cause === "string") { - message = error4.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); - } - 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 getBufferResponse(response); - } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; - } - function withDefaults(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: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - } - var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } - }); - } -}); - -// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node6 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint + endpoint: () => endpoint }); module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); @@ -21218,9 +21179,101 @@ var require_dist_node6 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node7 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/deprecation/dist-node/index.js +var require_dist_node3 = __commonJS({ + "node_modules/deprecation/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var Deprecation = class extends Error { + constructor(message) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "Deprecation"; + } + }; + exports2.Deprecation = Deprecation; + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node4 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; var __create2 = Object.create; var __defProp2 = Object.defineProperty; @@ -21310,9 +21363,9 @@ var require_dist_node7 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js -var require_dist_node8 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js +var require_dist_node5 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21336,7 +21389,7 @@ var require_dist_node8 = __commonJS({ request: () => request }); module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node6(); + var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; function isPlainObject(value) { @@ -21350,7 +21403,7 @@ var require_dist_node8 = __commonJS({ 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); } - var import_request_error = require_dist_node7(); + var import_request_error = require_dist_node4(); function getBufferResponse(response) { return response.arrayBuffer(); } @@ -21520,9 +21573,9 @@ var require_dist_node8 = __commonJS({ } }); -// node_modules/@octokit/graphql/dist-node/index.js -var require_dist_node9 = __commonJS({ - "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node6 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21541,129 +21594,340 @@ var require_dist_node9 = __commonJS({ return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export2(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint }); - module2.exports = __toCommonJS2(index_exports); - var import_request3 = require_dist_node8(); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); - var VERSION = "7.1.1"; - var import_request2 = require_dist_node8(); - var import_request = require_dist_node8(); - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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; + }, {}); } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + function isPlainObject(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 (isPlainObject(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]; } } - }; - 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`) - ); + 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); } - 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` - ) - ); + 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+)|(?:(? { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } + function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; } - if (!result.variables) { - result.variables = {}; + } + return result; + } + function encodeReserved(str2) { + return str2.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, "]"); } - 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 part; + }).join(""); + } + function encodeUnreserved(str2) { + return encodeURIComponent(str2).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; } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; + } + function isDefined2(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context2, operator, key, modifier) { + var value = context2[key], result = []; + if (isDefined2(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)); } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(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(",")); + } + } } - return response.data.data; - }); + } else { + if (operator === ";") { + if (isDefined2(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; } - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); + function parseUrl(template) { + return { + expand: expand.bind(null, template) }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); } - var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" - }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" + function expand(template, context2) { + 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(context2, 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 parse(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 = omit(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 = omit(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(/(? { + 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 parse(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 }); } + var endpoint = withDefaults(null, DEFAULTS); } }); -// node_modules/@octokit/auth-token/dist-node/index.js -var require_dist_node10 = __commonJS({ - "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node7 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; + var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) @@ -21677,53 +21941,490 @@ var require_dist_node10 = __commonJS({ } return to; }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - createTokenAuth: () => createTokenAuth + RequestError: () => RequestError }); module2.exports = __toCommonJS2(dist_src_exports); - 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, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); - } - 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" - ); + var import_deprecation = require_dist_node3(); + var import_once = __toESM2(require_once()); + var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + request: () => request + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_endpoint = require_dist_node6(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "8.4.1"; + function isPlainObject(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); + } + var import_request_error = require_dist_node7(); + function getBufferResponse(response) { + return response.arrayBuffer(); + } + function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + 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" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error4; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error4) => { + if (error4 instanceof import_request_error.RequestError) + throw error4; + else if (error4.name === "AbortError") + throw error4; + let message = error4.message; + if (error4.name === "TypeError" && "cause" in error4) { + if (error4.cause instanceof Error) { + message = error4.cause.message; + } else if (typeof error4.cause === "string") { + message = error4.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); + } + 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 getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; + } + function withDefaults(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: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + } + var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }); + } +}); + +// node_modules/@octokit/graphql/dist-node/index.js +var require_dist_node9 = __commonJS({ + "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export2(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest + }); + module2.exports = __toCommonJS2(index_exports); + var import_request3 = require_dist_node8(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "7.1.1"; + var import_request2 = require_dist_node8(); + var import_request = require_dist_node8(); + 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.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + }; + 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 withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); + } + } +}); + +// node_modules/@octokit/auth-token/dist-node/index.js +var require_dist_node10 = __commonJS({ + "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + createTokenAuth: () => createTokenAuth + }); + module2.exports = __toCommonJS2(dist_src_exports); + 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, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + 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) + }); }; } }); @@ -26499,7 +27200,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -31214,5021 +31915,5826 @@ var require_cacheUtils = __commonJS({ } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); - var HttpPipeline = class _HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = void 0; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - this._policies.push({ - policy, - options - }); - this._orderedPolicies = void 0; + } else { + return void 0; } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { - removedPolicies.push(policyDescriptor.policy); - return false; - } else { - return true; - } - }); - this._orderedPolicies = void 0; - return removedPolicies; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - clone() { - return new _HttpPipeline(this._policies); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - static create() { - return new _HttpPipeline(); + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - orderPolicies() { - const result = []; - const policyMap = /* @__PURE__ */ new Map(); - function createPhase(name) { - return { - name, - policies: /* @__PURE__ */ new Set(), - hasRun: false, - hasAfterPolicies: false - }; - } - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } else if (phase === "Serialize") { - return serializePhase; - } else if (phase === "Deserialize") { - return deserializePhase; - } else if (phase === "Sign") { - return signPhase; - } else { - return noPhase; - } - } - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: /* @__PURE__ */ new Set(), - dependants: /* @__PURE__ */ new Set() - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); - } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); - } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); - } - } - } - } - function walkPhase(phase) { - phase.hasRun = true; - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - continue; - } - if (node.dependsOn.size === 0) { - result.push(node.policy); - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); - } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - walkPhase(noPhase); - } - return; - } - if (phase.hasAfterPolicies) { - walkPhase(noPhase); - } - } - } - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - walkPhases(); - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return result; } - }; - function createEmptyPipeline() { - return HttpPipeline.create(); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@azure/logger/dist/index.js -var require_dist = __commonJS({ - "node_modules/@azure/logger/dist/index.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var os3 = require("os"); - var util = require("util"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); - function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os3.EOL}`); - } - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; - var enabledString; - var enabledNamespaces = []; - var skippedNamespaces = []; - var debuggers = []; - if (debugEnvVariable) { - enable(debugEnvVariable); - } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log - }); - function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); - } else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); - } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - } - function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - } - return false; - } - function disable() { - const result = enabledString || ""; - enable(""); - return result; - } - function createDebugger(namespace) { - const newDebugger = Object.assign(debug6, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend: extend3 - }); - function debug6(...args) { - if (!newDebugger.enabled) { - return; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); } - newDebugger.log(...args); - } - debuggers.push(newDebugger); - return newDebugger; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return false; - } - function extend3(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; - } - var debug5 = debugObj; - var registeredLoggers = /* @__PURE__ */ new Set(); - var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; - var azureLogLevel; - var AzureLogger = debug5("azure"); - AzureLogger.log = (...args) => { - debug5.log(...args); }; - var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; - if (logLevelFromEnv) { - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); - } else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - } - function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve4(output.toString()); + }); + })); + }); } - azureLogLevel = level; - const enabledNamespaces2 = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces2.push(logger.namespace); - } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve4(Buffer.concat(chunks)); + }); + })); + }); } - debug5.enable(enabledNamespaces2.join(",")); - } - function getLogLevel() { - return azureLogLevel; - } - var levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 }; - function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") - }; - } - function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); - }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces2 = debug5.disable(); - debug5.enable(enabledNamespaces2 + "," + logger.namespace); + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - registeredLoggers.add(logger); - return logger; - } - function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); - } - function isAzureLogLevel(logLevel) { - return AZURE_LOG_LEVELS.includes(logLevel); - } - exports2.AzureLogger = AzureLogger; - exports2.createClientLogger = createClientLogger; - exports2.getLogLevel = getLogLevel; - exports2.setLogLevel = setLogLevel; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js -var require_log = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_dist(); - exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - } -}); - -// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js -var require_createAbortablePromise = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createAbortablePromise = createAbortablePromise; - var abort_controller_1 = require_commonjs(); - function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve4, reject) => { - function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - function removeListeners() { - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve4(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - function onAbort() { - cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); - removeListeners(); - rejectOnAbort(); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { - return rejectOnAbort(); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - try { - buildPromise((x) => { - removeListeners(); - resolve4(x); - }, (x) => { - removeListeners(); - reject(x); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); }); - } catch (err) { - reject(err); + data.pipe(req); + } else { + req.end(); } - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); - }); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/random.js -var require_random = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - function getRandomIntegerInclusive(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - const offset = Math.floor(Math.random() * (max - min + 1)); - return offset + min; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/delay.js -var require_delay = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay2; - exports2.calculateRetryDelay = calculateRetryDelay; - var createAbortablePromise_js_1 = require_createAbortablePromise(); - var random_js_1 = require_random(); - var StandardAbortMessage = "The delay was aborted."; - function delay2(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve4) => { - token = setTimeout(resolve4, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage - }); - } - function calculateRetryDelay(retryAttempt, config) { - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); - return { retryAfterInMs }; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js -var require_aborterUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cancelablePromiseRace = cancelablePromiseRace; - async function cancelablePromiseRace(abortablePromiseBuilders, options) { - var _a, _b; - const aborter = new AbortController(); - function abortHandler() { - aborter.abort(); } - (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); - try { - return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); - } finally { - aborter.abort(); - (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/object.js -var require_object = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isObject = isObject2; - function isObject2(input) { - return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/error.js -var require_error = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isError = isError; - exports2.getErrorMessage = getErrorMessage2; - var object_js_1 = require_object(); - function isError(e) { - if ((0, object_js_1.isObject)(e)) { - const hasName = typeof e.name === "string"; - const hasMessage = typeof e.message === "string"; - return hasName && hasMessage; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return false; - } - function getErrorMessage2(e) { - if (isError(e)) { - return e.message; - } else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } else { - stringified = String(e); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - } catch (err) { - stringified = "[unable to stringify input]"; } - return `Unknown error ${stringified}`; + return info6; } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.computeSha256Hash = computeSha256Hash; - var crypto_1 = require("crypto"); - async function computeSha256Hmac(key, stringToSign, encoding) { - const decodedKey = Buffer.from(key, "base64"); - return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); - } - async function computeSha256Hash(content, encoding) { - return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/typeGuards.js -var require_typeGuards = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isDefined = isDefined2; - exports2.isObjectWithProperties = isObjectWithProperties; - exports2.objectHasProperty = objectHasProperty; - function isDefined2(thing) { - return typeof thing !== "undefined" && thing !== null; - } - function isObjectWithProperties(thing, properties) { - if (!isDefined2(thing) || typeof thing !== "object") { - return false; - } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - return true; - } - function objectHasProperty(thing, property) { - return isDefined2(thing) && typeof thing === "object" && property in thing; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js -var require_uuidUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomUUID = randomUUID2; - var crypto_1 = require("crypto"); - var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; - function randomUUID2() { - return uuidFunction(); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js -var require_checkEnvironment = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { - "use strict"; - var _a; - var _b; - var _c; - var _d; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; - exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; - exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); - exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; - exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; - exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); - exports2.isNode = exports2.isNodeLike; - exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; - exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; - } -}); - -// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js -var require_bytesEncoding = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - function uint8ArrayToString(bytes, format) { - return Buffer.from(bytes).toString(format); - } - function stringToUint8Array(value, format) { - return Buffer.from(value, format); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/index.js -var require_commonjs2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; - var delay_js_1 = require_delay(); - Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { - return delay_js_1.delay; - } }); - Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { - return delay_js_1.calculateRetryDelay; - } }); - var aborterUtils_js_1 = require_aborterUtils(); - Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { - return aborterUtils_js_1.cancelablePromiseRace; - } }); - var createAbortablePromise_js_1 = require_createAbortablePromise(); - Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { - return createAbortablePromise_js_1.createAbortablePromise; - } }); - var random_js_1 = require_random(); - Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { - return random_js_1.getRandomIntegerInclusive; - } }); - var object_js_1 = require_object(); - Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { - return object_js_1.isObject; - } }); - var error_js_1 = require_error(); - Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { - return error_js_1.isError; - } }); - Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { - return error_js_1.getErrorMessage; - } }); - var sha256_js_1 = require_sha256(); - Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hash; - } }); - Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hmac; - } }); - var typeGuards_js_1 = require_typeGuards(); - Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { - return typeGuards_js_1.isDefined; - } }); - Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { - return typeGuards_js_1.isObjectWithProperties; - } }); - Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { - return typeGuards_js_1.objectHasProperty; - } }); - var uuidUtils_js_1 = require_uuidUtils(); - Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { - return uuidUtils_js_1.randomUUID; - } }); - var checkEnvironment_js_1 = require_checkEnvironment(); - Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBrowser; - } }); - Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBun; - } }); - Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNode; - } }); - Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeLike; - } }); - Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeRuntime; - } }); - Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { - return checkEnvironment_js_1.isDeno; - } }); - Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { - return checkEnvironment_js_1.isReactNative; - } }); - Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { - return checkEnvironment_js_1.isWebWorker; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js -var require_sanitizer = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = void 0; - var core_util_1 = require_commonjs2(); - var RedactedString = "REDACTED"; - var defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate" - ]; - var defaultAllowedQueryParameters = ["api-version"]; - var Sanitizer = class { - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { - allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); - allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); - } - sanitize(obj) { - const seen = /* @__PURE__ */ new Set(); - return JSON.stringify(obj, (key, value) => { - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); - } - if (key === "headers") { - return this.sanitizeHeaders(value); - } else if (key === "url") { - return this.sanitizeUrl(value); - } else if (key === "query") { - return this.sanitizeQuery(value); - } else if (key === "body") { - return void 0; - } else if (key === "response") { - return void 0; - } else if (key === "operationSpec") { - return void 0; - } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - } - return value; - }, 2); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - sanitizeUrl(value) { - if (typeof value !== "string" || value === null || value === "") { - return value; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const url = new URL(value); - if (!url.search) { - return value; + if (!useProxy) { + agent = this._agent; } - for (const [key] of url.searchParams) { - if (!this.allowedQueryParameters.has(key.toLowerCase())) { - url.searchParams.set(key, RedactedString); - } + if (agent) { + return agent; } - return url.toString(); - } - sanitizeHeaders(obj) { - const sanitized = {}; - for (const key of Object.keys(obj)) { - if (this.allowedHeaderNames.has(key.toLowerCase())) { - sanitized[key] = obj[key]; + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - sanitized[key] = RedactedString; + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - return sanitized; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - sanitizeQuery(value) { - if (typeof value !== "object" || value === null) { - return value; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (this.allowedQueryParameters.has(k.toLowerCase())) { - sanitized[k] = value[k]; - } else { - sanitized[k] = RedactedString; - } + if (proxyAgent) { + return proxyAgent; } - return sanitized; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve4) => setTimeout(() => resolve4(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve4(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve4(response); + } + })); + }); } }; - exports2.Sanitizer = Sanitizer; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js -var require_logPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log(); - var sanitizer_js_1 = require_sanitizer(); - exports2.logPolicyName = "logPolicy"; - function logPolicy(options = {}) { - var _a; - const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - return { - name: exports2.logPolicyName, - async sendRequest(request, next) { - if (!logger.enabled) { - return next(request); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - logger(`Request: ${sanitizer.sanitize(request)}`); - const response = await next(request); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); - return response; } - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js -var require_redirectPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - exports2.redirectPolicyName = "redirectPolicy"; - var allowedRedirect = ["GET", "HEAD"]; - function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: exports2.redirectPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return handleRedirect(next, response, maxRetries); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - }; - } - async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { - const url = new URL(locationHeader, request.url); - request.url = url.toString(); - if (status === 303) { - request.method = "GET"; - request.headers.delete("Content-Length"); - delete request.body; + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); } - request.headers.delete("Authorization"); - const res = await next(request); - return handleRedirect(next, res, maxRetries, currentRetries + 1); - } - return response; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs -var tslib_es6_exports = {}; -__export(tslib_es6_exports, { - __addDisposableResource: () => __addDisposableResource, - __assign: () => __assign, - __asyncDelegator: () => __asyncDelegator, - __asyncGenerator: () => __asyncGenerator, - __asyncValues: () => __asyncValues, - __await: () => __await, - __awaiter: () => __awaiter, - __classPrivateFieldGet: () => __classPrivateFieldGet, - __classPrivateFieldIn: () => __classPrivateFieldIn, - __classPrivateFieldSet: () => __classPrivateFieldSet, - __createBinding: () => __createBinding, - __decorate: () => __decorate, - __disposeResources: () => __disposeResources, - __esDecorate: () => __esDecorate, - __exportStar: () => __exportStar, - __extends: () => __extends, - __generator: () => __generator, - __importDefault: () => __importDefault, - __importStar: () => __importStar, - __makeTemplateObject: () => __makeTemplateObject, - __metadata: () => __metadata, - __param: () => __param, - __propKey: () => __propKey, - __read: () => __read, - __rest: () => __rest, - __runInitializers: () => __runInitializers, - __setFunctionName: () => __setFunctionName, - __spread: () => __spread, - __spreadArray: () => __spreadArray, - __spreadArrays: () => __spreadArrays, - __values: () => __values2, - default: () => tslib_es6_default -}); -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context2 = {}; - for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; - context2.addInitializer = function(f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} -function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -} -function __propKey(x) { - return typeof x === "symbol" ? x : "".concat(x); -} -function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); -} -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; + }; + function createEmptyPipeline() { + return HttpPipeline.create(); } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; } -} -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} -function __values2(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function() { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; +}); + +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os3 = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error4) { - e = { error: error4 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os3.EOL}`); } - } - return ar; -} -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - if (f) i[n] = f(i[n]); + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log + }); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function(e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function() { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function(v) { - return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; - } : f; - } -} -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve4, reject) { - v = o[n](v), settle(resolve4, reject, v.done, v.value); - }); - }; - } - function settle(resolve4, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve4({ value: v2, done: d }); - }, reject); - } -} -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - } - __setModuleDefault(result, mod); - return result; -} -function __importDefault(mod) { - return mod && mod.__esModule ? mod : { default: mod }; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldIn(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} -function __addDisposableResource(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; + function disable() { + const result = enabledString || ""; + enable(""); + return result; } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; + function createDebugger(namespace) { + const newDebugger = Object.assign(debug6, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug6(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { - try { - inner.call(this); - } catch (e) { - return Promise.reject(e); + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; } + return false; + } + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; + } + var debug5 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug5("azure"); + AzureLogger.log = (...args) => { + debug5.log(...args); }; - env.stack.push({ value, dispose, async }); - } else if (async) { - env.stack.push({ async: true }); - } - return value; -} -function __disposeResources(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { - fail(e); - return next(); - }); - } else s |= 1; - } catch (e) { - fail(e); + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); } } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; - } - return next(); -} -var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; -var init_tslib_es6 = __esm({ - "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() { - extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics(d, b); - }; - __assign = function() { - __assign = Object.assign || function __assign4(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); } - return t; - }; - return __assign.apply(this, arguments); - }; - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - }); - __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; - }; - tslib_es6_default = { - __extends, - __assign, - __rest, - __decorate, - __param, - __metadata, - __awaiter, - __generator, - __createBinding, - __exportStar, - __values: __values2, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn, - __addDisposableResource, - __disposeResources + debug5.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 }; + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; + } + function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; + } + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces2 = debug5.disable(); + debug5.enable(enabledNamespaces2 + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; + } + function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + } + function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); + } + exports2.AzureLogger = AzureLogger; + exports2.createClientLogger = createClientLogger; + exports2.getLogLevel = getLogLevel; + exports2.setLogLevel = setLogLevel; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js -var require_userAgentPlatform = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js +var require_log = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getHeaderName = getHeaderName; - exports2.setPlatformSpecificData = setPlatformSpecificData; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var os3 = tslib_1.__importStar(require("node:os")); - var process2 = tslib_1.__importStar(require("node:process")); - function getHeaderName() { - return "User-Agent"; - } - async function setPlatformSpecificData(map2) { - if (process2 && process2.versions) { - const versions = process2.versions; - if (versions.bun) { - map2.set("Bun", versions.bun); - } else if (versions.deno) { - map2.set("Deno", versions.deno); - } else if (versions.node) { - map2.set("Node", versions.node); - } - } - map2.set("OS", `(${os3.arch()}-${os3.type()}-${os3.release()})`); - } + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js -var require_constants8 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; - exports2.SDK_VERSION = "1.17.0"; - exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js -var require_userAgent = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUserAgentHeaderName = getUserAgentHeaderName; - exports2.getUserAgentValue = getUserAgentValue; - var userAgentPlatform_js_1 = require_userAgentPlatform(); - var constants_js_1 = require_constants8(); - function getUserAgentString(telemetryInfo) { - const parts = []; - for (const [key, value] of telemetryInfo) { - const token = value ? `${key}/${value}` : key; - parts.push(token); - } - return parts.join(" "); - } - function getUserAgentHeaderName() { - return (0, userAgentPlatform_js_1.getHeaderName)(); - } - async function getUserAgentValue(prefix) { - const runtimeInfo = /* @__PURE__ */ new Map(); - runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); - await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); - const defaultAgent = getUserAgentString(runtimeInfo); - const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; - return userAgentValue; - } + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js -var require_userAgentPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.userAgentPolicyName = void 0; - exports2.userAgentPolicy = userAgentPolicy; - var userAgent_js_1 = require_userAgent(); - var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); - exports2.userAgentPolicyName = "userAgentPolicy"; - function userAgentPolicy(options = {}) { - const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); - return { - name: exports2.userAgentPolicyName, - async sendRequest(request, next) { - if (!request.headers.has(UserAgentHeaderName)) { - request.headers.set(UserAgentHeaderName, await userAgentValue); - } - return next(request); + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve4, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); } - }; + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve4(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js -var require_typeGuards2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/random.js +var require_random = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isNodeReadableStream = isNodeReadableStream; - exports2.isWebReadableStream = isWebReadableStream; - exports2.isReadableStream = isReadableStream; - exports2.isBlob = isBlob; - function isNodeReadableStream(x) { - return Boolean(x && typeof x["pipe"] === "function"); - } - function isWebReadableStream(x) { - return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); - } - function isReadableStream(x) { - return isNodeReadableStream(x) || isWebReadableStream(x); - } - function isBlob(x) { - return typeof x.stream === "function"; + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; + function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js -var require_file2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRawContent = getRawContent; - exports2.createFileFromStream = createFileFromStream; - exports2.createFile = createFile; - var core_util_1 = require_commonjs2(); - var typeGuards_js_1 = require_typeGuards2(); - var unimplementedMethods = { - arrayBuffer: () => { - throw new Error("Not implemented"); - }, - slice: () => { - throw new Error("Not implemented"); - }, - text: () => { - throw new Error("Not implemented"); - } - }; - var rawContent = Symbol("rawContent"); - function hasRawContent(x) { - return typeof x[rawContent] === "function"; - } - function getRawContent(blob) { - if (hasRawContent(blob)) { - return blob[rawContent](); - } else { - return blob.stream(); - } - } - function createFileFromStream(stream2, name, options = {}) { - var _a, _b, _c, _d; - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { - const s = stream2(); - if ((0, typeGuards_js_1.isNodeReadableStream)(s)) { - throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); - } - return s; - }, [rawContent]: stream2 }); + exports2.delay = delay2; + exports2.calculateRetryDelay = calculateRetryDelay; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var random_js_1 = require_random(); + var StandardAbortMessage = "The delay was aborted."; + function delay2(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve4) => { + token = setTimeout(resolve4, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage + }); } - function createFile(content, name, options = {}) { - var _a, _b, _c; - if (core_util_1.isNodeLike) { - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); - } else { - return new File([content], name, options); - } + function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js -var require_concat = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.concat = concat; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var node_stream_1 = require("node:stream"); - var typeGuards_js_1 = require_typeGuards2(); - var file_js_1 = require_file2(); - function streamAsyncIterator() { - return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { - const reader = this.getReader(); - try { - while (true) { - const { done, value } = yield tslib_1.__await(reader.read()); - if (done) { - return yield tslib_1.__await(void 0); - } - yield yield tslib_1.__await(value); - } - } finally { - reader.releaseLock(); - } - }); - } - function makeAsyncIterable(webStream) { - if (!webStream[Symbol.asyncIterator]) { - webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); - } - if (!webStream.values) { - webStream.values = streamAsyncIterator.bind(webStream); - } - } - function ensureNodeStream(stream2) { - if (stream2 instanceof ReadableStream) { - makeAsyncIterable(stream2); - return node_stream_1.Readable.fromWeb(stream2); - } else { - return stream2; + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); } - } - function toStream(source) { - if (source instanceof Uint8Array) { - return node_stream_1.Readable.from(Buffer.from(source)); - } else if ((0, typeGuards_js_1.isBlob)(source)) { - return toStream((0, file_js_1.getRawContent)(source)); - } else { - return ensureNodeStream(source); + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); } } - async function concat(sources) { - return function() { - const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); - return node_stream_1.Readable.from((function() { - return tslib_1.__asyncGenerator(this, arguments, function* () { - var _a, e_1, _b, _c; - for (const stream2 of streams) { - try { - for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream2)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { - _c = stream_1_1.value; - _d = false; - const chunk = _c; - yield yield tslib_1.__await(chunk); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1)); - } finally { - if (e_1) throw e_1.error; - } - } - } - }); - })()); - }; - } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js -var require_multipartPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/object.js +var require_object = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.multipartPolicyName = void 0; - exports2.multipartPolicy = multipartPolicy; - var core_util_1 = require_commonjs2(); - var concat_js_1 = require_concat(); - var typeGuards_js_1 = require_typeGuards2(); - function generateBoundary() { - return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; + exports2.isObject = isObject2; + function isObject2(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); } - function encodeHeaders(headers) { - let result = ""; - for (const [key, value] of headers) { - result += `${key}: ${value}\r -`; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isError = isError; + exports2.getErrorMessage = getErrorMessage2; + var object_js_1 = require_object(); + function isError(e) { + if ((0, object_js_1.isObject)(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; } - return result; + return false; } - function getLength(source) { - if (source instanceof Uint8Array) { - return source.byteLength; - } else if ((0, typeGuards_js_1.isBlob)(source)) { - return source.size === -1 ? void 0 : source.size; + function getErrorMessage2(e) { + if (isError(e)) { + return e.message; } else { - return void 0; - } - } - function getTotalLength(sources) { - let total = 0; - for (const source of sources) { - const partLength = getLength(source); - if (partLength === void 0) { - return void 0; - } else { - total += partLength; - } - } - return total; - } - async function buildRequestBody(request, parts, boundary) { - const sources = [ - (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"), - ...parts.flatMap((part) => [ - (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), - (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), - (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), - part.body, - (0, core_util_1.stringToUint8Array)(`\r ---${boundary}`, "utf-8") - ]), - (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8") - ]; - const contentLength = getTotalLength(sources); - if (contentLength) { - request.headers.set("Content-Length", contentLength); - } - request.body = await (0, concat_js_1.concat)(sources); - } - exports2.multipartPolicyName = "multipartPolicy"; - var maxBoundaryLength = 70; - var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); - function assertValidBoundary(boundary) { - if (boundary.length > maxBoundaryLength) { - throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); - } - if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { - throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); - } - } - function multipartPolicy() { - return { - name: exports2.multipartPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.multipartBody) { - return next(request); - } - if (request.body) { - throw new Error("multipartBody and regular body cannot be set at the same time"); - } - let boundary = request.multipartBody.boundary; - const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; - const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); - if (!parsedHeader) { - throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); - } - const [, contentType, parsedBoundary] = parsedHeader; - if (parsedBoundary && boundary && parsedBoundary !== boundary) { - throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); - } - boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary; - if (boundary) { - assertValidBoundary(boundary); + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); } else { - boundary = generateBoundary(); + stringified = String(e); } - request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); - await buildRequestBody(request, request.multipartBody.parts, boundary); - request.multipartBody = void 0; - return next(request); + } catch (err) { + stringified = "[unable to stringify input]"; } - }; + return `Unknown error ${stringified}`; + } } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js -var require_decompressResponsePolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decompressResponsePolicyName = void 0; - exports2.decompressResponsePolicy = decompressResponsePolicy; - exports2.decompressResponsePolicyName = "decompressResponsePolicy"; - function decompressResponsePolicy() { - return { - name: exports2.decompressResponsePolicyName, - async sendRequest(request, next) { - if (request.method !== "HEAD") { - request.headers.set("Accept-Encoding", "gzip,deflate"); - } - return next(request); - } - }; + exports2.computeSha256Hmac = computeSha256Hmac; + exports2.computeSha256Hash = computeSha256Hash; + var crypto_1 = require("crypto"); + async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); + } + async function computeSha256Hash(content, encoding) { + return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); } } }); -// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + exports2.isDefined = isDefined2; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined2(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined2(thing) || typeof thing !== "object") { + return false; } - }; - exports2.AbortError = AbortError; + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined2(thing) && typeof thing === "object" && property in thing; + } } }); -// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs3 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js +var require_uuidUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { "use strict"; + var _a; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError2(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); + exports2.randomUUID = randomUUID2; + var crypto_1 = require("crypto"); + var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; + function randomUUID2() { + return uuidFunction(); + } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js -var require_helpers = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js +var require_checkEnvironment = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { "use strict"; + var _a; + var _b; + var _c; + var _d; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay2; - exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; - var abort_controller_1 = require_commonjs3(); - var StandardAbortMessage = "The operation was aborted."; - function delay2(delayInMs, value, options) { - return new Promise((resolve4, reject) => { - let timer = void 0; - let onAborted = void 0; - const rejectOnAbort = () => { - return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); - }; - const removeListeners = () => { - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { - options.abortSignal.removeEventListener("abort", onAborted); - } - }; - onAborted = () => { - if (timer) { - clearTimeout(timer); - } - removeListeners(); - return rejectOnAbort(); - }; - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { - return rejectOnAbort(); - } - timer = setTimeout(() => { - removeListeners(); - resolve4(value); - }, delayInMs); - if (options === null || options === void 0 ? void 0 : options.abortSignal) { - options.abortSignal.addEventListener("abort", onAborted); - } - }); - } - function parseHeaderValueAsNumber(response, headerName) { - const value = response.headers.get(headerName); - if (!value) - return; - const valueAsNum = Number(value); - if (Number.isNaN(valueAsNum)) - return; - return valueAsNum; - } + exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; + exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; + exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); + exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; + exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; + exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); + exports2.isNode = exports2.isNodeLike; + exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; + exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js -var require_throttlingRetryStrategy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js +var require_bytesEncoding = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; - exports2.throttlingRetryStrategy = throttlingRetryStrategy; - var helpers_js_1 = require_helpers(); - var RetryAfterHeader = "Retry-After"; - var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; - function getRetryAfterInMs(response) { - if (!(response && [429, 503].includes(response.status))) - return void 0; - try { - for (const header of AllRetryAfterHeaders) { - const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); - if (retryAfterValue === 0 || retryAfterValue) { - const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; - return retryAfterValue * multiplyingFactor; - } - } - const retryAfterHeader = response.headers.get(RetryAfterHeader); - if (!retryAfterHeader) - return; - const date = Date.parse(retryAfterHeader); - const diff = date - Date.now(); - return Number.isFinite(diff) ? Math.max(0, diff) : void 0; - } catch (_a) { - return void 0; - } - } - function isThrottlingRetryResponse(response) { - return Number.isFinite(getRetryAfterInMs(response)); + exports2.uint8ArrayToString = uint8ArrayToString; + exports2.stringToUint8Array = stringToUint8Array; + function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); } - function throttlingRetryStrategy() { - return { - name: "throttlingRetryStrategy", - retry({ response }) { - const retryAfterInMs = getRetryAfterInMs(response); - if (!Number.isFinite(retryAfterInMs)) { - return { skipStrategy: true }; - } - return { - retryAfterInMs - }; - } - }; + function stringToUint8Array(value, format) { + return Buffer.from(value, format); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js -var require_exponentialRetryStrategy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryStrategy = exponentialRetryStrategy; - exports2.isExponentialRetryResponse = isExponentialRetryResponse; - exports2.isSystemError = isSystemError; + exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; + var delay_js_1 = require_delay(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { + return delay_js_1.calculateRetryDelay; + } }); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var random_js_1 = require_random(); + Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { + return random_js_1.getRandomIntegerInclusive; + } }); + var object_js_1 = require_object(); + Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { + return object_js_1.isObject; + } }); + var error_js_1 = require_error(); + Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { + return error_js_1.isError; + } }); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var sha256_js_1 = require_sha256(); + Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hash; + } }); + Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hmac; + } }); + var typeGuards_js_1 = require_typeGuards(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + var uuidUtils_js_1 = require_uuidUtils(); + Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { + return uuidUtils_js_1.randomUUID; + } }); + var checkEnvironment_js_1 = require_checkEnvironment(); + Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBrowser; + } }); + Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBun; + } }); + Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNode; + } }); + Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeLike; + } }); + Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeRuntime; + } }); + Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { + return checkEnvironment_js_1.isDeno; + } }); + Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { + return checkEnvironment_js_1.isReactNative; + } }); + Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { + return checkEnvironment_js_1.isWebWorker; + } }); + var bytesEncoding_js_1 = require_bytesEncoding(); + Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { + return bytesEncoding_js_1.uint8ArrayToString; + } }); + Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { + return bytesEncoding_js_1.stringToUint8Array; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js +var require_sanitizer = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Sanitizer = void 0; var core_util_1 = require_commonjs2(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; - var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; - function exponentialRetryStrategy(options = {}) { - var _a, _b; - const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; - const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - let retryAfterInMs = retryInterval; - return { - name: "exponentialRetryStrategy", - retry({ retryCount, response, responseError }) { - const matchedSystemError = isSystemError(responseError); - const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; - const isExponential = isExponentialRetryResponse(response); - const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; - const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); - if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { - return { skipStrategy: true }; + var RedactedString = "REDACTED"; + var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" + ]; + var defaultAllowedQueryParameters = ["api-version"]; + var Sanitizer = class { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); } - if (responseError && !matchedSystemError && !isExponential) { - return { errorToThrow: responseError }; + if (key === "headers") { + return this.sanitizeHeaders(value); + } else if (key === "url") { + return this.sanitizeUrl(value); + } else if (key === "query") { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); } - const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); - const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); - retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2); - return { retryAfterInMs }; + return value; + }, 2); + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; } - }; - } - function isExponentialRetryResponse(response) { - return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); - } - function isSystemError(err) { - if (!err) { - return false; + const url = new URL(value); + if (!url.search) { + return value; + } + for (const [key] of url.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url.searchParams.set(key, RedactedString); + } + } + return url.toString(); } - return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; - } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } + }; + exports2.Sanitizer = Sanitizer; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js -var require_retryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js +var require_logPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.retryPolicy = retryPolicy; - var helpers_js_1 = require_helpers(); - var logger_1 = require_dist(); - var abort_controller_1 = require_commonjs3(); - var constants_js_1 = require_constants8(); - var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); - var retryPolicyName = "retryPolicy"; - function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { - const logger = options.logger || retryPolicyLogger; + exports2.logPolicyName = void 0; + exports2.logPolicy = logPolicy; + var log_js_1 = require_log(); + var sanitizer_js_1 = require_sanitizer(); + exports2.logPolicyName = "logPolicy"; + function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); return { - name: retryPolicyName, + name: exports2.logPolicyName, async sendRequest(request, next) { - var _a, _b; - let response; - let responseError; - let retryCount = -1; - retryRequest: while (true) { - retryCount += 1; - response = void 0; - responseError = void 0; - try { - logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); - response = await next(request); - logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); - } catch (e) { - logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); - responseError = e; - if (!e || responseError.name !== "RestError") { - throw e; - } - response = responseError.response; - } - if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - logger.error(`Retry ${retryCount}: Request aborted.`); - const abortError = new abort_controller_1.AbortError(); - throw abortError; - } - if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { - logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); - if (responseError) { - throw responseError; - } else if (response) { - return response; - } else { - throw new Error("Maximum retries reached with no response or error to throw"); - } - } - logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); - strategiesLoop: for (const strategy of strategies) { - const strategyLogger = strategy.logger || retryPolicyLogger; - strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); - const modifiers = strategy.retry({ - retryCount, - response, - responseError - }); - if (modifiers.skipStrategy) { - strategyLogger.info(`Retry ${retryCount}: Skipped.`); - continue strategiesLoop; - } - const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; - if (errorToThrow) { - strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); - throw errorToThrow; - } - if (retryAfterInMs || retryAfterInMs === 0) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); - await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); - continue retryRequest; - } - if (redirectTo) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); - request.url = redirectTo; - continue retryRequest; - } - } - if (responseError) { - logger.info(`None of the retry strategies could work with the received error. Throwing it.`); - throw responseError; - } - if (response) { - logger.info(`None of the retry strategies could work with the received response. Returning it.`); - return response; - } + if (!logger.enabled) { + return next(request); } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; } }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js -var require_defaultRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.defaultRetryPolicyName = void 0; - exports2.defaultRetryPolicy = defaultRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.defaultRetryPolicyName = "defaultRetryPolicy"; - function defaultRetryPolicy(options = {}) { - var _a; + exports2.redirectPolicyName = void 0; + exports2.redirectPolicy = redirectPolicy; + exports2.redirectPolicyName = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; return { - name: exports2.defaultRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest + name: exports2.redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + } }; } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js -var require_httpHeaders = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createHttpHeaders = createHttpHeaders; - function normalizeName(name) { - return name.toLowerCase(); - } - function* headerIterator(map2) { - for (const entry of map2.values()) { - yield [entry.name, entry.value]; - } - } - var HttpHeadersImpl = class { - constructor(rawHeaders) { - this._headersMap = /* @__PURE__ */ new Map(); - if (rawHeaders) { - for (const headerName of Object.keys(rawHeaders)) { - this.set(headerName, rawHeaders[headerName]); - } - } - } - /** - * Set a header in this collection with the provided name and value. The name is - * case-insensitive. - * @param name - The name of the header to set. This value is case-insensitive. - * @param value - The value of the header to set. - */ - set(name, value) { - this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); - } - /** - * Get the header value for the provided header name, or undefined if no header exists in this - * collection with the provided name. - * @param name - The name of the header. This value is case-insensitive. - */ - get(name) { - var _a; - return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; - } - /** - * Get whether or not this header collection contains a header entry for the provided header name. - * @param name - The name of the header to set. This value is case-insensitive. - */ - has(name) { - return this._headersMap.has(normalizeName(name)); - } - /** - * Remove the header with the provided headerName. - * @param name - The name of the header to remove. - */ - delete(name) { - this._headersMap.delete(normalizeName(name)); - } - /** - * Get the JSON object representation of this HTTP header collection. - */ - toJSON(options = {}) { - const result = {}; - if (options.preserveCase) { - for (const entry of this._headersMap.values()) { - result[entry.name] = entry.value; - } - } else { - for (const [normalizedName, entry] of this._headersMap) { - result[normalizedName] = entry.value; - } + async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url = new URL(locationHeader, request.url); + request.url = url.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; } - return result; - } - /** - * Get the string representation of this HTTP header collection. - */ - toString() { - return JSON.stringify(this.toJSON({ preserveCase: true })); - } - /** - * Iterate over tuples of header [name, value] pairs. - */ - [Symbol.iterator]() { - return headerIterator(this._headersMap); + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); } - }; - function createHttpHeaders(rawHeaders) { - return new HttpHeadersImpl(rawHeaders); + return response; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js -var require_formDataPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.formDataPolicyName = void 0; - exports2.formDataPolicy = formDataPolicy; - var core_util_1 = require_commonjs2(); - var httpHeaders_js_1 = require_httpHeaders(); - exports2.formDataPolicyName = "formDataPolicy"; - function formDataToFormDataMap(formData) { - var _a; - const formDataMap = {}; - for (const [key, value] of formData.entries()) { - (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = []; - formDataMap[key].push(value); - } - return formDataMap; - } - function formDataPolicy() { - return { - name: exports2.formDataPolicyName, - async sendRequest(request, next) { - if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { - request.formData = formDataToFormDataMap(request.body); - request.body = void 0; - } - if (request.formData) { - const contentType = request.headers.get("Content-Type"); - if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { - request.body = wwwFormUrlEncode(request.formData); - } else { - await prepareFormData(request.formData, request); - } - request.formData = void 0; - } - return next(request); - } - }; - } - function wwwFormUrlEncode(formData) { - const urlSearchParams = new URLSearchParams(); - for (const [key, value] of Object.entries(formData)) { - if (Array.isArray(value)) { - for (const subValue of value) { - urlSearchParams.append(key, subValue.toString()); - } - } else { - urlSearchParams.append(key, value.toString()); - } - } - return urlSearchParams.toString(); - } - async function prepareFormData(formData, request) { - const contentType = request.headers.get("Content-Type"); - if (contentType && !contentType.startsWith("multipart/form-data")) { - return; - } - request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); - const parts = []; - for (const [fieldName, values] of Object.entries(formData)) { - for (const value of Array.isArray(values) ? values : [values]) { - if (typeof value === "string") { - parts.push({ - headers: (0, httpHeaders_js_1.createHttpHeaders)({ - "Content-Disposition": `form-data; name="${fieldName}"` - }), - body: (0, core_util_1.stringToUint8Array)(value, "utf-8") - }); - } else if (value === void 0 || value === null || typeof value !== "object") { - throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); - } else { - const fileName = value.name || "blob"; - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); - headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); - headers.set("Content-Type", value.type || "application/octet-stream"); - parts.push({ - headers, - body: value - }); - } - } - } - request.multipartBody = { parts }; +// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __addDisposableResource: () => __addDisposableResource, + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __disposeResources: () => __disposeResources, + __esDecorate: () => __esDecorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __propKey: () => __propKey, + __read: () => __read, + __rest: () => __rest, + __runInitializers: () => __runInitializers, + __setFunctionName: () => __setFunctionName, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values2, + default: () => tslib_es6_default +}); +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; } + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; } -}); - -// node_modules/ms/index.js -var require_ms = __commonJS({ - "node_modules/ms/index.js"(exports2, module2) { - var s = 1e3; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - module2.exports = function(val2, options) { - options = options || {}; - var type2 = typeof val2; - if (type2 === "string" && val2.length > 0) { - return parse(val2); - } else if (type2 === "number" && isFinite(val2)) { - return options.long ? fmtLong(val2) : fmtShort(val2); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2) - ); + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context2 = {}; + for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; + context2.addInitializer = function(f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); }; - function parse(str2) { - str2 = String(str2); - if (str2.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str2 - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type2 = (match[2] || "ms").toLowerCase(); - switch (type2) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "weeks": - case "week": - case "w": - return n * w; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return void 0; - } + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; } - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; - } - if (msAbs >= m) { - return Math.round(ms / m) + "m"; - } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - return ms + "ms"; } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, "minute"); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return ms + " ms"; } - function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n) { + return function(v) { + return step([n, v]); + }; } -}); - -// node_modules/debug/src/common.js -var require_common = __commonJS({ - "node_modules/debug/src/common.js"(exports2, module2) { - function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce3; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require_ms(); - createDebug.destroy = destroy; - Object.keys(env).forEach((key) => { - createDebug[key] = env[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash = 0; - for (let i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; - } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug5(...args) { - if (!debug5.enabled) { - return; - } - const self2 = debug5; - const curr = Number(/* @__PURE__ */ new Date()); - const ms = curr - (prevTime || curr); - self2.diff = ms; - self2.prev = prevTime; - self2.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); - } - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - if (match === "%%") { - return "%"; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === "function") { - const val2 = args[index]; - match = formatter.call(self2, val2); - args.splice(index, 1); - index--; - } - return match; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); - } - debug5.namespace = namespace; - debug5.useColors = createDebug.useColors(); - debug5.color = createDebug.selectColor(namespace); - debug5.extend = extend3; - debug5.destroy = createDebug.destroy; - Object.defineProperty(debug5, "enabled", { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, - set: (v) => { - enableOverride = v; - } - }); - if (typeof createDebug.init === "function") { - createDebug.init(debug5); - } - return debug5; - } - function extend3(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns of split) { - if (ns[0] === "-") { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; } - } - } - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { - if (template[templateIndex] === "*") { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; } - } - while (templateIndex < template.length && template[templateIndex] === "*") { - templateIndex++; - } - return templateIndex === template.length; - } - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; - } - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; } - } - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; } - } - return false; + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; } - function coerce3(val2) { - if (val2 instanceof Error) { - return val2.stack || val2.message; - } - return val2; - } - function destroy() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - createDebug.enable(createDebug.load()); - return createDebug; + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; } - module2.exports = setup; + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; } -}); - -// node_modules/debug/src/browser.js -var require_browser = __commonJS({ - "node_modules/debug/src/browser.js"(exports2, module2) { - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load2; - exports2.useColors = useColors; - exports2.storage = localstorage(); - exports2.destroy = /* @__PURE__ */ (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } +} +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} +function __values2(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function() { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error4) { + e = { error: error4 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); }; - })(); - exports2.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - let m; - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 - typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker - typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + if (f) i[n] = f(i[n]); } - function formatArgs(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; - } - index++; - if (match === "%c") { - lastC = index; - } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function(e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function() { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function(v) { + return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; + } : f; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve4, reject) { + v = o[n](v), settle(resolve4, reject, v.done, v.value); }); - args.splice(lastC, 0, c); + }; + } + function settle(resolve4, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve4({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; } - exports2.log = console.debug || console.log || (() => { - }); - function save(namespaces) { - try { - if (namespaces) { - exports2.storage.setItem("debug", namespaces); - } else { - exports2.storage.removeItem("debug"); - } - } catch (error4) { - } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; } - function load2() { - let r; + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { - r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); - } catch (error4) { - } - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; + inner.call(this); + } catch (e) { + return Promise.reject(e); } - return r; - } - function localstorage() { + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { try { - return localStorage; - } catch (error4) { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); } } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error4) { - return "[UnexpectedJSONParseError]: " + error4.message; + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; +var init_tslib_es6 = __esm({ + "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() { + extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + __assign = function() { + __assign = Object.assign || function __assign4(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; }; - } -}); - -// node_modules/has-flag/index.js -var require_has_flag = __commonJS({ - "node_modules/has-flag/index.js"(exports2, module2) { - "use strict"; - module2.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf("--"); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; + }; + tslib_es6_default = { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values: __values2, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources }; } }); -// node_modules/supports-color/index.js -var require_supports_color = __commonJS({ - "node_modules/supports-color/index.js"(exports2, module2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js +var require_userAgentPlatform = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { "use strict"; - var os3 = require("os"); - var tty = require("tty"); - var hasFlag = require_has_flag(); - var { env } = process; - var forceColor; - if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { - forceColor = 0; - } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { - forceColor = 1; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getHeaderName = getHeaderName; + exports2.setPlatformSpecificData = setPlatformSpecificData; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var os3 = tslib_1.__importStar(require("node:os")); + var process2 = tslib_1.__importStar(require("node:process")); + function getHeaderName() { + return "User-Agent"; } - if ("FORCE_COLOR" in env) { - if (env.FORCE_COLOR === "true") { - forceColor = 1; - } else if (env.FORCE_COLOR === "false") { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + async function setPlatformSpecificData(map2) { + if (process2 && process2.versions) { + const versions = process2.versions; + if (versions.bun) { + map2.set("Bun", versions.bun); + } else if (versions.deno) { + map2.set("Deno", versions.deno); + } else if (versions.node) { + map2.set("Node", versions.node); + } } + map2.set("OS", `(${os3.arch()}-${os3.type()}-${os3.release()})`); } - function translateLevel(level) { - if (level === 0) { - return false; - } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; - } - function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } - if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { - return 3; - } - if (hasFlag("color=256")) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === void 0) { - return 0; - } - const min = forceColor || 0; - if (env.TERM === "dumb") { - return min; - } - if (process.platform === "win32") { - const osRelease = os3.release().split("."); - if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - return 1; - } - if ("CI" in env) { - if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { - return 1; - } - return min; - } - if ("TEAMCITY_VERSION" in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - if (env.COLORTERM === "truecolor") { - return 3; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js +var require_constants8 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; + exports2.SDK_VERSION = "1.17.0"; + exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js +var require_userAgent = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getUserAgentHeaderName = getUserAgentHeaderName; + exports2.getUserAgentValue = getUserAgentValue; + var userAgentPlatform_js_1 = require_userAgentPlatform(); + var constants_js_1 = require_constants8(); + function getUserAgentString(telemetryInfo) { + const parts = []; + for (const [key, value] of telemetryInfo) { + const token = value ? `${key}/${value}` : key; + parts.push(token); } - if ("TERM_PROGRAM" in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (env.TERM_PROGRAM) { - case "iTerm.app": - return version >= 3 ? 3 : 2; - case "Apple_Terminal": - return 2; + return parts.join(" "); + } + function getUserAgentHeaderName() { + return (0, userAgentPlatform_js_1.getHeaderName)(); + } + async function getUserAgentValue(prefix) { + const runtimeInfo = /* @__PURE__ */ new Map(); + runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); + await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); + const defaultAgent = getUserAgentString(runtimeInfo); + const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; + return userAgentValue; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js +var require_userAgentPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.userAgentPolicyName = void 0; + exports2.userAgentPolicy = userAgentPolicy; + var userAgent_js_1 = require_userAgent(); + var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); + exports2.userAgentPolicyName = "userAgentPolicy"; + function userAgentPolicy(options = {}) { + const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); + return { + name: exports2.userAgentPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(UserAgentHeaderName)) { + request.headers.set(UserAgentHeaderName, await userAgentValue); + } + return next(request); } - } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - if ("COLORTERM" in env) { - return 1; - } - return min; + }; } - function getSupportLevel(stream2) { - const level = supportsColor(stream2, stream2 && stream2.isTTY); - return translateLevel(level); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js +var require_typeGuards2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isNodeReadableStream = isNodeReadableStream; + exports2.isWebReadableStream = isWebReadableStream; + exports2.isReadableStream = isReadableStream; + exports2.isBlob = isBlob; + function isNodeReadableStream(x) { + return Boolean(x && typeof x["pipe"] === "function"); + } + function isWebReadableStream(x) { + return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); + } + function isReadableStream(x) { + return isNodeReadableStream(x) || isWebReadableStream(x); + } + function isBlob(x) { + return typeof x.stream === "function"; } - module2.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) - }; } }); -// node_modules/debug/src/node.js -var require_node = __commonJS({ - "node_modules/debug/src/node.js"(exports2, module2) { - var tty = require("tty"); - var util = require("util"); - exports2.init = init; - exports2.log = log; - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load2; - exports2.useColors = useColors; - exports2.destroy = util.deprecate( - () => { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js +var require_file2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRawContent = getRawContent; + exports2.createFileFromStream = createFileFromStream; + exports2.createFile = createFile; + var core_util_1 = require_commonjs2(); + var typeGuards_js_1 = require_typeGuards2(); + var unimplementedMethods = { + arrayBuffer: () => { + throw new Error("Not implemented"); }, - "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." - ); - exports2.colors = [6, 2, 3, 4, 5, 1]; - try { - const supportsColor = require_supports_color(); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports2.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; + slice: () => { + throw new Error("Not implemented"); + }, + text: () => { + throw new Error("Not implemented"); } - } catch (error4) { + }; + var rawContent = Symbol("rawContent"); + function hasRawContent(x) { + return typeof x[rawContent] === "function"; } - exports2.inspectOpts = Object.keys(process.env).filter((key) => { - return /^debug_/i.test(key); - }).reduce((obj, key) => { - const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - let val2 = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val2)) { - val2 = true; - } else if (/^(no|off|false|disabled)$/i.test(val2)) { - val2 = false; - } else if (val2 === "null") { - val2 = null; + function getRawContent(blob) { + if (hasRawContent(blob)) { + return blob[rawContent](); } else { - val2 = Number(val2); + return blob.stream(); } - obj[prop] = val2; - return obj; - }, {}); - function useColors() { - return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); } - function formatArgs(args) { - const { namespace: name, useColors: useColors2 } = this; - if (useColors2) { - const c = this.color; - const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); - const prefix = ` ${colorCode};1m${name} \x1B[0m`; - args[0] = prefix + args[0].split("\n").join("\n" + prefix); - args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + function createFileFromStream(stream2, name, options = {}) { + var _a, _b, _c, _d; + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { + const s = stream2(); + if ((0, typeGuards_js_1.isNodeReadableStream)(s)) { + throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); + } + return s; + }, [rawContent]: stream2 }); + } + function createFile(content, name, options = {}) { + var _a, _b, _c; + if (core_util_1.isNodeLike) { + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); } else { - args[0] = getDate() + name + " " + args[0]; + return new File([content], name, options); } } - function getDate() { - if (exports2.inspectOpts.hideDate) { - return ""; - } - return (/* @__PURE__ */ new Date()).toISOString() + " "; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js +var require_concat = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.concat = concat; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var node_stream_1 = require("node:stream"); + var typeGuards_js_1 = require_typeGuards2(); + var file_js_1 = require_file2(); + function streamAsyncIterator() { + return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { + const reader = this.getReader(); + try { + while (true) { + const { done, value } = yield tslib_1.__await(reader.read()); + if (done) { + return yield tslib_1.__await(void 0); + } + yield yield tslib_1.__await(value); + } + } finally { + reader.releaseLock(); + } + }); } - function log(...args) { - return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + function makeAsyncIterable(webStream) { + if (!webStream[Symbol.asyncIterator]) { + webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); + } + if (!webStream.values) { + webStream.values = streamAsyncIterator.bind(webStream); + } } - function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; + function ensureNodeStream(stream2) { + if (stream2 instanceof ReadableStream) { + makeAsyncIterable(stream2); + return node_stream_1.Readable.fromWeb(stream2); } else { - delete process.env.DEBUG; + return stream2; } } - function load2() { - return process.env.DEBUG; - } - function init(debug5) { - debug5.inspectOpts = {}; - const keys = Object.keys(exports2.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug5.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + function toStream(source) { + if (source instanceof Uint8Array) { + return node_stream_1.Readable.from(Buffer.from(source)); + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return toStream((0, file_js_1.getRawContent)(source)); + } else { + return ensureNodeStream(source); } } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" "); - }; - formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); - }; - } -}); - -// node_modules/debug/src/index.js -var require_src = __commonJS({ - "node_modules/debug/src/index.js"(exports2, module2) { - if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { - module2.exports = require_browser(); - } else { - module2.exports = require_node(); + async function concat(sources) { + return function() { + const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); + return node_stream_1.Readable.from((function() { + return tslib_1.__asyncGenerator(this, arguments, function* () { + var _a, e_1, _b, _c; + for (const stream2 of streams) { + try { + for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream2)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { + _c = stream_1_1.value; + _d = false; + const chunk = _c; + yield yield tslib_1.__await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1)); + } finally { + if (e_1) throw e_1.error; + } + } + } + }); + })()); + }; } } }); -// node_modules/agent-base/dist/helpers.js -var require_helpers2 = __commonJS({ - "node_modules/agent-base/dist/helpers.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js +var require_multipartPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.req = exports2.json = exports2.toBuffer = void 0; - var http = __importStar4(require("http")); - var https2 = __importStar4(require("https")); - async function toBuffer(stream2) { - let length = 0; - const chunks = []; - for await (const chunk of stream2) { - length += chunk.length; - chunks.push(chunk); + exports2.multipartPolicyName = void 0; + exports2.multipartPolicy = multipartPolicy; + var core_util_1 = require_commonjs2(); + var concat_js_1 = require_concat(); + var typeGuards_js_1 = require_typeGuards2(); + function generateBoundary() { + return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; + } + function encodeHeaders(headers) { + let result = ""; + for (const [key, value] of headers) { + result += `${key}: ${value}\r +`; } - return Buffer.concat(chunks, length); + return result; } - exports2.toBuffer = toBuffer; - async function json2(stream2) { - const buf = await toBuffer(stream2); - const str2 = buf.toString("utf8"); - try { - return JSON.parse(str2); - } catch (_err) { - const err = _err; - err.message += ` (input: ${str2})`; - throw err; + function getLength(source) { + if (source instanceof Uint8Array) { + return source.byteLength; + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return source.size === -1 ? void 0 : source.size; + } else { + return void 0; } } - exports2.json = json2; - function req(url, opts = {}) { - const href = typeof url === "string" ? url : url.href; - const req2 = (href.startsWith("https:") ? https2 : http).request(url, opts); - const promise = new Promise((resolve4, reject) => { - req2.once("response", resolve4).once("error", reject).end(); - }); - req2.then = promise.then.bind(promise); - return req2; + function getTotalLength(sources) { + let total = 0; + for (const source of sources) { + const partLength = getLength(source); + if (partLength === void 0) { + return void 0; + } else { + total += partLength; + } + } + return total; } - exports2.req = req; - } -}); - -// node_modules/agent-base/dist/index.js -var require_dist2 = __commonJS({ - "node_modules/agent-base/dist/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + async function buildRequestBody(request, parts, boundary) { + const sources = [ + (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"), + ...parts.flatMap((part) => [ + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + part.body, + (0, core_util_1.stringToUint8Array)(`\r +--${boundary}`, "utf-8") + ]), + (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8") + ]; + const contentLength = getTotalLength(sources); + if (contentLength) { + request.headers.set("Content-Length", contentLength); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + request.body = await (0, concat_js_1.concat)(sources); + } + exports2.multipartPolicyName = "multipartPolicy"; + var maxBoundaryLength = 70; + var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); + function assertValidBoundary(boundary) { + if (boundary.length > maxBoundaryLength) { + throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); } - __setModuleDefault4(result, mod); - return result; - }; - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Agent = void 0; - var net = __importStar4(require("net")); - var http = __importStar4(require("http")); - var https_1 = require("https"); - __exportStar4(require_helpers2(), exports2); - var INTERNAL = Symbol("AgentBaseInternalState"); - var Agent = class extends http.Agent { - constructor(opts) { - super(opts); - this[INTERNAL] = {}; + if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { + throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); } - /** - * Determine whether this is an `http` or `https` request. - */ - isSecureEndpoint(options) { - if (options) { - if (typeof options.secureEndpoint === "boolean") { - return options.secureEndpoint; + } + function multipartPolicy() { + return { + name: exports2.multipartPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.multipartBody) { + return next(request); } - if (typeof options.protocol === "string") { - return options.protocol === "https:"; + if (request.body) { + throw new Error("multipartBody and regular body cannot be set at the same time"); } - } - const { stack } = new Error(); - if (typeof stack !== "string") - return false; - return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); - } - // In order to support async signatures in `connect()` and Node's native - // connection pooling in `http.Agent`, the array of sockets for each origin - // has to be updated synchronously. This is so the length of the array is - // accurate when `addRequest()` is next called. We achieve this by creating a - // fake socket and adding it to `sockets[origin]` and incrementing - // `totalSocketCount`. - incrementSockets(name) { - if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { - return null; - } - if (!this.sockets[name]) { - this.sockets[name] = []; - } - const fakeSocket = new net.Socket({ writable: false }); - this.sockets[name].push(fakeSocket); - this.totalSocketCount++; - return fakeSocket; - } - decrementSockets(name, socket) { - if (!this.sockets[name] || socket === null) { - return; - } - const sockets = this.sockets[name]; - const index = sockets.indexOf(socket); - if (index !== -1) { - sockets.splice(index, 1); - this.totalSocketCount--; - if (sockets.length === 0) { - delete this.sockets[name]; + let boundary = request.multipartBody.boundary; + const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; + const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); + if (!parsedHeader) { + throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); } - } - } - // In order to properly update the socket pool, we need to call `getName()` on - // the core `https.Agent` if it is a secureEndpoint. - getName(options) { - const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options); - if (secureEndpoint) { - return https_1.Agent.prototype.getName.call(this, options); - } - return super.getName(options); - } - createSocket(req, options, cb) { - const connectOpts = { - ...options, - secureEndpoint: this.isSecureEndpoint(options) - }; - const name = this.getName(connectOpts); - const fakeSocket = this.incrementSockets(name); - Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { - this.decrementSockets(name, fakeSocket); - if (socket instanceof http.Agent) { - try { - return socket.addRequest(req, connectOpts); - } catch (err) { - return cb(err); - } + const [, contentType, parsedBoundary] = parsedHeader; + if (parsedBoundary && boundary && parsedBoundary !== boundary) { + throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); } - this[INTERNAL].currentSocket = socket; - super.createSocket(req, options, cb); - }, (err) => { - this.decrementSockets(name, fakeSocket); - cb(err); - }); - } - createConnection() { - const socket = this[INTERNAL].currentSocket; - this[INTERNAL].currentSocket = void 0; - if (!socket) { - throw new Error("No socket was returned in the `connect()` function"); - } - return socket; - } - get defaultPort() { - return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); - } - set defaultPort(v) { - if (this[INTERNAL]) { - this[INTERNAL].defaultPort = v; + boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary; + if (boundary) { + assertValidBoundary(boundary); + } else { + boundary = generateBoundary(); + } + request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); + await buildRequestBody(request, request.multipartBody.parts, boundary); + request.multipartBody = void 0; + return next(request); } - } - get protocol() { - return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); - } - set protocol(v) { - if (this[INTERNAL]) { - this[INTERNAL].protocol = v; + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js +var require_decompressResponsePolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.decompressResponsePolicyName = void 0; + exports2.decompressResponsePolicy = decompressResponsePolicy; + exports2.decompressResponsePolicyName = "decompressResponsePolicy"; + function decompressResponsePolicy() { + return { + name: exports2.decompressResponsePolicyName, + async sendRequest(request, next) { + if (request.method !== "HEAD") { + request.headers.set("Accept-Encoding", "gzip,deflate"); + } + return next(request); } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } }; - exports2.Agent = Agent; + exports2.AbortError = AbortError; } }); -// node_modules/https-proxy-agent/dist/parse-proxy-response.js -var require_parse_proxy_response = __commonJS({ - "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs3 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { "use strict"; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.parseProxyResponse = void 0; - var debug_1 = __importDefault4(require_src()); - var debug5 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); - function parseProxyResponse(socket) { + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError2(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js +var require_helpers = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay2; + exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; + var abort_controller_1 = require_commonjs3(); + var StandardAbortMessage = "The operation was aborted."; + function delay2(delayInMs, value, options) { return new Promise((resolve4, reject) => { - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once("readable", read); - } - function cleanup() { - socket.removeListener("end", onend); - socket.removeListener("error", onerror); - socket.removeListener("readable", read); - } - function onend() { - cleanup(); - debug5("onend"); - reject(new Error("Proxy connection ended before receiving CONNECT response")); - } - function onerror(err) { - cleanup(); - debug5("onerror %o", err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf("\r\n\r\n"); - if (endOfHeaders === -1) { - debug5("have not received end of HTTP headers yet..."); - read(); - return; - } - const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); - const firstLine = headerParts.shift(); - if (!firstLine) { - socket.destroy(); - return reject(new Error("No header received from proxy CONNECT response")); + let timer = void 0; + let onAborted = void 0; + const rejectOnAbort = () => { + return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); } - const firstLineParts = firstLine.split(" "); - const statusCode = +firstLineParts[1]; - const statusText = firstLineParts.slice(2).join(" "); - const headers = {}; - for (const header of headerParts) { - if (!header) - continue; - const firstColon = header.indexOf(":"); - if (firstColon === -1) { - socket.destroy(); - return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); - } - const key = header.slice(0, firstColon).toLowerCase(); - const value = header.slice(firstColon + 1).trimStart(); - const current = headers[key]; - if (typeof current === "string") { - headers[key] = [current, value]; - } else if (Array.isArray(current)) { - current.push(value); - } else { - headers[key] = value; - } + }; + onAborted = () => { + if (timer) { + clearTimeout(timer); } - debug5("got proxy server response: %o %o", firstLine, headers); - cleanup(); - resolve4({ - connect: { - statusCode, - statusText, - headers - }, - buffered - }); + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve4(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); } - socket.on("error", onerror); - socket.on("end", onend); - read(); }); } - exports2.parseProxyResponse = parseProxyResponse; + function parseHeaderValueAsNumber(response, headerName) { + const value = response.headers.get(headerName); + if (!value) + return; + const valueAsNum = Number(value); + if (Number.isNaN(valueAsNum)) + return; + return valueAsNum; + } } }); -// node_modules/https-proxy-agent/dist/index.js -var require_dist3 = __commonJS({ - "node_modules/https-proxy-agent/dist/index.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js +var require_throttlingRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpsProxyAgent = void 0; - var net = __importStar4(require("net")); - var tls = __importStar4(require("tls")); - var assert_1 = __importDefault4(require("assert")); - var debug_1 = __importDefault4(require_src()); - var agent_base_1 = require_dist2(); - var url_1 = require("url"); - var parse_proxy_response_1 = require_parse_proxy_response(); - var debug5 = (0, debug_1.default)("https-proxy-agent"); - var setServernameFromNonIpHost = (options) => { - if (options.servername === void 0 && options.host && !net.isIP(options.host)) { - return { - ...options, - servername: options.host - }; - } - return options; - }; - var HttpsProxyAgent = class extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.options = { path: void 0 }; - this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug5("Creating new HttpsProxyAgent instance: %o", this.proxy.href); - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); - const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; - this.connectOpts = { - // Attempt to negotiate http/1.1 for proxy servers that support http/2 - ALPNProtocols: ["http/1.1"], - ...opts ? omit(opts, "headers") : null, - host, - port - }; + exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; + exports2.throttlingRetryStrategy = throttlingRetryStrategy; + var helpers_js_1 = require_helpers(); + var RetryAfterHeader = "Retry-After"; + var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; + function getRetryAfterInMs(response) { + if (!(response && [429, 503].includes(response.status))) + return void 0; + try { + for (const header of AllRetryAfterHeaders) { + const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); + if (retryAfterValue === 0 || retryAfterValue) { + const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; + return retryAfterValue * multiplyingFactor; + } + } + const retryAfterHeader = response.headers.get(RetryAfterHeader); + if (!retryAfterHeader) + return; + const date = Date.parse(retryAfterHeader); + const diff = date - Date.now(); + return Number.isFinite(diff) ? Math.max(0, diff) : void 0; + } catch (_a) { + return void 0; } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - */ - async connect(req, opts) { - const { proxy } = this; - if (!opts.host) { - throw new TypeError('No "host" provided'); + } + function isThrottlingRetryResponse(response) { + return Number.isFinite(getRetryAfterInMs(response)); + } + function throttlingRetryStrategy() { + return { + name: "throttlingRetryStrategy", + retry({ response }) { + const retryAfterInMs = getRetryAfterInMs(response); + if (!Number.isFinite(retryAfterInMs)) { + return { skipStrategy: true }; + } + return { + retryAfterInMs + }; } - let socket; - if (proxy.protocol === "https:") { - debug5("Creating `tls.Socket`: %o", this.connectOpts); - socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); - } else { - debug5("Creating `net.Socket`: %o", this.connectOpts); - socket = net.connect(this.connectOpts); - } - const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; - const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; - let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r -`; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; - } - headers.Host = `${host}:${opts.port}`; - if (!headers["Proxy-Connection"]) { - headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; - } - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r -`; - } - const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); - socket.write(`${payload}\r -`); - const { connect, buffered } = await proxyResponsePromise; - req.emit("proxyConnect", connect); - this.emit("proxyConnect", connect, req); - if (connect.statusCode === 200) { - req.once("socket", resume); - if (opts.secureEndpoint) { - debug5("Upgrading socket connection to TLS"); - return tls.connect({ - ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), - socket - }); - } - return socket; - } - socket.destroy(); - const fakeSocket = new net.Socket({ writable: false }); - fakeSocket.readable = true; - req.once("socket", (s) => { - debug5("Replaying proxy buffer for failed request"); - (0, assert_1.default)(s.listenerCount("data") > 0); - s.push(buffered); - s.push(null); - }); - return fakeSocket; - } - }; - HttpsProxyAgent.protocols = ["http", "https"]; - exports2.HttpsProxyAgent = HttpsProxyAgent; - function resume(socket) { - socket.resume(); - } - function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - } -}); - -// node_modules/http-proxy-agent/dist/index.js -var require_dist4 = __commonJS({ - "node_modules/http-proxy-agent/dist/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpProxyAgent = void 0; - var net = __importStar4(require("net")); - var tls = __importStar4(require("tls")); - var debug_1 = __importDefault4(require_src()); - var events_1 = require("events"); - var agent_base_1 = require_dist2(); - var url_1 = require("url"); - var debug5 = (0, debug_1.default)("http-proxy-agent"); - var HttpProxyAgent = class extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug5("Creating new HttpProxyAgent instance: %o", this.proxy.href); - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); - const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; - this.connectOpts = { - ...opts ? omit(opts, "headers") : null, - host, - port - }; - } - addRequest(req, opts) { - req._header = null; - this.setRequestProps(req, opts); - super.addRequest(req, opts); - } - setRequestProps(req, opts) { - const { proxy } = this; - const protocol = opts.secureEndpoint ? "https:" : "http:"; - const hostname = req.getHeader("host") || "localhost"; - const base = `${protocol}//${hostname}`; - const url = new url_1.URL(req.path, base); - if (opts.port !== 80) { - url.port = String(opts.port); - } - req.path = String(url); - const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; - } - if (!headers["Proxy-Connection"]) { - headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; - } - for (const name of Object.keys(headers)) { - const value = headers[name]; - if (value) { - req.setHeader(name, value); - } - } - } - async connect(req, opts) { - req._header = null; - if (!req.path.includes("://")) { - this.setRequestProps(req, opts); - } - let first; - let endOfHeaders; - debug5("Regenerating stored HTTP header string for request"); - req._implicitHeader(); - if (req.outputData && req.outputData.length > 0) { - debug5("Patching connection write() output buffer with updated header"); - first = req.outputData[0].data; - endOfHeaders = first.indexOf("\r\n\r\n") + 4; - req.outputData[0].data = req._header + first.substring(endOfHeaders); - debug5("Output buffer: %o", req.outputData[0].data); - } - let socket; - if (this.proxy.protocol === "https:") { - debug5("Creating `tls.Socket`: %o", this.connectOpts); - socket = tls.connect(this.connectOpts); - } else { - debug5("Creating `net.Socket`: %o", this.connectOpts); - socket = net.connect(this.connectOpts); - } - await (0, events_1.once)(socket, "connect"); - return socket; - } - }; - HttpProxyAgent.protocols = ["http", "https"]; - exports2.HttpProxyAgent = HttpProxyAgent; - function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; + }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js -var require_proxyPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js +var require_exponentialRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; - exports2.loadNoProxy = loadNoProxy; - exports2.getDefaultProxySettings = getDefaultProxySettings; - exports2.proxyPolicy = proxyPolicy; - var https_proxy_agent_1 = require_dist3(); - var http_proxy_agent_1 = require_dist4(); - var log_js_1 = require_log(); - var HTTPS_PROXY = "HTTPS_PROXY"; - var HTTP_PROXY = "HTTP_PROXY"; - var ALL_PROXY = "ALL_PROXY"; - var NO_PROXY = "NO_PROXY"; - exports2.proxyPolicyName = "proxyPolicy"; - exports2.globalNoProxyList = []; - var noProxyListLoaded = false; - var globalBypassedMap = /* @__PURE__ */ new Map(); - function getEnvironmentValue(name) { - if (process.env[name]) { - return process.env[name]; - } else if (process.env[name.toLowerCase()]) { - return process.env[name.toLowerCase()]; - } - return void 0; - } - function loadEnvironmentProxyValue() { - if (!process) { - return void 0; - } - const httpsProxy = getEnvironmentValue(HTTPS_PROXY); - const allProxy = getEnvironmentValue(ALL_PROXY); - const httpProxy = getEnvironmentValue(HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; - } - function isBypassed(uri, noProxyList, bypassedMap) { - if (noProxyList.length === 0) { - return false; - } - const host = new URL(uri).hostname; - if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { - return bypassedMap.get(host); - } - let isBypassedFlag = false; - for (const pattern of noProxyList) { - if (pattern[0] === ".") { - if (host.endsWith(pattern)) { - isBypassedFlag = true; - } else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } + exports2.exponentialRetryStrategy = exponentialRetryStrategy; + exports2.isExponentialRetryResponse = isExponentialRetryResponse; + exports2.isSystemError = isSystemError; + var core_util_1 = require_commonjs2(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; + var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; + function exponentialRetryStrategy(options = {}) { + var _a, _b; + const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; + const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + let retryAfterInMs = retryInterval; + return { + name: "exponentialRetryStrategy", + retry({ retryCount, response, responseError }) { + const matchedSystemError = isSystemError(responseError); + const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; + const isExponential = isExponentialRetryResponse(response); + const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; + const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); + if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { + return { skipStrategy: true }; } - } else { - if (host === pattern) { - isBypassedFlag = true; + if (responseError && !matchedSystemError && !isExponential) { + return { errorToThrow: responseError }; } + const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); + const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); + retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2); + return { retryAfterInMs }; } - } - bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); - return isBypassedFlag; - } - function loadNoProxy() { - const noProxy = getEnvironmentValue(NO_PROXY); - noProxyListLoaded = true; - if (noProxy) { - return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); - } - return []; - } - function getDefaultProxySettings(proxyUrl) { - if (!proxyUrl) { - proxyUrl = loadEnvironmentProxyValue(); - if (!proxyUrl) { - return void 0; - } - } - const parsedUrl = new URL(proxyUrl); - const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; - return { - host: schema2 + parsedUrl.hostname, - port: Number.parseInt(parsedUrl.port || "80"), - username: parsedUrl.username, - password: parsedUrl.password }; } - function getDefaultProxySettingsInternal() { - const envProxy = loadEnvironmentProxyValue(); - return envProxy ? new URL(envProxy) : void 0; - } - function getUrlFromProxySettings(settings) { - let parsedProxyUrl; - try { - parsedProxyUrl = new URL(settings.host); - } catch (_a) { - throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); - } - parsedProxyUrl.port = String(settings.port); - if (settings.username) { - parsedProxyUrl.username = settings.username; - } - if (settings.password) { - parsedProxyUrl.password = settings.password; - } - return parsedProxyUrl; - } - function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { - if (request.agent) { - return; - } - const url = new URL(request.url); - const isInsecure = url.protocol !== "https:"; - if (request.tlsSettings) { - log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); - } - const headers = request.headers.toJSON(); - if (isInsecure) { - if (!cachedAgents.httpProxyAgent) { - cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpProxyAgent; - } else { - if (!cachedAgents.httpsProxyAgent) { - cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpsProxyAgent; - } + function isExponentialRetryResponse(response) { + return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); } - function proxyPolicy(proxySettings, options) { - if (!noProxyListLoaded) { - exports2.globalNoProxyList.push(...loadNoProxy()); + function isSystemError(err) { + if (!err) { + return false; } - const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); - const cachedAgents = {}; - return { - name: exports2.proxyPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) { - setProxyAgentOnRequest(request, cachedAgents, defaultProxy); - } else if (request.proxySettings) { - setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); - } - return next(request); - } - }; + return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js -var require_setClientRequestIdPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js +var require_retryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.setClientRequestIdPolicyName = void 0; - exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; - exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; - function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + exports2.retryPolicy = retryPolicy; + var helpers_js_1 = require_helpers(); + var logger_1 = require_dist(); + var abort_controller_1 = require_commonjs3(); + var constants_js_1 = require_constants8(); + var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); + var retryPolicyName = "retryPolicy"; + function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { + const logger = options.logger || retryPolicyLogger; return { - name: exports2.setClientRequestIdPolicyName, + name: retryPolicyName, async sendRequest(request, next) { - if (!request.headers.has(requestIdHeaderName)) { - request.headers.set(requestIdHeaderName, request.requestId); + var _a, _b; + let response; + let responseError; + let retryCount = -1; + retryRequest: while (true) { + retryCount += 1; + response = void 0; + responseError = void 0; + try { + logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); + response = await next(request); + logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); + } catch (e) { + logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); + responseError = e; + if (!e || responseError.name !== "RestError") { + throw e; + } + response = responseError.response; + } + if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + logger.error(`Retry ${retryCount}: Request aborted.`); + const abortError = new abort_controller_1.AbortError(); + throw abortError; + } + if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { + logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + if (responseError) { + throw responseError; + } else if (response) { + return response; + } else { + throw new Error("Maximum retries reached with no response or error to throw"); + } + } + logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + strategiesLoop: for (const strategy of strategies) { + const strategyLogger = strategy.logger || retryPolicyLogger; + strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); + const modifiers = strategy.retry({ + retryCount, + response, + responseError + }); + if (modifiers.skipStrategy) { + strategyLogger.info(`Retry ${retryCount}: Skipped.`); + continue strategiesLoop; + } + const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; + if (errorToThrow) { + strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); + throw errorToThrow; + } + if (retryAfterInMs || retryAfterInMs === 0) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); + await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); + continue retryRequest; + } + if (redirectTo) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); + request.url = redirectTo; + continue retryRequest; + } + } + if (responseError) { + logger.info(`None of the retry strategies could work with the received error. Throwing it.`); + throw responseError; + } + if (response) { + logger.info(`None of the retry strategies could work with the received response. Returning it.`); + return response; + } } - return next(request); } }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js -var require_tlsPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js +var require_defaultRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tlsPolicyName = void 0; - exports2.tlsPolicy = tlsPolicy; - exports2.tlsPolicyName = "tlsPolicy"; - function tlsPolicy(tlsSettings) { + exports2.defaultRetryPolicyName = void 0; + exports2.defaultRetryPolicy = defaultRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.defaultRetryPolicyName = "defaultRetryPolicy"; + function defaultRetryPolicy(options = {}) { + var _a; return { - name: exports2.tlsPolicyName, - sendRequest: async (req, next) => { - if (!req.tlsSettings) { - req.tlsSettings = tlsSettings; - } - return next(req); - } + name: exports2.defaultRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest }; } } }); -// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js -var require_tracingContext = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js +var require_httpHeaders = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0; - exports2.knownContextKeys = { - span: Symbol.for("@azure/core-tracing span"), - namespace: Symbol.for("@azure/core-tracing namespace") - }; - function createTracingContext(options = {}) { - let context2 = new TracingContextImpl(options.parentContext); - if (options.span) { - context2 = context2.setValue(exports2.knownContextKeys.span, options.span); - } - if (options.namespace) { - context2 = context2.setValue(exports2.knownContextKeys.namespace, options.namespace); - } - return context2; + exports2.createHttpHeaders = createHttpHeaders; + function normalizeName(name) { + return name.toLowerCase(); } - exports2.createTracingContext = createTracingContext; - var TracingContextImpl = class _TracingContextImpl { - constructor(initialContext) { - this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); - } - setValue(key, value) { - const newContext = new _TracingContextImpl(this); - newContext._contextMap.set(key, value); - return newContext; - } - getValue(key) { - return this._contextMap.get(key); - } - deleteValue(key) { - const newContext = new _TracingContextImpl(this); - newContext._contextMap.delete(key); - return newContext; + function* headerIterator(map2) { + for (const entry of map2.values()) { + yield [entry.name, entry.value]; } - }; - exports2.TracingContextImpl = TracingContextImpl; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/state.js -var require_state = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.state = void 0; - exports2.state = { - instrumenterImplementation: void 0 - }; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js -var require_instrumenter = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0; - var tracingContext_js_1 = require_tracingContext(); - var state_js_1 = require_state(); - function createDefaultTracingSpan() { - return { - end: () => { - }, - isRecording: () => false, - recordException: () => { - }, - setAttribute: () => { - }, - setStatus: () => { - } - }; } - exports2.createDefaultTracingSpan = createDefaultTracingSpan; - function createDefaultInstrumenter() { - return { - createRequestHeaders: () => { - return {}; - }, - parseTraceparentHeader: () => { - return void 0; - }, - startSpan: (_name, spanOptions) => { - return { - span: createDefaultTracingSpan(), - tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }) - }; - }, - withContext(_context, callback, ...callbackArgs) { - return callback(...callbackArgs); + var HttpHeadersImpl = class { + constructor(rawHeaders) { + this._headersMap = /* @__PURE__ */ new Map(); + if (rawHeaders) { + for (const headerName of Object.keys(rawHeaders)) { + this.set(headerName, rawHeaders[headerName]); + } } - }; - } - exports2.createDefaultInstrumenter = createDefaultInstrumenter; - function useInstrumenter(instrumenter) { - state_js_1.state.instrumenterImplementation = instrumenter; - } - exports2.useInstrumenter = useInstrumenter; - function getInstrumenter() { - if (!state_js_1.state.instrumenterImplementation) { - state_js_1.state.instrumenterImplementation = createDefaultInstrumenter(); } - return state_js_1.state.instrumenterImplementation; - } - exports2.getInstrumenter = getInstrumenter; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js -var require_tracingClient = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTracingClient = void 0; - var instrumenter_js_1 = require_instrumenter(); - var tracingContext_js_1 = require_tracingContext(); - function createTracingClient(options) { - const { namespace, packageName, packageVersion } = options; - function startSpan(name, operationOptions, spanOptions) { - var _a; - const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); - let tracingContext = startSpanResult.tracingContext; - const span = startSpanResult.span; - if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { - tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace); - } - span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); - const updatedOptions = Object.assign({}, operationOptions, { - tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }) - }); - return { - span, - updatedOptions - }; + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param name - The name of the header to set. This value is case-insensitive. + * @param value - The value of the header to set. + */ + set(name, value) { + this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); } - async function withSpan(name, operationOptions, callback, spanOptions) { - const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); - try { - const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); - span.setStatus({ status: "success" }); - return result; - } catch (err) { - span.setStatus({ status: "error", error: err }); - throw err; - } finally { - span.end(); - } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param name - The name of the header. This value is case-insensitive. + */ + get(name) { + var _a; + return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; } - function withContext(context2, callback, ...callbackArgs) { - return (0, instrumenter_js_1.getInstrumenter)().withContext(context2, callback, ...callbackArgs); + /** + * Get whether or not this header collection contains a header entry for the provided header name. + * @param name - The name of the header to set. This value is case-insensitive. + */ + has(name) { + return this._headersMap.has(normalizeName(name)); } - function parseTraceparentHeader(traceparentHeader) { - return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader); + /** + * Remove the header with the provided headerName. + * @param name - The name of the header to remove. + */ + delete(name) { + this._headersMap.delete(normalizeName(name)); } - function createRequestHeaders(tracingContext) { - return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext); + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJSON(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const entry of this._headersMap.values()) { + result[entry.name] = entry.value; + } + } else { + for (const [normalizedName, entry] of this._headersMap) { + result[normalizedName] = entry.value; + } + } + return result; } - return { - startSpan, - withSpan, - withContext, - parseTraceparentHeader, - createRequestHeaders - }; - } - exports2.createTracingClient = createTracingClient; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/index.js -var require_commonjs4 = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTracingClient = exports2.useInstrumenter = void 0; - var instrumenter_js_1 = require_instrumenter(); - Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() { - return instrumenter_js_1.useInstrumenter; - } }); - var tracingClient_js_1 = require_tracingClient(); - Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() { - return tracingClient_js_1.createTracingClient; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js -var require_inspect = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.custom = void 0; - var node_util_1 = require("node:util"); - exports2.custom = node_util_1.inspect.custom; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js -var require_restError = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RestError = void 0; - exports2.isRestError = isRestError; - var core_util_1 = require_commonjs2(); - var inspect_js_1 = require_inspect(); - var sanitizer_js_1 = require_sanitizer(); - var errorSanitizer = new sanitizer_js_1.Sanitizer(); - var RestError = class _RestError extends Error { - constructor(message, options = {}) { - super(message); - this.name = "RestError"; - this.code = options.code; - this.statusCode = options.statusCode; - Object.defineProperty(this, "request", { value: options.request, enumerable: false }); - Object.defineProperty(this, "response", { value: options.response, enumerable: false }); - Object.setPrototypeOf(this, _RestError.prototype); + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJSON({ preserveCase: true })); } /** - * Logging method for util.inspect in Node + * Iterate over tuples of header [name, value] pairs. */ - [inspect_js_1.custom]() { - return `RestError: ${this.message} - ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; + [Symbol.iterator]() { + return headerIterator(this._headersMap); } }; - exports2.RestError = RestError; - RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; - RestError.PARSE_ERROR = "PARSE_ERROR"; - function isRestError(e) { - if (e instanceof RestError) { - return true; - } - return (0, core_util_1.isError)(e) && e.name === "RestError"; + function createHttpHeaders(rawHeaders) { + return new HttpHeadersImpl(rawHeaders); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js -var require_tracingPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js +var require_formDataPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tracingPolicyName = void 0; - exports2.tracingPolicy = tracingPolicy; - var core_tracing_1 = require_commonjs4(); - var constants_js_1 = require_constants8(); - var userAgent_js_1 = require_userAgent(); - var log_js_1 = require_log(); + exports2.formDataPolicyName = void 0; + exports2.formDataPolicy = formDataPolicy; var core_util_1 = require_commonjs2(); - var restError_js_1 = require_restError(); - var sanitizer_js_1 = require_sanitizer(); - exports2.tracingPolicyName = "tracingPolicy"; - function tracingPolicy(options = {}) { - const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - const tracingClient = tryCreateTracingClient(); + var httpHeaders_js_1 = require_httpHeaders(); + exports2.formDataPolicyName = "formDataPolicy"; + function formDataToFormDataMap(formData) { + var _a; + const formDataMap = {}; + for (const [key, value] of formData.entries()) { + (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = []; + formDataMap[key].push(value); + } + return formDataMap; + } + function formDataPolicy() { return { - name: exports2.tracingPolicyName, + name: exports2.formDataPolicyName, async sendRequest(request, next) { - var _a; - if (!tracingClient) { - return next(request); - } - const userAgent = await userAgentPromise; - const spanAttributes = { - "http.url": sanitizer.sanitizeUrl(request.url), - "http.method": request.method, - "http.user_agent": userAgent, - requestId: request.requestId - }; - if (userAgent) { - spanAttributes["http.user_agent"] = userAgent; - } - const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; - if (!span || !tracingContext) { - return next(request); + if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { + request.formData = formDataToFormDataMap(request.body); + request.body = void 0; } - try { - const response = await tracingClient.withContext(tracingContext, next, request); - tryProcessResponse(span, response); - return response; - } catch (err) { - tryProcessError(span, err); - throw err; + if (request.formData) { + const contentType = request.headers.get("Content-Type"); + if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { + request.body = wwwFormUrlEncode(request.formData); + } else { + await prepareFormData(request.formData, request); + } + request.formData = void 0; } + return next(request); } }; } - function tryCreateTracingClient() { - try { - return (0, core_tracing_1.createTracingClient)({ - namespace: "", - packageName: "@azure/core-rest-pipeline", - packageVersion: constants_js_1.SDK_VERSION - }); - } catch (e) { - log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); - return void 0; - } - } - function tryCreateSpan(tracingClient, request, spanAttributes) { - try { - const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { - spanKind: "client", - spanAttributes - }); - if (!span.isRecording()) { - span.end(); - return void 0; - } - const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); - for (const [key, value] of Object.entries(headers)) { - request.headers.set(key, value); + function wwwFormUrlEncode(formData) { + const urlSearchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(formData)) { + if (Array.isArray(value)) { + for (const subValue of value) { + urlSearchParams.append(key, subValue.toString()); + } + } else { + urlSearchParams.append(key, value.toString()); } - return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; - } catch (e) { - log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); - return void 0; } + return urlSearchParams.toString(); } - function tryProcessError(span, error4) { - try { - span.setStatus({ - status: "error", - error: (0, core_util_1.isError)(error4) ? error4 : void 0 - }); - if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) { - span.setAttribute("http.status_code", error4.statusCode); - } - span.end(); - } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + async function prepareFormData(formData, request) { + const contentType = request.headers.get("Content-Type"); + if (contentType && !contentType.startsWith("multipart/form-data")) { + return; } - } - function tryProcessResponse(span, response) { - try { - span.setAttribute("http.status_code", response.status); - const serviceRequestId = response.headers.get("x-ms-request-id"); - if (serviceRequestId) { - span.setAttribute("serviceRequestId", serviceRequestId); + request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); + const parts = []; + for (const [fieldName, values] of Object.entries(formData)) { + for (const value of Array.isArray(values) ? values : [values]) { + if (typeof value === "string") { + parts.push({ + headers: (0, httpHeaders_js_1.createHttpHeaders)({ + "Content-Disposition": `form-data; name="${fieldName}"` + }), + body: (0, core_util_1.stringToUint8Array)(value, "utf-8") + }); + } else if (value === void 0 || value === null || typeof value !== "object") { + throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); + } else { + const fileName = value.name || "blob"; + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); + headers.set("Content-Type", value.type || "application/octet-stream"); + parts.push({ + headers, + body: value + }); + } } - span.setStatus({ - status: "success" - }); - span.end(); - } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); } + request.multipartBody = { parts }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js -var require_createPipelineFromOptions = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineFromOptions = createPipelineFromOptions; - var logPolicy_js_1 = require_logPolicy(); - var pipeline_js_1 = require_pipeline(); - var redirectPolicy_js_1 = require_redirectPolicy(); - var userAgentPolicy_js_1 = require_userAgentPolicy(); - var multipartPolicy_js_1 = require_multipartPolicy(); - var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); - var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); - var formDataPolicy_js_1 = require_formDataPolicy(); - var core_util_1 = require_commonjs2(); - var proxyPolicy_js_1 = require_proxyPolicy(); - var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); - var tlsPolicy_js_1 = require_tlsPolicy(); - var tracingPolicy_js_1 = require_tracingPolicy(); - function createPipelineFromOptions(options) { - var _a; - const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); - if (core_util_1.isNodeLike) { - if (options.tlsOptions) { - pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); - } - pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); - pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); +// node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/ms/index.js"(exports2, module2) { + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module2.exports = function(val2, options) { + options = options || {}; + var type2 = typeof val2; + if (type2 === "string" && val2.length > 0) { + return parse(val2); + } else if (type2 === "number" && isFinite(val2)) { + return options.long ? fmtLong(val2) : fmtShort(val2); } - pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); - pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); - pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); - pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); - pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); - pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { - afterPhase: "Retry" - }); - if (core_util_1.isNodeLike) { - pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2) + ); + }; + function parse(str2) { + str2 = String(str2); + if (str2.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str2 + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type2 = (match[2] || "ms").toLowerCase(); + switch (type2) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; } - pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); - return pipeline; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js -var require_nodeHttpClient = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getBodyLength = getBodyLength; - exports2.createNodeHttpClient = createNodeHttpClient; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var http = tslib_1.__importStar(require("node:http")); - var https2 = tslib_1.__importStar(require("node:https")); - var zlib = tslib_1.__importStar(require("node:zlib")); - var node_stream_1 = require("node:stream"); - var abort_controller_1 = require_commonjs3(); - var httpHeaders_js_1 = require_httpHeaders(); - var restError_js_1 = require_restError(); - var log_js_1 = require_log(); - var DEFAULT_TLS_SETTINGS = {}; - function isReadableStream(body) { - return body && typeof body.pipe === "function"; - } - function isStreamComplete(stream2) { - return new Promise((resolve4) => { - const handler = () => { - resolve4(); - stream2.removeListener("close", handler); - stream2.removeListener("end", handler); - stream2.removeListener("error", handler); - }; - stream2.on("close", handler); - stream2.on("end", handler); - stream2.on("error", handler); - }); } - function isArrayBuffer(body) { - return body && typeof body.byteLength === "number"; + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; } - var ReportTransform = class extends node_stream_1.Transform { - // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type - _transform(chunk, _encoding, callback) { - this.push(chunk); - this.loadedBytes += chunk.length; - try { - this.progressCallback({ loadedBytes: this.loadedBytes }); - callback(); - } catch (e) { - callback(e); - } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); } - constructor(progressCallback) { - super(); - this.loadedBytes = 0; - this.progressCallback = progressCallback; + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); } - }; - var NodeHttpClient = class { - constructor() { - this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); } - /** - * Makes a request over an underlying transport layer and returns the response. - * @param request - The request to be made. - */ - async sendRequest(request) { - var _a, _b, _c; - const abortController = new AbortController(); - let abortListener; - if (request.abortSignal) { - if (request.abortSignal.aborted) { - throw new abort_controller_1.AbortError("The operation was aborted."); - } - abortListener = (event) => { - if (event.type === "abort") { - abortController.abort(); - } - }; - request.abortSignal.addEventListener("abort", abortListener); - } - if (request.timeout > 0) { - setTimeout(() => { - abortController.abort(); - }, request.timeout); - } - const acceptEncoding = request.headers.get("Accept-Encoding"); - const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); - let body = typeof request.body === "function" ? request.body() : request.body; - if (body && !request.headers.has("Content-Length")) { - const bodyLength = getBodyLength(body); - if (bodyLength !== null) { - request.headers.set("Content-Length", bodyLength); - } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/debug/src/common.js +var require_common = __commonJS({ + "node_modules/debug/src/common.js"(exports2, module2) { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce3; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; } - let responseStream; - try { - if (body && request.onUploadProgress) { - const onUploadProgress = request.onUploadProgress; - const uploadReportStream = new ReportTransform(onUploadProgress); - uploadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in upload progress", e); - }); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } else { - uploadReportStream.end(body); - } - body = uploadReportStream; - } - const res = await this.makeRequest(request, abortController, body); - const headers = getResponseHeaders(res); - const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; - const response = { - status, - headers, - request - }; - if (request.method === "HEAD") { - res.resume(); - return response; - } - responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; - const onDownloadProgress = request.onDownloadProgress; - if (onDownloadProgress) { - const downloadReportStream = new ReportTransform(onDownloadProgress); - downloadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in download progress", e); - }); - responseStream.pipe(downloadReportStream); - responseStream = downloadReportStream; + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug5(...args) { + if (!debug5.enabled) { + return; } - if ( - // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code - ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status)) - ) { - response.readableStreamBody = responseStream; - } else { - response.bodyAsText = await streamToText(responseStream); + const self2 = debug5; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); } - return response; - } finally { - if (request.abortSignal && abortListener) { - let uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; } - let downloadStreamDone = Promise.resolve(); - if (isReadableStream(responseStream)) { - downloadStreamDone = isStreamComplete(responseStream); + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val2 = args[index]; + match = formatter.call(self2, val2); + args.splice(index, 1); + index--; } - Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { - var _a2; - if (abortListener) { - (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener); - } - }).catch((e) => { - log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); - }); + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug5.namespace = namespace; + debug5.useColors = createDebug.useColors(); + debug5.color = createDebug.selectColor(namespace); + debug5.extend = extend3; + debug5.destroy = createDebug.destroy; + Object.defineProperty(debug5, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug5); } + return debug5; } - makeRequest(request, abortController, body) { - var _a; - const url = new URL(request.url); - const isInsecure = url.protocol !== "https:"; - if (isInsecure && !request.allowInsecureConnection) { - throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + function extend3(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } } - const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); - const options = { - agent, - hostname: url.hostname, - path: `${url.pathname}${url.search}`, - port: url.port, - method: request.method, - headers: request.headers.toJSON({ preserveCase: true }) - }; - return new Promise((resolve4, reject) => { - const req = isInsecure ? http.request(options, resolve4) : https2.request(options, resolve4); - req.once("error", (err) => { - var _a2; - reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); - }); - abortController.signal.addEventListener("abort", () => { - const abortError = new abort_controller_1.AbortError("The operation was aborted."); - req.destroy(abortError); - reject(abortError); - }); - if (body && isReadableStream(body)) { - body.pipe(req); - } else if (body) { - if (typeof body === "string" || Buffer.isBuffer(body)) { - req.end(body); - } else if (isArrayBuffer(body)) { - req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; } else { - log_js_1.logger.error("Unrecognized body type", body); - reject(new restError_js_1.RestError("Unrecognized body type")); + searchIndex++; + templateIndex++; } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; } else { - req.end(); + return false; } - }); + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; } - getOrCreateAgent(request, isInsecure) { - var _a; - const disableKeepAlive = request.disableKeepAlive; - if (isInsecure) { - if (disableKeepAlive) { - return http.globalAgent; - } - if (!this.cachedHttpAgent) { - this.cachedHttpAgent = new http.Agent({ keepAlive: true }); - } - return this.cachedHttpAgent; - } else { - if (disableKeepAlive && !request.tlsSettings) { - return https2.globalAgent; - } - const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; - let agent = this.cachedHttpsAgents.get(tlsSettings); - if (agent && agent.options.keepAlive === !disableKeepAlive) { - return agent; + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; } - log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); - agent = new https2.Agent(Object.assign({ - // keepAlive is true if disableKeepAlive is false. - keepAlive: !disableKeepAlive - }, tlsSettings)); - this.cachedHttpsAgents.set(tlsSettings, agent); - return agent; } - } - }; - function getResponseHeaders(res) { - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); - for (const header of Object.keys(res.headers)) { - const value = res.headers[header]; - if (Array.isArray(value)) { - if (value.length > 0) { - headers.set(header, value[0]); + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; } - } else if (value) { - headers.set(header, value); } + return false; } - return headers; - } - function getDecodedResponseStream(stream2, headers) { - const contentEncoding = headers.get("Content-Encoding"); - if (contentEncoding === "gzip") { - const unzip = zlib.createGunzip(); - stream2.pipe(unzip); - return unzip; - } else if (contentEncoding === "deflate") { - const inflate = zlib.createInflate(); - stream2.pipe(inflate); - return inflate; + function coerce3(val2) { + if (val2 instanceof Error) { + return val2.stack || val2.message; + } + return val2; } - return stream2; - } - function streamToText(stream2) { - return new Promise((resolve4, reject) => { - const buffer = []; - stream2.on("data", (chunk) => { - if (Buffer.isBuffer(chunk)) { - buffer.push(chunk); - } else { - buffer.push(Buffer.from(chunk)); - } - }); - stream2.on("end", () => { - resolve4(Buffer.concat(buffer).toString("utf8")); - }); - stream2.on("error", (e) => { - if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { - reject(e); - } else { - reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { - code: restError_js_1.RestError.PARSE_ERROR - })); - } - }); - }); - } - function getBodyLength(body) { - if (!body) { - return 0; - } else if (Buffer.isBuffer(body)) { - return body.length; - } else if (isReadableStream(body)) { - return null; - } else if (isArrayBuffer(body)) { - return body.byteLength; - } else if (typeof body === "string") { - return Buffer.from(body).length; - } else { - return null; + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } + createDebug.enable(createDebug.load()); + return createDebug; } - function createNodeHttpClient() { - return new NodeHttpClient(); - } + module2.exports = setup; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js -var require_defaultHttpClient = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createDefaultHttpClient = createDefaultHttpClient; - var nodeHttpClient_js_1 = require_nodeHttpClient(); - function createDefaultHttpClient() { - return (0, nodeHttpClient_js_1.createNodeHttpClient)(); - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js -var require_pipelineRequest = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineRequest = createPipelineRequest; - var httpHeaders_js_1 = require_httpHeaders(); - var core_util_1 = require_commonjs2(); - var PipelineRequestImpl = class { - constructor(options) { - var _a, _b, _c, _d, _e, _f, _g; - this.url = options.url; - this.body = options.body; - this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); - this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; - this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; - this.multipartBody = options.multipartBody; - this.formData = options.formData; - this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; - this.proxySettings = options.proxySettings; - this.streamResponseStatusCodes = options.streamResponseStatusCodes; - this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; - this.abortSignal = options.abortSignal; - this.tracingOptions = options.tracingOptions; - this.onUploadProgress = options.onUploadProgress; - this.onDownloadProgress = options.onDownloadProgress; - this.requestId = options.requestId || (0, core_util_1.randomUUID)(); - this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; - this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; +// node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/debug/src/browser.js"(exports2, module2) { + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.storage = localstorage(); + exports2.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports2.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; } - }; - function createPipelineRequest(options) { - return new PipelineRequestImpl(options); + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js -var require_exponentialRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryPolicyName = void 0; - exports2.exponentialRetryPolicy = exponentialRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; - function exponentialRetryPolicy(options = {}) { - var _a; - return (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })) - ], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index++; + if (match === "%c") { + lastC = index; + } }); + args.splice(lastC, 0, c); + } + exports2.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports2.storage.setItem("debug", namespaces); + } else { + exports2.storage.removeItem("debug"); + } + } catch (error4) { + } + } + function load2() { + let r; + try { + r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); + } catch (error4) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error4) { + } } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error4) { + return "[UnexpectedJSONParseError]: " + error4.message; + } + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js -var require_systemErrorRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { +// node_modules/has-flag/index.js +var require_has_flag = __commonJS({ + "node_modules/has-flag/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.systemErrorRetryPolicyName = void 0; - exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; - function systemErrorRetryPolicy(options = {}) { - var _a; - return { - name: exports2.systemErrorRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })) - ], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest - }; - } + module2.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js -var require_throttlingRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { +// node_modules/supports-color/index.js +var require_supports_color = __commonJS({ + "node_modules/supports-color/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.throttlingRetryPolicyName = void 0; - exports2.throttlingRetryPolicy = throttlingRetryPolicy; - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants8(); - exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; - function throttlingRetryPolicy(options = {}) { - var _a; + var os3 = require("os"); + var tty = require("tty"); + var hasFlag = require_has_flag(); + var { env } = process; + var forceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { + forceColor = 0; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = 1; + } + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + forceColor = 1; + } else if (env.FORCE_COLOR === "false") { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } return { - name: exports2.throttlingRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 }; } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js -var require_tokenCycler = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_CYCLER_OPTIONS = void 0; - exports2.createTokenCycler = createTokenCycler; - var helpers_js_1 = require_helpers(); - exports2.DEFAULT_CYCLER_OPTIONS = { - forcedRefreshWindowInMs: 1e3, - // Force waiting for a refresh 1s before the token expires - retryIntervalInMs: 3e3, - // Allow refresh attempts every 3s - refreshWindowInMs: 1e3 * 60 * 2 - // Start refreshing 2m before expiry - }; - async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { - async function tryGetAccessToken() { - if (Date.now() < refreshTimeout) { - try { - return await getAccessToken(); - } catch (_a) { - return null; - } - } else { - const finalToken = await getAccessToken(); - if (finalToken === null) { - throw new Error("Failed to refresh access token."); - } - return finalToken; - } + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; } - let token = await tryGetAccessToken(); - while (token === null) { - await (0, helpers_js_1.delay)(retryIntervalInMs); - token = await tryGetAccessToken(); + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; } - return token; - } - function createTokenCycler(credential, tokenCyclerOptions) { - let refreshWorker = null; - let token = null; - let tenantId; - const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); - const cycler = { - /** - * Produces true if a refresh job is currently in progress. - */ - get isRefreshing() { - return refreshWorker !== null; - }, - /** - * Produces true if the cycler SHOULD refresh (we are within the refresh - * window and not already refreshing) - */ - get shouldRefresh() { - var _a; - if (cycler.isRefreshing) { - return false; - } - if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { - return true; - } - return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); - }, - /** - * Produces true if the cycler MUST refresh (null or nearly-expired - * token). - */ - get mustRefresh() { - return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); - } - }; - function refresh(scopes, getTokenOptions) { - var _a; - if (!cycler.isRefreshing) { - const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); - refreshWorker = beginRefresh( - tryGetAccessToken, - options.retryIntervalInMs, - // If we don't have a token, then we should timeout immediately - (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now() - ).then((_token) => { - refreshWorker = null; - token = _token; - tenantId = getTokenOptions.tenantId; - return token; - }).catch((reason) => { - refreshWorker = null; - token = null; - tenantId = void 0; - throw reason; - }); - } - return refreshWorker; + if (hasFlag("color=256")) { + return 2; } - return async (scopes, tokenOptions) => { - const hasClaimChallenge = Boolean(tokenOptions.claims); - const tenantIdChanged = tenantId !== tokenOptions.tenantId; - if (hasClaimChallenge) { - token = null; + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (process.platform === "win32") { + const osRelease = os3.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; } - const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; - if (mustRefresh) { - return refresh(scopes, tokenOptions); + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { + return 1; } - if (cycler.shouldRefresh) { - refresh(scopes, tokenOptions); + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; } - return token; - }; + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; + } + function getSupportLevel(stream2) { + const level = supportsColor(stream2, stream2 && stream2.isTTY); + return translateLevel(level); } + module2.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js -var require_bearerTokenAuthenticationPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bearerTokenAuthenticationPolicyName = void 0; - exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log(); - exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; - async function defaultAuthorizeRequest(options) { - const { scopes, getAccessToken, request } = options; - const getTokenOptions = { - abortSignal: request.abortSignal, - tracingOptions: request.tracingOptions - }; - const accessToken = await getAccessToken(scopes, getTokenOptions); - if (accessToken) { - options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); - } - } - function getChallenge(response) { - const challenge = response.headers.get("WWW-Authenticate"); - if (response.status === 401 && challenge) { - return challenge; - } - return; - } - function bearerTokenAuthenticationPolicy(options) { - var _a; - const { credential, scopes, challengeCallbacks } = options; - const logger = options.logger || log_js_1.logger; - const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); - const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( - credential - /* , options */ - ) : () => Promise.resolve(null); - return { - name: exports2.bearerTokenAuthenticationPolicyName, - /** - * If there's no challenge parameter: - * - It will try to retrieve the token using the cache, or the credential's getToken. - * - Then it will try the next policy with or without the retrieved token. - * - * It uses the challenge parameters to: - * - Skip a first attempt to get the token from the credential if there's no cached token, - * since it expects the token to be retrievable only after the challenge. - * - Prepare the outgoing request if the `prepareRequest` method has been provided. - * - Send an initial request to receive the challenge if it fails. - * - Process a challenge if the response contains it. - * - Retrieve a token with the challenge information, then re-send the request. - */ - async sendRequest(request, next) { - if (!request.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); - } - await callbacks.authorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - getAccessToken, - logger - }); - let response; - let error4; - try { - response = await next(request); - } catch (err) { - error4 = err; - response = err.response; - } - if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) { - const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - response, - getAccessToken, - logger - }); - if (shouldSendRequest) { - return next(request); - } - } - if (error4) { - throw error4; - } else { - return response; - } - } - }; +// node_modules/debug/src/node.js +var require_node = __commonJS({ + "node_modules/debug/src/node.js"(exports2, module2) { + var tty = require("tty"); + var util = require("util"); + exports2.init = init; + exports2.log = log; + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.destroy = util.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports2.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports2.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error4) { + } + exports2.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + let val2 = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val2)) { + val2 = true; + } else if (/^(no|off|false|disabled)$/i.test(val2)) { + val2 = false; + } else if (val2 === "null") { + val2 = null; + } else { + val2 = Number(val2); + } + obj[prop] = val2; + return obj; + }, {}); + function useColors() { + return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + " " + args[0]; + } + } + function getDate() { + if (exports2.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + function log(...args) { + return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load2() { + return process.env.DEBUG; } + function init(debug5) { + debug5.inspectOpts = {}; + const keys = Object.keys(exports2.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug5.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + } + } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js -var require_ndJsonPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { +// node_modules/debug/src/index.js +var require_src = __commonJS({ + "node_modules/debug/src/index.js"(exports2, module2) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module2.exports = require_browser(); + } else { + module2.exports = require_node(); + } + } +}); + +// node_modules/agent-base/dist/helpers.js +var require_helpers2 = __commonJS({ + "node_modules/agent-base/dist/helpers.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ndJsonPolicyName = void 0; - exports2.ndJsonPolicy = ndJsonPolicy; - exports2.ndJsonPolicyName = "ndJsonPolicy"; - function ndJsonPolicy() { - return { - name: exports2.ndJsonPolicyName, - async sendRequest(request, next) { - if (typeof request.body === "string" && request.body.startsWith("[")) { - const body = JSON.parse(request.body); - if (Array.isArray(body)) { - request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); - } - } - return next(request); - } - }; + exports2.req = exports2.json = exports2.toBuffer = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + async function toBuffer(stream2) { + let length = 0; + const chunks = []; + for await (const chunk of stream2) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); + } + exports2.toBuffer = toBuffer; + async function json2(stream2) { + const buf = await toBuffer(stream2); + const str2 = buf.toString("utf8"); + try { + return JSON.parse(str2); + } catch (_err) { + const err = _err; + err.message += ` (input: ${str2})`; + throw err; + } + } + exports2.json = json2; + function req(url, opts = {}) { + const href = typeof url === "string" ? url : url.href; + const req2 = (href.startsWith("https:") ? https2 : http).request(url, opts); + const promise = new Promise((resolve4, reject) => { + req2.once("response", resolve4).once("error", reject).end(); + }); + req2.then = promise.then.bind(promise); + return req2; } + exports2.req = req; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js -var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { +// node_modules/agent-base/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/agent-base/dist/index.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; - exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log(); - exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; - var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; - async function sendAuthorizeRequest(options) { - var _a, _b; - const { scopes, getAccessToken, request } = options; - const getTokenOptions = { - abortSignal: request.abortSignal, - tracingOptions: request.tracingOptions - }; - return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; - } - function auxiliaryAuthenticationHeaderPolicy(options) { - const { credentials, scopes } = options; - const logger = options.logger || log_js_1.logger; - const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); - return { - name: exports2.auxiliaryAuthenticationHeaderPolicyName, - async sendRequest(request, next) { - if (!request.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); + exports2.Agent = void 0; + var net = __importStar4(require("net")); + var http = __importStar4(require("http")); + var https_1 = require("https"); + __exportStar4(require_helpers2(), exports2); + var INTERNAL = Symbol("AgentBaseInternalState"); + var Agent = class extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + if (typeof options.secureEndpoint === "boolean") { + return options.secureEndpoint; } - if (!credentials || credentials.length === 0) { - logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); - return next(request); + if (typeof options.protocol === "string") { + return options.protocol === "https:"; } - const tokenPromises = []; - for (const credential of credentials) { - let getAccessToken = tokenCyclerMap.get(credential); - if (!getAccessToken) { - getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); - tokenCyclerMap.set(credential, getAccessToken); - } - tokenPromises.push(sendAuthorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - getAccessToken, - logger - })); + } + const { stack } = new Error(); + if (typeof stack !== "string") + return false; + return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + if (!this.sockets[name]) { + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + this.totalSocketCount--; + if (sockets.length === 0) { + delete this.sockets[name]; } - const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); - if (auxiliaryTokens.length === 0) { - logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); - return next(request); + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options); + if (secureEndpoint) { + return https_1.Agent.prototype.getName.call(this, options); + } + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options) + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + try { + return socket.addRequest(req, connectOpts); + } catch (err) { + return cb(err); + } } - request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); - return next(request); + this[INTERNAL].currentSocket = socket; + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = void 0; + if (!socket) { + throw new Error("No socket was returned in the `connect()` function"); } - }; - } + return socket; + } + get defaultPort() { + return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } + }; + exports2.Agent = Agent; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js -var require_commonjs5 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { +// node_modules/https-proxy-agent/dist/parse-proxy-response.js +var require_parse_proxy_response = __commonJS({ + "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { "use strict"; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; - var pipeline_js_1 = require_pipeline(); - Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() { + exports2.parseProxyResponse = void 0; + var debug_1 = __importDefault4(require_src()); + var debug5 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); + function parseProxyResponse(socket) { + return new Promise((resolve4, reject) => { + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once("readable", read); + } + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("readable", read); + } + function onend() { + cleanup(); + debug5("onend"); + reject(new Error("Proxy connection ended before receiving CONNECT response")); + } + function onerror(err) { + cleanup(); + debug5("onerror %o", err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf("\r\n\r\n"); + if (endOfHeaders === -1) { + debug5("have not received end of HTTP headers yet..."); + read(); + return; + } + const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error("No header received from proxy CONNECT response")); + } + const firstLineParts = firstLine.split(" "); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(" "); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(":"); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === "string") { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } + } + debug5("got proxy server response: %o %o", firstLine, headers); + cleanup(); + resolve4({ + connect: { + statusCode, + statusText, + headers + }, + buffered + }); + } + socket.on("error", onerror); + socket.on("end", onend); + read(); + }); + } + exports2.parseProxyResponse = parseProxyResponse; + } +}); + +// node_modules/https-proxy-agent/dist/index.js +var require_dist3 = __commonJS({ + "node_modules/https-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpsProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var assert_1 = __importDefault4(require("assert")); + var debug_1 = __importDefault4(require_src()); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var parse_proxy_response_1 = require_parse_proxy_response(); + var debug5 = (0, debug_1.default)("https-proxy-agent"); + var setServernameFromNonIpHost = (options) => { + if (options.servername === void 0 && options.host && !net.isIP(options.host)) { + return { + ...options, + servername: options.host + }; + } + return options; + }; + var HttpsProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: void 0 }; + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug5("Creating new HttpsProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ["http/1.1"], + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + let socket; + if (proxy.protocol === "https:") { + debug5("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } else { + debug5("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r +`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r +`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r +`); + const { connect, buffered } = await proxyResponsePromise; + req.emit("proxyConnect", connect); + this.emit("proxyConnect", connect, req); + if (connect.statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debug5("Upgrading socket connection to TLS"); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), + socket + }); + } + return socket; + } + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debug5("Replaying proxy buffer for failed request"); + (0, assert_1.default)(s.listenerCount("data") > 0); + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } + }; + HttpsProxyAgent.protocols = ["http", "https"]; + exports2.HttpsProxyAgent = HttpsProxyAgent; + function resume(socket) { + socket.resume(); + } + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + } +}); + +// node_modules/http-proxy-agent/dist/index.js +var require_dist4 = __commonJS({ + "node_modules/http-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var debug_1 = __importDefault4(require_src()); + var events_1 = require("events"); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var debug5 = (0, debug_1.default)("http-proxy-agent"); + var HttpProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug5("Creating new HttpProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + addRequest(req, opts) { + req._header = null; + this.setRequestProps(req, opts); + super.addRequest(req, opts); + } + setRequestProps(req, opts) { + const { proxy } = this; + const protocol = opts.secureEndpoint ? "https:" : "http:"; + const hostname = req.getHeader("host") || "localhost"; + const base = `${protocol}//${hostname}`; + const url = new url_1.URL(req.path, base); + if (opts.port !== 80) { + url.port = String(opts.port); + } + req.path = String(url); + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + const value = headers[name]; + if (value) { + req.setHeader(name, value); + } + } + } + async connect(req, opts) { + req._header = null; + if (!req.path.includes("://")) { + this.setRequestProps(req, opts); + } + let first; + let endOfHeaders; + debug5("Regenerating stored HTTP header string for request"); + req._implicitHeader(); + if (req.outputData && req.outputData.length > 0) { + debug5("Patching connection write() output buffer with updated header"); + first = req.outputData[0].data; + endOfHeaders = first.indexOf("\r\n\r\n") + 4; + req.outputData[0].data = req._header + first.substring(endOfHeaders); + debug5("Output buffer: %o", req.outputData[0].data); + } + let socket; + if (this.proxy.protocol === "https:") { + debug5("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(this.connectOpts); + } else { + debug5("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + await (0, events_1.once)(socket, "connect"); + return socket; + } + }; + HttpProxyAgent.protocols = ["http", "https"]; + exports2.HttpProxyAgent = HttpProxyAgent; + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js +var require_proxyPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; + exports2.loadNoProxy = loadNoProxy; + exports2.getDefaultProxySettings = getDefaultProxySettings; + exports2.proxyPolicy = proxyPolicy; + var https_proxy_agent_1 = require_dist3(); + var http_proxy_agent_1 = require_dist4(); + var log_js_1 = require_log(); + var HTTPS_PROXY = "HTTPS_PROXY"; + var HTTP_PROXY = "HTTP_PROXY"; + var ALL_PROXY = "ALL_PROXY"; + var NO_PROXY = "NO_PROXY"; + exports2.proxyPolicyName = "proxyPolicy"; + exports2.globalNoProxyList = []; + var noProxyListLoaded = false; + var globalBypassedMap = /* @__PURE__ */ new Map(); + function getEnvironmentValue(name) { + if (process.env[name]) { + return process.env[name]; + } else if (process.env[name.toLowerCase()]) { + return process.env[name.toLowerCase()]; + } + return void 0; + } + function loadEnvironmentProxyValue() { + if (!process) { + return void 0; + } + const httpsProxy = getEnvironmentValue(HTTPS_PROXY); + const allProxy = getEnvironmentValue(ALL_PROXY); + const httpProxy = getEnvironmentValue(HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; + } + function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = new URL(uri).hostname; + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } + } else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; + } + function loadNoProxy() { + const noProxy = getEnvironmentValue(NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); + } + return []; + } + function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return void 0; + } + } + const parsedUrl = new URL(proxyUrl); + const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; + return { + host: schema2 + parsedUrl.hostname, + port: Number.parseInt(parsedUrl.port || "80"), + username: parsedUrl.username, + password: parsedUrl.password + }; + } + function getDefaultProxySettingsInternal() { + const envProxy = loadEnvironmentProxyValue(); + return envProxy ? new URL(envProxy) : void 0; + } + function getUrlFromProxySettings(settings) { + let parsedProxyUrl; + try { + parsedProxyUrl = new URL(settings.host); + } catch (_a) { + throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); + } + parsedProxyUrl.port = String(settings.port); + if (settings.username) { + parsedProxyUrl.username = settings.username; + } + if (settings.password) { + parsedProxyUrl.password = settings.password; + } + return parsedProxyUrl; + } + function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { + if (request.agent) { + return; + } + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (request.tlsSettings) { + log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); + } + const headers = request.headers.toJSON(); + if (isInsecure) { + if (!cachedAgents.httpProxyAgent) { + cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpProxyAgent; + } else { + if (!cachedAgents.httpsProxyAgent) { + cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpsProxyAgent; + } + } + function proxyPolicy(proxySettings, options) { + if (!noProxyListLoaded) { + exports2.globalNoProxyList.push(...loadNoProxy()); + } + const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); + const cachedAgents = {}; + return { + name: exports2.proxyPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) { + setProxyAgentOnRequest(request, cachedAgents, defaultProxy); + } else if (request.proxySettings) { + setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js +var require_setClientRequestIdPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.setClientRequestIdPolicyName = void 0; + exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; + exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; + function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + return { + name: exports2.setClientRequestIdPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(requestIdHeaderName)) { + request.headers.set(requestIdHeaderName, request.requestId); + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js +var require_tlsPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.tlsPolicyName = void 0; + exports2.tlsPolicy = tlsPolicy; + exports2.tlsPolicyName = "tlsPolicy"; + function tlsPolicy(tlsSettings) { + return { + name: exports2.tlsPolicyName, + sendRequest: async (req, next) => { + if (!req.tlsSettings) { + req.tlsSettings = tlsSettings; + } + return next(req); + } + }; + } + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js +var require_tracingContext = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0; + exports2.knownContextKeys = { + span: Symbol.for("@azure/core-tracing span"), + namespace: Symbol.for("@azure/core-tracing namespace") + }; + function createTracingContext(options = {}) { + let context2 = new TracingContextImpl(options.parentContext); + if (options.span) { + context2 = context2.setValue(exports2.knownContextKeys.span, options.span); + } + if (options.namespace) { + context2 = context2.setValue(exports2.knownContextKeys.namespace, options.namespace); + } + return context2; + } + exports2.createTracingContext = createTracingContext; + var TracingContextImpl = class _TracingContextImpl { + constructor(initialContext) { + this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); + } + setValue(key, value) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.set(key, value); + return newContext; + } + getValue(key) { + return this._contextMap.get(key); + } + deleteValue(key) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.delete(key); + return newContext; + } + }; + exports2.TracingContextImpl = TracingContextImpl; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/state.js +var require_state = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.state = void 0; + exports2.state = { + instrumenterImplementation: void 0 + }; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js +var require_instrumenter = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0; + var tracingContext_js_1 = require_tracingContext(); + var state_js_1 = require_state(); + function createDefaultTracingSpan() { + return { + end: () => { + }, + isRecording: () => false, + recordException: () => { + }, + setAttribute: () => { + }, + setStatus: () => { + } + }; + } + exports2.createDefaultTracingSpan = createDefaultTracingSpan; + function createDefaultInstrumenter() { + return { + createRequestHeaders: () => { + return {}; + }, + parseTraceparentHeader: () => { + return void 0; + }, + startSpan: (_name, spanOptions) => { + return { + span: createDefaultTracingSpan(), + tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }) + }; + }, + withContext(_context, callback, ...callbackArgs) { + return callback(...callbackArgs); + } + }; + } + exports2.createDefaultInstrumenter = createDefaultInstrumenter; + function useInstrumenter(instrumenter) { + state_js_1.state.instrumenterImplementation = instrumenter; + } + exports2.useInstrumenter = useInstrumenter; + function getInstrumenter() { + if (!state_js_1.state.instrumenterImplementation) { + state_js_1.state.instrumenterImplementation = createDefaultInstrumenter(); + } + return state_js_1.state.instrumenterImplementation; + } + exports2.getInstrumenter = getInstrumenter; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js +var require_tracingClient = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTracingClient = void 0; + var instrumenter_js_1 = require_instrumenter(); + var tracingContext_js_1 = require_tracingContext(); + function createTracingClient(options) { + const { namespace, packageName, packageVersion } = options; + function startSpan(name, operationOptions, spanOptions) { + var _a; + const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); + let tracingContext = startSpanResult.tracingContext; + const span = startSpanResult.span; + if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { + tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace); + } + span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); + const updatedOptions = Object.assign({}, operationOptions, { + tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }) + }); + return { + span, + updatedOptions + }; + } + async function withSpan(name, operationOptions, callback, spanOptions) { + const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); + try { + const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); + span.setStatus({ status: "success" }); + return result; + } catch (err) { + span.setStatus({ status: "error", error: err }); + throw err; + } finally { + span.end(); + } + } + function withContext(context2, callback, ...callbackArgs) { + return (0, instrumenter_js_1.getInstrumenter)().withContext(context2, callback, ...callbackArgs); + } + function parseTraceparentHeader(traceparentHeader) { + return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader); + } + function createRequestHeaders(tracingContext) { + return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext); + } + return { + startSpan, + withSpan, + withContext, + parseTraceparentHeader, + createRequestHeaders + }; + } + exports2.createTracingClient = createTracingClient; + } +}); + +// node_modules/@azure/core-tracing/dist/commonjs/index.js +var require_commonjs4 = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTracingClient = exports2.useInstrumenter = void 0; + var instrumenter_js_1 = require_instrumenter(); + Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() { + return instrumenter_js_1.useInstrumenter; + } }); + var tracingClient_js_1 = require_tracingClient(); + Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() { + return tracingClient_js_1.createTracingClient; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js +var require_inspect = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.custom = void 0; + var node_util_1 = require("node:util"); + exports2.custom = node_util_1.inspect.custom; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js +var require_restError = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RestError = void 0; + exports2.isRestError = isRestError; + var core_util_1 = require_commonjs2(); + var inspect_js_1 = require_inspect(); + var sanitizer_js_1 = require_sanitizer(); + var errorSanitizer = new sanitizer_js_1.Sanitizer(); + var RestError = class _RestError extends Error { + constructor(message, options = {}) { + super(message); + this.name = "RestError"; + this.code = options.code; + this.statusCode = options.statusCode; + Object.defineProperty(this, "request", { value: options.request, enumerable: false }); + Object.defineProperty(this, "response", { value: options.response, enumerable: false }); + Object.setPrototypeOf(this, _RestError.prototype); + } + /** + * Logging method for util.inspect in Node + */ + [inspect_js_1.custom]() { + return `RestError: ${this.message} + ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; + } + }; + exports2.RestError = RestError; + RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; + RestError.PARSE_ERROR = "PARSE_ERROR"; + function isRestError(e) { + if (e instanceof RestError) { + return true; + } + return (0, core_util_1.isError)(e) && e.name === "RestError"; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js +var require_tracingPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.tracingPolicyName = void 0; + exports2.tracingPolicy = tracingPolicy; + var core_tracing_1 = require_commonjs4(); + var constants_js_1 = require_constants8(); + var userAgent_js_1 = require_userAgent(); + var log_js_1 = require_log(); + var core_util_1 = require_commonjs2(); + var restError_js_1 = require_restError(); + var sanitizer_js_1 = require_sanitizer(); + exports2.tracingPolicyName = "tracingPolicy"; + function tracingPolicy(options = {}) { + const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + const tracingClient = tryCreateTracingClient(); + return { + name: exports2.tracingPolicyName, + async sendRequest(request, next) { + var _a; + if (!tracingClient) { + return next(request); + } + const userAgent = await userAgentPromise; + const spanAttributes = { + "http.url": sanitizer.sanitizeUrl(request.url), + "http.method": request.method, + "http.user_agent": userAgent, + requestId: request.requestId + }; + if (userAgent) { + spanAttributes["http.user_agent"] = userAgent; + } + const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; + if (!span || !tracingContext) { + return next(request); + } + try { + const response = await tracingClient.withContext(tracingContext, next, request); + tryProcessResponse(span, response); + return response; + } catch (err) { + tryProcessError(span, err); + throw err; + } + } + }; + } + function tryCreateTracingClient() { + try { + return (0, core_tracing_1.createTracingClient)({ + namespace: "", + packageName: "@azure/core-rest-pipeline", + packageVersion: constants_js_1.SDK_VERSION + }); + } catch (e) { + log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); + return void 0; + } + } + function tryCreateSpan(tracingClient, request, spanAttributes) { + try { + const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { + spanKind: "client", + spanAttributes + }); + if (!span.isRecording()) { + span.end(); + return void 0; + } + const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); + for (const [key, value] of Object.entries(headers)) { + request.headers.set(key, value); + } + return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; + } catch (e) { + log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + return void 0; + } + } + function tryProcessError(span, error4) { + try { + span.setStatus({ + status: "error", + error: (0, core_util_1.isError)(error4) ? error4 : void 0 + }); + if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) { + span.setAttribute("http.status_code", error4.statusCode); + } + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + } + } + function tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); + } + span.setStatus({ + status: "success" + }); + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + } + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js +var require_createPipelineFromOptions = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createPipelineFromOptions = createPipelineFromOptions; + var logPolicy_js_1 = require_logPolicy(); + var pipeline_js_1 = require_pipeline(); + var redirectPolicy_js_1 = require_redirectPolicy(); + var userAgentPolicy_js_1 = require_userAgentPolicy(); + var multipartPolicy_js_1 = require_multipartPolicy(); + var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); + var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); + var formDataPolicy_js_1 = require_formDataPolicy(); + var core_util_1 = require_commonjs2(); + var proxyPolicy_js_1 = require_proxyPolicy(); + var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); + var tlsPolicy_js_1 = require_tlsPolicy(); + var tracingPolicy_js_1 = require_tracingPolicy(); + function createPipelineFromOptions(options) { + var _a; + const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); + if (core_util_1.isNodeLike) { + if (options.tlsOptions) { + pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); + } + pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); + pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); + } + pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); + pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); + pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); + pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); + pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); + pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { + afterPhase: "Retry" + }); + if (core_util_1.isNodeLike) { + pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + } + pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); + return pipeline; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js +var require_nodeHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getBodyLength = getBodyLength; + exports2.createNodeHttpClient = createNodeHttpClient; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var http = tslib_1.__importStar(require("node:http")); + var https2 = tslib_1.__importStar(require("node:https")); + var zlib = tslib_1.__importStar(require("node:zlib")); + var node_stream_1 = require("node:stream"); + var abort_controller_1 = require_commonjs3(); + var httpHeaders_js_1 = require_httpHeaders(); + var restError_js_1 = require_restError(); + var log_js_1 = require_log(); + var DEFAULT_TLS_SETTINGS = {}; + function isReadableStream(body) { + return body && typeof body.pipe === "function"; + } + function isStreamComplete(stream2) { + return new Promise((resolve4) => { + const handler = () => { + resolve4(); + stream2.removeListener("close", handler); + stream2.removeListener("end", handler); + stream2.removeListener("error", handler); + }; + stream2.on("close", handler); + stream2.on("end", handler); + stream2.on("error", handler); + }); + } + function isArrayBuffer(body) { + return body && typeof body.byteLength === "number"; + } + var ReportTransform = class extends node_stream_1.Transform { + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + _transform(chunk, _encoding, callback) { + this.push(chunk); + this.loadedBytes += chunk.length; + try { + this.progressCallback({ loadedBytes: this.loadedBytes }); + callback(); + } catch (e) { + callback(e); + } + } + constructor(progressCallback) { + super(); + this.loadedBytes = 0; + this.progressCallback = progressCallback; + } + }; + var NodeHttpClient = class { + constructor() { + this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); + } + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + var _a, _b, _c; + const abortController = new AbortController(); + let abortListener; + if (request.abortSignal) { + if (request.abortSignal.aborted) { + throw new abort_controller_1.AbortError("The operation was aborted."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController.abort(); + } + }; + request.abortSignal.addEventListener("abort", abortListener); + } + if (request.timeout > 0) { + setTimeout(() => { + abortController.abort(); + }, request.timeout); + } + const acceptEncoding = request.headers.get("Accept-Encoding"); + const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); + let body = typeof request.body === "function" ? request.body() : request.body; + if (body && !request.headers.has("Content-Length")) { + const bodyLength = getBodyLength(body); + if (bodyLength !== null) { + request.headers.set("Content-Length", bodyLength); + } + } + let responseStream; + try { + if (body && request.onUploadProgress) { + const onUploadProgress = request.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + uploadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in upload progress", e); + }); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); + } else { + uploadReportStream.end(body); + } + body = uploadReportStream; + } + const res = await this.makeRequest(request, abortController, body); + const headers = getResponseHeaders(res); + const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; + const response = { + status, + headers, + request + }; + if (request.method === "HEAD") { + res.resume(); + return response; + } + responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; + const onDownloadProgress = request.onDownloadProgress; + if (onDownloadProgress) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + downloadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in download progress", e); + }); + responseStream.pipe(downloadReportStream); + responseStream = downloadReportStream; + } + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status)) + ) { + response.readableStreamBody = responseStream; + } else { + response.bodyAsText = await streamToText(responseStream); + } + return response; + } finally { + if (request.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(responseStream)) { + downloadStreamDone = isStreamComplete(responseStream); + } + Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { + var _a2; + if (abortListener) { + (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener); + } + }).catch((e) => { + log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } + makeRequest(request, abortController, body) { + var _a; + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + } + const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); + const options = { + agent, + hostname: url.hostname, + path: `${url.pathname}${url.search}`, + port: url.port, + method: request.method, + headers: request.headers.toJSON({ preserveCase: true }) + }; + return new Promise((resolve4, reject) => { + const req = isInsecure ? http.request(options, resolve4) : https2.request(options, resolve4); + req.once("error", (err) => { + var _a2; + reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); + }); + abortController.signal.addEventListener("abort", () => { + const abortError = new abort_controller_1.AbortError("The operation was aborted."); + req.destroy(abortError); + reject(abortError); + }); + if (body && isReadableStream(body)) { + body.pipe(req); + } else if (body) { + if (typeof body === "string" || Buffer.isBuffer(body)) { + req.end(body); + } else if (isArrayBuffer(body)) { + req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } else { + log_js_1.logger.error("Unrecognized body type", body); + reject(new restError_js_1.RestError("Unrecognized body type")); + } + } else { + req.end(); + } + }); + } + getOrCreateAgent(request, isInsecure) { + var _a; + const disableKeepAlive = request.disableKeepAlive; + if (isInsecure) { + if (disableKeepAlive) { + return http.globalAgent; + } + if (!this.cachedHttpAgent) { + this.cachedHttpAgent = new http.Agent({ keepAlive: true }); + } + return this.cachedHttpAgent; + } else { + if (disableKeepAlive && !request.tlsSettings) { + return https2.globalAgent; + } + const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; + let agent = this.cachedHttpsAgents.get(tlsSettings); + if (agent && agent.options.keepAlive === !disableKeepAlive) { + return agent; + } + log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); + agent = new https2.Agent(Object.assign({ + // keepAlive is true if disableKeepAlive is false. + keepAlive: !disableKeepAlive + }, tlsSettings)); + this.cachedHttpsAgents.set(tlsSettings, agent); + return agent; + } + } + }; + function getResponseHeaders(res) { + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + for (const header of Object.keys(res.headers)) { + const value = res.headers[header]; + if (Array.isArray(value)) { + if (value.length > 0) { + headers.set(header, value[0]); + } + } else if (value) { + headers.set(header, value); + } + } + return headers; + } + function getDecodedResponseStream(stream2, headers) { + const contentEncoding = headers.get("Content-Encoding"); + if (contentEncoding === "gzip") { + const unzip = zlib.createGunzip(); + stream2.pipe(unzip); + return unzip; + } else if (contentEncoding === "deflate") { + const inflate = zlib.createInflate(); + stream2.pipe(inflate); + return inflate; + } + return stream2; + } + function streamToText(stream2) { + return new Promise((resolve4, reject) => { + const buffer = []; + stream2.on("data", (chunk) => { + if (Buffer.isBuffer(chunk)) { + buffer.push(chunk); + } else { + buffer.push(Buffer.from(chunk)); + } + }); + stream2.on("end", () => { + resolve4(Buffer.concat(buffer).toString("utf8")); + }); + stream2.on("error", (e) => { + if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { + reject(e); + } else { + reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { + code: restError_js_1.RestError.PARSE_ERROR + })); + } + }); + }); + } + function getBodyLength(body) { + if (!body) { + return 0; + } else if (Buffer.isBuffer(body)) { + return body.length; + } else if (isReadableStream(body)) { + return null; + } else if (isArrayBuffer(body)) { + return body.byteLength; + } else if (typeof body === "string") { + return Buffer.from(body).length; + } else { + return null; + } + } + function createNodeHttpClient() { + return new NodeHttpClient(); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js +var require_defaultHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createDefaultHttpClient = createDefaultHttpClient; + var nodeHttpClient_js_1 = require_nodeHttpClient(); + function createDefaultHttpClient() { + return (0, nodeHttpClient_js_1.createNodeHttpClient)(); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js +var require_pipelineRequest = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createPipelineRequest = createPipelineRequest; + var httpHeaders_js_1 = require_httpHeaders(); + var core_util_1 = require_commonjs2(); + var PipelineRequestImpl = class { + constructor(options) { + var _a, _b, _c, _d, _e, _f, _g; + this.url = options.url; + this.body = options.body; + this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); + this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; + this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; + this.multipartBody = options.multipartBody; + this.formData = options.formData; + this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; + this.proxySettings = options.proxySettings; + this.streamResponseStatusCodes = options.streamResponseStatusCodes; + this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; + this.abortSignal = options.abortSignal; + this.tracingOptions = options.tracingOptions; + this.onUploadProgress = options.onUploadProgress; + this.onDownloadProgress = options.onDownloadProgress; + this.requestId = options.requestId || (0, core_util_1.randomUUID)(); + this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; + this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; + } + }; + function createPipelineRequest(options) { + return new PipelineRequestImpl(options); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js +var require_exponentialRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.exponentialRetryPolicyName = void 0; + exports2.exponentialRetryPolicy = exponentialRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; + function exponentialRetryPolicy(options = {}) { + var _a; + return (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }); + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js +var require_systemErrorRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.systemErrorRetryPolicyName = void 0; + exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; + function systemErrorRetryPolicy(options = {}) { + var _a; + return { + name: exports2.systemErrorRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js +var require_throttlingRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.throttlingRetryPolicyName = void 0; + exports2.throttlingRetryPolicy = throttlingRetryPolicy; + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants8(); + exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; + function throttlingRetryPolicy(options = {}) { + var _a; + return { + name: exports2.throttlingRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js +var require_tokenCycler = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_CYCLER_OPTIONS = void 0; + exports2.createTokenCycler = createTokenCycler; + var helpers_js_1 = require_helpers(); + exports2.DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1e3, + // Force waiting for a refresh 1s before the token expires + retryIntervalInMs: 3e3, + // Allow refresh attempts every 3s + refreshWindowInMs: 1e3 * 60 * 2 + // Start refreshing 2m before expiry + }; + async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { + async function tryGetAccessToken() { + if (Date.now() < refreshTimeout) { + try { + return await getAccessToken(); + } catch (_a) { + return null; + } + } else { + const finalToken = await getAccessToken(); + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + let token = await tryGetAccessToken(); + while (token === null) { + await (0, helpers_js_1.delay)(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; + } + function createTokenCycler(credential, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + let tenantId; + const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + const cycler = { + /** + * Produces true if a refresh job is currently in progress. + */ + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) + */ + get shouldRefresh() { + var _a; + if (cycler.isRefreshing) { + return false; + } + if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { + return true; + } + return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); + } + }; + function refresh(scopes, getTokenOptions) { + var _a; + if (!cycler.isRefreshing) { + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); + refreshWorker = beginRefresh( + tryGetAccessToken, + options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now() + ).then((_token) => { + refreshWorker = null; + token = _token; + tenantId = getTokenOptions.tenantId; + return token; + }).catch((reason) => { + refreshWorker = null; + token = null; + tenantId = void 0; + throw reason; + }); + } + return refreshWorker; + } + return async (scopes, tokenOptions) => { + const hasClaimChallenge = Boolean(tokenOptions.claims); + const tenantIdChanged = tenantId !== tokenOptions.tenantId; + if (hasClaimChallenge) { + token = null; + } + const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; + if (mustRefresh) { + return refresh(scopes, tokenOptions); + } + if (cycler.shouldRefresh) { + refresh(scopes, tokenOptions); + } + return token; + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js +var require_bearerTokenAuthenticationPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.bearerTokenAuthenticationPolicyName = void 0; + exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log(); + exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; + async function defaultAuthorizeRequest(options) { + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions + }; + const accessToken = await getAccessToken(scopes, getTokenOptions); + if (accessToken) { + options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); + } + } + function getChallenge(response) { + const challenge = response.headers.get("WWW-Authenticate"); + if (response.status === 401 && challenge) { + return challenge; + } + return; + } + function bearerTokenAuthenticationPolicy(options) { + var _a; + const { credential, scopes, challengeCallbacks } = options; + const logger = options.logger || log_js_1.logger; + const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); + const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( + credential + /* , options */ + ) : () => Promise.resolve(null); + return { + name: exports2.bearerTokenAuthenticationPolicyName, + /** + * If there's no challenge parameter: + * - It will try to retrieve the token using the cache, or the credential's getToken. + * - Then it will try the next policy with or without the retrieved token. + * + * It uses the challenge parameters to: + * - Skip a first attempt to get the token from the credential if there's no cached token, + * since it expects the token to be retrievable only after the challenge. + * - Prepare the outgoing request if the `prepareRequest` method has been provided. + * - Send an initial request to receive the challenge if it fails. + * - Process a challenge if the response contains it. + * - Retrieve a token with the challenge information, then re-send the request. + */ + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + await callbacks.authorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + }); + let response; + let error4; + try { + response = await next(request); + } catch (err) { + error4 = err; + response = err.response; + } + if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) { + const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + response, + getAccessToken, + logger + }); + if (shouldSendRequest) { + return next(request); + } + } + if (error4) { + throw error4; + } else { + return response; + } + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js +var require_ndJsonPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ndJsonPolicyName = void 0; + exports2.ndJsonPolicy = ndJsonPolicy; + exports2.ndJsonPolicyName = "ndJsonPolicy"; + function ndJsonPolicy() { + return { + name: exports2.ndJsonPolicyName, + async sendRequest(request, next) { + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js +var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; + exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log(); + exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; + var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; + async function sendAuthorizeRequest(options) { + var _a, _b; + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions + }; + return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; + } + function auxiliaryAuthenticationHeaderPolicy(options) { + const { credentials, scopes } = options; + const logger = options.logger || log_js_1.logger; + const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); + return { + name: exports2.auxiliaryAuthenticationHeaderPolicyName, + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); + } + if (!credentials || credentials.length === 0) { + logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); + return next(request); + } + const tokenPromises = []; + for (const credential of credentials) { + let getAccessToken = tokenCyclerMap.get(credential); + if (!getAccessToken) { + getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); + tokenCyclerMap.set(credential, getAccessToken); + } + tokenPromises.push(sendAuthorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + })); + } + const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); + if (auxiliaryTokens.length === 0) { + logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); + return next(request); + } + request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); + return next(request); + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js +var require_commonjs5 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; + var pipeline_js_1 = require_pipeline(); + Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() { return pipeline_js_1.createEmptyPipeline; } }); var createPipelineFromOptions_js_1 = require_createPipelineFromOptions(); @@ -66649,7 +68155,7 @@ var require_requestUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; var core13 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib3(); var constants_1 = require_constants7(); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -66817,7 +68323,7 @@ var require_downloadUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; var core13 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib3(); var storage_blob_1 = require_dist7(); var buffer = __importStar4(require("buffer")); var fs9 = __importStar4(require("fs")); @@ -67394,8 +68900,8 @@ var require_cacheHttpClient = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; var core13 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib3(); + var auth_1 = require_auth2(); var fs9 = __importStar4(require("fs")); var url_1 = require("url"); var utils = __importStar4(require_cacheUtils()); @@ -67707,7255 +69213,8616 @@ var require_base642 = __commonJS({ break; } } - if (groupPos) { - base64 += encTable[p]; - base64 += "="; - if (groupPos == 1) - base64 += "="; + if (groupPos) { + base64 += encTable[p]; + base64 += "="; + if (groupPos == 1) + base64 += "="; + } + return base64; + } + exports2.base64encode = base64encode; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js +var require_protobufjs_utf8 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.utf8read = void 0; + var fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); + function utf8read(bytes) { + if (bytes.length < 1) + return ""; + let pos = 0, parts = [], chunk = [], i = 0, t; + let len = bytes.length; + while (pos < len) { + t = bytes[pos++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 65536; + chunk[i++] = 55296 + (t >> 10); + chunk[i++] = 56320 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; + if (i > 8191) { + parts.push(fromCharCodes(chunk)); + i = 0; + } + } + if (parts.length) { + if (i) + parts.push(fromCharCodes(chunk.slice(0, i))); + return parts.join(""); + } + return fromCharCodes(chunk.slice(0, i)); + } + exports2.utf8read = utf8read; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js +var require_binary_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WireType = exports2.mergeBinaryOptions = exports2.UnknownFieldHandler = void 0; + var UnknownFieldHandler; + (function(UnknownFieldHandler2) { + UnknownFieldHandler2.symbol = Symbol.for("protobuf-ts/unknown"); + UnknownFieldHandler2.onRead = (typeName, message, fieldNo, wireType, data) => { + let container = is(message) ? message[UnknownFieldHandler2.symbol] : message[UnknownFieldHandler2.symbol] = []; + container.push({ no: fieldNo, wireType, data }); + }; + UnknownFieldHandler2.onWrite = (typeName, message, writer) => { + for (let { no, wireType, data } of UnknownFieldHandler2.list(message)) + writer.tag(no, wireType).raw(data); + }; + UnknownFieldHandler2.list = (message, fieldNo) => { + if (is(message)) { + let all = message[UnknownFieldHandler2.symbol]; + return fieldNo ? all.filter((uf) => uf.no == fieldNo) : all; + } + return []; + }; + UnknownFieldHandler2.last = (message, fieldNo) => UnknownFieldHandler2.list(message, fieldNo).slice(-1)[0]; + const is = (message) => message && Array.isArray(message[UnknownFieldHandler2.symbol]); + })(UnknownFieldHandler = exports2.UnknownFieldHandler || (exports2.UnknownFieldHandler = {})); + function mergeBinaryOptions(a, b) { + return Object.assign(Object.assign({}, a), b); + } + exports2.mergeBinaryOptions = mergeBinaryOptions; + var WireType; + (function(WireType2) { + WireType2[WireType2["Varint"] = 0] = "Varint"; + WireType2[WireType2["Bit64"] = 1] = "Bit64"; + WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited"; + WireType2[WireType2["StartGroup"] = 3] = "StartGroup"; + WireType2[WireType2["EndGroup"] = 4] = "EndGroup"; + WireType2[WireType2["Bit32"] = 5] = "Bit32"; + })(WireType = exports2.WireType || (exports2.WireType = {})); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js +var require_goog_varint = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.varint32read = exports2.varint32write = exports2.int64toString = exports2.int64fromString = exports2.varint64write = exports2.varint64read = void 0; + function varint64read() { + let lowBits = 0; + let highBits = 0; + for (let shift = 0; shift < 28; shift += 7) { + let b = this.buf[this.pos++]; + lowBits |= (b & 127) << shift; + if ((b & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } + } + let middleByte = this.buf[this.pos++]; + lowBits |= (middleByte & 15) << 28; + highBits = (middleByte & 112) >> 4; + if ((middleByte & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } + for (let shift = 3; shift <= 31; shift += 7) { + let b = this.buf[this.pos++]; + highBits |= (b & 127) << shift; + if ((b & 128) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } + } + throw new Error("invalid varint"); + } + exports2.varint64read = varint64read; + function varint64write(lo, hi, bytes) { + for (let i = 0; i < 28; i = i + 7) { + const shift = lo >>> i; + const hasNext = !(shift >>> 7 == 0 && hi == 0); + const byte = (hasNext ? shift | 128 : shift) & 255; + bytes.push(byte); + if (!hasNext) { + return; + } + } + const splitBits = lo >>> 28 & 15 | (hi & 7) << 4; + const hasMoreBits = !(hi >> 3 == 0); + bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255); + if (!hasMoreBits) { + return; + } + for (let i = 3; i < 31; i = i + 7) { + const shift = hi >>> i; + const hasNext = !(shift >>> 7 == 0); + const byte = (hasNext ? shift | 128 : shift) & 255; + bytes.push(byte); + if (!hasNext) { + return; + } + } + bytes.push(hi >>> 31 & 1); + } + exports2.varint64write = varint64write; + var TWO_PWR_32_DBL = (1 << 16) * (1 << 16); + function int64fromString(dec) { + let minus = dec[0] == "-"; + if (minus) + dec = dec.slice(1); + const base = 1e6; + let lowBits = 0; + let highBits = 0; + function add1e6digit(begin, end) { + const digit1e6 = Number(dec.slice(begin, end)); + highBits *= base; + lowBits = lowBits * base + digit1e6; + if (lowBits >= TWO_PWR_32_DBL) { + highBits = highBits + (lowBits / TWO_PWR_32_DBL | 0); + lowBits = lowBits % TWO_PWR_32_DBL; + } + } + add1e6digit(-24, -18); + add1e6digit(-18, -12); + add1e6digit(-12, -6); + add1e6digit(-6); + return [minus, lowBits, highBits]; + } + exports2.int64fromString = int64fromString; + function int64toString(bitsLow, bitsHigh) { + if (bitsHigh >>> 0 <= 2097151) { + return "" + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); + } + let low = bitsLow & 16777215; + let mid = (bitsLow >>> 24 | bitsHigh << 8) >>> 0 & 16777215; + let high = bitsHigh >> 16 & 65535; + let digitA = low + mid * 6777216 + high * 6710656; + let digitB = mid + high * 8147497; + let digitC = high * 2; + let base = 1e7; + if (digitA >= base) { + digitB += Math.floor(digitA / base); + digitA %= base; + } + if (digitB >= base) { + digitC += Math.floor(digitB / base); + digitB %= base; + } + function decimalFrom1e7(digit1e7, needLeadingZeros) { + let partial = digit1e7 ? String(digit1e7) : ""; + if (needLeadingZeros) { + return "0000000".slice(partial.length) + partial; + } + return partial; + } + return decimalFrom1e7( + digitC, + /*needLeadingZeros=*/ + 0 + ) + decimalFrom1e7( + digitB, + /*needLeadingZeros=*/ + digitC + ) + // If the final 1e7 digit didn't need leading zeros, we would have + // returned via the trivial code path at the top. + decimalFrom1e7( + digitA, + /*needLeadingZeros=*/ + 1 + ); + } + exports2.int64toString = int64toString; + function varint32write(value, bytes) { + if (value >= 0) { + while (value > 127) { + bytes.push(value & 127 | 128); + value = value >>> 7; + } + bytes.push(value); + } else { + for (let i = 0; i < 9; i++) { + bytes.push(value & 127 | 128); + value = value >> 7; + } + bytes.push(1); + } + } + exports2.varint32write = varint32write; + function varint32read() { + let b = this.buf[this.pos++]; + let result = b & 127; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 7; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 14; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 127) << 21; + if ((b & 128) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 15) << 28; + for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++) + b = this.buf[this.pos++]; + if ((b & 128) != 0) + throw new Error("invalid varint"); + this.assertBounds(); + return result >>> 0; + } + exports2.varint32read = varint32read; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js +var require_pb_long = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PbLong = exports2.PbULong = exports2.detectBi = void 0; + var goog_varint_1 = require_goog_varint(); + var BI; + function detectBi() { + const dv = new DataView(new ArrayBuffer(8)); + const ok = globalThis.BigInt !== void 0 && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function"; + BI = ok ? { + MIN: BigInt("-9223372036854775808"), + MAX: BigInt("9223372036854775807"), + UMIN: BigInt("0"), + UMAX: BigInt("18446744073709551615"), + C: BigInt, + V: dv + } : void 0; + } + exports2.detectBi = detectBi; + detectBi(); + function assertBi(bi) { + if (!bi) + throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); + } + var RE_DECIMAL_STR = /^-?[0-9]+$/; + var TWO_PWR_32_DBL = 4294967296; + var HALF_2_PWR_32 = 2147483648; + var SharedPbLong = class { + /** + * Create a new instance with the given bits. + */ + constructor(lo, hi) { + this.lo = lo | 0; + this.hi = hi | 0; + } + /** + * Is this instance equal to 0? + */ + isZero() { + return this.lo == 0 && this.hi == 0; + } + /** + * Convert to a native number. + */ + toNumber() { + let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); + if (!Number.isSafeInteger(result)) + throw new Error("cannot convert to safe number"); + return result; + } + }; + var PbULong = class _PbULong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error("string is no integer"); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.UMIN) + throw new Error("signed value for ulong"); + if (value > BI.UMAX) + throw new Error("ulong too large"); + BI.V.setBigUint64(0, value, true); + return new _PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + } + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error("string is no integer"); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) + throw new Error("signed value for ulong"); + return new _PbULong(lo, hi); + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error("number is no integer"); + if (value < 0) + throw new Error("signed value for ulong"); + return new _PbULong(value, value / TWO_PWR_32_DBL); + } + throw new Error("unknown value " + typeof value); + } + /** + * Convert to decimal string. + */ + toString() { + return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); + } + /** + * Convert to native bigint. + */ + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigUint64(0, true); + } + }; + exports2.PbULong = PbULong; + PbULong.ZERO = new PbULong(0, 0); + var PbLong = class _PbLong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error("string is no integer"); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.MIN) + throw new Error("signed long too small"); + if (value > BI.MAX) + throw new Error("signed long too large"); + BI.V.setBigInt64(0, value, true); + return new _PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + } + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error("string is no integer"); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) { + if (hi > HALF_2_PWR_32 || hi == HALF_2_PWR_32 && lo != 0) + throw new Error("signed long too small"); + } else if (hi >= HALF_2_PWR_32) + throw new Error("signed long too large"); + let pbl = new _PbLong(lo, hi); + return minus ? pbl.negate() : pbl; + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error("number is no integer"); + return value > 0 ? new _PbLong(value, value / TWO_PWR_32_DBL) : new _PbLong(-value, -value / TWO_PWR_32_DBL).negate(); + } + throw new Error("unknown value " + typeof value); + } + /** + * Do we have a minus sign? + */ + isNegative() { + return (this.hi & HALF_2_PWR_32) !== 0; + } + /** + * Negate two's complement. + * Invert all the bits and add one to the result. + */ + negate() { + let hi = ~this.hi, lo = this.lo; + if (lo) + lo = ~lo + 1; + else + hi += 1; + return new _PbLong(lo, hi); + } + /** + * Convert to decimal string. + */ + toString() { + if (BI) + return this.toBigInt().toString(); + if (this.isNegative()) { + let n = this.negate(); + return "-" + goog_varint_1.int64toString(n.lo, n.hi); + } + return goog_varint_1.int64toString(this.lo, this.hi); + } + /** + * Convert to native bigint. + */ + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigInt64(0, true); } - return base64; - } - exports2.base64encode = base64encode; + }; + exports2.PbLong = PbLong; + PbLong.ZERO = new PbLong(0, 0); } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js -var require_protobufjs_utf8 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js +var require_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.utf8read = void 0; - var fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); - function utf8read(bytes) { - if (bytes.length < 1) - return ""; - let pos = 0, parts = [], chunk = [], i = 0, t; - let len = bytes.length; - while (pos < len) { - t = bytes[pos++]; - if (t < 128) - chunk[i++] = t; - else if (t > 191 && t < 224) - chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 65536; - chunk[i++] = 55296 + (t >> 10); - chunk[i++] = 56320 + (t & 1023); - } else - chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; - if (i > 8191) { - parts.push(fromCharCodes(chunk)); - i = 0; + exports2.BinaryReader = exports2.binaryReadOptions = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var defaultsRead = { + readUnknownField: true, + readerFactory: (bytes) => new BinaryReader(bytes) + }; + function binaryReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; + } + exports2.binaryReadOptions = binaryReadOptions; + var BinaryReader = class { + constructor(buf, textDecoder) { + this.varint64 = goog_varint_1.varint64read; + this.uint32 = goog_varint_1.varint32read; + this.buf = buf; + this.len = buf.length; + this.pos = 0; + this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true + }); + } + /** + * Reads a tag - field number and wire type. + */ + tag() { + let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; + if (fieldNo <= 0 || wireType < 0 || wireType > 5) + throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); + return [fieldNo, wireType]; + } + /** + * Skip one element on the wire and return the skipped data. + * Supports WireType.StartGroup since v2.0.0-alpha.23. + */ + skip(wireType) { + let start = this.pos; + switch (wireType) { + case binary_format_contract_1.WireType.Varint: + while (this.buf[this.pos++] & 128) { + } + break; + case binary_format_contract_1.WireType.Bit64: + this.pos += 4; + case binary_format_contract_1.WireType.Bit32: + this.pos += 4; + break; + case binary_format_contract_1.WireType.LengthDelimited: + let len = this.uint32(); + this.pos += len; + break; + case binary_format_contract_1.WireType.StartGroup: + let t; + while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { + this.skip(t); + } + break; + default: + throw new Error("cant skip wire type " + wireType); } + this.assertBounds(); + return this.buf.subarray(start, this.pos); } - if (parts.length) { - if (i) - parts.push(fromCharCodes(chunk.slice(0, i))); - return parts.join(""); + /** + * Throws error if position in byte array is out of range. + */ + assertBounds() { + if (this.pos > this.len) + throw new RangeError("premature EOF"); } - return fromCharCodes(chunk.slice(0, i)); - } - exports2.utf8read = utf8read; + /** + * Read a `int32` field, a signed 32 bit varint. + */ + int32() { + return this.uint32() | 0; + } + /** + * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. + */ + sint32() { + let zze = this.uint32(); + return zze >>> 1 ^ -(zze & 1); + } + /** + * Read a `int64` field, a signed 64-bit varint. + */ + int64() { + return new pb_long_1.PbLong(...this.varint64()); + } + /** + * Read a `uint64` field, an unsigned 64-bit varint. + */ + uint64() { + return new pb_long_1.PbULong(...this.varint64()); + } + /** + * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. + */ + sint64() { + let [lo, hi] = this.varint64(); + let s = -(lo & 1); + lo = (lo >>> 1 | (hi & 1) << 31) ^ s; + hi = hi >>> 1 ^ s; + return new pb_long_1.PbLong(lo, hi); + } + /** + * Read a `bool` field, a variant. + */ + bool() { + let [lo, hi] = this.varint64(); + return lo !== 0 || hi !== 0; + } + /** + * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. + */ + fixed32() { + return this.view.getUint32((this.pos += 4) - 4, true); + } + /** + * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. + */ + sfixed32() { + return this.view.getInt32((this.pos += 4) - 4, true); + } + /** + * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. + */ + fixed64() { + return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); + } + /** + * Read a `fixed64` field, a signed, fixed-length 64-bit integer. + */ + sfixed64() { + return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); + } + /** + * Read a `float` field, 32-bit floating point number. + */ + float() { + return this.view.getFloat32((this.pos += 4) - 4, true); + } + /** + * Read a `double` field, a 64-bit floating point number. + */ + double() { + return this.view.getFloat64((this.pos += 8) - 8, true); + } + /** + * Read a `bytes` field, length-delimited arbitrary data. + */ + bytes() { + let len = this.uint32(); + let start = this.pos; + this.pos += len; + this.assertBounds(); + return this.buf.subarray(start, start + len); + } + /** + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); + } + }; + exports2.BinaryReader = BinaryReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js -var require_binary_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js +var require_assert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WireType = exports2.mergeBinaryOptions = exports2.UnknownFieldHandler = void 0; - var UnknownFieldHandler; - (function(UnknownFieldHandler2) { - UnknownFieldHandler2.symbol = Symbol.for("protobuf-ts/unknown"); - UnknownFieldHandler2.onRead = (typeName, message, fieldNo, wireType, data) => { - let container = is(message) ? message[UnknownFieldHandler2.symbol] : message[UnknownFieldHandler2.symbol] = []; - container.push({ no: fieldNo, wireType, data }); - }; - UnknownFieldHandler2.onWrite = (typeName, message, writer) => { - for (let { no, wireType, data } of UnknownFieldHandler2.list(message)) - writer.tag(no, wireType).raw(data); - }; - UnknownFieldHandler2.list = (message, fieldNo) => { - if (is(message)) { - let all = message[UnknownFieldHandler2.symbol]; - return fieldNo ? all.filter((uf) => uf.no == fieldNo) : all; - } - return []; - }; - UnknownFieldHandler2.last = (message, fieldNo) => UnknownFieldHandler2.list(message, fieldNo).slice(-1)[0]; - const is = (message) => message && Array.isArray(message[UnknownFieldHandler2.symbol]); - })(UnknownFieldHandler = exports2.UnknownFieldHandler || (exports2.UnknownFieldHandler = {})); - function mergeBinaryOptions(a, b) { - return Object.assign(Object.assign({}, a), b); + exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; + function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } } - exports2.mergeBinaryOptions = mergeBinaryOptions; - var WireType; - (function(WireType2) { - WireType2[WireType2["Varint"] = 0] = "Varint"; - WireType2[WireType2["Bit64"] = 1] = "Bit64"; - WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited"; - WireType2[WireType2["StartGroup"] = 3] = "StartGroup"; - WireType2[WireType2["EndGroup"] = 4] = "EndGroup"; - WireType2[WireType2["Bit32"] = 5] = "Bit32"; - })(WireType = exports2.WireType || (exports2.WireType = {})); + exports2.assert = assert; + function assertNever2(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + } + exports2.assertNever = assertNever2; + var FLOAT32_MAX = 34028234663852886e22; + var FLOAT32_MIN = -34028234663852886e22; + var UINT32_MAX = 4294967295; + var INT32_MAX = 2147483647; + var INT32_MIN = -2147483648; + function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid int 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error("invalid int 32: " + arg); + } + exports2.assertInt32 = assertInt32; + function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid uint 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error("invalid uint 32: " + arg); + } + exports2.assertUInt32 = assertUInt32; + function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error("invalid float 32: " + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error("invalid float 32: " + arg); + } + exports2.assertFloat32 = assertFloat32; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js -var require_goog_varint = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js +var require_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.varint32read = exports2.varint32write = exports2.int64toString = exports2.int64fromString = exports2.varint64write = exports2.varint64read = void 0; - function varint64read() { - let lowBits = 0; - let highBits = 0; - for (let shift = 0; shift < 28; shift += 7) { - let b = this.buf[this.pos++]; - lowBits |= (b & 127) << shift; - if ((b & 128) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } - } - let middleByte = this.buf[this.pos++]; - lowBits |= (middleByte & 15) << 28; - highBits = (middleByte & 112) >> 4; - if ((middleByte & 128) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } - for (let shift = 3; shift <= 31; shift += 7) { - let b = this.buf[this.pos++]; - highBits |= (b & 127) << shift; - if ((b & 128) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } - } - throw new Error("invalid varint"); + exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var assert_1 = require_assert(); + var defaultsWrite = { + writeUnknownFields: true, + writerFactory: () => new BinaryWriter() + }; + function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; } - exports2.varint64read = varint64read; - function varint64write(lo, hi, bytes) { - for (let i = 0; i < 28; i = i + 7) { - const shift = lo >>> i; - const hasNext = !(shift >>> 7 == 0 && hi == 0); - const byte = (hasNext ? shift | 128 : shift) & 255; - bytes.push(byte); - if (!hasNext) { - return; - } - } - const splitBits = lo >>> 28 & 15 | (hi & 7) << 4; - const hasMoreBits = !(hi >> 3 == 0); - bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255); - if (!hasMoreBits) { - return; - } - for (let i = 3; i < 31; i = i + 7) { - const shift = hi >>> i; - const hasNext = !(shift >>> 7 == 0); - const byte = (hasNext ? shift | 128 : shift) & 255; - bytes.push(byte); - if (!hasNext) { - return; - } + exports2.binaryWriteOptions = binaryWriteOptions; + var BinaryWriter = class { + constructor(textEncoder) { + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; } - bytes.push(hi >>> 31 & 1); - } - exports2.varint64write = varint64write; - var TWO_PWR_32_DBL = (1 << 16) * (1 << 16); - function int64fromString(dec) { - let minus = dec[0] == "-"; - if (minus) - dec = dec.slice(1); - const base = 1e6; - let lowBits = 0; - let highBits = 0; - function add1e6digit(begin, end) { - const digit1e6 = Number(dec.slice(begin, end)); - highBits *= base; - lowBits = lowBits * base + digit1e6; - if (lowBits >= TWO_PWR_32_DBL) { - highBits = highBits + (lowBits / TWO_PWR_32_DBL | 0); - lowBits = lowBits % TWO_PWR_32_DBL; + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; } + this.chunks = []; + return bytes; } - add1e6digit(-24, -18); - add1e6digit(-18, -12); - add1e6digit(-12, -6); - add1e6digit(-6); - return [minus, lowBits, highBits]; - } - exports2.int64fromString = int64fromString; - function int64toString(bitsLow, bitsHigh) { - if (bitsHigh >>> 0 <= 2097151) { - return "" + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; } - let low = bitsLow & 16777215; - let mid = (bitsLow >>> 24 | bitsHigh << 8) >>> 0 & 16777215; - let high = bitsHigh >> 16 & 65535; - let digitA = low + mid * 6777216 + high * 6710656; - let digitB = mid + high * 8147497; - let digitC = high * 2; - let base = 1e7; - if (digitA >= base) { - digitB += Math.floor(digitA / base); - digitA %= base; + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + let chunk = this.finish(); + let prev = this.stack.pop(); + if (!prev) + throw new Error("invalid state, fork stack empty"); + this.chunks = prev.chunks; + this.buf = prev.buf; + this.uint32(chunk.byteLength); + return this.raw(chunk); } - if (digitB >= base) { - digitC += Math.floor(digitB / base); - digitB %= base; + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type2) { + return this.uint32((fieldNo << 3 | type2) >>> 0); } - function decimalFrom1e7(digit1e7, needLeadingZeros) { - let partial = digit1e7 ? String(digit1e7) : ""; - if (needLeadingZeros) { - return "0000000".slice(partial.length) + partial; + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; } - return partial; + this.chunks.push(chunk); + return this; } - return decimalFrom1e7( - digitC, - /*needLeadingZeros=*/ - 0 - ) + decimalFrom1e7( - digitB, - /*needLeadingZeros=*/ - digitC - ) + // If the final 1e7 digit didn't need leading zeros, we would have - // returned via the trivial code path at the top. - decimalFrom1e7( - digitA, - /*needLeadingZeros=*/ - 1 - ); - } - exports2.int64toString = int64toString; - function varint32write(value, bytes) { - if (value >= 0) { + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); while (value > 127) { - bytes.push(value & 127 | 128); + this.buf.push(value & 127 | 128); value = value >>> 7; } - bytes.push(value); - } else { - for (let i = 0; i < 9; i++) { - bytes.push(value & 127 | 128); - value = value >> 7; - } - bytes.push(1); - } - } - exports2.varint32write = varint32write; - function varint32read() { - let b = this.buf[this.pos++]; - let result = b & 127; - if ((b & 128) == 0) { - this.assertBounds(); - return result; + this.buf.push(value); + return this; } - b = this.buf[this.pos++]; - result |= (b & 127) << 7; - if ((b & 128) == 0) { - this.assertBounds(); - return result; + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; } - b = this.buf[this.pos++]; - result |= (b & 127) << 14; - if ((b & 128) == 0) { - this.assertBounds(); - return result; + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; } - b = this.buf[this.pos++]; - result |= (b & 127) << 21; - if ((b & 128) == 0) { - this.assertBounds(); - return result; + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); + return this.raw(value); } - b = this.buf[this.pos++]; - result |= (b & 15) << 28; - for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++) - b = this.buf[this.pos++]; - if ((b & 128) != 0) - throw new Error("invalid varint"); - this.assertBounds(); - return result >>> 0; - } - exports2.varint32read = varint32read; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js -var require_pb_long = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PbLong = exports2.PbULong = exports2.detectBi = void 0; - var goog_varint_1 = require_goog_varint(); - var BI; - function detectBi() { - const dv = new DataView(new ArrayBuffer(8)); - const ok = globalThis.BigInt !== void 0 && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function"; - BI = ok ? { - MIN: BigInt("-9223372036854775808"), - MAX: BigInt("9223372036854775807"), - UMIN: BigInt("0"), - UMAX: BigInt("18446744073709551615"), - C: BigInt, - V: dv - } : void 0; - } - exports2.detectBi = detectBi; - detectBi(); - function assertBi(bi) { - if (!bi) - throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); - } - var RE_DECIMAL_STR = /^-?[0-9]+$/; - var TWO_PWR_32_DBL = 4294967296; - var HALF_2_PWR_32 = 2147483648; - var SharedPbLong = class { /** - * Create a new instance with the given bits. + * Write a `string` value, length-delimited data converted to UTF-8 text. */ - constructor(lo, hi) { - this.lo = lo | 0; - this.hi = hi | 0; + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); + return this.raw(chunk); } /** - * Is this instance equal to 0? + * Write a `float` value, 32-bit floating point number. */ - isZero() { - return this.lo == 0 && this.hi == 0; + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); } /** - * Convert to a native number. + * Write a `double` value, a 64-bit floating point number. */ - toNumber() { - let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); - if (!Number.isSafeInteger(result)) - throw new Error("cannot convert to safe number"); - return result; + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); } - }; - var PbULong = class _PbULong extends SharedPbLong { /** - * Create instance from a `string`, `number` or `bigint`. + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. */ - static from(value) { - if (BI) - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - if (value == "") - throw new Error("string is no integer"); - value = BI.C(value); - case "number": - if (value === 0) - return this.ZERO; - value = BI.C(value); - case "bigint": - if (!value) - return this.ZERO; - if (value < BI.UMIN) - throw new Error("signed value for ulong"); - if (value > BI.UMAX) - throw new Error("ulong too large"); - BI.V.setBigUint64(0, value, true); - return new _PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); - } - else - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - value = value.trim(); - if (!RE_DECIMAL_STR.test(value)) - throw new Error("string is no integer"); - let [minus, lo, hi] = goog_varint_1.int64fromString(value); - if (minus) - throw new Error("signed value for ulong"); - return new _PbULong(lo, hi); - case "number": - if (value == 0) - return this.ZERO; - if (!Number.isSafeInteger(value)) - throw new Error("number is no integer"); - if (value < 0) - throw new Error("signed value for ulong"); - return new _PbULong(value, value / TWO_PWR_32_DBL); - } - throw new Error("unknown value " + typeof value); + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); } /** - * Convert to decimal string. + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. */ - toString() { - return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); } /** - * Convert to native bigint. + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. */ - toBigInt() { - assertBi(BI); - BI.V.setInt32(0, this.lo, true); - BI.V.setInt32(4, this.hi, true); - return BI.V.getBigUint64(0, true); + sint32(value) { + assert_1.assertInt32(value); + value = (value << 1 ^ value >> 31) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; } - }; - exports2.PbULong = PbULong; - PbULong.ZERO = new PbULong(0, 0); - var PbLong = class _PbLong extends SharedPbLong { /** - * Create instance from a `string`, `number` or `bigint`. + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. */ - static from(value) { - if (BI) - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - if (value == "") - throw new Error("string is no integer"); - value = BI.C(value); - case "number": - if (value === 0) - return this.ZERO; - value = BI.C(value); - case "bigint": - if (!value) - return this.ZERO; - if (value < BI.MIN) - throw new Error("signed long too small"); - if (value > BI.MAX) - throw new Error("signed long too large"); - BI.V.setBigInt64(0, value, true); - return new _PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); - } - else - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - value = value.trim(); - if (!RE_DECIMAL_STR.test(value)) - throw new Error("string is no integer"); - let [minus, lo, hi] = goog_varint_1.int64fromString(value); - if (minus) { - if (hi > HALF_2_PWR_32 || hi == HALF_2_PWR_32 && lo != 0) - throw new Error("signed long too small"); - } else if (hi >= HALF_2_PWR_32) - throw new Error("signed long too large"); - let pbl = new _PbLong(lo, hi); - return minus ? pbl.negate() : pbl; - case "number": - if (value == 0) - return this.ZERO; - if (!Number.isSafeInteger(value)) - throw new Error("number is no integer"); - return value > 0 ? new _PbLong(value, value / TWO_PWR_32_DBL) : new _PbLong(-value, -value / TWO_PWR_32_DBL).negate(); - } - throw new Error("unknown value " + typeof value); + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); } /** - * Do we have a minus sign? + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. */ - isNegative() { - return (this.hi & HALF_2_PWR_32) !== 0; + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); } /** - * Negate two's complement. - * Invert all the bits and add one to the result. + * Write a `int64` value, a signed 64-bit varint. */ - negate() { - let hi = ~this.hi, lo = this.lo; - if (lo) - lo = ~lo + 1; - else - hi += 1; - return new _PbLong(lo, hi); + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; } /** - * Convert to decimal string. + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. */ - toString() { - if (BI) - return this.toBigInt().toString(); - if (this.isNegative()) { - let n = this.negate(); - return "-" + goog_varint_1.int64toString(n.lo, n.hi); - } - return goog_varint_1.int64toString(this.lo, this.hi); + sint64(value) { + let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; } /** - * Convert to native bigint. + * Write a `uint64` value, an unsigned 64-bit varint. */ - toBigInt() { - assertBi(BI); - BI.V.setInt32(0, this.lo, true); - BI.V.setInt32(4, this.hi, true); - return BI.V.getBigInt64(0, true); + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + }; + exports2.BinaryWriter = BinaryWriter; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js +var require_json_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; + var defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0 + }; + var defaultsRead = { + ignoreUnknownFields: false + }; + function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; + } + exports2.jsonReadOptions = jsonReadOptions; + function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.jsonWriteOptions = jsonWriteOptions; + function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; + return c; + } + exports2.mergeJsonOptions = mergeJsonOptions; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js +var require_message_type_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MESSAGE_TYPE = void 0; + exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js +var require_lower_camel_case = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.lowerCamelCase = void 0; + function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == "_") { + capNext = true; + } else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } else if (i == 0) { + sb.push(next.toLowerCase()); + } else { + sb.push(next); + } + } + return sb.join(""); + } + exports2.lowerCamelCase = lowerCamelCase; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js +var require_reflection_info = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; + var lower_camel_case_1 = require_lower_camel_case(); + var ScalarType; + (function(ScalarType2) { + ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; + ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; + ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; + ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; + ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; + ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; + ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; + ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; + ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; + ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; + ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; + ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; + ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; + ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; + ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; + })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); + var LongType; + (function(LongType2) { + LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; + LongType2[LongType2["STRING"] = 1] = "STRING"; + LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; + })(LongType = exports2.LongType || (exports2.LongType = {})); + var RepeatType; + (function(RepeatType2) { + RepeatType2[RepeatType2["NO"] = 0] = "NO"; + RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; + RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; + })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); + function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; + return field; + } + exports2.normalizeFieldInfo = normalizeFieldInfo; + function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readFieldOptions = readFieldOptions; + function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readFieldOption = readFieldOption; + function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMessageOption = readMessageOption; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js +var require_oneof = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; + function isOneofGroup(any) { + if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === void 0) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; + } + } + exports2.isOneofGroup = isOneofGroup; + function getOneofValue(oneof, kind) { + return oneof[kind]; + } + exports2.getOneofValue = getOneofValue; + function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== void 0) { + oneof[kind] = value; + } + } + exports2.setOneofValue = setOneofValue; + function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== void 0 && kind !== void 0) { + oneof[kind] = value; + } + } + exports2.setUnknownOneofValue = setUnknownOneofValue; + function clearOneofValue(oneof) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; } - }; - exports2.PbLong = PbLong; - PbLong.ZERO = new PbLong(0, 0); + oneof.oneofKind = void 0; + } + exports2.clearOneofValue = clearOneofValue; + function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === void 0) { + return void 0; + } + return oneof[oneof.oneofKind]; + } + exports2.getSelectedOneofValue = getSelectedOneofValue; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js -var require_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js +var require_reflection_type_check = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryReader = exports2.binaryReadOptions = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); - var defaultsRead = { - readUnknownField: true, - readerFactory: (bytes) => new BinaryReader(bytes) - }; - function binaryReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.binaryReadOptions = binaryReadOptions; - var BinaryReader = class { - constructor(buf, textDecoder) { - this.varint64 = goog_varint_1.varint64read; - this.uint32 = goog_varint_1.varint32read; - this.buf = buf; - this.len = buf.length; - this.pos = 0; - this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); - this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { - fatal: true, - ignoreBOM: true - }); - } - /** - * Reads a tag - field number and wire type. - */ - tag() { - let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; - if (fieldNo <= 0 || wireType < 0 || wireType > 5) - throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); - return [fieldNo, wireType]; + exports2.ReflectionTypeCheck = void 0; + var reflection_info_1 = require_reflection_info(); + var oneof_1 = require_oneof(); + var ReflectionTypeCheck = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; } - /** - * Skip one element on the wire and return the skipped data. - * Supports WireType.StartGroup since v2.0.0-alpha.23. - */ - skip(wireType) { - let start = this.pos; - switch (wireType) { - case binary_format_contract_1.WireType.Varint: - while (this.buf[this.pos++] & 128) { + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); } - break; - case binary_format_contract_1.WireType.Bit64: - this.pos += 4; - case binary_format_contract_1.WireType.Bit32: - this.pos += 4; - break; - case binary_format_contract_1.WireType.LengthDelimited: - let len = this.uint32(); - this.pos += len; - break; - case binary_format_contract_1.WireType.StartGroup: - let t; - while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { - this.skip(t); + } else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; } - break; - default: - throw new Error("cant skip wire type " + wireType); + } } - this.assertBounds(); - return this.buf.subarray(start, this.pos); - } - /** - * Throws error if position in byte array is out of range. - */ - assertBounds() { - if (this.pos > this.len) - throw new RangeError("premature EOF"); + this.data = { req, known, oneofs: Object.values(oneofs) }; } /** - * Read a `int32` field, a signed 32 bit varint. + * Is the argument a valid message as specified by the + * reflection information? + * + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. + * + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. */ - int32() { - return this.uint32() | 0; + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === void 0 || typeof message != "object") + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + if (keys.some((k) => !data.known.includes(k))) + return false; + } + if (depth < 1) { + return true; + } + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === void 0) + continue; + const field = this.fields.find((f) => f.localName === group.oneofKind); + if (!field) + return false; + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + for (const field of this.fields) { + if (field.oneof !== void 0) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; + } + return true; } - /** - * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. - */ - sint32() { - let zze = this.uint32(); - return zze >>> 1 ^ -(zze & 1); + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === void 0) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != "object" || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } + break; + } + return true; } - /** - * Read a `int64` field, a signed 64-bit varint. - */ - int64() { - return new pb_long_1.PbLong(...this.varint64()); + message(arg, type2, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type2.isAssignable(arg, depth); + } + return type2.is(arg, depth); } - /** - * Read a `uint64` field, an unsigned 64-bit varint. - */ - uint64() { - return new pb_long_1.PbULong(...this.varint64()); + messages(arg, type2, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.isAssignable(arg[i], depth - 1)) + return false; + } else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.is(arg[i], depth - 1)) + return false; + } + return true; } - /** - * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. - */ - sint64() { - let [lo, hi] = this.varint64(); - let s = -(lo & 1); - lo = (lo >>> 1 | (hi & 1) << 31) ^ s; - hi = hi >>> 1 ^ s; - return new pb_long_1.PbLong(lo, hi); + scalar(arg, type2, longType) { + let argType = typeof arg; + switch (type2) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == "boolean"; + case reflection_info_1.ScalarType.STRING: + return argType == "string"; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == "number" && !isNaN(arg); + default: + return argType == "number" && Number.isInteger(arg); + } } - /** - * Read a `bool` field, a variant. - */ - bool() { - let [lo, hi] = this.varint64(); - return lo !== 0 || hi !== 0; + scalars(arg, type2, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type2, longType)) + return false; + } + return true; } - /** - * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. - */ - fixed32() { - return this.view.getUint32((this.pos += 4) - 4, true); + mapKeys(map2, type2, depth) { + let keys = Object.keys(map2); + switch (type2) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); + default: + return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + } } - /** - * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. - */ - sfixed32() { - return this.view.getInt32((this.pos += 4) - 4, true); + }; + exports2.ReflectionTypeCheck = ReflectionTypeCheck; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js +var require_reflection_long_convert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionLongConvert = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionLongConvert(long, type2) { + switch (type2) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + return long.toString(); } - /** - * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. - */ - fixed64() { - return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); + } + exports2.reflectionLongConvert = reflectionLongConvert; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js +var require_reflection_json_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonReader = void 0; + var json_typings_1 = require_json_typings(); + var base64_1 = require_base642(); + var reflection_info_1 = require_reflection_info(); + var pb_long_1 = require_pb_long(); + var assert_1 = require_assert(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var ReflectionJsonReader = class { + constructor(info6) { + this.info = info6; } - /** - * Read a `fixed64` field, a signed, fixed-length 64-bit integer. - */ - sfixed64() { - return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); + prepare() { + var _a; + if (this.fMap === void 0) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } + } } - /** - * Read a `float` field, 32-bit floating point number. - */ - float() { - return this.view.getFloat32((this.pos += 4) - 4, true); + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + } } /** - * Read a `double` field, a 64-bit floating point number. + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. */ - double() { - return this.view.getFloat64((this.pos += 8) - 8, true); + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + let target; + if (field.oneof) { + if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { + continue; + } + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } else { + target = message; + } + if (field.kind == "map") { + if (jsonValue === null) { + continue; + } + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + const fieldObj = target[localName]; + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + let val2; + switch (field.V.kind) { + case "message": + val2 = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val2; + } + } else if (field.repeat) { + if (jsonValue === null) + continue; + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + const fieldArr = target[localName]; + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val2; + switch (field.kind) { + case "message": + val2 = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name, jsonValue); + fieldArr.push(val2); + } + } else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { + this.assert(field.oneof === void 0, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + if (jsonValue === null) + continue; + let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + target[localName] = val2; + break; + case "scalar": + if (jsonValue === null) + continue; + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } + } } /** - * Read a `bytes` field, length-delimited arbitrary data. + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). */ - bytes() { - let len = this.uint32(); - let start = this.pos; - this.pos += len; - this.assertBounds(); - return this.buf.subarray(start, start + len); + enum(type2, json2, fieldName, ignoreUnknownFields) { + if (type2[0] == "google.protobuf.NullValue") + assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); + if (json2 === null) + return 0; + switch (typeof json2) { + case "number": + assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); + return json2; + case "string": + let localEnumName = json2; + if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) + localEnumName = json2.substring(type2[2].length); + let enumNumber = type2[1][localEnumName]; + if (typeof enumNumber === "undefined" && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); + return enumNumber; + } + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); } - /** - * Read a `string` field, length-delimited data converted to UTF-8 text. - */ - string() { - return this.textDecoder.decode(this.bytes()); + scalar(json2, type2, longType, fieldName) { + let e; + try { + switch (type2) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json2 === null) + return 0; + if (json2 === "NaN") + return Number.NaN; + if (json2 === "Infinity") + return Number.POSITIVE_INFINITY; + if (json2 === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json2 === "") { + e = "empty string"; + break; + } + if (typeof json2 == "string" && json2.trim().length !== json2.length) { + e = "extra whitespace"; + break; + } + if (typeof json2 != "string" && typeof json2 != "number") { + break; + } + let float2 = Number(json2); + if (Number.isNaN(float2)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float2)) { + e = "too large or small"; + break; + } + if (type2 == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float2); + return float2; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json2 === null) + return 0; + let int32; + if (typeof json2 == "number") + int32 = json2; + else if (json2 === "") + e = "empty string"; + else if (typeof json2 == "string") { + if (json2.trim().length !== json2.length) + e = "extra whitespace"; + else + int32 = Number(json2); + } + if (int32 === void 0) + break; + if (type2 == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json2 === null) + return false; + if (typeof json2 !== "boolean") + break; + return json2; + // string: + case reflection_info_1.ScalarType.STRING: + if (json2 === null) + return ""; + if (typeof json2 !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json2); + } catch (e2) { + e2 = "invalid UTF8"; + break; + } + return json2; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json2 === null || json2 === "") + return new Uint8Array(0); + if (typeof json2 !== "string") + break; + return base64_1.base64decode(json2); + } + } catch (error4) { + e = error4.message; + } + this.assert(false, fieldName + (e ? " - " + e : ""), json2); } }; - exports2.BinaryReader = BinaryReader; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js -var require_assert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; - function assert(condition, msg) { - if (!condition) { - throw new Error(msg); - } - } - exports2.assert = assert; - function assertNever2(value, msg) { - throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); - } - exports2.assertNever = assertNever2; - var FLOAT32_MAX = 34028234663852886e22; - var FLOAT32_MIN = -34028234663852886e22; - var UINT32_MAX = 4294967295; - var INT32_MAX = 2147483647; - var INT32_MIN = -2147483648; - function assertInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid int 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) - throw new Error("invalid int 32: " + arg); - } - exports2.assertInt32 = assertInt32; - function assertUInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid uint 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) - throw new Error("invalid uint 32: " + arg); - } - exports2.assertUInt32 = assertUInt32; - function assertFloat32(arg) { - if (typeof arg !== "number") - throw new Error("invalid float 32: " + typeof arg); - if (!Number.isFinite(arg)) - return; - if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) - throw new Error("invalid float 32: " + arg); - } - exports2.assertFloat32 = assertFloat32; + exports2.ReflectionJsonReader = ReflectionJsonReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js -var require_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js +var require_reflection_json_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; + exports2.ReflectionJsonWriter = void 0; + var base64_1 = require_base642(); var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); + var reflection_info_1 = require_reflection_info(); var assert_1 = require_assert(); - var defaultsWrite = { - writeUnknownFields: true, - writerFactory: () => new BinaryWriter() - }; - function binaryWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.binaryWriteOptions = binaryWriteOptions; - var BinaryWriter = class { - constructor(textEncoder) { - this.stack = []; - this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); - this.chunks = []; - this.buf = []; + var ReflectionJsonWriter = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; } /** - * Return all bytes written and reset this writer. + * Converts the message to a JSON object, based on the field descriptors. */ - finish() { - this.chunks.push(new Uint8Array(this.buf)); - let len = 0; - for (let i = 0; i < this.chunks.length; i++) - len += this.chunks[i].length; - let bytes = new Uint8Array(len); - let offset = 0; - for (let i = 0; i < this.chunks.length; i++) { - bytes.set(this.chunks[i], offset); - offset += this.chunks[i].length; + write(message, options) { + const json2 = {}, source = message; + for (const field of this.fields) { + if (!field.oneof) { + let jsonValue2 = this.field(field, source[field.localName], options); + if (jsonValue2 !== void 0) + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; + continue; + } + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; + const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== void 0); + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; } - this.chunks = []; - return bytes; - } - /** - * Start a new fork for length-delimited data like a message - * or a packed repeated field. - * - * Must be joined later with `join()`. - */ - fork() { - this.stack.push({ chunks: this.chunks, buf: this.buf }); - this.chunks = []; - this.buf = []; - return this; - } - /** - * Join the last fork. Write its length and bytes, then - * return to the previous state. - */ - join() { - let chunk = this.finish(); - let prev = this.stack.pop(); - if (!prev) - throw new Error("invalid state, fork stack empty"); - this.chunks = prev.chunks; - this.buf = prev.buf; - this.uint32(chunk.byteLength); - return this.raw(chunk); - } - /** - * Writes a tag (field number and wire type). - * - * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. - * - * Generated code should compute the tag ahead of time and call `uint32()`. - */ - tag(fieldNo, type2) { - return this.uint32((fieldNo << 3 | type2) >>> 0); + return json2; } - /** - * Write a chunk of raw bytes. - */ - raw(chunk) { - if (this.buf.length) { - this.chunks.push(new Uint8Array(this.buf)); - this.buf = []; + field(field, value, options) { + let jsonValue = void 0; + if (field.kind == "map") { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); + const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + } + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); + const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val2 = this.message(messageType, value[i], field.name, options); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + } + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } } - this.chunks.push(chunk); - return this; + return jsonValue; } /** - * Write a `uint32` value, an unsigned 32 bit varint. + * Returns `null` as the default for google.protobuf.NullValue. */ - uint32(value) { - assert_1.assertUInt32(value); - while (value > 127) { - this.buf.push(value & 127 | 128); - value = value >>> 7; + enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type2[0] == "google.protobuf.NullValue") + return !emitDefaultValues && !optional ? void 0 : null; + if (value === void 0) { + assert_1.assert(optional); + return void 0; } - this.buf.push(value); - return this; - } - /** - * Write a `int32` value, a signed 32 bit varint. - */ - int32(value) { - assert_1.assertInt32(value); - goog_varint_1.varint32write(value, this.buf); - return this; - } - /** - * Write a `bool` value, a variant. - */ - bool(value) { - this.buf.push(value ? 1 : 0); - return this; - } - /** - * Write a `bytes` value, length-delimited arbitrary data. - */ - bytes(value) { - this.uint32(value.byteLength); - return this.raw(value); - } - /** - * Write a `string` value, length-delimited data converted to UTF-8 text. - */ - string(value) { - let chunk = this.textEncoder.encode(value); - this.uint32(chunk.byteLength); - return this.raw(chunk); - } - /** - * Write a `float` value, 32-bit floating point number. - */ - float(value) { - assert_1.assertFloat32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setFloat32(0, value, true); - return this.raw(chunk); - } - /** - * Write a `double` value, a 64-bit floating point number. - */ - double(value) { - let chunk = new Uint8Array(8); - new DataView(chunk.buffer).setFloat64(0, value, true); - return this.raw(chunk); - } - /** - * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. - */ - fixed32(value) { - assert_1.assertUInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setUint32(0, value, true); - return this.raw(chunk); - } - /** - * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. - */ - sfixed32(value) { - assert_1.assertInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setInt32(0, value, true); - return this.raw(chunk); - } - /** - * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. - */ - sint32(value) { - assert_1.assertInt32(value); - value = (value << 1 ^ value >> 31) >>> 0; - goog_varint_1.varint32write(value, this.buf); - return this; - } - /** - * Write a `fixed64` value, a signed, fixed-length 64-bit integer. - */ - sfixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbLong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); - } - /** - * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. - */ - fixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbULong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); - } - /** - * Write a `int64` value, a signed 64-bit varint. - */ - int64(value) { - let long = pb_long_1.PbLong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + if (value === 0 && !emitDefaultValues && !optional) + return void 0; + assert_1.assert(typeof value == "number"); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type2[1].hasOwnProperty(value)) + return value; + if (type2[2]) + return type2[2] + type2[1][value]; + return type2[1][value]; } - /** - * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. - */ - sint64(value) { - let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; - goog_varint_1.varint64write(lo, hi, this.buf); - return this; + message(type2, value, fieldName, options) { + if (value === void 0) + return options.emitDefaultValues ? null : void 0; + return type2.internalJsonWrite(value, options); } - /** - * Write a `uint64` value, an unsigned 64-bit varint. - */ - uint64(value) { - let long = pb_long_1.PbULong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + scalar(type2, value, fieldName, optional, emitDefaultValues) { + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + const ed = emitDefaultValues || optional; + switch (type2) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assert(typeof value == "number"); + if (Number.isNaN(value)) + return "NaN"; + if (value === Number.POSITIVE_INFINITY) + return "Infinity"; + if (value === Number.NEGATIVE_INFINITY) + return "-Infinity"; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? "" : void 0; + assert_1.assert(typeof value == "string"); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : void 0; + assert_1.assert(typeof value == "boolean"); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return void 0; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return void 0; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : void 0; + return base64_1.base64encode(value); + } } }; - exports2.BinaryWriter = BinaryWriter; + exports2.ReflectionJsonWriter = ReflectionJsonWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js -var require_json_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js +var require_reflection_scalar_default = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; - var defaultsWrite = { - emitDefaultValues: false, - enumAsInteger: false, - useProtoFieldName: false, - prettySpaces: 0 - }; - var defaultsRead = { - ignoreUnknownFields: false - }; - function jsonReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.jsonReadOptions = jsonReadOptions; - function jsonWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.jsonWriteOptions = jsonWriteOptions; - function mergeJsonOptions(a, b) { - var _a, _b; - let c = Object.assign(Object.assign({}, a), b); - c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; - return c; + exports2.reflectionScalarDefault = void 0; + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var pb_long_1 = require_pb_long(); + function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { + switch (type2) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + return 0; + } } - exports2.mergeJsonOptions = mergeJsonOptions; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js -var require_message_type_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MESSAGE_TYPE = void 0; - exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); + exports2.reflectionScalarDefault = reflectionScalarDefault; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js -var require_lower_camel_case = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js +var require_reflection_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.lowerCamelCase = void 0; - function lowerCamelCase(snakeCase) { - let capNext = false; - const sb = []; - for (let i = 0; i < snakeCase.length; i++) { - let next = snakeCase.charAt(i); - if (next == "_") { - capNext = true; - } else if (/\d/.test(next)) { - sb.push(next); - capNext = true; - } else if (capNext) { - sb.push(next.toUpperCase()); - capNext = false; - } else if (i == 0) { - sb.push(next.toLowerCase()); - } else { - sb.push(next); + exports2.ReflectionBinaryReader = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var ReflectionBinaryReader = class { + constructor(info6) { + this.info = info6; + } + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); } } - return sb.join(""); - } - exports2.lowerCamelCase = lowerCamelCase; + /** + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(reader, message, options, length) { + this.prepare(); + const end = length === void 0 ? reader.len : reader.pos + length; + while (reader.pos < end) { + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; + } + let target = message, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + target = target[field.oneof]; + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : void 0; + if (repeated) { + let arr = target[localName]; + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } else + arr.push(this.scalar(reader, T, L)); + } else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + target[localName][mapKey] = mapVal; + break; + } + } + } + /** + * Read a map field, expecting key field = 1, value field = 2 + */ + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = void 0; + let val2 = void 0; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val2 = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val2 = reader.int32(); + break; + case "message": + val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } + } + if (key === void 0) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val2 === void 0) + switch (field.V.kind) { + case "scalar": + val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val2 = 0; + break; + case "message": + val2 = field.V.T().create(); + break; + } + return [key, val2]; + } + scalar(reader, type2, longType) { + switch (type2) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } + } + }; + exports2.ReflectionBinaryReader = ReflectionBinaryReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js -var require_reflection_info = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js +var require_reflection_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; - var lower_camel_case_1 = require_lower_camel_case(); - var ScalarType; - (function(ScalarType2) { - ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; - ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; - ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; - ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; - ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; - ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; - ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; - ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; - ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; - ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; - ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; - ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; - ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; - ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; - ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; - })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); - var LongType; - (function(LongType2) { - LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; - LongType2[LongType2["STRING"] = 1] = "STRING"; - LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; - })(LongType = exports2.LongType || (exports2.LongType = {})); - var RepeatType; - (function(RepeatType2) { - RepeatType2[RepeatType2["NO"] = 0] = "NO"; - RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; - RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; - })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); - function normalizeFieldInfo(field) { - var _a, _b, _c, _d; - field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); - field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); - field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; - field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; - return field; - } - exports2.normalizeFieldInfo = normalizeFieldInfo; - function readFieldOptions(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readFieldOptions = readFieldOptions; - function readFieldOption(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; + exports2.ReflectionBinaryWriter = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); + var pb_long_1 = require_pb_long(); + var ReflectionBinaryWriter = class { + constructor(info6) { + this.info = info6; + } + prepare() { + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); + } + } + /** + * Writes the message to binary format. + */ + write(message, writer, options) { + this.prepare(); + for (const field of this.fields) { + let value, emitDefault, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; + value = group[localName]; + emitDefault = true; + } else { + value = message[localName]; + emitDefault = false; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } else if (value === void 0) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == "object" && value !== null); + for (const [key, val2] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val2); + break; + } + } + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); + } + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); + break; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == "true" || key == "false"); + keyValue = key == "true"; + break; + } + this.scalar(writer, field.K, 1, keyValue, true); + switch (field.V.kind) { + case "scalar": + this.scalar(writer, field.V.T, 2, value, true); + break; + case "enum": + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; + case "message": + this.message(writer, options, field.V.T(), 2, value); + break; + } + writer.join(); } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + message(writer, options, handler, fieldNo, value) { + if (value === void 0) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readFieldOption = readFieldOption; - function readMessageOption(messageType, extensionName, extensionType) { - const options = messageType.options; - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + /** + * Write a single scalar value. + */ + scalar(writer, type2, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type2, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); + } } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readMessageOption = readMessageOption; + /** + * Write an array of scalar values in packed format. + */ + packed(writer, type2, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let [, method] = this.scalarInfo(type2); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + writer.join(); + } + /** + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. + */ + scalarInfo(type2, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === void 0; + let d = value === 0; + switch (type2) { + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; + case reflection_info_1.ScalarType.STRING: + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; + case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; + case reflection_info_1.ScalarType.FLOAT: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; + case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; + case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; + case reflection_info_1.ScalarType.SINT32: + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; + } + return [t, m, i || d]; + } + }; + exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js -var require_oneof = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js +var require_reflection_create = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; - function isOneofGroup(any) { - if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { - return false; - } - switch (typeof any.oneofKind) { - case "string": - if (any[any.oneofKind] === void 0) - return false; - return Object.keys(any).length == 2; - case "undefined": - return Object.keys(any).length == 1; - default: - return false; - } - } - exports2.isOneofGroup = isOneofGroup; - function getOneofValue(oneof, kind) { - return oneof[kind]; - } - exports2.getOneofValue = getOneofValue; - function setOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== void 0) { - oneof[kind] = value; - } - } - exports2.setOneofValue = setOneofValue; - function setUnknownOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== void 0 && kind !== void 0) { - oneof[kind] = value; - } - } - exports2.setUnknownOneofValue = setUnknownOneofValue; - function clearOneofValue(oneof) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = void 0; - } - exports2.clearOneofValue = clearOneofValue; - function getSelectedOneofValue(oneof) { - if (oneof.oneofKind === void 0) { - return void 0; + exports2.reflectionCreate = void 0; + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var message_type_contract_1 = require_message_type_contract(); + function reflectionCreate(type2) { + const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); + for (let field of type2.fields) { + let name = field.localName; + if (field.opt) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: void 0 }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } } - return oneof[oneof.oneofKind]; + return msg; } - exports2.getSelectedOneofValue = getSelectedOneofValue; + exports2.reflectionCreate = reflectionCreate; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js -var require_reflection_type_check = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js +var require_reflection_merge_partial = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionTypeCheck = void 0; - var reflection_info_1 = require_reflection_info(); - var oneof_1 = require_oneof(); - var ReflectionTypeCheck = class { - constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; - } - prepare() { - if (this.data) - return; - const req = [], known = [], oneofs = []; - for (let field of this.fields) { - if (field.oneof) { - if (!oneofs.includes(field.oneof)) { - oneofs.push(field.oneof); - req.push(field.oneof); - known.push(field.oneof); - } - } else { - known.push(field.localName); - switch (field.kind) { - case "scalar": - case "enum": - if (!field.opt || field.repeat) - req.push(field.localName); - break; - case "message": - if (field.repeat) - req.push(field.localName); - break; - case "map": - req.push(field.localName); - break; - } + exports2.reflectionMergePartial = void 0; + function reflectionMergePartial(info6, target, source) { + let fieldValue, input = source, output; + for (let field of info6.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { + continue; } - } - this.data = { req, known, oneofs: Object.values(oneofs) }; - } - /** - * Is the argument a valid message as specified by the - * reflection information? - * - * Checks all field types recursively. The `depth` - * specifies how deep into the structure the check will be. - * - * With a depth of 0, only the presence of fields - * is checked. - * - * With a depth of 1 or more, the field types are checked. - * - * With a depth of 2 or more, the members of map, repeated - * and message fields are checked. - * - * Message fields will be checked recursively with depth - 1. - * - * The number of map entries / repeated values being checked - * is < depth. - */ - is(message, depth, allowExcessProperties = false) { - if (depth < 0) - return true; - if (message === null || message === void 0 || typeof message != "object") - return false; - this.prepare(); - let keys = Object.keys(message), data = this.data; - if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) - return false; - if (!allowExcessProperties) { - if (keys.some((k) => !data.known.includes(k))) - return false; - } - if (depth < 1) { - return true; - } - for (const name of data.oneofs) { - const group = message[name]; - if (!oneof_1.isOneofGroup(group)) - return false; - if (group.oneofKind === void 0) + fieldValue = group[name]; + output = target[field.oneof]; + output.oneofKind = group.oneofKind; + if (fieldValue == void 0) { + delete output[name]; continue; - const field = this.fields.find((f) => f.localName === group.oneofKind); - if (!field) - return false; - if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) - return false; - } - for (const field of this.fields) { - if (field.oneof !== void 0) + } + } else { + fieldValue = input[name]; + output = target; + if (fieldValue == void 0) { continue; - if (!this.field(message[field.localName], field, allowExcessProperties, depth)) - return false; + } } - return true; - } - field(arg, field, allowExcessProperties, depth) { - let repeated = field.repeat; + if (field.repeat) + output[name].length = fieldValue.length; switch (field.kind) { case "scalar": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, field.T, depth, field.L); - return this.scalar(arg, field.T, field.L); case "enum": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); - return this.scalar(arg, reflection_info_1.ScalarType.INT32); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; + else + output[name] = fieldValue; + break; case "message": - if (arg === void 0) - return true; - if (repeated) - return this.messages(arg, field.T(), allowExcessProperties, depth); - return this.message(arg, field.T(), allowExcessProperties, depth); + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === void 0) + output[name] = T.create(fieldValue); + else + T.mergePartial(output[name], fieldValue); + break; case "map": - if (typeof arg != "object" || arg === null) - return false; - if (depth < 2) - return true; - if (!this.mapKeys(arg, field.K, depth)) - return false; switch (field.V.kind) { case "scalar": - return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); case "enum": - return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + Object.assign(output[name], fieldValue); + break; case "message": - return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + let T2 = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T2.create(fieldValue[k]); + break; } break; } - return true; - } - message(arg, type2, allowExcessProperties, depth) { - if (allowExcessProperties) { - return type2.isAssignable(arg, depth); - } - return type2.is(arg, depth); - } - messages(arg, type2, allowExcessProperties, depth) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (allowExcessProperties) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.isAssignable(arg[i], depth - 1)) - return false; - } else { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.is(arg[i], depth - 1)) - return false; - } - return true; - } - scalar(arg, type2, longType) { - let argType = typeof arg; - switch (type2) { - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - switch (longType) { - case reflection_info_1.LongType.BIGINT: - return argType == "bigint"; - case reflection_info_1.LongType.NUMBER: - return argType == "number" && !isNaN(arg); - default: - return argType == "string"; - } - case reflection_info_1.ScalarType.BOOL: - return argType == "boolean"; - case reflection_info_1.ScalarType.STRING: - return argType == "string"; - case reflection_info_1.ScalarType.BYTES: - return arg instanceof Uint8Array; - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return argType == "number" && !isNaN(arg); - default: - return argType == "number" && Number.isInteger(arg); - } - } - scalars(arg, type2, depth, longType) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (Array.isArray(arg)) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!this.scalar(arg[i], type2, longType)) - return false; - } - return true; - } - mapKeys(map2, type2, depth) { - let keys = Object.keys(map2); - switch (type2) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); - case reflection_info_1.ScalarType.BOOL: - return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); - default: - return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); - } } - }; - exports2.ReflectionTypeCheck = ReflectionTypeCheck; + } + exports2.reflectionMergePartial = reflectionMergePartial; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js -var require_reflection_long_convert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js +var require_reflection_equals = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionLongConvert = void 0; + exports2.reflectionEquals = void 0; var reflection_info_1 = require_reflection_info(); - function reflectionLongConvert(long, type2) { - switch (type2) { - case reflection_info_1.LongType.BIGINT: - return long.toBigInt(); - case reflection_info_1.LongType.NUMBER: - return long.toNumber(); - default: - return long.toString(); + function reflectionEquals(info6, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info6.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) + return false; + break; + } } + return true; + } + exports2.reflectionEquals = reflectionEquals; + var objectValues = Object.values; + function primitiveEq(type2, a, b) { + if (a === b) + return true; + if (type2 !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; + } + function repeatedPrimitiveEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type2, a[i], b[i])) + return false; + return true; + } + function repeatedMsgEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type2.equals(a[i], b[i])) + return false; + return true; } - exports2.reflectionLongConvert = reflectionLongConvert; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js -var require_reflection_json_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js +var require_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonReader = void 0; - var json_typings_1 = require_json_typings(); - var base64_1 = require_base642(); + exports2.MessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); var reflection_info_1 = require_reflection_info(); - var pb_long_1 = require_pb_long(); - var assert_1 = require_assert(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var ReflectionJsonReader = class { - constructor(info6) { - this.info = info6; - } - prepare() { - var _a; - if (this.fMap === void 0) { - this.fMap = {}; - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - for (const field of fieldsInput) { - this.fMap[field.name] = field; - this.fMap[field.jsonName] = field; - this.fMap[field.localName] = field; - } - } + var reflection_type_check_1 = require_reflection_type_check(); + var reflection_json_reader_1 = require_reflection_json_reader(); + var reflection_json_writer_1 = require_reflection_json_writer(); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + var reflection_create_1 = require_reflection_create(); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + var json_typings_1 = require_json_typings(); + var json_format_contract_1 = require_json_format_contract(); + var reflection_equals_1 = require_reflection_equals(); + var binary_writer_1 = require_binary_writer(); + var binary_reader_1 = require_binary_reader(); + var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); + var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; + var MessageType = class { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + messageTypeDescriptor.value = this; + this.messagePrototype = Object.create(null, baseDescriptors); + this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); + this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); + this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } - // Cannot parse JSON for #. - assert(condition, fieldName, jsonValue) { - if (!condition) { - let what = json_typings_1.typeofJsonValue(jsonValue); - if (what == "number" || what == "boolean") - what = jsonValue.toString(); - throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== void 0) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); } + return message; } /** - * Reads a message from canonical JSON format into the target message. - * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. + * Clone the message. * - * If a message field is already present, it will be merged with the - * new data. + * Unknown fields are discarded. */ - read(input, message, options) { - this.prepare(); - const oneofsHandled = []; - for (const [jsonKey, jsonValue] of Object.entries(input)) { - const field = this.fMap[jsonKey]; - if (!field) { - if (!options.ignoreUnknownFields) - throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); - continue; - } - const localName = field.localName; - let target; - if (field.oneof) { - if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { - continue; - } - if (oneofsHandled.includes(field.oneof)) - throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); - oneofsHandled.push(field.oneof); - target = message[field.oneof] = { - oneofKind: localName - }; - } else { - target = message; - } - if (field.kind == "map") { - if (jsonValue === null) { - continue; - } - this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); - const fieldObj = target[localName]; - for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { - this.assert(jsonObjValue !== null, field.name + " map value", null); - let val2; - switch (field.V.kind) { - case "message": - val2 = field.V.T().internalJsonRead(jsonObjValue, options); - break; - case "enum": - val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); - let key = jsonObjKey; - if (field.K == reflection_info_1.ScalarType.BOOL) - key = key == "true" ? true : key == "false" ? false : key; - key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); - fieldObj[key] = val2; - } - } else if (field.repeat) { - if (jsonValue === null) - continue; - this.assert(Array.isArray(jsonValue), field.name, jsonValue); - const fieldArr = target[localName]; - for (const jsonItem of jsonValue) { - this.assert(jsonItem !== null, field.name, null); - let val2; - switch (field.kind) { - case "message": - val2 = field.T().internalJsonRead(jsonItem, options); - break; - case "enum": - val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonItem, field.T, field.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name, jsonValue); - fieldArr.push(val2); - } - } else { - switch (field.kind) { - case "message": - if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { - this.assert(field.oneof === void 0, field.name + " (oneof member)", null); - continue; - } - target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); - break; - case "enum": - if (jsonValue === null) - continue; - let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - target[localName] = val2; - break; - case "scalar": - if (jsonValue === null) - continue; - target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); - break; - } - } - } + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; } /** - * Returns `false` for unrecognized string representations. - * - * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. */ - enum(type2, json2, fieldName, ignoreUnknownFields) { - if (type2[0] == "google.protobuf.NullValue") - assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); - if (json2 === null) - return 0; - switch (typeof json2) { - case "number": - assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); - return json2; - case "string": - let localEnumName = json2; - if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) - localEnumName = json2.substring(type2[2].length); - let enumNumber = type2[1][localEnumName]; - if (typeof enumNumber === "undefined" && ignoreUnknownFields) { - return false; - } - assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); - return enumNumber; - } - assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); } - scalar(json2, type2, longType, fieldName) { - let e; - try { - switch (type2) { - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - if (json2 === null) - return 0; - if (json2 === "NaN") - return Number.NaN; - if (json2 === "Infinity") - return Number.POSITIVE_INFINITY; - if (json2 === "-Infinity") - return Number.NEGATIVE_INFINITY; - if (json2 === "") { - e = "empty string"; - break; - } - if (typeof json2 == "string" && json2.trim().length !== json2.length) { - e = "extra whitespace"; - break; - } - if (typeof json2 != "string" && typeof json2 != "number") { - break; - } - let float2 = Number(json2); - if (Number.isNaN(float2)) { - e = "not a number"; - break; - } - if (!Number.isFinite(float2)) { - e = "too large or small"; - break; - } - if (type2 == reflection_info_1.ScalarType.FLOAT) - assert_1.assertFloat32(float2); - return float2; - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - if (json2 === null) - return 0; - let int32; - if (typeof json2 == "number") - int32 = json2; - else if (json2 === "") - e = "empty string"; - else if (typeof json2 == "string") { - if (json2.trim().length !== json2.length) - e = "extra whitespace"; - else - int32 = Number(json2); - } - if (int32 === void 0) - break; - if (type2 == reflection_info_1.ScalarType.UINT32) - assert_1.assertUInt32(int32); - else - assert_1.assertInt32(int32); - return int32; - // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.UINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); - // bool: - case reflection_info_1.ScalarType.BOOL: - if (json2 === null) - return false; - if (typeof json2 !== "boolean") - break; - return json2; - // string: - case reflection_info_1.ScalarType.STRING: - if (json2 === null) - return ""; - if (typeof json2 !== "string") { - e = "extra whitespace"; - break; - } - try { - encodeURIComponent(json2); - } catch (e2) { - e2 = "invalid UTF8"; - break; - } - return json2; - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - if (json2 === null || json2 === "") - return new Uint8Array(0); - if (typeof json2 !== "string") - break; - return base64_1.base64decode(json2); - } - } catch (error4) { - e = error4.message; - } - this.assert(false, fieldName + (e ? " - " + e : ""), json2); + /** + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); } - }; - exports2.ReflectionJsonReader = ReflectionJsonReader; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js -var require_reflection_json_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonWriter = void 0; - var base64_1 = require_base642(); - var pb_long_1 = require_pb_long(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var ReflectionJsonWriter = class { - constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + /** + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); } /** - * Converts the message to a JSON object, based on the field descriptors. + * Copy partial data into the target message. */ - write(message, options) { - const json2 = {}, source = message; - for (const field of this.fields) { - if (!field.oneof) { - let jsonValue2 = this.field(field, source[field.localName], options); - if (jsonValue2 !== void 0) - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; - continue; - } - const group = source[field.oneof]; - if (group.oneofKind !== field.localName) - continue; - const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; - let jsonValue = this.field(field, group[field.localName], opt); - assert_1.assert(jsonValue !== void 0); - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; - } - return json2; + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); } - field(field, value, options) { - let jsonValue = void 0; - if (field.kind == "map") { - assert_1.assert(typeof value == "object" && value !== null); - const jsonObj = {}; - switch (field.V.kind) { - case "scalar": - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "message": - const messageType = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.message(messageType, entryValue, field.name, options); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "enum": - const enumInfo = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); - const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - } - if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) - jsonValue = jsonObj; - } else if (field.repeat) { - assert_1.assert(Array.isArray(value)); - const jsonArr = []; - switch (field.kind) { - case "scalar": - for (let i = 0; i < value.length; i++) { - const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "enum": - const enumInfo = field.T(); - for (let i = 0; i < value.length; i++) { - assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); - const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "message": - const messageType = field.T(); - for (let i = 0; i < value.length; i++) { - const val2 = this.message(messageType, value[i], field.name, options); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - } - if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) - jsonValue = jsonArr; - } else { - switch (field.kind) { - case "scalar": - jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); - break; - case "enum": - jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); - break; - case "message": - jsonValue = this.message(field.T(), value, field.name, options); - break; - } - } - return jsonValue; + /** + * Create a new message from binary format. + */ + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + } + /** + * Read a new message from a JSON value. + */ + fromJson(json2, options) { + return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + } + /** + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. + */ + fromJsonString(json2, options) { + let value = JSON.parse(json2); + return this.fromJson(value, options); + } + /** + * Write the message to canonical JSON value. + */ + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + } + /** + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` + */ + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); } /** - * Returns `null` as the default for google.protobuf.NullValue. + * Write the message to binary format. */ - enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { - if (type2[0] == "google.protobuf.NullValue") - return !emitDefaultValues && !optional ? void 0 : null; - if (value === void 0) { - assert_1.assert(optional); - return void 0; + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + } + /** + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. + */ + internalJsonRead(json2, options, target) { + if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json2, message, options); + return message; } - if (value === 0 && !emitDefaultValues && !optional) - return void 0; - assert_1.assert(typeof value == "number"); - assert_1.assert(Number.isInteger(value)); - if (enumAsInteger || !type2[1].hasOwnProperty(value)) - return value; - if (type2[2]) - return type2[2] + type2[1][value]; - return type2[1][value]; + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); } - message(type2, value, fieldName, options) { - if (value === void 0) - return options.emitDefaultValues ? null : void 0; - return type2.internalJsonWrite(value, options); + /** + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). + * + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); } - scalar(type2, value, fieldName, optional, emitDefaultValues) { - if (value === void 0) { - assert_1.assert(optional); - return void 0; - } - const ed = emitDefaultValues || optional; - switch (type2) { - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertInt32(value); - return value; - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertUInt32(value); - return value; - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.FLOAT: - assert_1.assertFloat32(value); - case reflection_info_1.ScalarType.DOUBLE: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assert(typeof value == "number"); - if (Number.isNaN(value)) - return "NaN"; - if (value === Number.POSITIVE_INFINITY) - return "Infinity"; - if (value === Number.NEGATIVE_INFINITY) - return "-Infinity"; - return value; - // string: - case reflection_info_1.ScalarType.STRING: - if (value === "") - return ed ? "" : void 0; - assert_1.assert(typeof value == "string"); - return value; - // bool: - case reflection_info_1.ScalarType.BOOL: - if (value === false) - return ed ? false : void 0; - assert_1.assert(typeof value == "boolean"); - return value; - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let ulong = pb_long_1.PbULong.from(value); - if (ulong.isZero() && !ed) - return void 0; - return ulong.toString(); - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let long = pb_long_1.PbLong.from(value); - if (long.isZero() && !ed) - return void 0; - return long.toString(); - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - assert_1.assert(value instanceof Uint8Array); - if (!value.byteLength) - return ed ? "" : void 0; - return base64_1.base64encode(value); - } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. + * + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. + */ + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; + } + /** + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. + * + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. + */ + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; } }; - exports2.ReflectionJsonWriter = ReflectionJsonWriter; + exports2.MessageType = MessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js -var require_reflection_scalar_default = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js +var require_reflection_contains_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionScalarDefault = void 0; - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var pb_long_1 = require_pb_long(); - function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { - switch (type2) { - case reflection_info_1.ScalarType.BOOL: - return false; - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return 0; - case reflection_info_1.ScalarType.BYTES: - return new Uint8Array(0); - case reflection_info_1.ScalarType.STRING: - return ""; - default: - return 0; - } + exports2.containsMessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; } - exports2.reflectionScalarDefault = reflectionScalarDefault; + exports2.containsMessageType = containsMessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js -var require_reflection_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js +var require_enum_object = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryReader = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var ReflectionBinaryReader = class { - constructor(info6) { - this.info = info6; - } - prepare() { - var _a; - if (!this.fieldNoToField) { - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); - } - } - /** - * Reads a message from binary format into the target message. - * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. - * - * If a message field is already present, it will be merged with the - * new data. - */ - read(reader, message, options, length) { - this.prepare(); - const end = length === void 0 ? reader.len : reader.pos + length; - while (reader.pos < end) { - const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); - if (!field) { - let u = options.readUnknownField; - if (u == "throw") - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); - continue; - } - let target = message, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - target = target[field.oneof]; - if (target.oneofKind !== localName) - target = message[field.oneof] = { - oneofKind: localName - }; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - let L = field.kind == "scalar" ? field.L : void 0; - if (repeated) { - let arr = target[localName]; - if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { - let e = reader.uint32() + reader.pos; - while (reader.pos < e) - arr.push(this.scalar(reader, T, L)); - } else - arr.push(this.scalar(reader, T, L)); - } else - target[localName] = this.scalar(reader, T, L); - break; - case "message": - if (repeated) { - let arr = target[localName]; - let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); - arr.push(msg); - } else - target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); - break; - case "map": - let [mapKey, mapVal] = this.mapEntry(field, reader, options); - target[localName][mapKey] = mapVal; - break; - } - } + exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; + function isEnumObject(arg) { + if (typeof arg != "object" || arg === null) { + return false; } - /** - * Read a map field, expecting key field = 1, value field = 2 - */ - mapEntry(field, reader, options) { - let length = reader.uint32(); - let end = reader.pos + length; - let key = void 0; - let val2 = void 0; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case 1: - if (field.K == reflection_info_1.ScalarType.BOOL) - key = reader.bool().toString(); - else - key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); - break; - case 2: - switch (field.V.kind) { - case "scalar": - val2 = this.scalar(reader, field.V.T, field.V.L); - break; - case "enum": - val2 = reader.int32(); - break; - case "message": - val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); - break; - } - break; - default: - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); - } - } - if (key === void 0) { - let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); - key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; - } - if (val2 === void 0) - switch (field.V.kind) { - case "scalar": - val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); - break; - case "enum": - val2 = 0; - break; - case "message": - val2 = field.V.T().create(); - break; - } - return [key, val2]; + if (!arg.hasOwnProperty(0)) { + return false; } - scalar(reader, type2, longType) { - switch (type2) { - case reflection_info_1.ScalarType.INT32: - return reader.int32(); - case reflection_info_1.ScalarType.STRING: - return reader.string(); - case reflection_info_1.ScalarType.BOOL: - return reader.bool(); - case reflection_info_1.ScalarType.DOUBLE: - return reader.double(); - case reflection_info_1.ScalarType.FLOAT: - return reader.float(); - case reflection_info_1.ScalarType.INT64: - return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); - case reflection_info_1.ScalarType.UINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); - case reflection_info_1.ScalarType.FIXED32: - return reader.fixed32(); - case reflection_info_1.ScalarType.BYTES: - return reader.bytes(); - case reflection_info_1.ScalarType.UINT32: - return reader.uint32(); - case reflection_info_1.ScalarType.SFIXED32: - return reader.sfixed32(); - case reflection_info_1.ScalarType.SFIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); - case reflection_info_1.ScalarType.SINT32: - return reader.sint32(); - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + let nam = arg[num]; + if (nam === void 0) + return false; + if (arg[nam] !== num) + return false; + } else { + let num2 = arg[k]; + if (num2 === void 0) + return false; + if (typeof num2 !== "number") + return false; + if (arg[num2] === void 0) + return false; } } - }; - exports2.ReflectionBinaryReader = ReflectionBinaryReader; + return true; + } + exports2.isEnumObject = isEnumObject; + function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; + } + exports2.listEnumValues = listEnumValues; + function listEnumNames(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.name); + } + exports2.listEnumNames = listEnumNames; + function listEnumNumbers(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + } + exports2.listEnumNumbers = listEnumNumbers; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var json_typings_1 = require_json_typings(); + Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { + return json_typings_1.typeofJsonValue; + } }); + Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { + return json_typings_1.isJsonObject; + } }); + var base64_1 = require_base642(); + Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { + return base64_1.base64decode; + } }); + Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { + return base64_1.base64encode; + } }); + var protobufjs_utf8_1 = require_protobufjs_utf8(); + Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { + return protobufjs_utf8_1.utf8read; + } }); + var binary_format_contract_1 = require_binary_format_contract(); + Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { + return binary_format_contract_1.WireType; + } }); + Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { + return binary_format_contract_1.mergeBinaryOptions; + } }); + Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { + return binary_format_contract_1.UnknownFieldHandler; + } }); + var binary_reader_1 = require_binary_reader(); + Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { + return binary_reader_1.BinaryReader; + } }); + Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { + return binary_reader_1.binaryReadOptions; + } }); + var binary_writer_1 = require_binary_writer(); + Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { + return binary_writer_1.BinaryWriter; + } }); + Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { + return binary_writer_1.binaryWriteOptions; + } }); + var pb_long_1 = require_pb_long(); + Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { + return pb_long_1.PbLong; + } }); + Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { + return pb_long_1.PbULong; + } }); + var json_format_contract_1 = require_json_format_contract(); + Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonReadOptions; + } }); + Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonWriteOptions; + } }); + Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { + return json_format_contract_1.mergeJsonOptions; + } }); + var message_type_contract_1 = require_message_type_contract(); + Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { + return message_type_contract_1.MESSAGE_TYPE; + } }); + var message_type_1 = require_message_type(); + Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { + return message_type_1.MessageType; + } }); + var reflection_info_1 = require_reflection_info(); + Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { + return reflection_info_1.ScalarType; + } }); + Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { + return reflection_info_1.LongType; + } }); + Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { + return reflection_info_1.RepeatType; + } }); + Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { + return reflection_info_1.normalizeFieldInfo; + } }); + Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { + return reflection_info_1.readFieldOptions; + } }); + Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { + return reflection_info_1.readFieldOption; + } }); + Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { + return reflection_info_1.readMessageOption; + } }); + var reflection_type_check_1 = require_reflection_type_check(); + Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { + return reflection_type_check_1.ReflectionTypeCheck; + } }); + var reflection_create_1 = require_reflection_create(); + Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { + return reflection_create_1.reflectionCreate; + } }); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { + return reflection_scalar_default_1.reflectionScalarDefault; + } }); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { + return reflection_merge_partial_1.reflectionMergePartial; + } }); + var reflection_equals_1 = require_reflection_equals(); + Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { + return reflection_equals_1.reflectionEquals; + } }); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { + return reflection_binary_reader_1.ReflectionBinaryReader; + } }); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { + return reflection_binary_writer_1.ReflectionBinaryWriter; + } }); + var reflection_json_reader_1 = require_reflection_json_reader(); + Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { + return reflection_json_reader_1.ReflectionJsonReader; + } }); + var reflection_json_writer_1 = require_reflection_json_writer(); + Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { + return reflection_json_writer_1.ReflectionJsonWriter; + } }); + var reflection_contains_message_type_1 = require_reflection_contains_message_type(); + Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { + return reflection_contains_message_type_1.containsMessageType; + } }); + var oneof_1 = require_oneof(); + Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { + return oneof_1.isOneofGroup; + } }); + Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { + return oneof_1.setOneofValue; + } }); + Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { + return oneof_1.getOneofValue; + } }); + Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { + return oneof_1.clearOneofValue; + } }); + Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { + return oneof_1.getSelectedOneofValue; + } }); + var enum_object_1 = require_enum_object(); + Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { + return enum_object_1.listEnumValues; + } }); + Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { + return enum_object_1.listEnumNames; + } }); + Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { + return enum_object_1.listEnumNumbers; + } }); + Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { + return enum_object_1.isEnumObject; + } }); + var lower_camel_case_1 = require_lower_camel_case(); + Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { + return lower_camel_case_1.lowerCamelCase; + } }); + var assert_1 = require_assert(); + Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { + return assert_1.assert; + } }); + Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { + return assert_1.assertNever; + } }); + Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { + return assert_1.assertInt32; + } }); + Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { + return assert_1.assertUInt32; + } }); + Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { + return assert_1.assertFloat32; + } }); } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js -var require_reflection_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js +var require_reflection_info2 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryWriter = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var pb_long_1 = require_pb_long(); - var ReflectionBinaryWriter = class { - constructor(info6) { - this.info = info6; - } - prepare() { - if (!this.fields) { - const fieldsInput = this.info.fields ? this.info.fields.concat() : []; - this.fields = fieldsInput.sort((a, b) => a.no - b.no); - } - } - /** - * Writes the message to binary format. - */ - write(message, writer, options) { - this.prepare(); - for (const field of this.fields) { - let value, emitDefault, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - const group = message[field.oneof]; - if (group.oneofKind !== localName) - continue; - value = group[localName]; - emitDefault = true; - } else { - value = message[localName]; - emitDefault = false; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (repeated) { - assert_1.assert(Array.isArray(value)); - if (repeated == reflection_info_1.RepeatType.PACKED) - this.packed(writer, T, field.no, value); - else - for (const item of value) - this.scalar(writer, T, field.no, item, true); - } else if (value === void 0) - assert_1.assert(field.opt); - else - this.scalar(writer, T, field.no, value, emitDefault || field.opt); - break; - case "message": - if (repeated) { - assert_1.assert(Array.isArray(value)); - for (const item of value) - this.message(writer, options, field.T(), field.no, item); - } else { - this.message(writer, options, field.T(), field.no, value); - } - break; - case "map": - assert_1.assert(typeof value == "object" && value !== null); - for (const [key, val2] of Object.entries(value)) - this.mapEntry(writer, options, field, key, val2); - break; - } - } - let u = options.writeUnknownFields; - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); - } - mapEntry(writer, options, field, key, value) { - writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let keyValue = key; - switch (field.K) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - keyValue = Number.parseInt(key); - break; - case reflection_info_1.ScalarType.BOOL: - assert_1.assert(key == "true" || key == "false"); - keyValue = key == "true"; - break; - } - this.scalar(writer, field.K, 1, keyValue, true); - switch (field.V.kind) { - case "scalar": - this.scalar(writer, field.V.T, 2, value, true); - break; - case "enum": - this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); - break; - case "message": - this.message(writer, options, field.V.T(), 2, value); - break; - } - writer.join(); - } - message(writer, options, handler, fieldNo, value) { - if (value === void 0) - return; - handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); - writer.join(); + exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + var runtime_1 = require_commonjs11(); + function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + m.serverStreaming = !!m.serverStreaming; + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; + return m; + } + exports2.normalizeMethodInfo = normalizeMethodInfo; + function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readMethodOptions = readMethodOptions; + function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; } - /** - * Write a single scalar value. - */ - scalar(writer, type2, fieldNo, value, emitDefault) { - let [wireType, method, isDefault] = this.scalarInfo(type2, value); - if (!isDefault || emitDefault) { - writer.tag(fieldNo, wireType); - writer[method](value); - } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - /** - * Write an array of scalar values in packed format. - */ - packed(writer, type2, fieldNo, value) { - if (!value.length) - return; - assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); - writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let [, method] = this.scalarInfo(type2); - for (let i = 0; i < value.length; i++) - writer[method](value[i]); - writer.join(); + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMethodOption = readMethodOption; + function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return void 0; } - /** - * Get information for writing a scalar value. - * - * Returns tuple: - * [0]: appropriate WireType - * [1]: name of the appropriate method of IBinaryWriter - * [2]: whether the given value is a default value - * - * If argument `value` is omitted, [2] is always false. - */ - scalarInfo(type2, value) { - let t = binary_format_contract_1.WireType.Varint; - let m; - let i = value === void 0; - let d = value === 0; - switch (type2) { - case reflection_info_1.ScalarType.INT32: - m = "int32"; - break; - case reflection_info_1.ScalarType.STRING: - d = i || !value.length; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "string"; - break; - case reflection_info_1.ScalarType.BOOL: - d = value === false; - m = "bool"; - break; - case reflection_info_1.ScalarType.UINT32: - m = "uint32"; - break; - case reflection_info_1.ScalarType.DOUBLE: - t = binary_format_contract_1.WireType.Bit64; - m = "double"; - break; - case reflection_info_1.ScalarType.FLOAT: - t = binary_format_contract_1.WireType.Bit32; - m = "float"; - break; - case reflection_info_1.ScalarType.INT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "int64"; - break; - case reflection_info_1.ScalarType.UINT64: - d = i || pb_long_1.PbULong.from(value).isZero(); - m = "uint64"; - break; - case reflection_info_1.ScalarType.FIXED64: - d = i || pb_long_1.PbULong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "fixed64"; - break; - case reflection_info_1.ScalarType.BYTES: - d = i || !value.byteLength; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "bytes"; - break; - case reflection_info_1.ScalarType.FIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "fixed32"; - break; - case reflection_info_1.ScalarType.SFIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "sfixed32"; - break; - case reflection_info_1.ScalarType.SFIXED64: - d = i || pb_long_1.PbLong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "sfixed64"; - break; - case reflection_info_1.ScalarType.SINT32: - m = "sint32"; - break; - case reflection_info_1.ScalarType.SINT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "sint64"; - break; - } - return [t, m, i || d]; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - }; - exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readServiceOption = readServiceOption; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js -var require_reflection_create = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js +var require_service_type = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionCreate = void 0; - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var message_type_contract_1 = require_message_type_contract(); - function reflectionCreate(type2) { - const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); - for (let field of type2.fields) { - let name = field.localName; - if (field.opt) - continue; - if (field.oneof) - msg[field.oneof] = { oneofKind: void 0 }; - else if (field.repeat) - msg[name] = []; - else - switch (field.kind) { - case "scalar": - msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); - break; - case "enum": - msg[name] = 0; - break; - case "map": - msg[name] = {}; - break; - } + exports2.ServiceType = void 0; + var reflection_info_1 = require_reflection_info2(); + var ServiceType = class { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; } - return msg; - } - exports2.reflectionCreate = reflectionCreate; + }; + exports2.ServiceType = ServiceType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js -var require_reflection_merge_partial = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js +var require_rpc_error = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionMergePartial = void 0; - function reflectionMergePartial(info6, target, source) { - let fieldValue, input = source, output; - for (let field of info6.fields) { - let name = field.localName; - if (field.oneof) { - const group = input[field.oneof]; - if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { - continue; - } - fieldValue = group[name]; - output = target[field.oneof]; - output.oneofKind = group.oneofKind; - if (fieldValue == void 0) { - delete output[name]; - continue; - } - } else { - fieldValue = input[name]; - output = target; - if (fieldValue == void 0) { - continue; - } + exports2.RpcError = void 0; + var RpcError = class extends Error { + constructor(message, code = "UNKNOWN", meta) { + super(message); + this.name = "RpcError"; + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; + } + toString() { + const l = [this.name + ": " + this.message]; + if (this.code) { + l.push(""); + l.push("Code: " + this.code); } - if (field.repeat) - output[name].length = fieldValue.length; - switch (field.kind) { - case "scalar": - case "enum": - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = fieldValue[i]; - else - output[name] = fieldValue; - break; - case "message": - let T = field.T(); - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = T.create(fieldValue[i]); - else if (output[name] === void 0) - output[name] = T.create(fieldValue); - else - T.mergePartial(output[name], fieldValue); - break; - case "map": - switch (field.V.kind) { - case "scalar": - case "enum": - Object.assign(output[name], fieldValue); - break; - case "message": - let T2 = field.V.T(); - for (let k of Object.keys(fieldValue)) - output[name][k] = T2.create(fieldValue[k]); - break; - } - break; + if (this.serviceName && this.methodName) { + l.push("Method: " + this.serviceName + "/" + this.methodName); + } + let m = Object.entries(this.meta); + if (m.length) { + l.push(""); + l.push("Meta:"); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); + } } + return l.join("\n"); } - } - exports2.reflectionMergePartial = reflectionMergePartial; + }; + exports2.RpcError = RpcError; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js -var require_reflection_equals = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js +var require_rpc_options = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionEquals = void 0; - var reflection_info_1 = require_reflection_info(); - function reflectionEquals(info6, a, b) { - if (a === b) - return true; - if (!a || !b) - return false; - for (let field of info6.fields) { - let localName = field.localName; - let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; - let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; - switch (field.kind) { - case "enum": - case "scalar": - let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) - return false; + exports2.mergeRpcOptions = void 0; + var runtime_1 = require_commonjs11(); + function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val2 = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); break; - case "map": - if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) - return false; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); break; - case "message": - let T = field.T(); - if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) - return false; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); break; } } - return true; - } - exports2.reflectionEquals = reflectionEquals; - var objectValues = Object.values; - function primitiveEq(type2, a, b) { - if (a === b) - return true; - if (type2 !== reflection_info_1.ScalarType.BYTES) - return false; - let ba = a; - let bb = b; - if (ba.length !== bb.length) - return false; - for (let i = 0; i < ba.length; i++) - if (ba[i] != bb[i]) - return false; - return true; - } - function repeatedPrimitiveEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!primitiveEq(type2, a[i], b[i])) - return false; - return true; + return o; } - function repeatedMsgEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!type2.equals(a[i], b[i])) - return false; - return true; + exports2.mergeRpcOptions = mergeRpcOptions; + function copy(a, into) { + if (!a) + return; + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; + } } } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js -var require_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js +var require_deferred = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_type_check_1 = require_reflection_type_check(); - var reflection_json_reader_1 = require_reflection_json_reader(); - var reflection_json_writer_1 = require_reflection_json_writer(); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - var reflection_create_1 = require_reflection_create(); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - var json_typings_1 = require_json_typings(); - var json_format_contract_1 = require_json_format_contract(); - var reflection_equals_1 = require_reflection_equals(); - var binary_writer_1 = require_binary_writer(); - var binary_reader_1 = require_binary_reader(); - var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); - var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; - var MessageType = class { - constructor(name, fields, options) { - this.defaultCheckDepth = 16; - this.typeName = name; - this.fields = fields.map(reflection_info_1.normalizeFieldInfo); - this.options = options !== null && options !== void 0 ? options : {}; - messageTypeDescriptor.value = this; - this.messagePrototype = Object.create(null, baseDescriptors); - this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); - this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); - this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); - this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); - this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); - } - create(value) { - let message = reflection_create_1.reflectionCreate(this); - if (value !== void 0) { - reflection_merge_partial_1.reflectionMergePartial(this, message, value); + exports2.Deferred = exports2.DeferredState = void 0; + var DeferredState; + (function(DeferredState2) { + DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; + DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; + DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; + })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); + var Deferred = class { + /** + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. + */ + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve4, reject) => { + this._resolve = resolve4; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch((_) => { + }); } - return message; } /** - * Clone the message. - * - * Unknown fields are discarded. + * Get the current state of the promise. */ - clone(message) { - let copy = this.create(); - reflection_merge_partial_1.reflectionMergePartial(this, copy, message); - return copy; + get state() { + return this._state; } /** - * Determines whether two message of the same type have the same field values. - * Checks for deep equality, traversing repeated fields, oneof groups, maps - * and messages recursively. - * Will also return true if both messages are `undefined`. + * Get the deferred promise. */ - equals(a, b) { - return reflection_equals_1.reflectionEquals(this, a, b); + get promise() { + return this._promise; } /** - * Is the given value assignable to our message type - * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + * Resolve the promise. Throws if the promise is already resolved or rejected. */ - is(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, false); + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; } /** - * Is the given value assignable to our message type, - * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + * Reject the promise. Throws if the promise is already resolved or rejected. */ - isAssignable(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, true); + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; } /** - * Copy partial data into the target message. + * Resolve the promise. Ignore if not pending. */ - mergePartial(target, source) { - reflection_merge_partial_1.reflectionMergePartial(this, target, source); + resolvePending(val2) { + if (this._state === DeferredState.PENDING) + this.resolve(val2); } /** - * Create a new message from binary format. + * Reject the promise. Ignore if not pending. */ - fromBinary(data, options) { - let opt = binary_reader_1.binaryReadOptions(options); - return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); + } + }; + exports2.Deferred = Deferred; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js +var require_rpc_output_stream = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcOutputStreamController = void 0; + var deferred_1 = require_deferred(); + var runtime_1 = require_commonjs11(); + var RpcOutputStreamController = class { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [] + }; + this._closed = false; + this._itState = { q: [] }; + } + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); + } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); } + // --- Controller API /** - * Read a new message from a JSON value. + * Is this stream already closed by a completion or error? */ - fromJson(json2, options) { - return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + get closed() { + return this._closed !== false; } /** - * Read a new message from a JSON string. - * This is equivalent to `T.fromJson(JSON.parse(json))`. + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. */ - fromJsonString(json2, options) { - let value = JSON.parse(json2); - return this.fromJson(value, options); + notifyNext(message, error4, complete) { + runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); + if (message) + this.notifyMessage(message); + if (error4) + this.notifyError(error4); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. + * + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, "stream is closed"); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach((l) => l(message)); + this._lis.nxt.forEach((l) => l(message, void 0, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. + * + * Triggers onNext and onError callbacks. + */ + notifyError(error4) { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = error4; + this.pushIt(error4); + this._lis.err.forEach((l) => l(error4)); + this._lis.nxt.forEach((l) => l(void 0, error4, false)); + this.clearLis(); + } + /** + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. + */ + notifyComplete() { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach((l) => l()); + this._lis.nxt.forEach((l) => l(void 0, void 0, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); + runtime_1.assert(!state.p, "iterator contract broken"); + let first = state.q.shift(); + if (first) + return "value" in first ? Promise.resolve(first) : Promise.reject(first); + state.p = new deferred_1.Deferred(); + return state.p.promise; + } + }; + } + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (state.p) { + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + "value" in result ? p.resolve(result) : p.reject(result); + delete state.p; + } else { + state.q.push(result); + } + } + }; + exports2.RpcOutputStreamController = RpcOutputStreamController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js +var require_unary_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UnaryCall = void 0; + var UnaryCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.UnaryCall = UnaryCall; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js +var require_server_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerStreamingCall = void 0; + var ServerStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers + }; + }); + } + }; + exports2.ServerStreamingCall = ServerStreamingCall; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js +var require_client_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ClientStreamingCall = void 0; + var ClientStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; } /** - * Write the message to canonical JSON value. + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. */ - toJson(message, options) { - return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } - /** - * Convert the message to canonical JSON string. - * This is equivalent to `JSON.stringify(T.toJson(t))` - */ - toJsonString(message, options) { - var _a; - let value = this.toJson(message, options); - return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); } - /** - * Write the message to binary format. - */ - toBinary(message, options) { - let opt = binary_writer_1.binaryWriteOptions(options); - return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + }; + exports2.ClientStreamingCall = ClientStreamingCall; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js +var require_duplex_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - /** - * This is an internal method. If you just want to read a message from - * JSON, use `fromJson()` or `fromJsonString()`. - * - * Reads JSON value and merges the fields into the target - * according to protobuf rules. If the target is omitted, - * a new instance is created first. - */ - internalJsonRead(json2, options, target) { - if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refJsonReader.read(json2, message, options); - return message; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); - } - /** - * This is an internal method. If you just want to write a message - * to JSON, use `toJson()` or `toJsonString(). - * - * Writes JSON value and returns it. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.write(message, options); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DuplexStreamingCall = void 0; + var DuplexStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } /** - * This is an internal method. If you just want to write a message - * in binary format, use `toBinary()`. - * - * Serializes the message in binary format and appends it to the given - * writer. Returns passed writer. + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. */ - internalBinaryWrite(message, writer, options) { - this.refBinWriter.write(message, writer, options); - return writer; + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } - /** - * This is an internal method. If you just want to read a message from - * binary data, use `fromBinary()`. - * - * Reads data from binary format and merges the fields into - * the target according to protobuf rules. If the target is - * omitted, a new instance is created first. - */ - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refBinReader.read(reader, message, options, length); - return message; + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers + }; + }); } }; - exports2.MessageType = MessageType; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js -var require_reflection_contains_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.containsMessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - function containsMessageType(msg) { - return msg[message_type_contract_1.MESSAGE_TYPE] != null; - } - exports2.containsMessageType = containsMessageType; + exports2.DuplexStreamingCall = DuplexStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js -var require_enum_object = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js +var require_test_transport = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; - function isEnumObject(arg) { - if (typeof arg != "object" || arg === null) { - return false; + exports2.TestTransport = void 0; + var rpc_error_1 = require_rpc_error(); + var runtime_1 = require_commonjs11(); + var rpc_output_stream_1 = require_rpc_output_stream(); + var rpc_options_1 = require_rpc_options(); + var unary_call_1 = require_unary_call(); + var server_streaming_call_1 = require_server_streaming_call(); + var client_streaming_call_1 = require_client_streaming_call(); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + var TestTransport = class _TestTransport { + /** + * Initialize with mock data. Omitted fields have default value. + */ + constructor(data) { + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; } - if (!arg.hasOwnProperty(0)) { + /** + * Sent message(s) during the last operation. + */ + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; + } else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; + } + /** + * Sending message(s) completed? + */ + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } else if (typeof this.lastInput == "object") { + return true; + } return false; } - for (let k of Object.keys(arg)) { - let num = parseInt(k); - if (!Number.isNaN(num)) { - let nam = arg[num]; - if (nam === void 0) - return false; - if (arg[nam] !== num) - return false; + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); + } + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } else if (this.data.response !== void 0) { + r = this.data.response; } else { - let num2 = arg[k]; - if (num2 === void 0) - return false; - if (typeof num2 !== "number") - return false; - if (arg[num2] === void 0) - return false; + r = method.O.create(); } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); } - return true; - } - exports2.isEnumObject = isEnumObject; - function listEnumValues(enumObject) { - if (!isEnumObject(enumObject)) - throw new Error("not a typescript enum object"); - let values = []; - for (let [name, number] of Object.entries(enumObject)) - if (typeof number == "number") - values.push({ name, number }); - return values; - } - exports2.listEnumValues = listEnumValues; - function listEnumNames(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.name); - } - exports2.listEnumNames = listEnumNames; - function listEnumNumbers(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); - } - exports2.listEnumNumbers = listEnumNumbers; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/index.js -var require_commonjs11 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var json_typings_1 = require_json_typings(); - Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { - return json_typings_1.typeofJsonValue; - } }); - Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { - return json_typings_1.isJsonObject; - } }); - var base64_1 = require_base642(); - Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { - return base64_1.base64decode; - } }); - Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { - return base64_1.base64encode; - } }); - var protobufjs_utf8_1 = require_protobufjs_utf8(); - Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { - return protobufjs_utf8_1.utf8read; - } }); - var binary_format_contract_1 = require_binary_format_contract(); - Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { - return binary_format_contract_1.WireType; - } }); - Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { - return binary_format_contract_1.mergeBinaryOptions; - } }); - Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { - return binary_format_contract_1.UnknownFieldHandler; - } }); - var binary_reader_1 = require_binary_reader(); - Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { - return binary_reader_1.BinaryReader; - } }); - Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { - return binary_reader_1.binaryReadOptions; - } }); - var binary_writer_1 = require_binary_writer(); - Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { - return binary_writer_1.BinaryWriter; - } }); - Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { - return binary_writer_1.binaryWriteOptions; - } }); - var pb_long_1 = require_pb_long(); - Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { - return pb_long_1.PbLong; - } }); - Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { - return pb_long_1.PbULong; - } }); - var json_format_contract_1 = require_json_format_contract(); - Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonReadOptions; - } }); - Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonWriteOptions; - } }); - Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { - return json_format_contract_1.mergeJsonOptions; - } }); - var message_type_contract_1 = require_message_type_contract(); - Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { - return message_type_contract_1.MESSAGE_TYPE; - } }); - var message_type_1 = require_message_type(); - Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { - return message_type_1.MessageType; - } }); - var reflection_info_1 = require_reflection_info(); - Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { - return reflection_info_1.ScalarType; - } }); - Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { - return reflection_info_1.LongType; - } }); - Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { - return reflection_info_1.RepeatType; - } }); - Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { - return reflection_info_1.normalizeFieldInfo; - } }); - Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { - return reflection_info_1.readFieldOptions; - } }); - Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { - return reflection_info_1.readFieldOption; - } }); - Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { - return reflection_info_1.readMessageOption; - } }); - var reflection_type_check_1 = require_reflection_type_check(); - Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { - return reflection_type_check_1.ReflectionTypeCheck; - } }); - var reflection_create_1 = require_reflection_create(); - Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { - return reflection_create_1.reflectionCreate; - } }); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { - return reflection_scalar_default_1.reflectionScalarDefault; - } }); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { - return reflection_merge_partial_1.reflectionMergePartial; - } }); - var reflection_equals_1 = require_reflection_equals(); - Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { - return reflection_equals_1.reflectionEquals; - } }); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { - return reflection_binary_reader_1.ReflectionBinaryReader; - } }); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { - return reflection_binary_writer_1.ReflectionBinaryWriter; - } }); - var reflection_json_reader_1 = require_reflection_json_reader(); - Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { - return reflection_json_reader_1.ReflectionJsonReader; - } }); - var reflection_json_writer_1 = require_reflection_json_writer(); - Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { - return reflection_json_writer_1.ReflectionJsonWriter; - } }); - var reflection_contains_message_type_1 = require_reflection_contains_message_type(); - Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { - return reflection_contains_message_type_1.containsMessageType; - } }); - var oneof_1 = require_oneof(); - Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { - return oneof_1.isOneofGroup; - } }); - Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { - return oneof_1.setOneofValue; - } }); - Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { - return oneof_1.getOneofValue; - } }); - Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { - return oneof_1.clearOneofValue; - } }); - Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { - return oneof_1.getSelectedOneofValue; - } }); - var enum_object_1 = require_enum_object(); - Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { - return enum_object_1.listEnumValues; - } }); - Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { - return enum_object_1.listEnumNames; - } }); - Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { - return enum_object_1.listEnumNumbers; - } }); - Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { - return enum_object_1.isEnumObject; - } }); - var lower_camel_case_1 = require_lower_camel_case(); - Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { - return lower_camel_case_1.lowerCamelCase; - } }); - var assert_1 = require_assert(); - Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { - return assert_1.assert; - } }); - Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { - return assert_1.assertNever; - } }); - Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { - return assert_1.assertInt32; - } }); - Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { - return assert_1.assertUInt32; - } }); - Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { - return assert_1.assertFloat32; - } }); - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js -var require_reflection_info2 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; - var runtime_1 = require_commonjs11(); - function normalizeMethodInfo(method, service) { - var _a, _b, _c; - let m = method; - m.service = service; - m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); - m.serverStreaming = !!m.serverStreaming; - m.clientStreaming = !!m.clientStreaming; - m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; - m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; - return m; - } - exports2.normalizeMethodInfo = normalizeMethodInfo; - function readMethodOptions(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readMethodOptions = readMethodOptions; - function readMethodOption(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; + /** + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. + */ + streamResponses(method, stream2, abort) { + return __awaiter4(this, void 0, void 0, function* () { + const messages = []; + if (this.data.response === void 0) { + messages.push(method.O.create()); + } else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + try { + yield delay2(this.responseDelay, abort)(void 0); + } catch (error4) { + stream2.notifyError(error4); + return; + } + if (this.data.response instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.response); + return; + } + for (let msg of messages) { + stream2.notifyMessage(msg); + try { + yield delay2(this.betweenResponseDelay, abort)(void 0); + } catch (error4) { + stream2.notifyError(error4); + return; + } + } + if (this.data.status instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.status); + return; + } + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.trailers); + return; + } + stream2.notifyComplete(); + }); } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readMethodOption = readMethodOption; - function readServiceOption(service, extensionName, extensionType) { - const options = service.options; - if (!options) { - return void 0; + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readServiceOption = readServiceOption; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js -var require_service_type = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceType = void 0; - var reflection_info_1 = require_reflection_info2(); - var ServiceType = class { - constructor(typeName, methods, options) { - this.typeName = typeName; - this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); - this.options = options !== null && options !== void 0 ? options : {}; + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); } - }; - exports2.ServiceType = ServiceType; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js -var require_rpc_error = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcError = void 0; - var RpcError = class extends Error { - constructor(message, code = "UNKNOWN", meta) { - super(message); - this.name = "RpcError"; - Object.setPrototypeOf(this, new.target.prototype); - this.code = code; - this.meta = meta !== null && meta !== void 0 ? meta : {}; + unary(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); } - toString() { - const l = [this.name + ": " + this.message]; - if (this.code) { - l.push(""); - l.push("Code: " + this.code); + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); + } + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + } + }; + exports2.TestTransport = TestTransport; + TestTransport.defaultHeaders = { + responseHeader: "test" + }; + TestTransport.defaultStatus = { + code: "OK", + detail: "all good" + }; + TestTransport.defaultTrailers = { + responseTrailer: "test" + }; + function delay2(ms, abort) { + return (v) => new Promise((resolve4, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } else { + const id = setTimeout(() => resolve4(v), ms); + if (abort) { + abort.addEventListener("abort", (ev) => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } } - if (this.serviceName && this.methodName) { - l.push("Method: " + this.serviceName + "/" + this.methodName); + }); + } + var TestInputStream = class { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; + } + get sent() { + return this._sent; + } + get completed() { + return this._completed; + } + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); } - let m = Object.entries(this.meta); - if (m.length) { - l.push(""); - l.push("Meta:"); - for (let [k, v] of m) { - l.push(` ${k}: ${v}`); - } + const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; + return Promise.resolve(void 0).then(() => { + this._sent.push(message); + }).then(delay2(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); } - return l.join("\n"); + const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; + return Promise.resolve(void 0).then(() => { + this._completed = true; + }).then(delay2(delayMs, this.abort)); } }; - exports2.RpcError = RpcError; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js -var require_rpc_options = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js +var require_rpc_interceptor = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeRpcOptions = void 0; + exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; var runtime_1 = require_commonjs11(); - function mergeRpcOptions(defaults, options) { - if (!options) - return defaults; - let o = {}; - copy(defaults, o); - copy(options, o); - for (let key of Object.keys(options)) { - let val2 = options[key]; - switch (key) { - case "jsonOptions": - o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); - break; - case "binaryOptions": - o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); - break; - case "meta": - o.meta = {}; - copy(defaults.meta, o.meta); - copy(options.meta, o.meta); - break; - case "interceptors": - o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); - break; + function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); } + return tail(method, input, options); } - return o; - } - exports2.mergeRpcOptions = mergeRpcOptions; - function copy(a, into) { - if (!a) - return; - let c = into; - for (let [k, v] of Object.entries(a)) { - if (v instanceof Date) - c[k] = new Date(v.getTime()); - else if (Array.isArray(v)) - c[k] = v.concat(); - else - c[k] = v; + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); + } + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + } + return tail(method, options); + } + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); } + runtime_1.assertNever(kind); + } + exports2.stackIntercept = stackIntercept; + function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); + } + exports2.stackUnaryInterceptors = stackUnaryInterceptors; + function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); + } + exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; + function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); + } + exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; + function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); } + exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js -var require_deferred = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js +var require_server_call_context = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Deferred = exports2.DeferredState = void 0; - var DeferredState; - (function(DeferredState2) { - DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; - DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; - DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; - })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); - var Deferred = class { - /** - * @param preventUnhandledRejectionWarning - prevents the warning - * "Unhandled Promise rejection" by adding a noop rejection handler. - * Working with calls returned from the runtime-rpc package in an - * async function usually means awaiting one call property after - * the other. This means that the "status" is not being awaited when - * an earlier await for the "headers" is rejected. This causes the - * "unhandled promise reject" warning. A more correct behaviour for - * calls might be to become aware whether at least one of the - * promises is handled and swallow the rejection warning for the - * others. - */ - constructor(preventUnhandledRejectionWarning = true) { - this._state = DeferredState.PENDING; - this._promise = new Promise((resolve4, reject) => { - this._resolve = resolve4; - this._reject = reject; - }); - if (preventUnhandledRejectionWarning) { - this._promise.catch((_) => { - }); - } - } - /** - * Get the current state of the promise. - */ - get state() { - return this._state; - } - /** - * Get the deferred promise. - */ - get promise() { - return this._promise; + exports2.ServerCallContextController = void 0; + var ServerCallContextController = class { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; } /** - * Resolve the promise. Throws if the promise is already resolved or rejected. + * Set the call cancelled. + * + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. */ - resolve(value) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); - this._resolve(value); - this._state = DeferredState.RESOLVED; + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } + } } /** - * Reject the promise. Throws if the promise is already resolved or rejected. + * Send response headers. */ - reject(reason) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); - this._reject(reason); - this._state = DeferredState.REJECTED; + sendResponseHeaders(data) { + this._sendRH(data); } /** - * Resolve the promise. Ignore if not pending. + * Is the call cancelled? + * + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. */ - resolvePending(val2) { - if (this._state === DeferredState.PENDING) - this.resolve(val2); + get cancelled() { + return this._cancelled; } /** - * Reject the promise. Ignore if not pending. + * Add a callback for cancellation. */ - rejectPending(reason) { - if (this._state === DeferredState.PENDING) - this.reject(reason); + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; } }; - exports2.Deferred = Deferred; + exports2.ServerCallContextController = ServerCallContextController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var service_type_1 = require_service_type(); + Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { + return service_type_1.ServiceType; + } }); + var reflection_info_1 = require_reflection_info2(); + Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { + return reflection_info_1.readMethodOptions; + } }); + Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { + return reflection_info_1.readMethodOption; + } }); + Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { + return reflection_info_1.readServiceOption; + } }); + var rpc_error_1 = require_rpc_error(); + Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { + return rpc_error_1.RpcError; + } }); + var rpc_options_1 = require_rpc_options(); + Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { + return rpc_options_1.mergeRpcOptions; + } }); + var rpc_output_stream_1 = require_rpc_output_stream(); + Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { + return rpc_output_stream_1.RpcOutputStreamController; + } }); + var test_transport_1 = require_test_transport(); + Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { + return test_transport_1.TestTransport; + } }); + var deferred_1 = require_deferred(); + Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { + return deferred_1.Deferred; + } }); + Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { + return deferred_1.DeferredState; + } }); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { + return duplex_streaming_call_1.DuplexStreamingCall; + } }); + var client_streaming_call_1 = require_client_streaming_call(); + Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { + return client_streaming_call_1.ClientStreamingCall; + } }); + var server_streaming_call_1 = require_server_streaming_call(); + Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { + return server_streaming_call_1.ServerStreamingCall; + } }); + var unary_call_1 = require_unary_call(); + Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { + return unary_call_1.UnaryCall; + } }); + var rpc_interceptor_1 = require_rpc_interceptor(); + Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { + return rpc_interceptor_1.stackIntercept; + } }); + Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackDuplexStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackClientStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackServerStreamingInterceptors; + } }); + Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackUnaryInterceptors; + } }); + var server_call_context_1 = require_server_call_context(); + Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { + return server_call_context_1.ServerCallContextController; + } }); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js -var require_rpc_output_stream = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js +var require_cachescope = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcOutputStreamController = void 0; - var deferred_1 = require_deferred(); + exports2.CacheScope = void 0; var runtime_1 = require_commonjs11(); - var RpcOutputStreamController = class { + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var CacheScope$Type = class extends runtime_5.MessageType { constructor() { - this._lis = { - nxt: [], - msg: [], - err: [], - cmp: [] - }; - this._closed = false; - this._itState = { q: [] }; - } - // --- RpcOutputStream callback API - onNext(callback) { - return this.addLis(callback, this._lis.nxt); - } - onMessage(callback) { - return this.addLis(callback, this._lis.msg); - } - onError(callback) { - return this.addLis(callback, this._lis.err); - } - onComplete(callback) { - return this.addLis(callback, this._lis.cmp); - } - addLis(callback, list) { - list.push(callback); - return () => { - let i = list.indexOf(callback); - if (i >= 0) - list.splice(i, 1); - }; - } - // remove all listeners - clearLis() { - for (let l of Object.values(this._lis)) - l.splice(0, l.length); - } - // --- Controller API - /** - * Is this stream already closed by a completion or error? - */ - get closed() { - return this._closed !== false; - } - /** - * Emit message, close with error, or close successfully, but only one - * at a time. - * Can be used to wrap a stream by using the other stream's `onNext`. - */ - notifyNext(message, error4, complete) { - runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); - if (message) - this.notifyMessage(message); - if (error4) - this.notifyError(error4); - if (complete) - this.notifyComplete(); - } - /** - * Emits a new message. Throws if stream is closed. - * - * Triggers onNext and onMessage callbacks. - */ - notifyMessage(message) { - runtime_1.assert(!this.closed, "stream is closed"); - this.pushIt({ value: message, done: false }); - this._lis.msg.forEach((l) => l(message)); - this._lis.nxt.forEach((l) => l(message, void 0, false)); - } - /** - * Closes the stream with an error. Throws if stream is closed. - * - * Triggers onNext and onError callbacks. - */ - notifyError(error4) { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = error4; - this.pushIt(error4); - this._lis.err.forEach((l) => l(error4)); - this._lis.nxt.forEach((l) => l(void 0, error4, false)); - this.clearLis(); + super("github.actions.results.entities.v1.CacheScope", [ + { + no: 1, + name: "scope", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "permission", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); } - /** - * Closes the stream successfully. Throws if stream is closed. - * - * Triggers onNext and onComplete callbacks. - */ - notifyComplete() { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = true; - this.pushIt({ value: null, done: true }); - this._lis.cmp.forEach((l) => l()); - this._lis.nxt.forEach((l) => l(void 0, void 0, true)); - this.clearLis(); + create(value) { + const message = { scope: "", permission: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - /** - * Creates an async iterator (that can be used with `for await {...}`) - * to consume the stream. - * - * Some things to note: - * - If an error occurs, the `for await` will throw it. - * - If an error occurred before the `for await` was started, `for await` - * will re-throw it. - * - If the stream is already complete, the `for await` will be empty. - * - If your `for await` consumes slower than the stream produces, - * for example because you are relaying messages in a slow operation, - * messages are queued. - */ - [Symbol.asyncIterator]() { - if (this._closed === true) - this.pushIt({ value: null, done: true }); - else if (this._closed !== false) - this.pushIt(this._closed); - return { - next: () => { - let state = this._itState; - runtime_1.assert(state, "bad state"); - runtime_1.assert(!state.p, "iterator contract broken"); - let first = state.q.shift(); - if (first) - return "value" in first ? Promise.resolve(first) : Promise.reject(first); - state.p = new deferred_1.Deferred(); - return state.p.promise; + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string scope */ + 1: + message.scope = reader.string(); + break; + case /* int64 permission */ + 2: + message.permission = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } - }; - } - // "push" a new iterator result. - // this either resolves a pending promise, or enqueues the result. - pushIt(result) { - let state = this._itState; - if (state.p) { - const p = state.p; - runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); - "value" in result ? p.resolve(result) : p.reject(result); - delete state.p; - } else { - state.q.push(result); } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.scope !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); + if (message.permission !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.RpcOutputStreamController = RpcOutputStreamController; + exports2.CacheScope = new CacheScope$Type(); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js -var require_unary_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js +var require_cachemetadata = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheMetadata = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachescope_1 = require_cachescope(); + var CacheMetadata$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheMetadata", [ + { + no: 1, + name: "repository_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } + ]); } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + create(value) { + const message = { repositoryId: "0", scope: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 repository_id */ + 1: + message.repositoryId = reader.int64().toString(); + break; + case /* repeated github.actions.results.entities.v1.CacheScope scope */ + 2: + message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UnaryCall = void 0; - var UnaryCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * If you are only interested in the final outcome of this call, - * you can await it to receive a `FinishedUnaryCall`. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + return message; } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - response, - status, - trailers - }; - }); + internalBinaryWrite(message, writer, options) { + if (message.repositoryId !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); + for (let i = 0; i < message.scope.length; i++) + cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.UnaryCall = UnaryCall; + exports2.CacheMetadata = new CacheMetadata$Type(); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js -var require_server_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js +var require_cache2 = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachemetadata_1 = require_cachemetadata(); + var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + ]); + } + create(value) { + const message = { key: "", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* string version */ + 3: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerStreamingCall = void 0; - var ServerStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * You should first setup some listeners to the `request` to - * see the actual messages the server replied with. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + return message; } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - status, - trailers - }; - }); + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.version !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.ServerStreamingCall = ServerStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js -var require_client_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); + var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + ]); + } + create(value) { + const message = { ok: false, signedUploadUrl: "", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ClientStreamingCall = void 0; - var ClientStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + return message; } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - response, - status, - trailers - }; - }); + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.ClientStreamingCall = ClientStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js -var require_duplex_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); + var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size_bytes", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + ]); + } + create(value) { + const message = { key: "", sizeBytes: "0", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* int64 size_bytes */ + 3: + message.sizeBytes = reader.int64().toString(); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DuplexStreamingCall = void 0; - var DuplexStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + return message; } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - status, - trailers - }; - }); + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.sizeBytes !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.DuplexStreamingCall = DuplexStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js -var require_test_transport = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); + var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "entry_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + ]); + } + create(value) { + const message = { ok: false, entryId: "0", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* int64 entry_id */ + 2: + message.entryId = reader.int64().toString(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TestTransport = void 0; - var rpc_error_1 = require_rpc_error(); - var runtime_1 = require_commonjs11(); - var rpc_output_stream_1 = require_rpc_output_stream(); - var rpc_options_1 = require_rpc_options(); - var unary_call_1 = require_unary_call(); - var server_streaming_call_1 = require_server_streaming_call(); - var client_streaming_call_1 = require_client_streaming_call(); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - var TestTransport = class _TestTransport { - /** - * Initialize with mock data. Omitted fields have default value. - */ - constructor(data) { - this.suppressUncaughtRejections = true; - this.headerDelay = 10; - this.responseDelay = 50; - this.betweenResponseDelay = 10; - this.afterResponseDelay = 10; - this.data = data !== null && data !== void 0 ? data : {}; + return message; } - /** - * Sent message(s) during the last operation. - */ - get sentMessages() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.sent; - } else if (typeof this.lastInput == "object") { - return [this.lastInput.single]; - } - return []; + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.entryId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - /** - * Sending message(s) completed? - */ - get sendComplete() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.completed; - } else if (typeof this.lastInput == "object") { - return true; - } - return false; + }; + exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); + var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "restore_keys", + kind: "scalar", + repeat: 2, + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - // Creates a promise for response headers from the mock data. - promiseHeaders() { - var _a; - const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; - return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); + create(value) { + const message = { key: "", restoreKeys: [], version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - // Creates a promise for a single, valid, message from the mock data. - promiseSingleResponse(method) { - if (this.data.response instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.response); - } - let r; - if (Array.isArray(this.data.response)) { - runtime_1.assert(this.data.response.length > 0); - r = this.data.response[0]; - } else if (this.data.response !== void 0) { - r = this.data.response; - } else { - r = method.O.create(); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* repeated string restore_keys */ + 3: + message.restoreKeys.push(reader.string()); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } - runtime_1.assert(method.O.is(r)); - return Promise.resolve(r); + return message; } - /** - * Pushes response messages from the mock data to the output stream. - * If an error response, status or trailers are mocked, the stream is - * closed with the respective error. - * Otherwise, stream is completed successfully. - * - * The returned promise resolves when the stream is closed. It should - * not reject. If it does, code is broken. - */ - streamResponses(method, stream2, abort) { - return __awaiter4(this, void 0, void 0, function* () { - const messages = []; - if (this.data.response === void 0) { - messages.push(method.O.create()); - } else if (Array.isArray(this.data.response)) { - for (let msg of this.data.response) { - runtime_1.assert(method.O.is(msg)); - messages.push(msg); - } - } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { - runtime_1.assert(method.O.is(this.data.response)); - messages.push(this.data.response); - } - try { - yield delay2(this.responseDelay, abort)(void 0); - } catch (error4) { - stream2.notifyError(error4); - return; - } - if (this.data.response instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.response); - return; - } - for (let msg of messages) { - stream2.notifyMessage(msg); - try { - yield delay2(this.betweenResponseDelay, abort)(void 0); - } catch (error4) { - stream2.notifyError(error4); - return; - } - } - if (this.data.status instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.status); - return; - } - if (this.data.trailers instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.trailers); - return; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + for (let i = 0; i < message.restoreKeys.length; i++) + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); + var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_download_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "matched_key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ } - stream2.notifyComplete(); - }); - } - // Creates a promise for response status from the mock data. - promiseStatus() { - var _a; - const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; - return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); + ]); } - // Creates a promise for response trailers from the mock data. - promiseTrailers() { - var _a; - const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; - return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); + create(value) { + const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - maybeSuppressUncaught(...promise) { - if (this.suppressUncaughtRejections) { - for (let p of promise) { - p.catch(() => { - }); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_download_url */ + 2: + message.signedDownloadUrl = reader.string(); + break; + case /* string matched_key */ + 3: + message.matchedKey = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } + return message; } - mergeOptions(options) { - return rpc_options_1.mergeRpcOptions({}, options); + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedDownloadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); + if (message.matchedKey !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - unary(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); + }; + exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); + exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ + { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, + { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, + { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } + ]); + } +}); + +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js +var require_cache_twirp_client = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; + var cache_1 = require_cache2(); + var CacheServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - serverStreaming(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - clientStreaming(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - duplex(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } }; - exports2.TestTransport = TestTransport; - TestTransport.defaultHeaders = { - responseHeader: "test" - }; - TestTransport.defaultStatus = { - code: "OK", - detail: "all good" - }; - TestTransport.defaultTrailers = { - responseTrailer: "test" - }; - function delay2(ms, abort) { - return (v) => new Promise((resolve4, reject) => { - if (abort === null || abort === void 0 ? void 0 : abort.aborted) { - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - } else { - const id = setTimeout(() => resolve4(v), ms); - if (abort) { - abort.addEventListener("abort", (ev) => { - clearTimeout(id); - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - }); - } - } - }); - } - var TestInputStream = class { - constructor(data, abort) { - this._completed = false; - this._sent = []; - this.data = data; - this.abort = abort; - } - get sent() { - return this._sent; + exports2.CacheServiceClientJSON = CacheServiceClientJSON; + var CacheServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - get completed() { - return this._completed; + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); } - send(message) { - if (this.data.inputMessage instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputMessage); - } - const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; - return Promise.resolve(void 0).then(() => { - this._sent.push(message); - }).then(delay2(delayMs, this.abort)); + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); } - complete() { - if (this.data.inputComplete instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputComplete); - } - const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; - return Promise.resolve(void 0).then(() => { - this._completed = true; - }).then(delay2(delayMs, this.abort)); + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; + exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js -var require_rpc_interceptor = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/util.js +var require_util10 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; - var runtime_1 = require_commonjs11(); - function stackIntercept(kind, transport, method, options, input) { - var _a, _b, _c, _d; - if (kind == "unary") { - let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); - for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + exports2.maskSecretUrls = exports2.maskSigUrl = void 0; + var core_1 = require_core(); + function maskSigUrl(url) { + if (!url) + return; + try { + const parsedUrl = new URL(url); + const signature = parsedUrl.searchParams.get("sig"); + if (signature) { + (0, core_1.setSecret)(signature); + (0, core_1.setSecret)(encodeURIComponent(signature)); } - return tail(method, input, options); + } catch (error4) { + (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); } - if (kind == "serverStreaming") { - let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); - for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); - } - return tail(method, input, options); + } + exports2.maskSigUrl = maskSigUrl; + function maskSecretUrls(body) { + if (typeof body !== "object" || body === null) { + (0, core_1.debug)("body is not an object or is null"); + return; } - if (kind == "clientStreaming") { - let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); - for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); - } - return tail(method, options); + if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { + maskSigUrl(body.signed_upload_url); } - if (kind == "duplex") { - let tail = (mtd, opt) => transport.duplex(mtd, opt); - for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); - } - return tail(method, options); + if ("signed_download_url" in body && typeof body.signed_download_url === "string") { + maskSigUrl(body.signed_download_url); } - runtime_1.assertNever(kind); - } - exports2.stackIntercept = stackIntercept; - function stackUnaryInterceptors(transport, method, input, options) { - return stackIntercept("unary", transport, method, options, input); - } - exports2.stackUnaryInterceptors = stackUnaryInterceptors; - function stackServerStreamingInterceptors(transport, method, input, options) { - return stackIntercept("serverStreaming", transport, method, options, input); - } - exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; - function stackClientStreamingInterceptors(transport, method, options) { - return stackIntercept("clientStreaming", transport, method, options); - } - exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; - function stackDuplexStreamingInterceptors(transport, method, options) { - return stackIntercept("duplex", transport, method, options); } - exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; + exports2.maskSecretUrls = maskSecretUrls; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js -var require_server_call_context = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js +var require_cacheTwirpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerCallContextController = void 0; - var ServerCallContextController = class { - constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { - this._cancelled = false; - this._listeners = []; - this.method = method; - this.headers = headers; - this.deadline = deadline; - this.trailers = {}; - this._sendRH = sendResponseHeadersFn; - this.status = defaultStatus; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - /** - * Set the call cancelled. - * - * Invokes all callbacks registered with onCancel() and - * sets `cancelled = true`. - */ - notifyCancelled() { - if (!this._cancelled) { - this._cancelled = true; - for (let l of this._listeners) { - l(); + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - } - /** - * Send response headers. - */ - sendResponseHeaders(data) { - this._sendRH(data); - } - /** - * Is the call cancelled? - * - * When the client closes the connection before the server - * is done, the call is cancelled. - * - * If you want to cancel a request on the server, throw a - * RpcError with the CANCELLED status code. - */ - get cancelled() { - return this._cancelled; - } - /** - * Add a callback for cancellation. - */ - onCancel(callback) { - const l = this._listeners; - l.push(callback); - return () => { - let i = l.indexOf(callback); - if (i >= 0) - l.splice(i, 1); - }; - } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - exports2.ServerCallContextController = ServerCallContextController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js -var require_commonjs12 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var service_type_1 = require_service_type(); - Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { - return service_type_1.ServiceType; - } }); - var reflection_info_1 = require_reflection_info2(); - Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { - return reflection_info_1.readMethodOptions; - } }); - Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { - return reflection_info_1.readMethodOption; - } }); - Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { - return reflection_info_1.readServiceOption; - } }); - var rpc_error_1 = require_rpc_error(); - Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { - return rpc_error_1.RpcError; - } }); - var rpc_options_1 = require_rpc_options(); - Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { - return rpc_options_1.mergeRpcOptions; - } }); - var rpc_output_stream_1 = require_rpc_output_stream(); - Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { - return rpc_output_stream_1.RpcOutputStreamController; - } }); - var test_transport_1 = require_test_transport(); - Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { - return test_transport_1.TestTransport; - } }); - var deferred_1 = require_deferred(); - Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { - return deferred_1.Deferred; - } }); - Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { - return deferred_1.DeferredState; - } }); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { - return duplex_streaming_call_1.DuplexStreamingCall; - } }); - var client_streaming_call_1 = require_client_streaming_call(); - Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { - return client_streaming_call_1.ClientStreamingCall; - } }); - var server_streaming_call_1 = require_server_streaming_call(); - Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { - return server_streaming_call_1.ServerStreamingCall; - } }); - var unary_call_1 = require_unary_call(); - Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { - return unary_call_1.UnaryCall; - } }); - var rpc_interceptor_1 = require_rpc_interceptor(); - Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { - return rpc_interceptor_1.stackIntercept; - } }); - Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackDuplexStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackClientStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackServerStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackUnaryInterceptors; - } }); - var server_call_context_1 = require_server_call_context(); - Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { - return server_call_context_1.ServerCallContextController; - } }); - } -}); - -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js -var require_cachescope = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { - "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheScope = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var CacheScope$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheScope", [ - { - no: 1, - name: "scope", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "permission", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - } + exports2.internalCacheTwirpClient = void 0; + var core_1 = require_core(); + var user_agent_1 = require_user_agent(); + var errors_1 = require_errors2(); + var config_1 = require_config(); + var cacheUtils_1 = require_cacheUtils(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib3(); + var cache_twirp_client_1 = require_cache_twirp_client(); + var util_1 = require_util10(); + var CacheServiceClient = class { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3e3; + this.retryMultiplier = 1.5; + const token = (0, cacheUtils_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getCacheServiceURL)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; + } + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) ]); } - create(value) { - const message = { scope: "", permission: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { + return __awaiter4(this, void 0, void 0, function* () { + const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url}`); + const headers = { + "Content-Type": contentType + }; + try { + const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { + return this.httpClient.post(url, JSON.stringify(data), headers); + })); + return body; + } catch (error4) { + throw new Error(`Failed to ${method}: ${error4.message}`); + } + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string scope */ - 1: - message.scope = reader.string(); - break; - case /* int64 permission */ - 2: - message.permission = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + retryableRequest(operation) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ""; + let rawBody = ""; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, util_1.maskSecretUrls)(body); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } catch (error4) { + if (error4 instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + } + if (error4 instanceof errors_1.UsageError) { + throw error4; + } + if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { + throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + } + isRetryable = true; + errorMessage = error4.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; } - } - return message; + throw new Error(`Request failed`); + }); } - internalBinaryWrite(message, writer, options) { - if (message.scope !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); - if (message.permission !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; + } + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); + } + sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => setTimeout(resolve4, milliseconds)); + }); + } + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error("attempt should be a positive integer"); + } + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } }; - exports2.CacheScope = new CacheScope$Type(); + function internalCacheTwirpClient(options) { + const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new cache_twirp_client_1.CacheServiceClientJSON(client); + } + exports2.internalCacheTwirpClient = internalCacheTwirpClient; } }); -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js -var require_cachemetadata = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { +// node_modules/@actions/cache/lib/internal/tar.js +var require_tar = __commonJS({ + "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheMetadata = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachescope_1 = require_cachescope(); - var CacheMetadata$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheMetadata", [ - { - no: 1, - name: "repository_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } - ]); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - create(value) { - const message = { repositoryId: "0", scope: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int64 repository_id */ - 1: - message.repositoryId = reader.int64().toString(); + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTar = exports2.extractTar = exports2.listTar = void 0; + var exec_1 = require_exec(); + var io6 = __importStar4(require_io()); + var fs_1 = require("fs"); + var path8 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var IS_WINDOWS = process.platform === "win32"; + function getTarPath() { + return __awaiter4(this, void 0, void 0, function* () { + switch (process.platform) { + case "win32": { + const gnuTar = yield utils.getGnuTarPathOnWindows(); + const systemTar = constants_1.SystemTarPathOnWindows; + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else if ((0, fs_1.existsSync)(systemTar)) { + return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; + } + break; + } + case "darwin": { + const gnuTar = yield io6.which("gtar", false); + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else { + return { + path: yield io6.which("tar", true), + type: constants_1.ArchiveToolType.BSD + }; + } + } + default: + break; + } + return { + path: yield io6.which("tar", true), + type: constants_1.ArchiveToolType.GNU + }; + }); + } + function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + const args = [`"${tarPath.path}"`]; + const cacheFileName = utils.getCacheFileName(compressionMethod); + const tarFile = "cache.tar"; + const workingDirectory = getWorkingDirectory(); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (type2) { + case "create": + args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); + break; + case "extract": + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path8.sep}`, "g"), "/")); + break; + case "list": + args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "-P"); + break; + } + if (tarPath.type === constants_1.ArchiveToolType.GNU) { + switch (process.platform) { + case "win32": + args.push("--force-local"); break; - case /* repeated github.actions.results.entities.v1.CacheScope scope */ - 2: - message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + case "darwin": + args.push("--delay-directory-restore"); break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.repositoryId !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); - for (let i = 0; i < message.scope.length; i++) - cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } - }; - exports2.CacheMetadata = new CacheMetadata$Type(); + return args; + }); + } + function getCommands(compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + let args; + const tarPath = yield getTarPath(); + const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); + const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + if (BSD_TAR_ZSTD && type2 !== "create") { + args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; + } else { + args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; + } + if (BSD_TAR_ZSTD) { + return args; + } + return [args.join(" ")]; + }); + } + function getWorkingDirectory() { + var _a; + return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); + } + function getDecompressionProgram(tarPath, compressionMethod, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -d --long=30 --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path8.sep}`, "g"), "/") + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -d --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path8.sep}`, "g"), "/") + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; + default: + return ["-z"]; + } + }); + } + function getCompressionProgram(tarPath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheFileName = utils.getCacheFileName(compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --long=30 --force -o", + cacheFileName.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), + constants_1.TarFilename + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --force -o", + cacheFileName.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), + constants_1.TarFilename + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; + default: + return ["-z"]; + } + }); + } + function execCommands(commands, cwd) { + return __awaiter4(this, void 0, void 0, function* () { + for (const command of commands) { + try { + yield (0, exec_1.exec)(command, void 0, { + cwd, + env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) + }); + } catch (error4) { + throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + } + } + }); + } + function listTar(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const commands = yield getCommands(compressionMethod, "list", archivePath); + yield execCommands(commands); + }); + } + exports2.listTar = listTar; + function extractTar2(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const workingDirectory = getWorkingDirectory(); + yield io6.mkdirP(workingDirectory); + const commands = yield getCommands(compressionMethod, "extract", archivePath); + yield execCommands(commands); + }); + } + exports2.extractTar = extractTar2; + function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + (0, fs_1.writeFileSync)(path8.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); + const commands = yield getCommands(compressionMethod, "create"); + yield execCommands(commands, archiveFolder); + }); + } + exports2.createTar = createTar; } }); -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js -var require_cache2 = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { +// node_modules/@actions/cache/lib/cache.js +var require_cache3 = __commonJS({ + "node_modules/@actions/cache/lib/cache.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachemetadata_1 = require_cachemetadata(); - var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - create(value) { - const message = { key: "", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* string version */ - 3: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return message; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + var core13 = __importStar4(require_core()); + var path8 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var cacheHttpClient = __importStar4(require_cacheHttpClient()); + var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); + var config_1 = require_config(); + var tar_1 = require_tar(); + var http_client_1 = require_lib3(); + var ValidationError = class _ValidationError extends Error { + constructor(message) { + super(message); + this.name = "ValidationError"; + Object.setPrototypeOf(this, _ValidationError.prototype); } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.version !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + }; + exports2.ValidationError = ValidationError; + var ReserveCacheError = class _ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = "ReserveCacheError"; + Object.setPrototypeOf(this, _ReserveCacheError.prototype); } }; - exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); - var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_upload_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + exports2.ReserveCacheError = ReserveCacheError; + var FinalizeCacheError = class _FinalizeCacheError extends Error { + constructor(message) { + super(message); + this.name = "FinalizeCacheError"; + Object.setPrototypeOf(this, _FinalizeCacheError.prototype); } - create(value) { - const message = { ok: false, signedUploadUrl: "", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + }; + exports2.FinalizeCacheError = FinalizeCacheError; + function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_upload_url */ - 2: - message.signedUploadUrl = reader.string(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + } + function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); } - }; - exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); - var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "size_bytes", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + } + function isFeatureAvailable() { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + switch (cacheServiceVersion) { + case "v2": + return !!process.env["ACTIONS_RESULTS_URL"]; + case "v1": + default: + return !!process.env["ACTIONS_CACHE_URL"]; + } + } + exports2.isFeatureAvailable = isFeatureAvailable; + function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core13.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + switch (cacheServiceVersion) { + case "v2": + return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + case "v1": + default: + return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + } + }); + } + exports2.restoreCache = restoreCache3; + function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core13.debug("Resolved Keys:"); + core13.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + let archivePath = ""; + try { + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod, + enableCrossOsArchive + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + return void 0; + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core13.info("Lookup only - skipping download"); + return cacheEntry.cacheKey; + } + archivePath = path8.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core13.debug(`Archive Path: ${archivePath}`); + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core13.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core13.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core13.info("Cache restored successfully"); + return cacheEntry.cacheKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core13.error(`Failed to restore: ${error4.message}`); + } else { + core13.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core13.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core13.debug("Resolved Keys:"); + core13.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + let archivePath = ""; + try { + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + const compressionMethod = yield utils.getCompressionMethod(); + const request = { + key: primaryKey, + restoreKeys, + version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) + }; + const response = yield twirpClient.GetCacheEntryDownloadURL(request); + if (!response.ok) { + core13.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); + return void 0; + } + const isRestoreKeyMatch = request.key !== response.matchedKey; + if (isRestoreKeyMatch) { + core13.info(`Cache hit for restore-key: ${response.matchedKey}`); + } else { + core13.info(`Cache hit for: ${response.matchedKey}`); + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core13.info("Lookup only - skipping download"); + return response.matchedKey; + } + archivePath = path8.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core13.debug(`Archive path: ${archivePath}`); + core13.debug(`Starting download of archive to: ${archivePath}`); + yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core13.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + if (core13.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core13.info("Cache restored successfully"); + return response.matchedKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core13.error(`Failed to restore: ${error4.message}`); + } else { + core13.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + if (archivePath) { + yield utils.unlinkFile(archivePath); + } + } catch (error4) { + core13.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function saveCache3(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core13.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + checkKey(key); + switch (cacheServiceVersion) { + case "v2": + return yield saveCacheV2(paths, key, options, enableCrossOsArchive); + case "v1": + default: + return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + } + }); + } + exports2.saveCache = saveCache3; + function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { + var _a, _b, _c, _d, _e; + return __awaiter4(this, void 0, void 0, function* () { + const compressionMethod = yield utils.getCompressionMethod(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core13.debug("Cache Paths:"); + core13.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path8.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core13.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core13.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const fileSizeLimit = 10 * 1024 * 1024 * 1024; + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core13.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core13.debug("Reserving Cache"); + const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod, + enableCrossOsArchive, + cacheSize: archiveFileSize + }); + if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { + cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { + throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); + } else { + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); + } + core13.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError.name) { + core13.info(`Failed to save: ${typedError.message}`); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core13.error(`Failed to save: ${typedError.message}`); + } else { + core13.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core13.debug(`Failed to delete archive: ${error4}`); + } + } + return cacheId; + }); + } + function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); + const compressionMethod = yield utils.getCompressionMethod(); + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core13.debug("Cache Paths:"); + core13.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path8.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core13.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core13.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core13.debug(`File Size: ${archiveFileSize}`); + options.archiveSizeBytes = archiveFileSize; + core13.debug("Reserving Cache"); + const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); + const request = { + key, + version + }; + let signedUploadUrl; + try { + const response = yield twirpClient.CreateCacheEntry(request); + if (!response.ok) { + if (response.message) { + core13.warning(`Cache reservation failed: ${response.message}`); + } + throw new Error(response.message || "Response was not ok"); + } + signedUploadUrl = response.signedUploadUrl; + } catch (error4) { + core13.debug(`Failed to reserve cache: ${error4}`); + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); + } + core13.debug(`Attempting to upload cache located at: ${archivePath}`); + yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); + const finalizeRequest = { + key, + version, + sizeBytes: `${archiveFileSize}` + }; + const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); + core13.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); + if (!finalizeResponse.ok) { + if (finalizeResponse.message) { + throw new FinalizeCacheError(finalizeResponse.message); + } + throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); + } + cacheId = parseInt(finalizeResponse.entryId); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError.name) { + core13.info(`Failed to save: ${typedError.message}`); + } else if (typedError.name === FinalizeCacheError.name) { + core13.warning(typedError.message); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core13.error(`Failed to save: ${typedError.message}`); + } else { + core13.warning(`Failed to save: ${typedError.message}`); + } } - ]); - } - create(value) { - const message = { key: "", sizeBytes: "0", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* int64 size_bytes */ - 3: - message.sizeBytes = reader.int64().toString(); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core13.debug(`Failed to delete archive: ${error4}`); } } - return message; + return cacheId; + }); + } + } +}); + +// node_modules/jsonschema/lib/helpers.js +var require_helpers3 = __commonJS({ + "node_modules/jsonschema/lib/helpers.js"(exports2, module2) { + "use strict"; + var uri = require("url"); + var ValidationError = exports2.ValidationError = function ValidationError2(message, instance, schema2, path8, name, argument) { + if (Array.isArray(path8)) { + this.path = path8; + this.property = path8.reduce(function(sum, item) { + return sum + makeSuffix(item); + }, "instance"); + } else if (path8 !== void 0) { + this.property = path8; } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.sizeBytes !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + if (message) { + this.message = message; } - }; - exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); - var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "entry_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + if (schema2) { + var id = schema2.$id || schema2.id; + this.schema = id || schema2; } - create(value) { - const message = { ok: false, entryId: "0", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + if (instance !== void 0) { + this.instance = instance; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 entry_id */ - 2: - message.entryId = reader.int64().toString(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + this.name = name; + this.argument = argument; + this.stack = this.toString(); + }; + ValidationError.prototype.toString = function toString2() { + return this.property + " " + this.message; + }; + var ValidatorResult = exports2.ValidatorResult = function ValidatorResult2(instance, schema2, options, ctx) { + this.instance = instance; + this.schema = schema2; + this.options = options; + this.path = ctx.path; + this.propertyPath = ctx.propertyPath; + this.errors = []; + this.throwError = options && options.throwError; + this.throwFirst = options && options.throwFirst; + this.throwAll = options && options.throwAll; + this.disableFormat = options && options.disableFormat === true; + }; + ValidatorResult.prototype.addError = function addError(detail) { + var err; + if (typeof detail == "string") { + err = new ValidationError(detail, this.instance, this.schema, this.path); + } else { + if (!detail) throw new Error("Missing error detail"); + if (!detail.message) throw new Error("Missing error message"); + if (!detail.name) throw new Error("Missing validator type"); + err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.entryId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + this.errors.push(err); + if (this.throwFirst) { + throw new ValidatorResultError(this); + } else if (this.throwError) { + throw err; } + return err; }; - exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); - var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "restore_keys", - kind: "scalar", - repeat: 2, - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + ValidatorResult.prototype.importErrors = function importErrors(res) { + if (typeof res == "string" || res && res.validatorType) { + this.addError(res); + } else if (res && res.errors) { + this.errors = this.errors.concat(res.errors); } - create(value) { - const message = { key: "", restoreKeys: [], version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + }; + function stringizer(v, i) { + return i + ": " + v.toString() + "\n"; + } + ValidatorResult.prototype.toString = function toString2(res) { + return this.errors.map(stringizer).join(""); + }; + Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() { + return !this.errors.length; + } }); + module2.exports.ValidatorResultError = ValidatorResultError; + function ValidatorResultError(result) { + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ValidatorResultError); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* repeated string restore_keys */ - 3: - message.restoreKeys.push(reader.string()); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + this.instance = result.instance; + this.schema = result.schema; + this.options = result.options; + this.errors = result.errors; + } + ValidatorResultError.prototype = new Error(); + ValidatorResultError.prototype.constructor = ValidatorResultError; + ValidatorResultError.prototype.name = "Validation Error"; + var SchemaError = exports2.SchemaError = function SchemaError2(msg, schema2) { + this.message = msg; + this.schema = schema2; + Error.call(this, msg); + Error.captureStackTrace(this, SchemaError2); + }; + SchemaError.prototype = Object.create( + Error.prototype, + { + constructor: { value: SchemaError, enumerable: false }, + name: { value: "SchemaError", enumerable: false } } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - for (let i = 0; i < message.restoreKeys.length; i++) - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + ); + var SchemaContext = exports2.SchemaContext = function SchemaContext2(schema2, options, path8, base, schemas) { + this.schema = schema2; + this.options = options; + if (Array.isArray(path8)) { + this.path = path8; + this.propertyPath = path8.reduce(function(sum, item) { + return sum + makeSuffix(item); + }, "instance"); + } else { + this.propertyPath = path8; } + this.base = base; + this.schemas = schemas; }; - exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); - var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_download_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "matched_key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); - } - create(value) { - const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + SchemaContext.prototype.resolve = function resolve4(target) { + return uri.resolve(this.base, target); + }; + SchemaContext.prototype.makeChild = function makeChild(schema2, propertyName) { + var path8 = propertyName === void 0 ? this.path : this.path.concat([propertyName]); + var id = schema2.$id || schema2.id; + var base = uri.resolve(this.base, id || ""); + var ctx = new SchemaContext(schema2, this.options, path8, base, Object.create(this.schemas)); + if (id && !ctx.schemas[base]) { + ctx.schemas[base] = schema2; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_download_url */ - 2: - message.signedDownloadUrl = reader.string(); - break; - case /* string matched_key */ - 3: - message.matchedKey = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + return ctx; + }; + var FORMAT_REGEXPS = exports2.FORMAT_REGEXPS = { + // 7.3.1. Dates, Times, and Duration + "date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/, + "date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/, + "time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/, + "duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i, + // 7.3.2. Email Addresses + // TODO: fix the email production + "email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/, + "idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u, + // 7.3.3. Hostnames + // 7.3.4. IP Addresses + "ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, + // FIXME whitespace is invalid + "ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/, + // 7.3.5. Resource Identifiers + // TODO: A more accurate regular expression for "uri" goes: + // [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)? + "uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/, + "uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/, + "iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/, + "iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u, + "uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + // 7.3.6. uri-template + "uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu, + // 7.3.7. JSON Pointers + "json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu, + "relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu, + // hostname regex from: http://stackoverflow.com/a/1420225/5628 + "hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, + "host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, + "utc-millisec": function(input) { + return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input); + }, + // 7.3.8. regex + "regex": function(input) { + var result = true; + try { + new RegExp(input); + } catch (e) { + result = false; } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedDownloadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); - if (message.matchedKey !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + return result; + }, + // Other definitions + // "style" was removed from JSON Schema in draft-4 and is deprecated + "style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/, + // "color" was removed from JSON Schema in draft-4 and is deprecated + "color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/, + "phone": /^\+(?:[0-9] ?){6,14}[0-9]$/, + "alpha": /^[a-zA-Z]+$/, + "alphanumeric": /^[a-zA-Z0-9]+$/ + }; + FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex; + FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex; + FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"]; + exports2.isFormat = function isFormat(input, format, validator) { + if (typeof input === "string" && FORMAT_REGEXPS[format] !== void 0) { + if (FORMAT_REGEXPS[format] instanceof RegExp) { + return FORMAT_REGEXPS[format].test(input); + } + if (typeof FORMAT_REGEXPS[format] === "function") { + return FORMAT_REGEXPS[format](input); + } + } else if (validator && validator.customFormats && typeof validator.customFormats[format] === "function") { + return validator.customFormats[format](input); } + return true; }; - exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); - exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ - { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, - { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, - { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } - ]); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js -var require_cache_twirp_client = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; - var cache_1 = require_cache2(); - var CacheServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + var makeSuffix = exports2.makeSuffix = function makeSuffix2(key) { + key = key.toString(); + if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) { + return "." + key; } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false - }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { - ignoreUnknownFields: true - })); + if (key.match(/^\d+$/)) { + return "[" + key + "]"; + } + return "[" + JSON.stringify(key) + "]"; + }; + exports2.deepCompareStrict = function deepCompareStrict(a, b) { + if (typeof a !== typeof b) { + return false; } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + if (a.length !== b.length) { + return false; + } + return a.every(function(v, i) { + return deepCompareStrict(a[i], b[i]); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + if (typeof a === "object") { + if (!a || !b) { + return a === b; + } + var aKeys = Object.keys(a); + var bKeys = Object.keys(b); + if (aKeys.length !== bKeys.length) { + return false; + } + return aKeys.every(function(v) { + return deepCompareStrict(a[v], b[v]); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } + return a === b; }; - exports2.CacheServiceClientJSON = CacheServiceClientJSON; - var CacheServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + function deepMerger(target, dst, e, i) { + if (typeof e === "object") { + dst[i] = deepMerge(target[i], e); + } else { + if (target.indexOf(e) === -1) { + dst.push(e); + } } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); + } + function copyist(src, dst, key) { + dst[key] = src[key]; + } + function copyistWithDeepMerge(target, src, dst, key) { + if (typeof src[key] !== "object" || !src[key]) { + dst[key] = src[key]; + } else { + if (!target[key]) { + dst[key] = src[key]; + } else { + dst[key] = deepMerge(target[key], src[key]); + } } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); + } + function deepMerge(target, src) { + var array = Array.isArray(src); + var dst = array && [] || {}; + if (array) { + target = target || []; + dst = dst.concat(target); + src.forEach(deepMerger.bind(null, target, dst)); + } else { + if (target && typeof target === "object") { + Object.keys(target).forEach(copyist.bind(null, target, dst)); + } + Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst)); } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); + return dst; + } + module2.exports.deepMerge = deepMerge; + exports2.objectGetPath = function objectGetPath(o, s) { + var parts = s.split("/").slice(1); + var k; + while (typeof (k = parts.shift()) == "string") { + var n = decodeURIComponent(k.replace(/~0/, "~").replace(/~1/g, "/")); + if (!(n in o)) return; + o = o[n]; } + return o; }; - exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; - } -}); - -// node_modules/@actions/cache/lib/internal/shared/util.js -var require_util10 = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.maskSecretUrls = exports2.maskSigUrl = void 0; - var core_1 = require_core(); - function maskSigUrl(url) { - if (!url) - return; - try { - const parsedUrl = new URL(url); - const signature = parsedUrl.searchParams.get("sig"); - if (signature) { - (0, core_1.setSecret)(signature); - (0, core_1.setSecret)(encodeURIComponent(signature)); - } - } catch (error4) { - (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); - } + function pathEncoder(v) { + return "/" + encodeURIComponent(v).replace(/~/g, "%7E"); } - exports2.maskSigUrl = maskSigUrl; - function maskSecretUrls(body) { - if (typeof body !== "object" || body === null) { - (0, core_1.debug)("body is not an object or is null"); - return; + exports2.encodePath = function encodePointer(a) { + return a.map(pathEncoder).join(""); + }; + exports2.getDecimalPlaces = function getDecimalPlaces(number) { + var decimalPlaces = 0; + if (isNaN(number)) return decimalPlaces; + if (typeof number !== "number") { + number = Number(number); } - if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { - maskSigUrl(body.signed_upload_url); + var parts = number.toString().split("e"); + if (parts.length === 2) { + if (parts[1][0] !== "-") { + return decimalPlaces; + } else { + decimalPlaces = Number(parts[1].slice(1)); + } } - if ("signed_download_url" in body && typeof body.signed_download_url === "string") { - maskSigUrl(body.signed_download_url); + var decimalParts = parts[0].split("."); + if (decimalParts.length === 2) { + decimalPlaces += decimalParts[1].length; } - } - exports2.maskSecretUrls = maskSecretUrls; + return decimalPlaces; + }; + exports2.isSchema = function isSchema(val2) { + return typeof val2 === "object" && val2 || typeof val2 === "boolean"; + }; } }); -// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js -var require_cacheTwirpClient = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { +// node_modules/jsonschema/lib/attribute.js +var require_attribute = __commonJS({ + "node_modules/jsonschema/lib/attribute.js"(exports2, module2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); + var helpers = require_helpers3(); + var ValidatorResult = helpers.ValidatorResult; + var SchemaError = helpers.SchemaError; + var attribute = {}; + attribute.ignoreProperties = { + // informative properties + "id": true, + "default": true, + "description": true, + "title": true, + // arguments to other properties + "additionalItems": true, + "then": true, + "else": true, + // special-handled properties + "$schema": true, + "$ref": true, + "extends": true + }; + var validators = attribute.validators = {}; + validators.type = function validateType(instance, schema2, options, ctx) { + if (instance === void 0) { + return null; + } + var result = new ValidatorResult(instance, schema2, options, ctx); + var types = Array.isArray(schema2.type) ? schema2.type : [schema2.type]; + if (!types.some(this.testType.bind(this, instance, schema2, options, ctx))) { + var list = types.map(function(v) { + if (!v) return; + var id = v.$id || v.id; + return id ? "<" + id + ">" : v + ""; + }); + result.addError({ + name: "type", + argument: list, + message: "is not of a type(s) " + list }); } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + return result; + }; + function testSchemaNoThrow(instance, options, ctx, callback, schema2) { + var throwError2 = options.throwError; + var throwAll = options.throwAll; + options.throwError = false; + options.throwAll = false; + var res = this.validateSchema(instance, schema2, options, ctx); + options.throwError = throwError2; + options.throwAll = throwAll; + if (!res.valid && callback instanceof Function) { + callback(res); + } + return res.valid; + } + validators.anyOf = function validateAnyOf(instance, schema2, options, ctx) { + if (instance === void 0) { + return null; + } + var result = new ValidatorResult(instance, schema2, options, ctx); + var inner = new ValidatorResult(instance, schema2, options, ctx); + if (!Array.isArray(schema2.anyOf)) { + throw new SchemaError("anyOf must be an array"); + } + if (!schema2.anyOf.some( + testSchemaNoThrow.bind( + this, + instance, + options, + ctx, + function(res) { + inner.importErrors(res); } + ) + )) { + var list = schema2.anyOf.map(function(v, i) { + var id = v.$id || v.id; + if (id) return "<" + id + ">"; + return v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]"; + }); + if (options.nestedErrors) { + result.importErrors(inner); } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + result.addError({ + name: "anyOf", + argument: list, + message: "is not any of " + list.join(",") + }); + } + return result; + }; + validators.allOf = function validateAllOf(instance, schema2, options, ctx) { + if (instance === void 0) { + return null; + } + if (!Array.isArray(schema2.allOf)) { + throw new SchemaError("allOf must be an array"); + } + var result = new ValidatorResult(instance, schema2, options, ctx); + var self2 = this; + schema2.allOf.forEach(function(v, i) { + var valid3 = self2.validateSchema(instance, v, options, ctx); + if (!valid3.valid) { + var id = v.$id || v.id; + var msg = id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]"; + result.addError({ + name: "allOf", + argument: { id: msg, length: valid3.errors.length, valid: valid3 }, + message: "does not match allOf schema " + msg + " with " + valid3.errors.length + " error[s]:" + }); + result.importErrors(valid3); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); }); + return result; }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.internalCacheTwirpClient = void 0; - var core_1 = require_core(); - var user_agent_1 = require_user_agent(); - var errors_1 = require_errors2(); - var config_1 = require_config(); - var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); - var cache_twirp_client_1 = require_cache_twirp_client(); - var util_1 = require_util10(); - var CacheServiceClient = class { - constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { - this.maxAttempts = 5; - this.baseRetryIntervalMilliseconds = 3e3; - this.retryMultiplier = 1.5; - const token = (0, cacheUtils_1.getRuntimeToken)(); - this.baseUrl = (0, config_1.getCacheServiceURL)(); - if (maxAttempts) { - this.maxAttempts = maxAttempts; - } - if (baseRetryIntervalMilliseconds) { - this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; - } - if (retryMultiplier) { - this.retryMultiplier = retryMultiplier; - } - this.httpClient = new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(token) - ]); + validators.oneOf = function validateOneOf(instance, schema2, options, ctx) { + if (instance === void 0) { + return null; } - // This function satisfies the Rpc interface. It is compatible with the JSON - // JSON generated client. - request(service, method, contentType, data) { - return __awaiter4(this, void 0, void 0, function* () { - const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; - (0, core_1.debug)(`[Request] ${method} ${url}`); - const headers = { - "Content-Type": contentType - }; - try { - const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { - return this.httpClient.post(url, JSON.stringify(data), headers); - })); - return body; - } catch (error4) { - throw new Error(`Failed to ${method}: ${error4.message}`); - } - }); + if (!Array.isArray(schema2.oneOf)) { + throw new SchemaError("oneOf must be an array"); } - retryableRequest(operation) { - return __awaiter4(this, void 0, void 0, function* () { - let attempt = 0; - let errorMessage = ""; - let rawBody = ""; - while (attempt < this.maxAttempts) { - let isRetryable = false; - try { - const response = yield operation(); - const statusCode = response.message.statusCode; - rawBody = yield response.readBody(); - (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); - (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); - const body = JSON.parse(rawBody); - (0, util_1.maskSecretUrls)(body); - (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); - if (this.isSuccessStatusCode(statusCode)) { - return { response, body }; - } - isRetryable = this.isRetryableHttpStatusCode(statusCode); - errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; - if (body.msg) { - if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { - throw new errors_1.UsageError(); - } - errorMessage = `${errorMessage}: ${body.msg}`; - } - } catch (error4) { - if (error4 instanceof SyntaxError) { - (0, core_1.debug)(`Raw Body: ${rawBody}`); - } - if (error4 instanceof errors_1.UsageError) { - throw error4; - } - if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { - throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); - } - isRetryable = true; - errorMessage = error4.message; - } - if (!isRetryable) { - throw new Error(`Received non-retryable error: ${errorMessage}`); - } - if (attempt + 1 === this.maxAttempts) { - throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); - } - const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); - (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); - yield this.sleep(retryTimeMilliseconds); - attempt++; + var result = new ValidatorResult(instance, schema2, options, ctx); + var inner = new ValidatorResult(instance, schema2, options, ctx); + var count = schema2.oneOf.filter( + testSchemaNoThrow.bind( + this, + instance, + options, + ctx, + function(res) { + inner.importErrors(res); } - throw new Error(`Request failed`); + ) + ).length; + var list = schema2.oneOf.map(function(v, i) { + var id = v.$id || v.id; + return id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]"; + }); + if (count !== 1) { + if (options.nestedErrors) { + result.importErrors(inner); + } + result.addError({ + name: "oneOf", + argument: list, + message: "is not exactly one from " + list.join(",") }); } - isSuccessStatusCode(statusCode) { - if (!statusCode) - return false; - return statusCode >= 200 && statusCode < 300; + return result; + }; + validators.if = function validateIf(instance, schema2, options, ctx) { + if (instance === void 0) return null; + if (!helpers.isSchema(schema2.if)) throw new Error('Expected "if" keyword to be a schema'); + var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema2.if); + var result = new ValidatorResult(instance, schema2, options, ctx); + var res; + if (ifValid) { + if (schema2.then === void 0) return; + if (!helpers.isSchema(schema2.then)) throw new Error('Expected "then" keyword to be a schema'); + res = this.validateSchema(instance, schema2.then, options, ctx.makeChild(schema2.then)); + result.importErrors(res); + } else { + if (schema2.else === void 0) return; + if (!helpers.isSchema(schema2.else)) throw new Error('Expected "else" keyword to be a schema'); + res = this.validateSchema(instance, schema2.else, options, ctx.makeChild(schema2.else)); + result.importErrors(res); } - isRetryableHttpStatusCode(statusCode) { - if (!statusCode) - return false; - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.GatewayTimeout, - http_client_1.HttpCodes.InternalServerError, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.TooManyRequests - ]; - return retryableStatusCodes.includes(statusCode); + return result; + }; + function getEnumerableProperty(object, key) { + if (Object.hasOwnProperty.call(object, key)) return object[key]; + if (!(key in object)) return; + while (object = Object.getPrototypeOf(object)) { + if (Object.propertyIsEnumerable.call(object, key)) return object[key]; } - sleep(milliseconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve4) => setTimeout(resolve4, milliseconds)); + } + validators.propertyNames = function validatePropertyNames(instance, schema2, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var subschema = schema2.propertyNames !== void 0 ? schema2.propertyNames : {}; + if (!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)'); + for (var property in instance) { + if (getEnumerableProperty(instance, property) !== void 0) { + var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema)); + result.importErrors(res); + } + } + return result; + }; + validators.properties = function validateProperties(instance, schema2, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var properties = schema2.properties || {}; + for (var property in properties) { + var subschema = properties[property]; + if (subschema === void 0) { + continue; + } else if (subschema === null) { + throw new SchemaError('Unexpected null, expected schema in "properties"'); + } + if (typeof options.preValidateProperty == "function") { + options.preValidateProperty(instance, property, subschema, options, ctx); + } + var prop = getEnumerableProperty(instance, property); + var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property)); + if (res.instance !== result.instance[property]) result.instance[property] = res.instance; + result.importErrors(res); + } + return result; + }; + function testAdditionalProperty(instance, schema2, options, ctx, property, result) { + if (!this.types.object(instance)) return; + if (schema2.properties && schema2.properties[property] !== void 0) { + return; + } + if (schema2.additionalProperties === false) { + result.addError({ + name: "additionalProperties", + argument: property, + message: "is not allowed to have the additional property " + JSON.stringify(property) }); + } else { + var additionalProperties = schema2.additionalProperties || {}; + if (typeof options.preValidateProperty == "function") { + options.preValidateProperty(instance, property, additionalProperties, options, ctx); + } + var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property)); + if (res.instance !== result.instance[property]) result.instance[property] = res.instance; + result.importErrors(res); } - getExponentialRetryTimeMilliseconds(attempt) { - if (attempt < 0) { - throw new Error("attempt should be a positive integer"); + } + validators.patternProperties = function validatePatternProperties(instance, schema2, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var patternProperties = schema2.patternProperties || {}; + for (var property in instance) { + var test = true; + for (var pattern in patternProperties) { + var subschema = patternProperties[pattern]; + if (subschema === void 0) { + continue; + } else if (subschema === null) { + throw new SchemaError('Unexpected null, expected schema in "patternProperties"'); + } + try { + var regexp = new RegExp(pattern, "u"); + } catch (_e) { + regexp = new RegExp(pattern); + } + if (!regexp.test(property)) { + continue; + } + test = false; + if (typeof options.preValidateProperty == "function") { + options.preValidateProperty(instance, property, subschema, options, ctx); + } + var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property)); + if (res.instance !== result.instance[property]) result.instance[property] = res.instance; + result.importErrors(res); } - if (attempt === 0) { - return this.baseRetryIntervalMilliseconds; + if (test) { + testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result); } - const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); - const maxTime = minTime * this.retryMultiplier; - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } + return result; }; - function internalCacheTwirpClient(options) { - const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); - return new cache_twirp_client_1.CacheServiceClientJSON(client); - } - exports2.internalCacheTwirpClient = internalCacheTwirpClient; - } -}); - -// node_modules/@actions/cache/lib/internal/tar.js -var require_tar = __commonJS({ - "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + validators.additionalProperties = function validateAdditionalProperties(instance, schema2, options, ctx) { + if (!this.types.object(instance)) return; + if (schema2.patternProperties) { + return null; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + var result = new ValidatorResult(instance, schema2, options, ctx); + for (var property in instance) { + testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result); } - __setModuleDefault4(result, mod); return result; }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); + validators.minProperties = function validateMinProperties(instance, schema2, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var keys = Object.keys(instance); + if (!(keys.length >= schema2.minProperties)) { + result.addError({ + name: "minProperties", + argument: schema2.minProperties, + message: "does not meet minimum property length of " + schema2.minProperties }); } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + return result; + }; + validators.maxProperties = function validateMaxProperties(instance, schema2, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var keys = Object.keys(instance); + if (!(keys.length <= schema2.maxProperties)) { + result.addError({ + name: "maxProperties", + argument: schema2.maxProperties, + message: "does not meet maximum property length of " + schema2.maxProperties + }); + } + return result; + }; + validators.items = function validateItems(instance, schema2, options, ctx) { + var self2 = this; + if (!this.types.array(instance)) return; + if (schema2.items === void 0) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + instance.every(function(value, i) { + if (Array.isArray(schema2.items)) { + var items = schema2.items[i] === void 0 ? schema2.additionalItems : schema2.items[i]; + } else { + var items = schema2.items; } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + if (items === void 0) { + return true; } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + if (items === false) { + result.addError({ + name: "items", + message: "additionalItems not permitted" + }); + return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + var res = self2.validateSchema(value, items, options, ctx.makeChild(items, i)); + if (res.instance !== result.instance[i]) result.instance[i] = res.instance; + result.importErrors(res); + return true; }); + return result; }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTar = exports2.extractTar = exports2.listTar = void 0; - var exec_1 = require_exec(); - var io6 = __importStar4(require_io()); - var fs_1 = require("fs"); - var path8 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var constants_1 = require_constants7(); - var IS_WINDOWS = process.platform === "win32"; - function getTarPath() { - return __awaiter4(this, void 0, void 0, function* () { - switch (process.platform) { - case "win32": { - const gnuTar = yield utils.getGnuTarPathOnWindows(); - const systemTar = constants_1.SystemTarPathOnWindows; - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else if ((0, fs_1.existsSync)(systemTar)) { - return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; - } - break; - } - case "darwin": { - const gnuTar = yield io6.which("gtar", false); - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else { - return { - path: yield io6.which("tar", true), - type: constants_1.ArchiveToolType.BSD - }; - } - } - default: - break; - } - return { - path: yield io6.which("tar", true), - type: constants_1.ArchiveToolType.GNU - }; - }); - } - function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - const args = [`"${tarPath.path}"`]; - const cacheFileName = utils.getCacheFileName(compressionMethod); - const tarFile = "cache.tar"; - const workingDirectory = getWorkingDirectory(); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (type2) { - case "create": - args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); - break; - case "extract": - args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path8.sep}`, "g"), "/")); - break; - case "list": - args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), "-P"); - break; - } - if (tarPath.type === constants_1.ArchiveToolType.GNU) { - switch (process.platform) { - case "win32": - args.push("--force-local"); - break; - case "darwin": - args.push("--delay-directory-restore"); - break; - } - } - return args; + validators.contains = function validateContains(instance, schema2, options, ctx) { + var self2 = this; + if (!this.types.array(instance)) return; + if (schema2.contains === void 0) return; + if (!helpers.isSchema(schema2.contains)) throw new Error('Expected "contains" keyword to be a schema'); + var result = new ValidatorResult(instance, schema2, options, ctx); + var count = instance.some(function(value, i) { + var res = self2.validateSchema(value, schema2.contains, options, ctx.makeChild(schema2.contains, i)); + return res.errors.length === 0; }); - } - function getCommands(compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - let args; - const tarPath = yield getTarPath(); - const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); - const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - if (BSD_TAR_ZSTD && type2 !== "create") { - args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; - } else { - args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; + if (count === false) { + result.addError({ + name: "contains", + argument: schema2.contains, + message: "must contain an item matching given schema" + }); + } + return result; + }; + validators.minimum = function validateMinimum(instance, schema2, options, ctx) { + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + if (schema2.exclusiveMinimum && schema2.exclusiveMinimum === true) { + if (!(instance > schema2.minimum)) { + result.addError({ + name: "minimum", + argument: schema2.minimum, + message: "must be greater than " + schema2.minimum + }); } - if (BSD_TAR_ZSTD) { - return args; + } else { + if (!(instance >= schema2.minimum)) { + result.addError({ + name: "minimum", + argument: schema2.minimum, + message: "must be greater than or equal to " + schema2.minimum + }); } - return [args.join(" ")]; - }); - } - function getWorkingDirectory() { - var _a; - return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); - } - function getDecompressionProgram(tarPath, compressionMethod, archivePath) { - return __awaiter4(this, void 0, void 0, function* () { - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -d --long=30 --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path8.sep}`, "g"), "/") - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -d --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path8.sep}`, "g"), "/") - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; - default: - return ["-z"]; + } + return result; + }; + validators.maximum = function validateMaximum(instance, schema2, options, ctx) { + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + if (schema2.exclusiveMaximum && schema2.exclusiveMaximum === true) { + if (!(instance < schema2.maximum)) { + result.addError({ + name: "maximum", + argument: schema2.maximum, + message: "must be less than " + schema2.maximum + }); } - }); - } - function getCompressionProgram(tarPath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const cacheFileName = utils.getCacheFileName(compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --long=30 --force -o", - cacheFileName.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), - constants_1.TarFilename - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --force -o", - cacheFileName.replace(new RegExp(`\\${path8.sep}`, "g"), "/"), - constants_1.TarFilename - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; - default: - return ["-z"]; + } else { + if (!(instance <= schema2.maximum)) { + result.addError({ + name: "maximum", + argument: schema2.maximum, + message: "must be less than or equal to " + schema2.maximum + }); } - }); - } - function execCommands(commands, cwd) { - return __awaiter4(this, void 0, void 0, function* () { - for (const command of commands) { - try { - yield (0, exec_1.exec)(command, void 0, { - cwd, - env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) + } + return result; + }; + validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema2, options, ctx) { + if (typeof schema2.exclusiveMinimum === "boolean") return; + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var valid3 = instance > schema2.exclusiveMinimum; + if (!valid3) { + result.addError({ + name: "exclusiveMinimum", + argument: schema2.exclusiveMinimum, + message: "must be strictly greater than " + schema2.exclusiveMinimum + }); + } + return result; + }; + validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema2, options, ctx) { + if (typeof schema2.exclusiveMaximum === "boolean") return; + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var valid3 = instance < schema2.exclusiveMaximum; + if (!valid3) { + result.addError({ + name: "exclusiveMaximum", + argument: schema2.exclusiveMaximum, + message: "must be strictly less than " + schema2.exclusiveMaximum + }); + } + return result; + }; + var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema2, options, ctx, validationType, errorMessage) { + if (!this.types.number(instance)) return; + var validationArgument = schema2[validationType]; + if (validationArgument == 0) { + throw new SchemaError(validationType + " cannot be zero"); + } + var result = new ValidatorResult(instance, schema2, options, ctx); + var instanceDecimals = helpers.getDecimalPlaces(instance); + var divisorDecimals = helpers.getDecimalPlaces(validationArgument); + var maxDecimals = Math.max(instanceDecimals, divisorDecimals); + var multiplier = Math.pow(10, maxDecimals); + if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) { + result.addError({ + name: validationType, + argument: validationArgument, + message: errorMessage + JSON.stringify(validationArgument) + }); + } + return result; + }; + validators.multipleOf = function validateMultipleOf(instance, schema2, options, ctx) { + return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "multipleOf", "is not a multiple of (divisible by) "); + }; + validators.divisibleBy = function validateDivisibleBy(instance, schema2, options, ctx) { + return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "divisibleBy", "is not divisible by (multiple of) "); + }; + validators.required = function validateRequired(instance, schema2, options, ctx) { + var result = new ValidatorResult(instance, schema2, options, ctx); + if (instance === void 0 && schema2.required === true) { + result.addError({ + name: "required", + message: "is required" + }); + } else if (this.types.object(instance) && Array.isArray(schema2.required)) { + schema2.required.forEach(function(n) { + if (getEnumerableProperty(instance, n) === void 0) { + result.addError({ + name: "required", + argument: n, + message: "requires property " + JSON.stringify(n) }); - } catch (error4) { - throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); } - } - }); - } - function listTar(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const commands = yield getCommands(compressionMethod, "list", archivePath); - yield execCommands(commands); - }); - } - exports2.listTar = listTar; - function extractTar2(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const workingDirectory = getWorkingDirectory(); - yield io6.mkdirP(workingDirectory); - const commands = yield getCommands(compressionMethod, "extract", archivePath); - yield execCommands(commands); - }); - } - exports2.extractTar = extractTar2; - function createTar(archiveFolder, sourceDirectories, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - (0, fs_1.writeFileSync)(path8.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); - const commands = yield getCommands(compressionMethod, "create"); - yield execCommands(commands, archiveFolder); - }); - } - exports2.createTar = createTar; - } -}); - -// node_modules/@actions/cache/lib/cache.js -var require_cache3 = __commonJS({ - "node_modules/@actions/cache/lib/cache.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + return result; + }; + validators.pattern = function validatePattern(instance, schema2, options, ctx) { + if (!this.types.string(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var pattern = schema2.pattern; + try { + var regexp = new RegExp(pattern, "u"); + } catch (_e) { + regexp = new RegExp(pattern); + } + if (!instance.match(regexp)) { + result.addError({ + name: "pattern", + argument: schema2.pattern, + message: "does not match pattern " + JSON.stringify(schema2.pattern.toString()) + }); + } + return result; + }; + validators.format = function validateFormat(instance, schema2, options, ctx) { + if (instance === void 0) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + if (!result.disableFormat && !helpers.isFormat(instance, schema2.format, this)) { + result.addError({ + name: "format", + argument: schema2.format, + message: "does not conform to the " + JSON.stringify(schema2.format) + " format" + }); } - __setModuleDefault4(result, mod); return result; }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); + validators.minLength = function validateMinLength(instance, schema2, options, ctx) { + if (!this.types.string(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var hsp = instance.match(/[\uDC00-\uDFFF]/g); + var length = instance.length - (hsp ? hsp.length : 0); + if (!(length >= schema2.minLength)) { + result.addError({ + name: "minLength", + argument: schema2.minLength, + message: "does not meet minimum length of " + schema2.minLength }); } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return result; }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; - var core13 = __importStar4(require_core()); - var path8 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var cacheHttpClient = __importStar4(require_cacheHttpClient()); - var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); - var config_1 = require_config(); - var tar_1 = require_tar(); - var http_client_1 = require_lib(); - var ValidationError = class _ValidationError extends Error { - constructor(message) { - super(message); - this.name = "ValidationError"; - Object.setPrototypeOf(this, _ValidationError.prototype); + validators.maxLength = function validateMaxLength(instance, schema2, options, ctx) { + if (!this.types.string(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + var hsp = instance.match(/[\uDC00-\uDFFF]/g); + var length = instance.length - (hsp ? hsp.length : 0); + if (!(length <= schema2.maxLength)) { + result.addError({ + name: "maxLength", + argument: schema2.maxLength, + message: "does not meet maximum length of " + schema2.maxLength + }); } + return result; }; - exports2.ValidationError = ValidationError; - var ReserveCacheError = class _ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = "ReserveCacheError"; - Object.setPrototypeOf(this, _ReserveCacheError.prototype); + validators.minItems = function validateMinItems(instance, schema2, options, ctx) { + if (!this.types.array(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + if (!(instance.length >= schema2.minItems)) { + result.addError({ + name: "minItems", + argument: schema2.minItems, + message: "does not meet minimum length of " + schema2.minItems + }); } + return result; }; - exports2.ReserveCacheError = ReserveCacheError; - var FinalizeCacheError = class _FinalizeCacheError extends Error { - constructor(message) { - super(message); - this.name = "FinalizeCacheError"; - Object.setPrototypeOf(this, _FinalizeCacheError.prototype); + validators.maxItems = function validateMaxItems(instance, schema2, options, ctx) { + if (!this.types.array(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + if (!(instance.length <= schema2.maxItems)) { + result.addError({ + name: "maxItems", + argument: schema2.maxItems, + message: "does not meet maximum length of " + schema2.maxItems + }); } + return result; }; - exports2.FinalizeCacheError = FinalizeCacheError; - function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } - } - function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + function testArrays(v, i, a) { + var j, len = a.length; + for (j = i + 1, len; j < len; j++) { + if (helpers.deepCompareStrict(v, a[j])) { + return false; + } } + return true; } - function isFeatureAvailable() { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - switch (cacheServiceVersion) { - case "v2": - return !!process.env["ACTIONS_RESULTS_URL"]; - case "v1": - default: - return !!process.env["ACTIONS_CACHE_URL"]; + validators.uniqueItems = function validateUniqueItems(instance, schema2, options, ctx) { + if (schema2.uniqueItems !== true) return; + if (!this.types.array(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + if (!instance.every(testArrays)) { + result.addError({ + name: "uniqueItems", + message: "contains duplicate item" + }); } - } - exports2.isFeatureAvailable = isFeatureAvailable; - function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { - return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core13.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - switch (cacheServiceVersion) { - case "v2": - return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - case "v1": - default: - return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - } - }); - } - exports2.restoreCache = restoreCache3; - function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { - return __awaiter4(this, void 0, void 0, function* () { - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core13.debug("Resolved Keys:"); - core13.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); - } - const compressionMethod = yield utils.getCompressionMethod(); - let archivePath = ""; - try { - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod, - enableCrossOsArchive - }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - return void 0; - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core13.info("Lookup only - skipping download"); - return cacheEntry.cacheKey; - } - archivePath = path8.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core13.debug(`Archive Path: ${archivePath}`); - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core13.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core13.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core13.info("Cache restored successfully"); - return cacheEntry.cacheKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core13.error(`Failed to restore: ${error4.message}`); - } else { - core13.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core13.debug(`Failed to delete archive: ${error4}`); - } - } - return void 0; - }); - } - function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { - return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core13.debug("Resolved Keys:"); - core13.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + return result; + }; + validators.dependencies = function validateDependencies(instance, schema2, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema2, options, ctx); + for (var property in schema2.dependencies) { + if (instance[property] === void 0) { + continue; } - for (const key of keys) { - checkKey(key); + var dep = schema2.dependencies[property]; + var childContext = ctx.makeChild(dep, property); + if (typeof dep == "string") { + dep = [dep]; } - let archivePath = ""; - try { - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - const compressionMethod = yield utils.getCompressionMethod(); - const request = { - key: primaryKey, - restoreKeys, - version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) - }; - const response = yield twirpClient.GetCacheEntryDownloadURL(request); - if (!response.ok) { - core13.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); - return void 0; - } - const isRestoreKeyMatch = request.key !== response.matchedKey; - if (isRestoreKeyMatch) { - core13.info(`Cache hit for restore-key: ${response.matchedKey}`); - } else { - core13.info(`Cache hit for: ${response.matchedKey}`); - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core13.info("Lookup only - skipping download"); - return response.matchedKey; - } - archivePath = path8.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core13.debug(`Archive path: ${archivePath}`); - core13.debug(`Starting download of archive to: ${archivePath}`); - yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core13.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - if (core13.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core13.info("Cache restored successfully"); - return response.matchedKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core13.error(`Failed to restore: ${error4.message}`); - } else { - core13.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - if (archivePath) { - yield utils.unlinkFile(archivePath); + if (Array.isArray(dep)) { + dep.forEach(function(prop) { + if (instance[prop] === void 0) { + result.addError({ + // FIXME there's two different "dependencies" errors here with slightly different outputs + // Can we make these the same? Or should we create different error types? + name: "dependencies", + argument: childContext.propertyPath, + message: "property " + prop + " not found, required by " + childContext.propertyPath + }); } - } catch (error4) { - core13.debug(`Failed to delete archive: ${error4}`); - } - } - return void 0; - }); - } - function saveCache3(paths, key, options, enableCrossOsArchive = false) { - return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core13.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - checkKey(key); - switch (cacheServiceVersion) { - case "v2": - return yield saveCacheV2(paths, key, options, enableCrossOsArchive); - case "v1": - default: - return yield saveCacheV1(paths, key, options, enableCrossOsArchive); - } - }); - } - exports2.saveCache = saveCache3; - function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { - var _a, _b, _c, _d, _e; - return __awaiter4(this, void 0, void 0, function* () { - const compressionMethod = yield utils.getCompressionMethod(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core13.debug("Cache Paths:"); - core13.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); - } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path8.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core13.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core13.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const fileSizeLimit = 10 * 1024 * 1024 * 1024; - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core13.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); - } - core13.debug("Reserving Cache"); - const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod, - enableCrossOsArchive, - cacheSize: archiveFileSize }); - if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { - cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; - } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { - throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); - } else { - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); - } - core13.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError.name) { - core13.info(`Failed to save: ${typedError.message}`); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core13.error(`Failed to save: ${typedError.message}`); - } else { - core13.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core13.debug(`Failed to delete archive: ${error4}`); + } else { + var res = this.validateSchema(instance, dep, options, childContext); + if (result.instance !== res.instance) result.instance = res.instance; + if (res && res.errors.length) { + result.addError({ + name: "dependencies", + argument: childContext.propertyPath, + message: "does not meet dependency required by " + childContext.propertyPath + }); + result.importErrors(res); } } - return cacheId; - }); - } - function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { - return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); - const compressionMethod = yield utils.getCompressionMethod(); - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core13.debug("Cache Paths:"); - core13.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); - } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path8.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core13.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core13.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core13.debug(`File Size: ${archiveFileSize}`); - options.archiveSizeBytes = archiveFileSize; - core13.debug("Reserving Cache"); - const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); - const request = { - key, - version - }; - let signedUploadUrl; - try { - const response = yield twirpClient.CreateCacheEntry(request); - if (!response.ok) { - if (response.message) { - core13.warning(`Cache reservation failed: ${response.message}`); - } - throw new Error(response.message || "Response was not ok"); - } - signedUploadUrl = response.signedUploadUrl; - } catch (error4) { - core13.debug(`Failed to reserve cache: ${error4}`); - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); - } - core13.debug(`Attempting to upload cache located at: ${archivePath}`); - yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); - const finalizeRequest = { - key, - version, - sizeBytes: `${archiveFileSize}` - }; - const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); - core13.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); - if (!finalizeResponse.ok) { - if (finalizeResponse.message) { - throw new FinalizeCacheError(finalizeResponse.message); - } - throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); - } - cacheId = parseInt(finalizeResponse.entryId); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError.name) { - core13.info(`Failed to save: ${typedError.message}`); - } else if (typedError.name === FinalizeCacheError.name) { - core13.warning(typedError.message); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core13.error(`Failed to save: ${typedError.message}`); - } else { - core13.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core13.debug(`Failed to delete archive: ${error4}`); - } + } + return result; + }; + validators["enum"] = function validateEnum(instance, schema2, options, ctx) { + if (instance === void 0) { + return null; + } + if (!Array.isArray(schema2["enum"])) { + throw new SchemaError("enum expects an array", schema2); + } + var result = new ValidatorResult(instance, schema2, options, ctx); + if (!schema2["enum"].some(helpers.deepCompareStrict.bind(null, instance))) { + result.addError({ + name: "enum", + argument: schema2["enum"], + message: "is not one of enum values: " + schema2["enum"].map(String).join(",") + }); + } + return result; + }; + validators["const"] = function validateEnum(instance, schema2, options, ctx) { + if (instance === void 0) { + return null; + } + var result = new ValidatorResult(instance, schema2, options, ctx); + if (!helpers.deepCompareStrict(schema2["const"], instance)) { + result.addError({ + name: "const", + argument: schema2["const"], + message: "does not exactly match expected constant: " + schema2["const"] + }); + } + return result; + }; + validators.not = validators.disallow = function validateNot(instance, schema2, options, ctx) { + var self2 = this; + if (instance === void 0) return null; + var result = new ValidatorResult(instance, schema2, options, ctx); + var notTypes = schema2.not || schema2.disallow; + if (!notTypes) return null; + if (!Array.isArray(notTypes)) notTypes = [notTypes]; + notTypes.forEach(function(type2) { + if (self2.testType(instance, schema2, options, ctx, type2)) { + var id = type2 && (type2.$id || type2.id); + var schemaId = id || type2; + result.addError({ + name: "not", + argument: schemaId, + message: "is of prohibited type " + schemaId + }); } - return cacheId; }); - } + return result; + }; + module2.exports = attribute; } }); -// node_modules/jsonschema/lib/helpers.js -var require_helpers3 = __commonJS({ - "node_modules/jsonschema/lib/helpers.js"(exports2, module2) { +// node_modules/jsonschema/lib/scan.js +var require_scan = __commonJS({ + "node_modules/jsonschema/lib/scan.js"(exports2, module2) { "use strict"; - var uri = require("url"); - var ValidationError = exports2.ValidationError = function ValidationError2(message, instance, schema2, path8, name, argument) { - if (Array.isArray(path8)) { - this.path = path8; - this.property = path8.reduce(function(sum, item) { - return sum + makeSuffix(item); - }, "instance"); - } else if (path8 !== void 0) { - this.property = path8; - } - if (message) { - this.message = message; + var urilib = require("url"); + var helpers = require_helpers3(); + module2.exports.SchemaScanResult = SchemaScanResult; + function SchemaScanResult(found, ref) { + this.id = found; + this.ref = ref; + } + module2.exports.scan = function scan(base, schema2) { + function scanSchema(baseuri, schema3) { + if (!schema3 || typeof schema3 != "object") return; + if (schema3.$ref) { + var resolvedUri = urilib.resolve(baseuri, schema3.$ref); + ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0; + return; + } + var id = schema3.$id || schema3.id; + var ourBase = id ? urilib.resolve(baseuri, id) : baseuri; + if (ourBase) { + if (ourBase.indexOf("#") < 0) ourBase += "#"; + if (found[ourBase]) { + if (!helpers.deepCompareStrict(found[ourBase], schema3)) { + throw new Error("Schema <" + ourBase + "> already exists with different definition"); + } + return found[ourBase]; + } + found[ourBase] = schema3; + if (ourBase[ourBase.length - 1] == "#") { + found[ourBase.substring(0, ourBase.length - 1)] = schema3; + } + } + scanArray(ourBase + "/items", Array.isArray(schema3.items) ? schema3.items : [schema3.items]); + scanArray(ourBase + "/extends", Array.isArray(schema3.extends) ? schema3.extends : [schema3.extends]); + scanSchema(ourBase + "/additionalItems", schema3.additionalItems); + scanObject(ourBase + "/properties", schema3.properties); + scanSchema(ourBase + "/additionalProperties", schema3.additionalProperties); + scanObject(ourBase + "/definitions", schema3.definitions); + scanObject(ourBase + "/patternProperties", schema3.patternProperties); + scanObject(ourBase + "/dependencies", schema3.dependencies); + scanArray(ourBase + "/disallow", schema3.disallow); + scanArray(ourBase + "/allOf", schema3.allOf); + scanArray(ourBase + "/anyOf", schema3.anyOf); + scanArray(ourBase + "/oneOf", schema3.oneOf); + scanSchema(ourBase + "/not", schema3.not); } - if (schema2) { - var id = schema2.$id || schema2.id; - this.schema = id || schema2; + function scanArray(baseuri, schemas) { + if (!Array.isArray(schemas)) return; + for (var i = 0; i < schemas.length; i++) { + scanSchema(baseuri + "/" + i, schemas[i]); + } } - if (instance !== void 0) { - this.instance = instance; + function scanObject(baseuri, schemas) { + if (!schemas || typeof schemas != "object") return; + for (var p in schemas) { + scanSchema(baseuri + "/" + p, schemas[p]); + } } - this.name = name; - this.argument = argument; - this.stack = this.toString(); - }; - ValidationError.prototype.toString = function toString2() { - return this.property + " " + this.message; + var found = {}; + var ref = {}; + scanSchema(base, schema2); + return new SchemaScanResult(found, ref); }; - var ValidatorResult = exports2.ValidatorResult = function ValidatorResult2(instance, schema2, options, ctx) { - this.instance = instance; - this.schema = schema2; - this.options = options; - this.path = ctx.path; - this.propertyPath = ctx.propertyPath; - this.errors = []; - this.throwError = options && options.throwError; - this.throwFirst = options && options.throwFirst; - this.throwAll = options && options.throwAll; - this.disableFormat = options && options.disableFormat === true; + } +}); + +// node_modules/jsonschema/lib/validator.js +var require_validator2 = __commonJS({ + "node_modules/jsonschema/lib/validator.js"(exports2, module2) { + "use strict"; + var urilib = require("url"); + var attribute = require_attribute(); + var helpers = require_helpers3(); + var scanSchema = require_scan().scan; + var ValidatorResult = helpers.ValidatorResult; + var ValidatorResultError = helpers.ValidatorResultError; + var SchemaError = helpers.SchemaError; + var SchemaContext = helpers.SchemaContext; + var anonymousBase = "/"; + var Validator2 = function Validator3() { + this.customFormats = Object.create(Validator3.prototype.customFormats); + this.schemas = {}; + this.unresolvedRefs = []; + this.types = Object.create(types); + this.attributes = Object.create(attribute.validators); }; - ValidatorResult.prototype.addError = function addError(detail) { - var err; - if (typeof detail == "string") { - err = new ValidationError(detail, this.instance, this.schema, this.path); - } else { - if (!detail) throw new Error("Missing error detail"); - if (!detail.message) throw new Error("Missing error message"); - if (!detail.name) throw new Error("Missing validator type"); - err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument); + Validator2.prototype.customFormats = {}; + Validator2.prototype.schemas = null; + Validator2.prototype.types = null; + Validator2.prototype.attributes = null; + Validator2.prototype.unresolvedRefs = null; + Validator2.prototype.addSchema = function addSchema(schema2, base) { + var self2 = this; + if (!schema2) { + return null; } - this.errors.push(err); - if (this.throwFirst) { - throw new ValidatorResultError(this); - } else if (this.throwError) { - throw err; + var scan = scanSchema(base || anonymousBase, schema2); + var ourUri = base || schema2.$id || schema2.id; + for (var uri in scan.id) { + this.schemas[uri] = scan.id[uri]; } - return err; - }; - ValidatorResult.prototype.importErrors = function importErrors(res) { - if (typeof res == "string" || res && res.validatorType) { - this.addError(res); - } else if (res && res.errors) { - this.errors = this.errors.concat(res.errors); + for (var uri in scan.ref) { + this.unresolvedRefs.push(uri); } + this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) { + return typeof self2.schemas[uri2] === "undefined"; + }); + return this.schemas[ourUri]; }; - function stringizer(v, i) { - return i + ": " + v.toString() + "\n"; - } - ValidatorResult.prototype.toString = function toString2(res) { - return this.errors.map(stringizer).join(""); - }; - Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() { - return !this.errors.length; - } }); - module2.exports.ValidatorResultError = ValidatorResultError; - function ValidatorResultError(result) { - if (Error.captureStackTrace) { - Error.captureStackTrace(this, ValidatorResultError); + Validator2.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) { + if (!Array.isArray(schemas)) return; + for (var i = 0; i < schemas.length; i++) { + this.addSubSchema(baseuri, schemas[i]); } - this.instance = result.instance; - this.schema = result.schema; - this.options = result.options; - this.errors = result.errors; - } - ValidatorResultError.prototype = new Error(); - ValidatorResultError.prototype.constructor = ValidatorResultError; - ValidatorResultError.prototype.name = "Validation Error"; - var SchemaError = exports2.SchemaError = function SchemaError2(msg, schema2) { - this.message = msg; - this.schema = schema2; - Error.call(this, msg); - Error.captureStackTrace(this, SchemaError2); }; - SchemaError.prototype = Object.create( - Error.prototype, - { - constructor: { value: SchemaError, enumerable: false }, - name: { value: "SchemaError", enumerable: false } - } - ); - var SchemaContext = exports2.SchemaContext = function SchemaContext2(schema2, options, path8, base, schemas) { - this.schema = schema2; - this.options = options; - if (Array.isArray(path8)) { - this.path = path8; - this.propertyPath = path8.reduce(function(sum, item) { - return sum + makeSuffix(item); - }, "instance"); - } else { - this.propertyPath = path8; + Validator2.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) { + if (!schemas || typeof schemas != "object") return; + for (var p in schemas) { + this.addSubSchema(baseuri, schemas[p]); } - this.base = base; + }; + Validator2.prototype.setSchemas = function setSchemas(schemas) { this.schemas = schemas; }; - SchemaContext.prototype.resolve = function resolve4(target) { - return uri.resolve(this.base, target); + Validator2.prototype.getSchema = function getSchema(urn) { + return this.schemas[urn]; }; - SchemaContext.prototype.makeChild = function makeChild(schema2, propertyName) { - var path8 = propertyName === void 0 ? this.path : this.path.concat([propertyName]); - var id = schema2.$id || schema2.id; - var base = uri.resolve(this.base, id || ""); - var ctx = new SchemaContext(schema2, this.options, path8, base, Object.create(this.schemas)); - if (id && !ctx.schemas[base]) { - ctx.schemas[base] = schema2; + Validator2.prototype.validate = function validate(instance, schema2, options, ctx) { + if (typeof schema2 !== "boolean" && typeof schema2 !== "object" || schema2 === null) { + throw new SchemaError("Expected `schema` to be an object or boolean"); } - return ctx; - }; - var FORMAT_REGEXPS = exports2.FORMAT_REGEXPS = { - // 7.3.1. Dates, Times, and Duration - "date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/, - "date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/, - "time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/, - "duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i, - // 7.3.2. Email Addresses - // TODO: fix the email production - "email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/, - "idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u, - // 7.3.3. Hostnames - // 7.3.4. IP Addresses - "ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, - // FIXME whitespace is invalid - "ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/, - // 7.3.5. Resource Identifiers - // TODO: A more accurate regular expression for "uri" goes: - // [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)? - "uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/, - "uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/, - "iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/, - "iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u, - "uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i, - // 7.3.6. uri-template - "uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu, - // 7.3.7. JSON Pointers - "json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu, - "relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu, - // hostname regex from: http://stackoverflow.com/a/1420225/5628 - "hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, - "host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, - "utc-millisec": function(input) { - return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input); - }, - // 7.3.8. regex - "regex": function(input) { - var result = true; - try { - new RegExp(input); - } catch (e) { - result = false; + if (!options) { + options = {}; + } + var id = schema2.$id || schema2.id; + var base = urilib.resolve(options.base || anonymousBase, id || ""); + if (!ctx) { + ctx = new SchemaContext(schema2, options, [], base, Object.create(this.schemas)); + if (!ctx.schemas[base]) { + ctx.schemas[base] = schema2; + } + var found = scanSchema(base, schema2); + for (var n in found.id) { + var sch = found.id[n]; + ctx.schemas[n] = sch; } + } + if (options.required && instance === void 0) { + var result = new ValidatorResult(instance, schema2, options, ctx); + result.addError("is required, but is undefined"); return result; - }, - // Other definitions - // "style" was removed from JSON Schema in draft-4 and is deprecated - "style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/, - // "color" was removed from JSON Schema in draft-4 and is deprecated - "color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/, - "phone": /^\+(?:[0-9] ?){6,14}[0-9]$/, - "alpha": /^[a-zA-Z]+$/, - "alphanumeric": /^[a-zA-Z0-9]+$/ + } + var result = this.validateSchema(instance, schema2, options, ctx); + if (!result) { + throw new Error("Result undefined"); + } else if (options.throwAll && result.errors.length) { + throw new ValidatorResultError(result); + } + return result; }; - FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex; - FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex; - FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"]; - exports2.isFormat = function isFormat(input, format, validator) { - if (typeof input === "string" && FORMAT_REGEXPS[format] !== void 0) { - if (FORMAT_REGEXPS[format] instanceof RegExp) { - return FORMAT_REGEXPS[format].test(input); + function shouldResolve(schema2) { + var ref = typeof schema2 === "string" ? schema2 : schema2.$ref; + if (typeof ref == "string") return ref; + return false; + } + Validator2.prototype.validateSchema = function validateSchema(instance, schema2, options, ctx) { + var result = new ValidatorResult(instance, schema2, options, ctx); + if (typeof schema2 === "boolean") { + if (schema2 === true) { + schema2 = {}; + } else if (schema2 === false) { + schema2 = { type: [] }; } - if (typeof FORMAT_REGEXPS[format] === "function") { - return FORMAT_REGEXPS[format](input); + } else if (!schema2) { + throw new Error("schema is undefined"); + } + if (schema2["extends"]) { + if (Array.isArray(schema2["extends"])) { + var schemaobj = { schema: schema2, ctx }; + schema2["extends"].forEach(this.schemaTraverser.bind(this, schemaobj)); + schema2 = schemaobj.schema; + schemaobj.schema = null; + schemaobj.ctx = null; + schemaobj = null; + } else { + schema2 = helpers.deepMerge(schema2, this.superResolve(schema2["extends"], ctx)); } - } else if (validator && validator.customFormats && typeof validator.customFormats[format] === "function") { - return validator.customFormats[format](input); } - return true; + var switchSchema = shouldResolve(schema2); + if (switchSchema) { + var resolved = this.resolve(schema2, switchSchema, ctx); + var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas); + return this.validateSchema(instance, resolved.subschema, options, subctx); + } + var skipAttributes = options && options.skipAttributes || []; + for (var key in schema2) { + if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) { + var validatorErr = null; + var validator = this.attributes[key]; + if (validator) { + validatorErr = validator.call(this, instance, schema2, options, ctx); + } else if (options.allowUnknownAttributes === false) { + throw new SchemaError("Unsupported attribute: " + key, schema2); + } + if (validatorErr) { + result.importErrors(validatorErr); + } + } + } + if (typeof options.rewrite == "function") { + var value = options.rewrite.call(this, instance, schema2, options, ctx); + result.instance = value; + } + return result; }; - var makeSuffix = exports2.makeSuffix = function makeSuffix2(key) { - key = key.toString(); - if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) { - return "." + key; + Validator2.prototype.schemaTraverser = function schemaTraverser(schemaobj, s) { + schemaobj.schema = helpers.deepMerge(schemaobj.schema, this.superResolve(s, schemaobj.ctx)); + }; + Validator2.prototype.superResolve = function superResolve(schema2, ctx) { + var ref = shouldResolve(schema2); + if (ref) { + return this.resolve(schema2, ref, ctx).subschema; } - if (key.match(/^\d+$/)) { - return "[" + key + "]"; + return schema2; + }; + Validator2.prototype.resolve = function resolve4(schema2, switchSchema, ctx) { + switchSchema = ctx.resolve(switchSchema); + if (ctx.schemas[switchSchema]) { + return { subschema: ctx.schemas[switchSchema], switchSchema }; } - return "[" + JSON.stringify(key) + "]"; + var parsed = urilib.parse(switchSchema); + var fragment = parsed && parsed.hash; + var document2 = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length); + if (!document2 || !ctx.schemas[document2]) { + throw new SchemaError("no such schema <" + switchSchema + ">", schema2); + } + var subschema = helpers.objectGetPath(ctx.schemas[document2], fragment.substr(1)); + if (subschema === void 0) { + throw new SchemaError("no such schema " + fragment + " located in <" + document2 + ">", schema2); + } + return { subschema, switchSchema }; }; - exports2.deepCompareStrict = function deepCompareStrict(a, b) { - if (typeof a !== typeof b) { - return false; + Validator2.prototype.testType = function validateType(instance, schema2, options, ctx, type2) { + if (type2 === void 0) { + return; + } else if (type2 === null) { + throw new SchemaError('Unexpected null in "type" keyword'); } - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - return a.every(function(v, i) { - return deepCompareStrict(a[i], b[i]); + if (typeof this.types[type2] == "function") { + return this.types[type2].call(this, instance); + } + if (type2 && typeof type2 == "object") { + var res = this.validateSchema(instance, type2, options, ctx); + return res === void 0 || !(res && res.errors.length); + } + return true; + }; + var types = Validator2.prototype.types = {}; + types.string = function testString(instance) { + return typeof instance == "string"; + }; + types.number = function testNumber(instance) { + return typeof instance == "number" && isFinite(instance); + }; + types.integer = function testInteger(instance) { + return typeof instance == "number" && instance % 1 === 0; + }; + types.boolean = function testBoolean(instance) { + return typeof instance == "boolean"; + }; + types.array = function testArray(instance) { + return Array.isArray(instance); + }; + types["null"] = function testNull(instance) { + return instance === null; + }; + types.date = function testDate(instance) { + return instance instanceof Date; + }; + types.any = function testAny(instance) { + return true; + }; + types.object = function testObject(instance) { + return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date); + }; + module2.exports = Validator2; + } +}); + +// node_modules/jsonschema/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/jsonschema/lib/index.js"(exports2, module2) { + "use strict"; + var Validator2 = module2.exports.Validator = require_validator2(); + module2.exports.ValidatorResult = require_helpers3().ValidatorResult; + module2.exports.ValidatorResultError = require_helpers3().ValidatorResultError; + module2.exports.ValidationError = require_helpers3().ValidationError; + module2.exports.SchemaError = require_helpers3().SchemaError; + module2.exports.SchemaScanResult = require_scan().SchemaScanResult; + module2.exports.scan = require_scan().scan; + module2.exports.validate = function(instance, schema2, options) { + var v = new Validator2(); + return v.validate(instance, schema2, options); + }; + } +}); + +// node_modules/@actions/tool-cache/lib/manifest.js +var require_manifest = __commonJS({ + "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); }); } - if (typeof a === "object") { - if (!a || !b) { - return a === b; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - var aKeys = Object.keys(a); - var bKeys = Object.keys(b); - if (aKeys.length !== bKeys.length) { - return false; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - return aKeys.every(function(v) { - return deepCompareStrict(a[v], b[v]); - }); - } - return a === b; + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - function deepMerger(target, dst, e, i) { - if (typeof e === "object") { - dst[i] = deepMerge(target[i], e); - } else { - if (target.indexOf(e) === -1) { - dst.push(e); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; + var semver8 = __importStar4(require_semver2()); + var core_1 = require_core(); + var os3 = require("os"); + var cp = require("child_process"); + var fs9 = require("fs"); + function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os3.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); + if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + file = candidate.files.find((item) => { + (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module2.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } else { + chk = semver8.satisfies(osVersion, item.platform_version); + } + } + return chk; + }); + if (file) { + (0, core_1.debug)(`matched ${candidate.version}`); + match = candidate; + break; + } + } + } + if (match && file) { + result = Object.assign({}, match); + result.files = [file]; + } + return result; + }); + } + exports2._findMatch = _findMatch; + function _getOsVersion() { + const plat = os3.platform(); + let version = ""; + if (plat === "darwin") { + version = cp.execSync("sw_vers -productVersion").toString(); + } else if (plat === "linux") { + const lsbContents = module2.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split("\n"); + for (const line of lines) { + const parts = line.split("="); + if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { + version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); + break; + } + } } } + return version; } - function copyist(src, dst, key) { - dst[key] = src[key]; + exports2._getOsVersion = _getOsVersion; + function _readLinuxVersionFile() { + const lsbReleaseFile = "/etc/lsb-release"; + const osReleaseFile = "/etc/os-release"; + let contents = ""; + if (fs9.existsSync(lsbReleaseFile)) { + contents = fs9.readFileSync(lsbReleaseFile).toString(); + } else if (fs9.existsSync(osReleaseFile)) { + contents = fs9.readFileSync(osReleaseFile).toString(); + } + return contents; } - function copyistWithDeepMerge(target, src, dst, key) { - if (typeof src[key] !== "object" || !src[key]) { - dst[key] = src[key]; - } else { - if (!target[key]) { - dst[key] = src[key]; + exports2._readLinuxVersionFile = _readLinuxVersionFile; + } +}); + +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; } else { - dst[key] = deepMerge(target[key], src[key]); + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } + } else { + return void 0; } } - function deepMerge(target, src) { - var array = Array.isArray(src); - var dst = array && [] || {}; - if (array) { - target = target || []; - dst = dst.concat(target); - src.forEach(deepMerger.bind(null, target, dst)); - } else { - if (target && typeof target === "object") { - Object.keys(target).forEach(copyist.bind(null, target, dst)); + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst)); } - return dst; + return false; } - module2.exports.deepMerge = deepMerge; - exports2.objectGetPath = function objectGetPath(o, s) { - var parts = s.split("/").slice(1); - var k; - while (typeof (k = parts.shift()) == "string") { - var n = decodeURIComponent(k.replace(/~0/, "~").replace(/~1/g, "/")); - if (!(n in o)) return; - o = o[n]; - } - return o; - }; - function pathEncoder(v) { - return "/" + encodeURIComponent(v).replace(/~/g, "%7E"); + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); } - exports2.encodePath = function encodePointer(a) { - return a.map(pathEncoder).join(""); - }; - exports2.getDecimalPlaces = function getDecimalPlaces(number) { - var decimalPlaces = 0; - if (isNaN(number)) return decimalPlaces; - if (typeof number !== "number") { - number = Number(number); + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - var parts = number.toString().split("e"); - if (parts.length === 2) { - if (parts[1][0] !== "-") { - return decimalPlaces; - } else { - decimalPlaces = Number(parts[1].slice(1)); - } + get username() { + return this._decodedUsername; } - var decimalParts = parts[0].split("."); - if (decimalParts.length === 2) { - decimalPlaces += decimalParts[1].length; + get password() { + return this._decodedPassword; } - return decimalPlaces; - }; - exports2.isSchema = function isSchema(val2) { - return typeof val2 === "object" && val2 || typeof val2 === "boolean"; }; } }); -// node_modules/jsonschema/lib/attribute.js -var require_attribute = __commonJS({ - "node_modules/jsonschema/lib/attribute.js"(exports2, module2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - var helpers = require_helpers3(); - var ValidatorResult = helpers.ValidatorResult; - var SchemaError = helpers.SchemaError; - var attribute = {}; - attribute.ignoreProperties = { - // informative properties - "id": true, - "default": true, - "description": true, - "title": true, - // arguments to other properties - "additionalItems": true, - "then": true, - "else": true, - // special-handled properties - "$schema": true, - "$ref": true, - "extends": true - }; - var validators = attribute.validators = {}; - validators.type = function validateType(instance, schema2, options, ctx) { - if (instance === void 0) { - return null; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - var result = new ValidatorResult(instance, schema2, options, ctx); - var types = Array.isArray(schema2.type) ? schema2.type : [schema2.type]; - if (!types.some(this.testType.bind(this, instance, schema2, options, ctx))) { - var list = types.map(function(v) { - if (!v) return; - var id = v.$id || v.id; - return id ? "<" + id + ">" : v + ""; - }); - result.addError({ - name: "type", - argument: list, - message: "is not of a type(s) " + list - }); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); return result; }; - function testSchemaNoThrow(instance, options, ctx, callback, schema2) { - var throwError2 = options.throwError; - var throwAll = options.throwAll; - options.throwError = false; - options.throwAll = false; - var res = this.validateSchema(instance, schema2, options, ctx); - options.throwError = throwError2; - options.throwAll = throwAll; - if (!res.valid && callback instanceof Function) { - callback(res); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); } - return res.valid; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - validators.anyOf = function validateAnyOf(instance, schema2, options, ctx) { - if (instance === void 0) { - return null; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - var result = new ValidatorResult(instance, schema2, options, ctx); - var inner = new ValidatorResult(instance, schema2, options, ctx); - if (!Array.isArray(schema2.anyOf)) { - throw new SchemaError("anyOf must be an array"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!schema2.anyOf.some( - testSchemaNoThrow.bind( - this, - instance, - options, - ctx, - function(res) { - inner.importErrors(res); - } - ) - )) { - var list = schema2.anyOf.map(function(v, i) { - var id = v.$id || v.id; - if (id) return "<" + id + ">"; - return v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]"; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve4(output.toString()); + }); + })); }); - if (options.nestedErrors) { - result.importErrors(inner); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve4(Buffer.concat(chunks)); + }); + })); + }); + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } } - result.addError({ - name: "anyOf", - argument: list, - message: "is not any of " + list.join(",") + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); }); } - return result; - }; - validators.allOf = function validateAllOf(instance, schema2, options, ctx) { - if (instance === void 0) { - return null; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (!Array.isArray(schema2.allOf)) { - throw new SchemaError("allOf must be an array"); + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - var result = new ValidatorResult(instance, schema2, options, ctx); - var self2 = this; - schema2.allOf.forEach(function(v, i) { - var valid3 = self2.validateSchema(instance, v, options, ctx); - if (!valid3.valid) { - var id = v.$id || v.id; - var msg = id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]"; - result.addError({ - name: "allOf", - argument: { id: msg, length: valid3.errors.length, valid: valid3 }, - message: "does not match allOf schema " + msg + " with " + valid3.errors.length + " error[s]:" - }); - result.importErrors(valid3); - } - }); - return result; - }; - validators.oneOf = function validateOneOf(instance, schema2, options, ctx) { - if (instance === void 0) { - return null; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - if (!Array.isArray(schema2.oneOf)) { - throw new SchemaError("oneOf must be an array"); + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - var result = new ValidatorResult(instance, schema2, options, ctx); - var inner = new ValidatorResult(instance, schema2, options, ctx); - var count = schema2.oneOf.filter( - testSchemaNoThrow.bind( - this, - instance, - options, - ctx, - function(res) { - inner.importErrors(res); - } - ) - ).length; - var list = schema2.oneOf.map(function(v, i) { - var id = v.$id || v.id; - return id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]"; - }); - if (count !== 1) { - if (options.nestedErrors) { - result.importErrors(inner); - } - result.addError({ - name: "oneOf", - argument: list, - message: "is not exactly one from " + list.join(",") + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); }); } - return result; - }; - validators.if = function validateIf(instance, schema2, options, ctx) { - if (instance === void 0) return null; - if (!helpers.isSchema(schema2.if)) throw new Error('Expected "if" keyword to be a schema'); - var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema2.if); - var result = new ValidatorResult(instance, schema2, options, ctx); - var res; - if (ifValid) { - if (schema2.then === void 0) return; - if (!helpers.isSchema(schema2.then)) throw new Error('Expected "then" keyword to be a schema'); - res = this.validateSchema(instance, schema2.then, options, ctx.makeChild(schema2.then)); - result.importErrors(res); - } else { - if (schema2.else === void 0) return; - if (!helpers.isSchema(schema2.else)) throw new Error('Expected "else" keyword to be a schema'); - res = this.validateSchema(instance, schema2.else, options, ctx.makeChild(schema2.else)); - result.importErrors(res); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return result; - }; - function getEnumerableProperty(object, key) { - if (Object.hasOwnProperty.call(object, key)) return object[key]; - if (!(key in object)) return; - while (object = Object.getPrototypeOf(object)) { - if (Object.propertyIsEnumerable.call(object, key)) return object[key]; + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - } - validators.propertyNames = function validatePropertyNames(instance, schema2, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var subschema = schema2.propertyNames !== void 0 ? schema2.propertyNames : {}; - if (!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)'); - for (var property in instance) { - if (getEnumerableProperty(instance, property) !== void 0) { - var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema)); - result.importErrors(res); - } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - }; - validators.properties = function validateProperties(instance, schema2, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var properties = schema2.properties || {}; - for (var property in properties) { - var subschema = properties[property]; - if (subschema === void 0) { - continue; - } else if (subschema === null) { - throw new SchemaError('Unexpected null, expected schema in "properties"'); - } - if (typeof options.preValidateProperty == "function") { - options.preValidateProperty(instance, property, subschema, options, ctx); - } - var prop = getEnumerableProperty(instance, property); - var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property)); - if (res.instance !== result.instance[property]) result.instance[property] = res.instance; - result.importErrors(res); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - }; - function testAdditionalProperty(instance, schema2, options, ctx, property, result) { - if (!this.types.object(instance)) return; - if (schema2.properties && schema2.properties[property] !== void 0) { - return; + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - if (schema2.additionalProperties === false) { - result.addError({ - name: "additionalProperties", - argument: property, - message: "is not allowed to have the additional property " + JSON.stringify(property) + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - } else { - var additionalProperties = schema2.additionalProperties || {}; - if (typeof options.preValidateProperty == "function") { - options.preValidateProperty(instance, property, additionalProperties, options, ctx); - } - var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property)); - if (res.instance !== result.instance[property]) result.instance[property] = res.instance; - result.importErrors(res); } - } - validators.patternProperties = function validatePatternProperties(instance, schema2, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var patternProperties = schema2.patternProperties || {}; - for (var property in instance) { - var test = true; - for (var pattern in patternProperties) { - var subschema = patternProperties[pattern]; - if (subschema === void 0) { - continue; - } else if (subschema === null) { - throw new SchemaError('Unexpected null, expected schema in "patternProperties"'); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - try { - var regexp = new RegExp(pattern, "u"); - } catch (_e) { - regexp = new RegExp(pattern); + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve4(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } - if (!regexp.test(property)) { - continue; + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } - test = false; - if (typeof options.preValidateProperty == "function") { - options.preValidateProperty(instance, property, subschema, options, ctx); + } + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } - var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property)); - if (res.instance !== result.instance[property]) result.instance[property] = res.instance; - result.importErrors(res); + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - if (test) { - testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); } } - return result; - }; - validators.additionalProperties = function validateAdditionalProperties(instance, schema2, options, ctx) { - if (!this.types.object(instance)) return; - if (schema2.patternProperties) { - return null; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - var result = new ValidatorResult(instance, schema2, options, ctx); - for (var property in instance) { - testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return result; - }; - validators.minProperties = function validateMinProperties(instance, schema2, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var keys = Object.keys(instance); - if (!(keys.length >= schema2.minProperties)) { - result.addError({ - name: "minProperties", - argument: schema2.minProperties, - message: "does not meet minimum property length of " + schema2.minProperties - }); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; } - return result; - }; - validators.maxProperties = function validateMaxProperties(instance, schema2, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var keys = Object.keys(instance); - if (!(keys.length <= schema2.maxProperties)) { - result.addError({ - name: "maxProperties", - argument: schema2.maxProperties, - message: "does not meet maximum property length of " + schema2.maxProperties - }); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - return result; - }; - validators.items = function validateItems(instance, schema2, options, ctx) { - var self2 = this; - if (!this.types.array(instance)) return; - if (schema2.items === void 0) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - instance.every(function(value, i) { - if (Array.isArray(schema2.items)) { - var items = schema2.items[i] === void 0 ? schema2.additionalItems : schema2.items[i]; - } else { - var items = schema2.items; + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - if (items === void 0) { - return true; + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - if (items === false) { - result.addError({ - name: "items", - message: "additionalItems not permitted" - }); - return false; + if (!useProxy) { + agent = this._agent; } - var res = self2.validateSchema(value, items, options, ctx.makeChild(items, i)); - if (res.instance !== result.instance[i]) result.instance[i] = res.instance; - result.importErrors(res); - return true; - }); - return result; - }; - validators.contains = function validateContains(instance, schema2, options, ctx) { - var self2 = this; - if (!this.types.array(instance)) return; - if (schema2.contains === void 0) return; - if (!helpers.isSchema(schema2.contains)) throw new Error('Expected "contains" keyword to be a schema'); - var result = new ValidatorResult(instance, schema2, options, ctx); - var count = instance.some(function(value, i) { - var res = self2.validateSchema(value, schema2.contains, options, ctx.makeChild(schema2.contains, i)); - return res.errors.length === 0; - }); - if (count === false) { - result.addError({ - name: "contains", - argument: schema2.contains, - message: "must contain an item matching given schema" - }); - } - return result; - }; - validators.minimum = function validateMinimum(instance, schema2, options, ctx) { - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - if (schema2.exclusiveMinimum && schema2.exclusiveMinimum === true) { - if (!(instance > schema2.minimum)) { - result.addError({ - name: "minimum", - argument: schema2.minimum, - message: "must be greater than " + schema2.minimum - }); + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - } else { - if (!(instance >= schema2.minimum)) { - result.addError({ - name: "minimum", - argument: schema2.minimum, - message: "must be greater than or equal to " + schema2.minimum + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false }); } + return agent; } - return result; - }; - validators.maximum = function validateMaximum(instance, schema2, options, ctx) { - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - if (schema2.exclusiveMaximum && schema2.exclusiveMaximum === true) { - if (!(instance < schema2.maximum)) { - result.addError({ - name: "maximum", - argument: schema2.maximum, - message: "must be less than " + schema2.maximum - }); + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - } else { - if (!(instance <= schema2.maximum)) { - result.addError({ - name: "maximum", - argument: schema2.maximum, - message: "must be less than or equal to " + schema2.maximum + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false }); } + return proxyAgent; } - return result; - }; - validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema2, options, ctx) { - if (typeof schema2.exclusiveMinimum === "boolean") return; - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var valid3 = instance > schema2.exclusiveMinimum; - if (!valid3) { - result.addError({ - name: "exclusiveMinimum", - argument: schema2.exclusiveMinimum, - message: "must be strictly greater than " + schema2.exclusiveMinimum + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve4) => setTimeout(() => resolve4(), ms)); }); } - return result; - }; - validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema2, options, ctx) { - if (typeof schema2.exclusiveMaximum === "boolean") return; - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var valid3 = instance < schema2.exclusiveMaximum; - if (!valid3) { - result.addError({ - name: "exclusiveMaximum", - argument: schema2.exclusiveMaximum, - message: "must be strictly less than " + schema2.exclusiveMaximum + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve4(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve4(response); + } + })); }); } - return result; }; - var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema2, options, ctx, validationType, errorMessage) { - if (!this.types.number(instance)) return; - var validationArgument = schema2[validationType]; - if (validationArgument == 0) { - throw new SchemaError(validationType + " cannot be zero"); + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - var result = new ValidatorResult(instance, schema2, options, ctx); - var instanceDecimals = helpers.getDecimalPlaces(instance); - var divisorDecimals = helpers.getDecimalPlaces(validationArgument); - var maxDecimals = Math.max(instanceDecimals, divisorDecimals); - var multiplier = Math.pow(10, maxDecimals); - if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) { - result.addError({ - name: validationType, - argument: validationArgument, - message: errorMessage + JSON.stringify(validationArgument) - }); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); return result; }; - validators.multipleOf = function validateMultipleOf(instance, schema2, options, ctx) { - return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "multipleOf", "is not a multiple of (divisible by) "); - }; - validators.divisibleBy = function validateDivisibleBy(instance, schema2, options, ctx) { - return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "divisibleBy", "is not divisible by (multiple of) "); - }; - validators.required = function validateRequired(instance, schema2, options, ctx) { - var result = new ValidatorResult(instance, schema2, options, ctx); - if (instance === void 0 && schema2.required === true) { - result.addError({ - name: "required", - message: "is required" - }); - } else if (this.types.object(instance) && Array.isArray(schema2.required)) { - schema2.required.forEach(function(n) { - if (getEnumerableProperty(instance, n) === void 0) { - result.addError({ - name: "required", - argument: n, - message: "requires property " + JSON.stringify(n) - }); - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); }); } - return result; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - validators.pattern = function validatePattern(instance, schema2, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var pattern = schema2.pattern; - try { - var regexp = new RegExp(pattern, "u"); - } catch (_e) { - regexp = new RegExp(pattern); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RetryHelper = void 0; + var core13 = __importStar4(require_core()); + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); + } + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); + } } - if (!instance.match(regexp)) { - result.addError({ - name: "pattern", - argument: schema2.pattern, - message: "does not match pattern " + JSON.stringify(schema2.pattern.toString()) + execute(action, isRetryable) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 1; + while (attempt < this.maxAttempts) { + try { + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; + } + core13.info(err.message); + } + const seconds = this.getSleepAmount(); + core13.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); + attempt++; + } + return yield action(); }); } - return result; - }; - validators.format = function validateFormat(instance, schema2, options, ctx) { - if (instance === void 0) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - if (!result.disableFormat && !helpers.isFormat(instance, schema2.format, this)) { - result.addError({ - name: "format", - argument: schema2.format, - message: "does not conform to the " + JSON.stringify(schema2.format) + " format" - }); + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; } - return result; - }; - validators.minLength = function validateMinLength(instance, schema2, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var hsp = instance.match(/[\uDC00-\uDFFF]/g); - var length = instance.length - (hsp ? hsp.length : 0); - if (!(length >= schema2.minLength)) { - result.addError({ - name: "minLength", - argument: schema2.minLength, - message: "does not meet minimum length of " + schema2.minLength + sleep(seconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => setTimeout(resolve4, seconds * 1e3)); }); } - return result; }; - validators.maxLength = function validateMaxLength(instance, schema2, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - var hsp = instance.match(/[\uDC00-\uDFFF]/g); - var length = instance.length - (hsp ? hsp.length : 0); - if (!(length <= schema2.maxLength)) { - result.addError({ - name: "maxLength", - argument: schema2.maxLength, - message: "does not meet maximum length of " + schema2.maxLength - }); + exports2.RetryHelper = RetryHelper; + } +}); + +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - return result; - }; - validators.minItems = function validateMinItems(instance, schema2, options, ctx) { - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - if (!(instance.length >= schema2.minItems)) { - result.addError({ - name: "minItems", - argument: schema2.minItems, - message: "does not meet minimum length of " + schema2.minItems - }); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); return result; }; - validators.maxItems = function validateMaxItems(instance, schema2, options, ctx) { - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - if (!(instance.length <= schema2.maxItems)) { - result.addError({ - name: "maxItems", - argument: schema2.maxItems, - message: "does not meet maximum length of " + schema2.maxItems + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); }); } - return result; - }; - function testArrays(v, i, a) { - var j, len = a.length; - for (j = i + 1, len; j < len; j++) { - if (helpers.deepCompareStrict(v, a[j])) { - return false; + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; + var core13 = __importStar4(require_core()); + var io6 = __importStar4(require_io()); + var crypto = __importStar4(require("crypto")); + var fs9 = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os3 = __importStar4(require("os")); + var path8 = __importStar4(require("path")); + var httpm = __importStar4(require_lib5()); + var semver8 = __importStar4(require_semver2()); + var stream2 = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError2 = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); } - return true; + }; + exports2.HTTPError = HTTPError2; + var IS_WINDOWS = process.platform === "win32"; + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url, dest, auth, headers) { + return __awaiter4(this, void 0, void 0, function* () { + dest = dest || path8.join(_getTempDirectory(), crypto.randomUUID()); + yield io6.mkdirP(path8.dirname(dest)); + core13.debug(`Downloading ${url}`); + core13.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError2 && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; + } + } + return true; + }); + }); } - validators.uniqueItems = function validateUniqueItems(instance, schema2, options, ctx) { - if (schema2.uniqueItems !== true) return; - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - if (!instance.every(testArrays)) { - result.addError({ - name: "uniqueItems", - message: "contains duplicate item" + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url, dest, auth, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (fs9.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); + } + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false }); - } - return result; - }; - validators.dependencies = function validateDependencies(instance, schema2, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema2, options, ctx); - for (var property in schema2.dependencies) { - if (instance[property] === void 0) { - continue; + if (auth) { + core13.debug("set auth"); + if (headers === void 0) { + headers = {}; + } + headers.authorization = auth; } - var dep = schema2.dependencies[property]; - var childContext = ctx.makeChild(dep, property); - if (typeof dep == "string") { - dep = [dep]; + const response = yield http.get(url, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError2(response.message.statusCode); + core13.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; } - if (Array.isArray(dep)) { - dep.forEach(function(prop) { - if (instance[prop] === void 0) { - result.addError({ - // FIXME there's two different "dependencies" errors here with slightly different outputs - // Can we make these the same? Or should we create different error types? - name: "dependencies", - argument: childContext.propertyPath, - message: "property " + prop + " not found, required by " + childContext.propertyPath - }); + const pipeline = util.promisify(stream2.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; + try { + yield pipeline(readStream, fs9.createWriteStream(dest)); + core13.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core13.debug("download failed"); + try { + yield io6.rmRF(dest); + } catch (err) { + core13.debug(`Failed to delete '${dest}'. ${err.message}`); } - }); - } else { - var res = this.validateSchema(instance, dep, options, childContext); - if (result.instance !== res.instance) result.instance = res.instance; - if (res && res.errors.length) { - result.addError({ - name: "dependencies", - argument: childContext.propertyPath, - message: "does not meet dependency required by " + childContext.propertyPath - }); - result.importErrors(res); } } - } - return result; - }; - validators["enum"] = function validateEnum(instance, schema2, options, ctx) { - if (instance === void 0) { - return null; - } - if (!Array.isArray(schema2["enum"])) { - throw new SchemaError("enum expects an array", schema2); - } - var result = new ValidatorResult(instance, schema2, options, ctx); - if (!schema2["enum"].some(helpers.deepCompareStrict.bind(null, instance))) { - result.addError({ - name: "enum", - argument: schema2["enum"], - message: "is not one of enum values: " + schema2["enum"].map(String).join(",") - }); - } - return result; - }; - validators["const"] = function validateEnum(instance, schema2, options, ctx) { - if (instance === void 0) { - return null; - } - var result = new ValidatorResult(instance, schema2, options, ctx); - if (!helpers.deepCompareStrict(schema2["const"], instance)) { - result.addError({ - name: "const", - argument: schema2["const"], - message: "does not exactly match expected constant: " + schema2["const"] - }); - } - return result; - }; - validators.not = validators.disallow = function validateNot(instance, schema2, options, ctx) { - var self2 = this; - if (instance === void 0) return null; - var result = new ValidatorResult(instance, schema2, options, ctx); - var notTypes = schema2.not || schema2.disallow; - if (!notTypes) return null; - if (!Array.isArray(notTypes)) notTypes = [notTypes]; - notTypes.forEach(function(type2) { - if (self2.testType(instance, schema2, options, ctx, type2)) { - var id = type2 && (type2.$id || type2.id); - var schemaId = id || type2; - result.addError({ - name: "not", - argument: schemaId, - message: "is of prohibited type " + schemaId - }); + }); + } + function extract7z(file, dest, _7zPath) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { + try { + const logLevel = core13.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file + ]; + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } else { + const escapedScript = path8.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true + }; + try { + const powershellPath = yield io6.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } } + return dest; }); - return result; - }; - module2.exports = attribute; - } -}); - -// node_modules/jsonschema/lib/scan.js -var require_scan = __commonJS({ - "node_modules/jsonschema/lib/scan.js"(exports2, module2) { - "use strict"; - var urilib = require("url"); - var helpers = require_helpers3(); - module2.exports.SchemaScanResult = SchemaScanResult; - function SchemaScanResult(found, ref) { - this.id = found; - this.ref = ref; } - module2.exports.scan = function scan(base, schema2) { - function scanSchema(baseuri, schema3) { - if (!schema3 || typeof schema3 != "object") return; - if (schema3.$ref) { - var resolvedUri = urilib.resolve(baseuri, schema3.$ref); - ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0; - return; + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); } - var id = schema3.$id || schema3.id; - var ourBase = id ? urilib.resolve(baseuri, id) : baseuri; - if (ourBase) { - if (ourBase.indexOf("#") < 0) ourBase += "#"; - if (found[ourBase]) { - if (!helpers.deepCompareStrict(found[ourBase], schema3)) { - throw new Error("Schema <" + ourBase + "> already exists with different definition"); - } - return found[ourBase]; - } - found[ourBase] = schema3; - if (ourBase[ourBase.length - 1] == "#") { - found[ourBase.substring(0, ourBase.length - 1)] = schema3; + dest = yield _createExtractFolder(dest); + core13.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() } + }); + core13.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; } - scanArray(ourBase + "/items", Array.isArray(schema3.items) ? schema3.items : [schema3.items]); - scanArray(ourBase + "/extends", Array.isArray(schema3.extends) ? schema3.extends : [schema3.extends]); - scanSchema(ourBase + "/additionalItems", schema3.additionalItems); - scanObject(ourBase + "/properties", schema3.properties); - scanSchema(ourBase + "/additionalProperties", schema3.additionalProperties); - scanObject(ourBase + "/definitions", schema3.definitions); - scanObject(ourBase + "/patternProperties", schema3.patternProperties); - scanObject(ourBase + "/dependencies", schema3.dependencies); - scanArray(ourBase + "/disallow", schema3.disallow); - scanArray(ourBase + "/allOf", schema3.allOf); - scanArray(ourBase + "/anyOf", schema3.anyOf); - scanArray(ourBase + "/oneOf", schema3.oneOf); - scanSchema(ourBase + "/not", schema3.not); - } - function scanArray(baseuri, schemas) { - if (!Array.isArray(schemas)) return; - for (var i = 0; i < schemas.length; i++) { - scanSchema(baseuri + "/" + i, schemas[i]); + if (core13.isDebug() && !flags.includes("v")) { + args.push("-v"); } - } - function scanObject(baseuri, schemas) { - if (!schemas || typeof schemas != "object") return; - for (var p in schemas) { - scanSchema(baseuri + "/" + p, schemas[p]); + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); } - } - var found = {}; - var ref = {}; - scanSchema(base, schema2); - return new SchemaScanResult(found, ref); - }; - } -}); - -// node_modules/jsonschema/lib/validator.js -var require_validator2 = __commonJS({ - "node_modules/jsonschema/lib/validator.js"(exports2, module2) { - "use strict"; - var urilib = require("url"); - var attribute = require_attribute(); - var helpers = require_helpers3(); - var scanSchema = require_scan().scan; - var ValidatorResult = helpers.ValidatorResult; - var ValidatorResultError = helpers.ValidatorResultError; - var SchemaError = helpers.SchemaError; - var SchemaContext = helpers.SchemaContext; - var anonymousBase = "/"; - var Validator2 = function Validator3() { - this.customFormats = Object.create(Validator3.prototype.customFormats); - this.schemas = {}; - this.unresolvedRefs = []; - this.types = Object.create(types); - this.attributes = Object.create(attribute.validators); - }; - Validator2.prototype.customFormats = {}; - Validator2.prototype.schemas = null; - Validator2.prototype.types = null; - Validator2.prototype.attributes = null; - Validator2.prototype.unresolvedRefs = null; - Validator2.prototype.addSchema = function addSchema(schema2, base) { - var self2 = this; - if (!schema2) { - return null; - } - var scan = scanSchema(base || anonymousBase, schema2); - var ourUri = base || schema2.$id || schema2.id; - for (var uri in scan.id) { - this.schemas[uri] = scan.id[uri]; - } - for (var uri in scan.ref) { - this.unresolvedRefs.push(uri); - } - this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) { - return typeof self2.schemas[uri2] === "undefined"; + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); + } + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; }); - return this.schemas[ourUri]; - }; - Validator2.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) { - if (!Array.isArray(schemas)) return; - for (var i = 0; i < schemas.length; i++) { - this.addSubSchema(baseuri, schemas[i]); - } - }; - Validator2.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) { - if (!schemas || typeof schemas != "object") return; - for (var p in schemas) { - this.addSubSchema(baseuri, schemas[p]); - } - }; - Validator2.prototype.setSchemas = function setSchemas(schemas) { - this.schemas = schemas; - }; - Validator2.prototype.getSchema = function getSchema(urn) { - return this.schemas[urn]; - }; - Validator2.prototype.validate = function validate(instance, schema2, options, ctx) { - if (typeof schema2 !== "boolean" && typeof schema2 !== "object" || schema2 === null) { - throw new SchemaError("Expected `schema` to be an object or boolean"); - } - if (!options) { - options = {}; - } - var id = schema2.$id || schema2.id; - var base = urilib.resolve(options.base || anonymousBase, id || ""); - if (!ctx) { - ctx = new SchemaContext(schema2, options, [], base, Object.create(this.schemas)); - if (!ctx.schemas[base]) { - ctx.schemas[base] = schema2; + } + exports2.extractTar = extractTar2; + function extractXar(file, dest, flags = []) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; } - var found = scanSchema(base, schema2); - for (var n in found.id) { - var sch = found.id[n]; - ctx.schemas[n] = sch; + args.push("-x", "-C", dest, "-f", file); + if (core13.isDebug()) { + args.push("-v"); } - } - if (options.required && instance === void 0) { - var result = new ValidatorResult(instance, schema2, options, ctx); - result.addError("is required, but is undefined"); - return result; - } - var result = this.validateSchema(instance, schema2, options, ctx); - if (!result) { - throw new Error("Result undefined"); - } else if (options.throwAll && result.errors.length) { - throw new ValidatorResultError(result); - } - return result; - }; - function shouldResolve(schema2) { - var ref = typeof schema2 === "string" ? schema2 : schema2.$ref; - if (typeof ref == "string") return ref; - return false; + const xarPath = yield io6.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; + }); } - Validator2.prototype.validateSchema = function validateSchema(instance, schema2, options, ctx) { - var result = new ValidatorResult(instance, schema2, options, ctx); - if (typeof schema2 === "boolean") { - if (schema2 === true) { - schema2 = {}; - } else if (schema2 === false) { - schema2 = { type: [] }; + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); } - } else if (!schema2) { - throw new Error("schema is undefined"); - } - if (schema2["extends"]) { - if (Array.isArray(schema2["extends"])) { - var schemaobj = { schema: schema2, ctx }; - schema2["extends"].forEach(this.schemaTraverser.bind(this, schemaobj)); - schema2 = schemaobj.schema; - schemaobj.schema = null; - schemaobj.ctx = null; - schemaobj = null; + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); } else { - schema2 = helpers.deepMerge(schema2, this.superResolve(schema2["extends"], ctx)); + yield extractZipNix(file, dest); } - } - var switchSchema = shouldResolve(schema2); - if (switchSchema) { - var resolved = this.resolve(schema2, switchSchema, ctx); - var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas); - return this.validateSchema(instance, resolved.subschema, options, subctx); - } - var skipAttributes = options && options.skipAttributes || []; - for (var key in schema2) { - if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) { - var validatorErr = null; - var validator = this.attributes[key]; - if (validator) { - validatorErr = validator.call(this, instance, schema2, options, ctx); - } else if (options.allowUnknownAttributes === false) { - throw new SchemaError("Unsupported attribute: " + key, schema2); - } - if (validatorErr) { - result.importErrors(validatorErr); - } + return dest; + }); + } + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io6.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core13.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io6.which("powershell", true); + core13.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); } + }); + } + function extractZipNix(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const unzipPath = yield io6.which("unzip", true); + const args = [file]; + if (!core13.isDebug()) { + args.unshift("-q"); + } + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); + }); + } + function cacheDir(sourceDir, tool, version, arch2) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver8.clean(version) || version; + arch2 = arch2 || os3.arch(); + core13.debug(`Caching tool ${tool} ${version} ${arch2}`); + core13.debug(`source dir: ${sourceDir}`); + if (!fs9.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); + } + const destPath = yield _createToolPath(tool, version, arch2); + for (const itemName of fs9.readdirSync(sourceDir)) { + const s = path8.join(sourceDir, itemName); + yield io6.cp(s, destPath, { recursive: true }); + } + _completeToolPath(tool, version, arch2); + return destPath; + }); + } + exports2.cacheDir = cacheDir; + function cacheFile(sourceFile, targetFile, tool, version, arch2) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver8.clean(version) || version; + arch2 = arch2 || os3.arch(); + core13.debug(`Caching tool ${tool} ${version} ${arch2}`); + core13.debug(`source file: ${sourceFile}`); + if (!fs9.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); + } + const destFolder = yield _createToolPath(tool, version, arch2); + const destPath = path8.join(destFolder, targetFile); + core13.debug(`destination file ${destPath}`); + yield io6.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch2); + return destFolder; + }); + } + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch2) { + if (!toolName) { + throw new Error("toolName parameter is required"); } - if (typeof options.rewrite == "function") { - var value = options.rewrite.call(this, instance, schema2, options, ctx); - result.instance = value; - } - return result; - }; - Validator2.prototype.schemaTraverser = function schemaTraverser(schemaobj, s) { - schemaobj.schema = helpers.deepMerge(schemaobj.schema, this.superResolve(s, schemaobj.ctx)); - }; - Validator2.prototype.superResolve = function superResolve(schema2, ctx) { - var ref = shouldResolve(schema2); - if (ref) { - return this.resolve(schema2, ref, ctx).subschema; - } - return schema2; - }; - Validator2.prototype.resolve = function resolve4(schema2, switchSchema, ctx) { - switchSchema = ctx.resolve(switchSchema); - if (ctx.schemas[switchSchema]) { - return { subschema: ctx.schemas[switchSchema], switchSchema }; - } - var parsed = urilib.parse(switchSchema); - var fragment = parsed && parsed.hash; - var document2 = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length); - if (!document2 || !ctx.schemas[document2]) { - throw new SchemaError("no such schema <" + switchSchema + ">", schema2); - } - var subschema = helpers.objectGetPath(ctx.schemas[document2], fragment.substr(1)); - if (subschema === void 0) { - throw new SchemaError("no such schema " + fragment + " located in <" + document2 + ">", schema2); - } - return { subschema, switchSchema }; - }; - Validator2.prototype.testType = function validateType(instance, schema2, options, ctx, type2) { - if (type2 === void 0) { - return; - } else if (type2 === null) { - throw new SchemaError('Unexpected null in "type" keyword'); - } - if (typeof this.types[type2] == "function") { - return this.types[type2].call(this, instance); - } - if (type2 && typeof type2 == "object") { - var res = this.validateSchema(instance, type2, options, ctx); - return res === void 0 || !(res && res.errors.length); + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); } - return true; - }; - var types = Validator2.prototype.types = {}; - types.string = function testString(instance) { - return typeof instance == "string"; - }; - types.number = function testNumber(instance) { - return typeof instance == "number" && isFinite(instance); - }; - types.integer = function testInteger(instance) { - return typeof instance == "number" && instance % 1 === 0; - }; - types.boolean = function testBoolean(instance) { - return typeof instance == "boolean"; - }; - types.array = function testArray(instance) { - return Array.isArray(instance); - }; - types["null"] = function testNull(instance) { - return instance === null; - }; - types.date = function testDate(instance) { - return instance instanceof Date; - }; - types.any = function testAny(instance) { - return true; - }; - types.object = function testObject(instance) { - return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date); - }; - module2.exports = Validator2; - } -}); - -// node_modules/jsonschema/lib/index.js -var require_lib2 = __commonJS({ - "node_modules/jsonschema/lib/index.js"(exports2, module2) { - "use strict"; - var Validator2 = module2.exports.Validator = require_validator2(); - module2.exports.ValidatorResult = require_helpers3().ValidatorResult; - module2.exports.ValidatorResultError = require_helpers3().ValidatorResultError; - module2.exports.ValidationError = require_helpers3().ValidationError; - module2.exports.SchemaError = require_helpers3().SchemaError; - module2.exports.SchemaScanResult = require_scan().SchemaScanResult; - module2.exports.scan = require_scan().scan; - module2.exports.validate = function(instance, schema2, options) { - var v = new Validator2(); - return v.validate(instance, schema2, options); - }; - } -}); - -// node_modules/@actions/tool-cache/lib/manifest.js -var require_manifest = __commonJS({ - "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + arch2 = arch2 || os3.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions2(toolName, arch2); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + let toolPath = ""; + if (versionSpec) { + versionSpec = semver8.clean(versionSpec) || ""; + const cachePath = path8.join(_getCacheDirectory(), toolName, versionSpec, arch2); + core13.debug(`checking cache: ${cachePath}`); + if (fs9.existsSync(cachePath) && fs9.existsSync(`${cachePath}.complete`)) { + core13.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); + toolPath = cachePath; + } else { + core13.debug("not found"); + } } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); + return toolPath; + } + exports2.find = find2; + function findAllVersions2(toolName, arch2) { + const versions = []; + arch2 = arch2 || os3.arch(); + const toolPath = path8.join(_getCacheDirectory(), toolName); + if (fs9.existsSync(toolPath)) { + const children = fs9.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path8.join(toolPath, child, arch2 || ""); + if (fs9.existsSync(fullPath) && fs9.existsSync(`${fullPath}.complete`)) { + versions.push(child); + } + } + } } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + return versions; + } + exports2.findAllVersions = findAllVersions2; + function getManifestFromRepo(owner, repo, auth, branch = "master") { + return __awaiter4(this, void 0, void 0, function* () { + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core13.debug("set auth"); + headers.authorization = auth; + } + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; + } + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; } } - function rejected(value) { + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + releases = JSON.parse(versionsRaw); + } catch (_a) { + core13.debug("Invalid json"); } } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return releases; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver8 = __importStar4(require_semver2()); - var core_1 = require_core(); - var os3 = require("os"); - var cp = require("child_process"); - var fs9 = require("fs"); - function _findMatch(versionSpec, stable, candidates, archFilter) { + } + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os3.arch()) { return __awaiter4(this, void 0, void 0, function* () { - const platFilter = os3.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { - file = candidate.files.find((item) => { - (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module2.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } else { - chk = semver8.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - (0, core_1.debug)(`matched ${candidate.version}`); - match = candidate; - break; - } - } - } - if (match && file) { - result = Object.assign({}, match); - result.files = [file]; + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; + }); + } + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!dest) { + dest = path8.join(_getTempDirectory(), crypto.randomUUID()); } - return result; + yield io6.mkdirP(dest); + return dest; }); } - exports2._findMatch = _findMatch; - function _getOsVersion() { - const plat = os3.platform(); + function _createToolPath(tool, version, arch2) { + return __awaiter4(this, void 0, void 0, function* () { + const folderPath = path8.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); + core13.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io6.rmRF(folderPath); + yield io6.rmRF(markerPath); + yield io6.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch2) { + const folderPath = path8.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); + const markerPath = `${folderPath}.complete`; + fs9.writeFileSync(markerPath, ""); + core13.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver8.clean(versionSpec) || ""; + core13.debug(`isExplicit: ${c}`); + const valid3 = semver8.valid(c) != null; + core13.debug(`explicit? ${valid3}`); + return valid3; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { let version = ""; - if (plat === "darwin") { - version = cp.execSync("sw_vers -productVersion").toString(); - } else if (plat === "linux") { - const lsbContents = module2.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split("\n"); - for (const line of lines) { - const parts = line.split("="); - if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { - version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); - break; - } - } + core13.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver8.gt(a, b)) { + return 1; + } + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver8.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; } } + if (version) { + core13.debug(`matched: ${version}`); + } else { + core13.debug("match not found"); + } return version; } - exports2._getOsVersion = _getOsVersion; - function _readLinuxVersionFile() { - const lsbReleaseFile = "/etc/lsb-release"; - const osReleaseFile = "/etc/os-release"; - let contents = ""; - if (fs9.existsSync(lsbReleaseFile)) { - contents = fs9.readFileSync(lsbReleaseFile).toString(); - } else if (fs9.existsSync(osReleaseFile)) { - contents = fs9.readFileSync(osReleaseFile).toString(); - } - return contents; + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); } - exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + module2.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return true; + } + return a !== a && b !== b; }; + } +}); + +// node_modules/@actions/http-client/lib/proxy.js +var require_proxy5 = __commonJS({ + "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core13 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); + exports2.getProxyUrl = getProxyUrl; + exports2.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - execute(action, isRetryable) { - return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core13.info(err.message); - } - const seconds = this.getSleepAmount(); - core13.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - return yield action(); - }); + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + get username() { + return this._decodedUsername; } - sleep(seconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve4) => setTimeout(resolve4, seconds * 1e3)); - }); + get password() { + return this._decodedPassword; } }; - exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib6 = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74975,15 +77842,25 @@ var require_tool_cache = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve4) { @@ -75012,523 +77889,616 @@ var require_tool_cache = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core13 = __importStar4(require_core()); - var io6 = __importStar4(require_io()); - var crypto = __importStar4(require("crypto")); - var fs9 = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os3 = __importStar4(require("os")); - var path8 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver8 = __importStar4(require_semver2()); - var stream2 = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError2 = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy5()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.HTTPError = HTTPError2; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path8.join(_getTempDirectory(), crypto.randomUUID()); - yield io6.mkdirP(path8.dirname(dest)); - core13.debug(`Downloading ${url}`); - core13.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError2 && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve4(output.toString()); + }); + })); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs9.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve4(Buffer.concat(chunks)); + }); + })); }); - if (auth) { - core13.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - headers.authorization = auth; - } - const response = yield http.get(url, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError2(response.message.statusCode); - core13.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; - } - const pipeline = util.promisify(stream2.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs9.createWriteStream(dest)); - core13.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core13.debug("download failed"); - try { - yield io6.rmRF(dest); - } catch (err) { - core13.debug(`Failed to delete '${dest}'. ${err.message}`); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core13.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } else { - const escapedScript = path8.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io6.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core13.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - core13.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core13.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - args.push("-x", "-C", dest, "-f", file); - if (core13.isDebug()) { - args.push("-v"); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve4(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - const xarPath = yield io6.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io6.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core13.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io6.which("powershell", true); - core13.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); - } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io6.which("unzip", true); - const args = [file]; - if (!core13.isDebug()) { - args.unshift("-q"); + req.end(); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir(sourceDir, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch2 = arch2 || os3.arch(); - core13.debug(`Caching tool ${tool} ${version} ${arch2}`); - core13.debug(`source dir: ${sourceDir}`); - if (!fs9.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const destPath = yield _createToolPath(tool, version, arch2); - for (const itemName of fs9.readdirSync(sourceDir)) { - const s = path8.join(sourceDir, itemName); - yield io6.cp(s, destPath, { recursive: true }); + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - _completeToolPath(tool, version, arch2); - return destPath; - }); - } - exports2.cacheDir = cacheDir; - function cacheFile(sourceFile, targetFile, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch2 = arch2 || os3.arch(); - core13.debug(`Caching tool ${tool} ${version} ${arch2}`); - core13.debug(`source file: ${sourceFile}`); - if (!fs9.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } } - const destFolder = yield _createToolPath(tool, version, arch2); - const destPath = path8.join(destFolder, targetFile); - core13.debug(`destination file ${destPath}`); - yield io6.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch2); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch2) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); + return info6; } - arch2 = arch2 || os3.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions2(toolName, arch2); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver8.clean(versionSpec) || ""; - const cachePath = path8.join(_getCacheDirectory(), toolName, versionSpec, arch2); - core13.debug(`checking cache: ${cachePath}`); - if (fs9.existsSync(cachePath) && fs9.existsSync(`${cachePath}.complete`)) { - core13.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); - toolPath = cachePath; - } else { - core13.debug("not found"); + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return toolPath; - } - exports2.find = find2; - function findAllVersions2(toolName, arch2) { - const versions = []; - arch2 = arch2 || os3.arch(); - const toolPath = path8.join(_getCacheDirectory(), toolName); - if (fs9.existsSync(toolPath)) { - const children = fs9.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path8.join(toolPath, child, arch2 || ""); - if (fs9.existsSync(fullPath) && fs9.existsSync(`${fullPath}.complete`)) { - versions.push(child); + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; } } } + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; + } + } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return versions; - } - exports2.findAllVersions = findAllVersions2; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core13.debug("set auth"); - headers.authorization = auth; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + if (!useProxy) { + agent = this._agent; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; - } + if (agent) { + return agent; } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core13.debug("Invalid json"); - } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os3.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path8.join(_getTempDirectory(), crypto.randomUUID()); + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - yield io6.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path8.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); - core13.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io6.rmRF(folderPath); - yield io6.rmRF(markerPath); - yield io6.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch2) { - const folderPath = path8.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); - const markerPath = `${folderPath}.complete`; - fs9.writeFileSync(markerPath, ""); - core13.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver8.clean(versionSpec) || ""; - core13.debug(`isExplicit: ${c}`); - const valid3 = semver8.valid(c) != null; - core13.debug(`explicit? ${valid3}`); - return valid3; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core13.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver8.gt(a, b)) { - return 1; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver8.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } + return agent; } - if (version) { - core13.debug(`matched: ${version}`); - } else { - core13.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; + if (proxyAgent) { + return proxyAgent; } - return true; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve4) => setTimeout(() => resolve4(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve4, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve4(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve4(response); + } + })); + }); } - return a !== a && b !== b; }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -80301,7 +83271,7 @@ var supportedAnalysisKinds = new Set(Object.values(AnalysisKind)); var core8 = __toESM(require_core()); // src/config/db-config.ts -var jsonschema = __toESM(require_lib2()); +var jsonschema = __toESM(require_lib4()); var semver4 = __toESM(require_semver2()); var PACK_IDENTIFIER_PATTERN = (function() { const alphaNumeric = "[a-z0-9]"; @@ -80528,7 +83498,7 @@ var os = __toESM(require("os")); var path5 = __toESM(require("path")); var import_perf_hooks = require("perf_hooks"); var core9 = __toESM(require_core()); -var import_http_client = __toESM(require_lib()); +var import_http_client = __toESM(require_lib6()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); var semver6 = __toESM(require_semver2()); diff --git a/lib/start-proxy-action-post.js b/lib/start-proxy-action-post.js index 74d09e9663..25f71a96ed 100644 --- a/lib/start-proxy-action-post.js +++ b/lib/start-proxy-action-post.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -19875,9 +19875,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -19934,737 +20016,826 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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 (isPlainObject(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+)|(?:(? a.concat(b), []); - } - function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - } - function encodeReserved(str2) { - return str2.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(str2) { - return encodeURIComponent(str2).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; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - function isDefined2(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context2, operator, key, modifier) { - var value = context2[key], result = []; - if (isDefined2(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)); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - result.push(encodeValue(operator, value[k], k)); + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; } - }); + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } } - }); + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - } else { - if (operator === ";") { - if (isDefined2(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; - } - function expand(template, context2) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_2, 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(context2, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); } - } else { - return encodeReserved(literal); + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } - } - function parse(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 = omit(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 = omit(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(","); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + req.end(); } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); - } - function endpointWithDefaults(defaults, route, options) { - return parse(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 - }); - } - var endpoint = withDefaults(null, DEFAULTS); - } -}); - -// node_modules/deprecation/dist-node/index.js -var require_dist_node3 = __commonJS({ - "node_modules/deprecation/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var Deprecation = class extends Error { - constructor(message) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; } - this.name = "Deprecation"; + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; } - }; - exports2.Deprecation = Deprecation; - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - return ret; + return additionalHeaders[header] || clientHeader || _default2; } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; + var httpClient = __importStar4(require_lib2()); + var undici_1 = require_undici(); + function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error("Parameter token or opts.auth is required"); + } else if (token && options.auth) { + throw new Error("Parameters token and opts.auth may not both be specified"); + } + return typeof options.auth === "string" ? options.auth : `token ${token}`; + } + exports2.getAuthString = getAuthString; + function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + exports2.getProxyAgent = getProxyAgent; + function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); + } + exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; + function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; + return proxyFetch; } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; } + exports2.getApiBaseUrl = getApiBaseUrl; } }); -// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node4 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { "use strict"; - var __create2 = Object.create; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - RequestError: () => RequestError - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_deprecation = require_dist_node3(); - var import_once = __toESM2(require_once()); - var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - request: () => request - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node2(); - var import_universal_user_agent = require_dist_node(); - var VERSION = "8.4.1"; - function isPlainObject(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); - } - var import_request_error = require_dist_node4(); - function getBufferResponse(response) { - return response.arrayBuffer(); - } - function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - 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" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } - }).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error4; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error4) => { - if (error4 instanceof import_request_error.RequestError) - throw error4; - else if (error4.name === "AbortError") - throw error4; - let message = error4.message; - if (error4.name === "TypeError" && "cause" in error4) { - if (error4.cause instanceof Error) { - message = error4.cause.message; - } else if (typeof error4.cause === "string") { - message = error4.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); - } - 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 getBufferResponse(response); - } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; - } - function withDefaults(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: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - } - var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } - }); - } -}); - -// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node6 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint + endpoint: () => endpoint }); module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); @@ -21218,9 +21179,101 @@ var require_dist_node6 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node7 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/deprecation/dist-node/index.js +var require_dist_node3 = __commonJS({ + "node_modules/deprecation/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var Deprecation = class extends Error { + constructor(message) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "Deprecation"; + } + }; + exports2.Deprecation = Deprecation; + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node4 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; var __create2 = Object.create; var __defProp2 = Object.defineProperty; @@ -21310,9 +21363,9 @@ var require_dist_node7 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js -var require_dist_node8 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js +var require_dist_node5 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21336,7 +21389,7 @@ var require_dist_node8 = __commonJS({ request: () => request }); module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node6(); + var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; function isPlainObject(value) { @@ -21350,7 +21403,7 @@ var require_dist_node8 = __commonJS({ 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); } - var import_request_error = require_dist_node7(); + var import_request_error = require_dist_node4(); function getBufferResponse(response) { return response.arrayBuffer(); } @@ -21520,9 +21573,9 @@ var require_dist_node8 = __commonJS({ } }); -// node_modules/@octokit/graphql/dist-node/index.js -var require_dist_node9 = __commonJS({ - "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node6 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21541,129 +21594,340 @@ var require_dist_node9 = __commonJS({ return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export2(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint }); - module2.exports = __toCommonJS2(index_exports); - var import_request3 = require_dist_node8(); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); - var VERSION = "7.1.1"; - var import_request2 = require_dist_node8(); - var import_request = require_dist_node8(); - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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; + }, {}); } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + function isPlainObject(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 (isPlainObject(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]; } } - }; - 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`) - ); + 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); } - 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` - ) - ); + 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+)|(?:(? { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } + function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; } - if (!result.variables) { - result.variables = {}; + } + return result; + } + function encodeReserved(str2) { + return str2.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, "]"); } - 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 part; + }).join(""); + } + function encodeUnreserved(str2) { + return encodeURIComponent(str2).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; } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; + } + function isDefined2(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context2, operator, key, modifier) { + var value = context2[key], result = []; + if (isDefined2(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)); } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(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(",")); + } + } } - return response.data.data; - }); + } else { + if (operator === ";") { + if (isDefined2(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; } - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); + function parseUrl(template) { + return { + expand: expand.bind(null, template) }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); } - var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" - }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" + function expand(template, context2) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_2, 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(context2, 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 parse(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 = omit(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 = omit(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(/(? { + 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 parse(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 }); } + var endpoint = withDefaults(null, DEFAULTS); } }); -// node_modules/@octokit/auth-token/dist-node/index.js -var require_dist_node10 = __commonJS({ - "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node7 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; + var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) @@ -21677,53 +21941,490 @@ var require_dist_node10 = __commonJS({ } return to; }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - createTokenAuth: () => createTokenAuth + RequestError: () => RequestError }); module2.exports = __toCommonJS2(dist_src_exports); - 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, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); - } - 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" - ); + var import_deprecation = require_dist_node3(); + var import_once = __toESM2(require_once()); + var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + request: () => request + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_endpoint = require_dist_node6(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "8.4.1"; + function isPlainObject(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); + } + var import_request_error = require_dist_node7(); + function getBufferResponse(response) { + return response.arrayBuffer(); + } + function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + 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" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error4; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error4) => { + if (error4 instanceof import_request_error.RequestError) + throw error4; + else if (error4.name === "AbortError") + throw error4; + let message = error4.message; + if (error4.name === "TypeError" && "cause" in error4) { + if (error4.cause instanceof Error) { + message = error4.cause.message; + } else if (typeof error4.cause === "string") { + message = error4.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); + } + 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 getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; + } + function withDefaults(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: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + } + var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }); + } +}); + +// node_modules/@octokit/graphql/dist-node/index.js +var require_dist_node9 = __commonJS({ + "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export2(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest + }); + module2.exports = __toCommonJS2(index_exports); + var import_request3 = require_dist_node8(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "7.1.1"; + var import_request2 = require_dist_node8(); + var import_request = require_dist_node8(); + 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.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + }; + 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 withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); + } + } +}); + +// node_modules/@octokit/auth-token/dist-node/index.js +var require_dist_node10 = __commonJS({ + "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + createTokenAuth: () => createTokenAuth + }); + module2.exports = __toCommonJS2(dist_src_exports); + 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, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + 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) + }); }; } }); @@ -26499,7 +27200,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -29372,7 +30073,7 @@ var require_validator = __commonJS({ }); // node_modules/jsonschema/lib/index.js -var require_lib2 = __commonJS({ +var require_lib3 = __commonJS({ "node_modules/jsonschema/lib/index.js"(exports2, module2) { "use strict"; var Validator2 = module2.exports.Validator = require_validator(); @@ -32511,339 +33212,1144 @@ var require_cacheUtils = __commonJS({ } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); - var HttpPipeline = class _HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = void 0; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - this._policies.push({ - policy, - options - }); - this._orderedPolicies = void 0; + } else { + return void 0; } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { - removedPolicies.push(policyDescriptor.policy); - return false; - } else { - return true; - } - }); - this._orderedPolicies = void 0; - return removedPolicies; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - clone() { - return new _HttpPipeline(this._policies); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - static create() { - return new _HttpPipeline(); + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - orderPolicies() { - const result = []; - const policyMap = /* @__PURE__ */ new Map(); - function createPhase(name) { - return { - name, - policies: /* @__PURE__ */ new Set(), - hasRun: false, - hasAfterPolicies: false - }; - } - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } else if (phase === "Serialize") { - return serializePhase; - } else if (phase === "Deserialize") { - return deserializePhase; - } else if (phase === "Sign") { - return signPhase; - } else { - return noPhase; - } - } - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: /* @__PURE__ */ new Set(), - dependants: /* @__PURE__ */ new Set() - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); - } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); - } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); - } - } - } - } - function walkPhase(phase) { - phase.hasRun = true; - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - continue; - } - if (node.dependsOn.size === 0) { - result.push(node.policy); - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); - } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - walkPhase(noPhase); - } - return; - } - if (phase.hasAfterPolicies) { - walkPhase(noPhase); - } - } - } - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - walkPhases(); - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return result; } - }; - function createEmptyPipeline() { - return HttpPipeline.create(); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@azure/logger/dist/index.js -var require_dist = __commonJS({ - "node_modules/@azure/logger/dist/index.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var os = require("os"); - var util = require("util"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); - function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); - } - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; - var enabledString; - var enabledNamespaces = []; - var skippedNamespaces = []; - var debuggers = []; - if (debugEnvVariable) { - enable(debugEnvVariable); - } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log - }); - function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); - } else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); - } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - } - function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - } - return false; - } - function disable() { - const result = enabledString || ""; - enable(""); - return result; - } - function createDebugger(namespace) { - const newDebugger = Object.assign(debug5, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend: extend3 - }); - function debug5(...args) { - if (!newDebugger.enabled) { - return; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); } - newDebugger.log(...args); - } - debuggers.push(newDebugger); - return newDebugger; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return false; - } - function extend3(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; - } - var debug4 = debugObj; - var registeredLoggers = /* @__PURE__ */ new Set(); - var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; - var azureLogLevel; - var AzureLogger = debug4("azure"); - AzureLogger.log = (...args) => { - debug4.log(...args); }; - var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; - if (logLevelFromEnv) { - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); - } else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - } - function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); + }); } - azureLogLevel = level; - const enabledNamespaces2 = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces2.push(logger.namespace); - } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); + }); } - debug4.enable(enabledNamespaces2.join(",")); - } - function getLogLevel() { - return azureLogLevel; - } - var levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 }; - function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; + } + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; + } + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } + }; + function createEmptyPipeline() { + return HttpPipeline.create(); + } + } +}); + +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; + } + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); + } + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); + } + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log + }); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } + } + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; + } + function disable() { + const result = enabledString || ""; + enable(""); + return result; + } + function createDebugger(namespace) { + const newDebugger = Object.assign(debug5, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug5(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; + } + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; + } + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; + } + var debug4 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug4("azure"); + AzureLogger.log = (...args) => { + debug4.log(...args); + }; + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + } + } + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); + } + } + debug4.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 + }; + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), info: createLogger(clientRootLogger, "info"), verbose: createLogger(clientRootLogger, "verbose") }; @@ -67946,7 +69452,7 @@ var require_requestUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var constants_1 = require_constants7(); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -68114,7 +69620,7 @@ var require_downloadUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var storage_blob_1 = require_dist7(); var buffer = __importStar4(require("buffer")); var fs2 = __importStar4(require("fs")); @@ -68691,8 +70197,8 @@ var require_cacheHttpClient = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; var core14 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib4(); + var auth_1 = require_auth2(); var fs2 = __importStar4(require("fs")); var url_1 = require("url"); var utils = __importStar4(require_cacheUtils()); @@ -73898,8 +75404,8 @@ var require_cacheTwirpClient = __commonJS({ var errors_1 = require_errors2(); var config_1 = require_config(); var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib4(); var cache_twirp_client_1 = require_cache_twirp_client(); var util_1 = require_util10(); var CacheServiceClient = class { @@ -74347,7 +75853,7 @@ var require_cache3 = __commonJS({ var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); var config_1 = require_config(); var tar_1 = require_tar(); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var ValidationError = class _ValidationError extends Error { constructor(message) { super(message); @@ -74756,78 +76262,476 @@ var require_config2 = __commonJS({ if (!ghWorkspaceDir) { throw new Error("Unable to get the GITHUB_WORKSPACE env variable"); } - return ghWorkspaceDir; - } - function getConcurrency() { - const numCPUs = os_1.default.cpus().length; - let concurrencyCap = 32; - if (numCPUs > 4) { - const concurrency = 16 * numCPUs; - concurrencyCap = concurrency > 300 ? 300 : concurrency; + return ghWorkspaceDir; + } + function getConcurrency() { + const numCPUs = os_1.default.cpus().length; + let concurrencyCap = 32; + if (numCPUs > 4) { + const concurrency = 16 * numCPUs; + concurrencyCap = concurrency > 300 ? 300 : concurrency; + } + const concurrencyOverride = process.env["ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY"]; + if (concurrencyOverride) { + const concurrency = parseInt(concurrencyOverride); + if (isNaN(concurrency) || concurrency < 1) { + throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY env variable"); + } + if (concurrency < concurrencyCap) { + (0, core_1.info)(`Set concurrency based on the value set in ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY.`); + return concurrency; + } + (0, core_1.info)(`ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY is higher than the cap of ${concurrencyCap} based on the number of cpus. Set it to the maximum value allowed.`); + return concurrencyCap; + } + return 5; + } + function getUploadChunkTimeout() { + const timeoutVar = process.env["ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS"]; + if (!timeoutVar) { + return 3e5; + } + const timeout = parseInt(timeoutVar); + if (isNaN(timeout)) { + throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS env variable"); + } + return timeout; + } + function getMaxArtifactListCount() { + const maxCountVar = process.env["ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT"] || "1000"; + const maxCount = parseInt(maxCountVar); + if (isNaN(maxCount) || maxCount < 1) { + throw new Error("Invalid value set for ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT env variable"); + } + return maxCount; + } + } +}); + +// node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js +var require_timestamp = __commonJS({ + "node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Timestamp = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var runtime_6 = require_commonjs11(); + var runtime_7 = require_commonjs11(); + var Timestamp$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.Timestamp", [ + { + no: 1, + name: "seconds", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 2, + name: "nanos", + kind: "scalar", + T: 5 + /*ScalarType.INT32*/ + } + ]); + } + /** + * Creates a new `Timestamp` for the current time. + */ + now() { + const msg = this.create(); + const ms = Date.now(); + msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); + msg.nanos = ms % 1e3 * 1e6; + return msg; + } + /** + * Converts a `Timestamp` to a JavaScript Date. + */ + toDate(message) { + return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1e3 + Math.ceil(message.nanos / 1e6)); + } + /** + * Converts a JavaScript Date to a `Timestamp`. + */ + fromDate(date) { + const msg = this.create(); + const ms = date.getTime(); + msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); + msg.nanos = ms % 1e3 * 1e6; + return msg; + } + /** + * In JSON format, the `Timestamp` type is encoded as a string + * in the RFC 3339 format. + */ + internalJsonWrite(message, options) { + let ms = runtime_6.PbLong.from(message.seconds).toNumber() * 1e3; + if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) + throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); + if (message.nanos < 0) + throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative."); + let z = "Z"; + if (message.nanos > 0) { + let nanosStr = (message.nanos + 1e9).toString().substring(1); + if (nanosStr.substring(3) === "000000") + z = "." + nanosStr.substring(0, 3) + "Z"; + else if (nanosStr.substring(6) === "000") + z = "." + nanosStr.substring(0, 6) + "Z"; + else + z = "." + nanosStr + "Z"; + } + return new Date(ms).toISOString().replace(".000Z", z); + } + /** + * In JSON format, the `Timestamp` type is encoded as a string + * in the RFC 3339 format. + */ + internalJsonRead(json2, options, target) { + if (typeof json2 !== "string") + throw new Error("Unable to parse Timestamp from JSON " + (0, runtime_5.typeofJsonValue)(json2) + "."); + let matches = json2.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/); + if (!matches) + throw new Error("Unable to parse Timestamp from JSON. Invalid format."); + let ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z")); + if (Number.isNaN(ms)) + throw new Error("Unable to parse Timestamp from JSON. Invalid value."); + if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) + throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); + if (!target) + target = this.create(); + target.seconds = runtime_6.PbLong.from(ms / 1e3).toString(); + target.nanos = 0; + if (matches[7]) + target.nanos = parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1e9; + return target; + } + create(value) { + const message = { seconds: "0", nanos: 0 }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 seconds */ + 1: + message.seconds = reader.int64().toString(); + break; + case /* int32 nanos */ + 2: + message.nanos = reader.int32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.seconds !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.seconds); + if (message.nanos !== 0) + writer.tag(2, runtime_1.WireType.Varint).int32(message.nanos); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.Timestamp = new Timestamp$Type(); + } +}); + +// node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js +var require_wrappers = __commonJS({ + "node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BytesValue = exports2.StringValue = exports2.BoolValue = exports2.UInt32Value = exports2.Int32Value = exports2.UInt64Value = exports2.Int64Value = exports2.FloatValue = exports2.DoubleValue = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var runtime_6 = require_commonjs11(); + var runtime_7 = require_commonjs11(); + var DoubleValue$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.DoubleValue", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 1 + /*ScalarType.DOUBLE*/ + } + ]); + } + /** + * Encode `DoubleValue` to JSON number. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(2, message.value, "value", false, true); + } + /** + * Decode `DoubleValue` from JSON number. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + return target; + } + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* double value */ + 1: + message.value = reader.double(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Bit64).double(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.DoubleValue = new DoubleValue$Type(); + var FloatValue$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.FloatValue", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 2 + /*ScalarType.FLOAT*/ + } + ]); + } + /** + * Encode `FloatValue` to JSON number. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(1, message.value, "value", false, true); + } + /** + * Decode `FloatValue` from JSON number. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + return target; + } + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* float value */ + 1: + message.value = reader.float(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Bit32).float(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FloatValue = new FloatValue$Type(); + var Int64Value$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.Int64Value", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + /** + * Encode `Int64Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true); + } + /** + * Decode `Int64Value` from JSON string. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.INT64, runtime_2.LongType.STRING, "value"); + return target; + } + create(value) { + const message = { value: "0" }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 value */ + 1: + message.value = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== "0") + writer.tag(1, runtime_3.WireType.Varint).int64(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.Int64Value = new Int64Value$Type(); + var UInt64Value$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.UInt64Value", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 4 + /*ScalarType.UINT64*/ + } + ]); + } + /** + * Encode `UInt64Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true); } - const concurrencyOverride = process.env["ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY"]; - if (concurrencyOverride) { - const concurrency = parseInt(concurrencyOverride); - if (isNaN(concurrency) || concurrency < 1) { - throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY env variable"); - } - if (concurrency < concurrencyCap) { - (0, core_1.info)(`Set concurrency based on the value set in ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY.`); - return concurrency; - } - (0, core_1.info)(`ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY is higher than the cap of ${concurrencyCap} based on the number of cpus. Set it to the maximum value allowed.`); - return concurrencyCap; + /** + * Decode `UInt64Value` from JSON string. + */ + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.UINT64, runtime_2.LongType.STRING, "value"); + return target; } - return 5; - } - function getUploadChunkTimeout() { - const timeoutVar = process.env["ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS"]; - if (!timeoutVar) { - return 3e5; + create(value) { + const message = { value: "0" }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; } - const timeout = parseInt(timeoutVar); - if (isNaN(timeout)) { - throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_TIMEOUT_MS env variable"); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* uint64 value */ + 1: + message.value = reader.uint64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - return timeout; - } - function getMaxArtifactListCount() { - const maxCountVar = process.env["ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT"] || "1000"; - const maxCount = parseInt(maxCountVar); - if (isNaN(maxCount) || maxCount < 1) { - throw new Error("Invalid value set for ACTIONS_ARTIFACT_MAX_ARTIFACT_COUNT env variable"); + internalBinaryWrite(message, writer, options) { + if (message.value !== "0") + writer.tag(1, runtime_3.WireType.Varint).uint64(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - return maxCount; - } - } -}); - -// node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js -var require_timestamp = __commonJS({ - "node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Timestamp = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var runtime_6 = require_commonjs11(); - var runtime_7 = require_commonjs11(); - var Timestamp$Type = class extends runtime_7.MessageType { + }; + exports2.UInt64Value = new UInt64Value$Type(); + var Int32Value$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.Timestamp", [ + super("google.protobuf.Int32Value", [ { no: 1, - name: "seconds", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 2, - name: "nanos", + name: "value", kind: "scalar", T: 5 /*ScalarType.INT32*/ @@ -74835,81 +76739,89 @@ var require_timestamp = __commonJS({ ]); } /** - * Creates a new `Timestamp` for the current time. + * Encode `Int32Value` to JSON string. */ - now() { - const msg = this.create(); - const ms = Date.now(); - msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); - msg.nanos = ms % 1e3 * 1e6; - return msg; + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(5, message.value, "value", false, true); } /** - * Converts a `Timestamp` to a JavaScript Date. + * Decode `Int32Value` from JSON string. */ - toDate(message) { - return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1e3 + Math.ceil(message.nanos / 1e6)); + internalJsonRead(json2, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json2, 5, void 0, "value"); + return target; } - /** - * Converts a JavaScript Date to a `Timestamp`. - */ - fromDate(date) { - const msg = this.create(); - const ms = date.getTime(); - msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1e3)).toString(); - msg.nanos = ms % 1e3 * 1e6; - return msg; + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int32 value */ + 1: + message.value = reader.int32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Varint).int32(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.Int32Value = new Int32Value$Type(); + var UInt32Value$Type = class extends runtime_7.MessageType { + constructor() { + super("google.protobuf.UInt32Value", [ + { + no: 1, + name: "value", + kind: "scalar", + T: 13 + /*ScalarType.UINT32*/ + } + ]); } /** - * In JSON format, the `Timestamp` type is encoded as a string - * in the RFC 3339 format. + * Encode `UInt32Value` to JSON string. */ internalJsonWrite(message, options) { - let ms = runtime_6.PbLong.from(message.seconds).toNumber() * 1e3; - if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) - throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); - if (message.nanos < 0) - throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative."); - let z = "Z"; - if (message.nanos > 0) { - let nanosStr = (message.nanos + 1e9).toString().substring(1); - if (nanosStr.substring(3) === "000000") - z = "." + nanosStr.substring(0, 3) + "Z"; - else if (nanosStr.substring(6) === "000") - z = "." + nanosStr.substring(0, 6) + "Z"; - else - z = "." + nanosStr + "Z"; - } - return new Date(ms).toISOString().replace(".000Z", z); + return this.refJsonWriter.scalar(13, message.value, "value", false, true); } /** - * In JSON format, the `Timestamp` type is encoded as a string - * in the RFC 3339 format. + * Decode `UInt32Value` from JSON string. */ internalJsonRead(json2, options, target) { - if (typeof json2 !== "string") - throw new Error("Unable to parse Timestamp from JSON " + (0, runtime_5.typeofJsonValue)(json2) + "."); - let matches = json2.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/); - if (!matches) - throw new Error("Unable to parse Timestamp from JSON. Invalid format."); - let ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z")); - if (Number.isNaN(ms)) - throw new Error("Unable to parse Timestamp from JSON. Invalid value."); - if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) - throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); if (!target) target = this.create(); - target.seconds = runtime_6.PbLong.from(ms / 1e3).toString(); - target.nanos = 0; - if (matches[7]) - target.nanos = parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1e9; + target.value = this.refJsonReader.scalar(json2, 13, void 0, "value"); return target; } create(value) { - const message = { seconds: "0", nanos: 0 }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); + (0, runtime_5.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -74917,13 +76829,9 @@ var require_timestamp = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* int64 seconds */ + case /* uint32 value */ 1: - message.seconds = reader.int64().toString(); - break; - case /* int32 nanos */ - 2: - message.nanos = reader.int32(); + message.value = reader.uint32(); break; default: let u = options.readUnknownField; @@ -74931,68 +76839,50 @@ var require_timestamp = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.seconds !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.seconds); - if (message.nanos !== 0) - writer.tag(2, runtime_1.WireType.Varint).int32(message.nanos); + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Varint).uint32(message.value); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.Timestamp = new Timestamp$Type(); - } -}); - -// node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js -var require_wrappers = __commonJS({ - "node_modules/@actions/artifact/lib/generated/google/protobuf/wrappers.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BytesValue = exports2.StringValue = exports2.BoolValue = exports2.UInt32Value = exports2.Int32Value = exports2.UInt64Value = exports2.Int64Value = exports2.FloatValue = exports2.DoubleValue = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var runtime_6 = require_commonjs11(); - var runtime_7 = require_commonjs11(); - var DoubleValue$Type = class extends runtime_7.MessageType { + exports2.UInt32Value = new UInt32Value$Type(); + var BoolValue$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.DoubleValue", [ + super("google.protobuf.BoolValue", [ { no: 1, name: "value", kind: "scalar", - T: 1 - /*ScalarType.DOUBLE*/ + T: 8 + /*ScalarType.BOOL*/ } ]); } /** - * Encode `DoubleValue` to JSON number. + * Encode `BoolValue` to JSON bool. */ internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(2, message.value, "value", false, true); + return message.value; } /** - * Decode `DoubleValue` from JSON number. + * Decode `BoolValue` from JSON bool. */ internalJsonRead(json2, options, target) { if (!target) target = this.create(); - target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + target.value = this.refJsonReader.scalar(json2, 8, void 0, "value"); return target; } create(value) { - const message = { value: 0 }; + const message = { value: false }; globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_5.reflectionMergePartial)(this, message, value); @@ -75003,9 +76893,9 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* double value */ + case /* bool value */ 1: - message.value = reader.double(); + message.value = reader.bool(); break; default: let u = options.readUnknownField; @@ -75019,44 +76909,44 @@ var require_wrappers = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Bit64).double(message.value); + if (message.value !== false) + writer.tag(1, runtime_3.WireType.Varint).bool(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.DoubleValue = new DoubleValue$Type(); - var FloatValue$Type = class extends runtime_7.MessageType { + exports2.BoolValue = new BoolValue$Type(); + var StringValue$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.FloatValue", [ + super("google.protobuf.StringValue", [ { no: 1, name: "value", kind: "scalar", - T: 2 - /*ScalarType.FLOAT*/ + T: 9 + /*ScalarType.STRING*/ } ]); } /** - * Encode `FloatValue` to JSON number. + * Encode `StringValue` to JSON string. */ internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(1, message.value, "value", false, true); + return message.value; } /** - * Decode `FloatValue` from JSON number. + * Decode `StringValue` from JSON string. */ internalJsonRead(json2, options, target) { if (!target) target = this.create(); - target.value = this.refJsonReader.scalar(json2, 1, void 0, "value"); + target.value = this.refJsonReader.scalar(json2, 9, void 0, "value"); return target; } create(value) { - const message = { value: 0 }; + const message = { value: "" }; globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_5.reflectionMergePartial)(this, message, value); @@ -75067,9 +76957,9 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* float value */ + case /* string value */ 1: - message.value = reader.float(); + message.value = reader.string(); break; default: let u = options.readUnknownField; @@ -75083,44 +76973,44 @@ var require_wrappers = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Bit32).float(message.value); + if (message.value !== "") + writer.tag(1, runtime_3.WireType.LengthDelimited).string(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.FloatValue = new FloatValue$Type(); - var Int64Value$Type = class extends runtime_7.MessageType { + exports2.StringValue = new StringValue$Type(); + var BytesValue$Type = class extends runtime_7.MessageType { constructor() { - super("google.protobuf.Int64Value", [ + super("google.protobuf.BytesValue", [ { no: 1, name: "value", kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + T: 12 + /*ScalarType.BYTES*/ } ]); } /** - * Encode `Int64Value` to JSON string. + * Encode `BytesValue` to JSON string. */ internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true); + return this.refJsonWriter.scalar(12, message.value, "value", false, true); } /** - * Decode `Int64Value` from JSON string. + * Decode `BytesValue` from JSON string. */ internalJsonRead(json2, options, target) { if (!target) target = this.create(); - target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.INT64, runtime_2.LongType.STRING, "value"); + target.value = this.refJsonReader.scalar(json2, 12, void 0, "value"); return target; } create(value) { - const message = { value: "0" }; + const message = { value: new Uint8Array(0) }; globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_5.reflectionMergePartial)(this, message, value); @@ -75131,9 +77021,9 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* int64 value */ + case /* bytes value */ 1: - message.value = reader.int64().toString(); + message.value = reader.bytes(); break; default: let u = options.readUnknownField; @@ -75147,47 +77037,195 @@ var require_wrappers = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== "0") - writer.tag(1, runtime_3.WireType.Varint).int64(message.value); + if (message.value.length) + writer.tag(1, runtime_3.WireType.LengthDelimited).bytes(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.Int64Value = new Int64Value$Type(); - var UInt64Value$Type = class extends runtime_7.MessageType { + exports2.BytesValue = new BytesValue$Type(); + } +}); + +// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js +var require_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArtifactService = exports2.DeleteArtifactResponse = exports2.DeleteArtifactRequest = exports2.GetSignedArtifactURLResponse = exports2.GetSignedArtifactURLRequest = exports2.ListArtifactsResponse_MonolithArtifact = exports2.ListArtifactsResponse = exports2.ListArtifactsRequest = exports2.FinalizeArtifactResponse = exports2.FinalizeArtifactRequest = exports2.CreateArtifactResponse = exports2.CreateArtifactRequest = exports2.FinalizeMigratedArtifactResponse = exports2.FinalizeMigratedArtifactRequest = exports2.MigrateArtifactResponse = exports2.MigrateArtifactRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var wrappers_1 = require_wrappers(); + var wrappers_2 = require_wrappers(); + var timestamp_1 = require_timestamp(); + var MigrateArtifactRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.MigrateArtifactRequest", [ + { + no: 1, + name: "workflow_run_backend_id", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { no: 3, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp } + ]); + } + create(value) { + const message = { workflowRunBackendId: "", name: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string workflow_run_backend_id */ + 1: + message.workflowRunBackendId = reader.string(); + break; + case /* string name */ + 2: + message.name = reader.string(); + break; + case /* google.protobuf.Timestamp expires_at */ + 3: + message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.name !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.expiresAt) + timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.MigrateArtifactRequest = new MigrateArtifactRequest$Type(); + var MigrateArtifactResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.MigrateArtifactResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedUploadUrl: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.MigrateArtifactResponse = new MigrateArtifactResponse$Type(); + var FinalizeMigratedArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.UInt64Value", [ + super("github.actions.results.api.v1.FinalizeMigratedArtifactRequest", [ { no: 1, - name: "value", + name: "workflow_run_backend_id", kind: "scalar", - T: 4 - /*ScalarType.UINT64*/ + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ } ]); } - /** - * Encode `UInt64Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true); - } - /** - * Decode `UInt64Value` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, runtime_1.ScalarType.UINT64, runtime_2.LongType.STRING, "value"); - return target; - } create(value) { - const message = { value: "0" }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { workflowRunBackendId: "", name: "", size: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -75195,9 +77233,17 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* uint64 value */ + case /* string workflow_run_backend_id */ 1: - message.value = reader.uint64().toString(); + message.workflowRunBackendId = reader.string(); + break; + case /* string name */ + 2: + message.name = reader.string(); + break; + case /* int64 size */ + 3: + message.size = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -75205,53 +77251,49 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== "0") - writer.tag(1, runtime_3.WireType.Varint).uint64(message.value); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.name !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.size !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.size); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.UInt64Value = new UInt64Value$Type(); - var Int32Value$Type = class extends runtime_7.MessageType { + exports2.FinalizeMigratedArtifactRequest = new FinalizeMigratedArtifactRequest$Type(); + var FinalizeMigratedArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.Int32Value", [ + super("github.actions.results.api.v1.FinalizeMigratedArtifactResponse", [ { no: 1, - name: "value", + name: "ok", kind: "scalar", - T: 5 - /*ScalarType.INT32*/ + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "artifact_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ } ]); } - /** - * Encode `Int32Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(5, message.value, "value", false, true); - } - /** - * Decode `Int32Value` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 5, void 0, "value"); - return target; - } create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { ok: false, artifactId: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -75259,9 +77301,13 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* int32 value */ + case /* bool ok */ 1: - message.value = reader.int32(); + message.ok = reader.bool(); + break; + case /* int64 artifact_id */ + 2: + message.artifactId = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -75269,53 +77315,62 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Varint).int32(message.value); + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.Int32Value = new Int32Value$Type(); - var UInt32Value$Type = class extends runtime_7.MessageType { + exports2.FinalizeMigratedArtifactResponse = new FinalizeMigratedArtifactResponse$Type(); + var CreateArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.UInt32Value", [ + super("github.actions.results.api.v1.CreateArtifactRequest", [ { no: 1, - name: "value", + name: "workflow_run_backend_id", kind: "scalar", - T: 13 - /*ScalarType.UINT32*/ + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "workflow_job_run_backend_id", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { no: 4, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp }, + { + no: 5, + name: "version", + kind: "scalar", + T: 5 + /*ScalarType.INT32*/ } ]); } - /** - * Encode `UInt32Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(13, message.value, "value", false, true); - } - /** - * Decode `UInt32Value` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 13, void 0, "value"); - return target; - } create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", version: 0 }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -75323,9 +77378,25 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* uint32 value */ + case /* string workflow_run_backend_id */ 1: - message.value = reader.uint32(); + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ + 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* string name */ + 3: + message.name = reader.string(); + break; + case /* google.protobuf.Timestamp expires_at */ + 4: + message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + break; + case /* int32 version */ + 5: + message.version = reader.int32(); break; default: let u = options.readUnknownField; @@ -75333,53 +77404,53 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Varint).uint32(message.value); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.name !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.expiresAt) + timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.version !== 0) + writer.tag(5, runtime_1.WireType.Varint).int32(message.version); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.UInt32Value = new UInt32Value$Type(); - var BoolValue$Type = class extends runtime_7.MessageType { + exports2.CreateArtifactRequest = new CreateArtifactRequest$Type(); + var CreateArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.BoolValue", [ + super("github.actions.results.api.v1.CreateArtifactResponse", [ { no: 1, - name: "value", + name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ } ]); } - /** - * Encode `BoolValue` to JSON bool. - */ - internalJsonWrite(message, options) { - return message.value; - } - /** - * Decode `BoolValue` from JSON bool. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 8, void 0, "value"); - return target; - } create(value) { - const message = { value: false }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { ok: false, signedUploadUrl: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -75387,9 +77458,13 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bool value */ + case /* bool ok */ 1: - message.value = reader.bool(); + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); break; default: let u = options.readUnknownField; @@ -75397,53 +77472,62 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== false) - writer.tag(1, runtime_3.WireType.Varint).bool(message.value); + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.BoolValue = new BoolValue$Type(); - var StringValue$Type = class extends runtime_7.MessageType { + exports2.CreateArtifactResponse = new CreateArtifactResponse$Type(); + var FinalizeArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.StringValue", [ + super("github.actions.results.api.v1.FinalizeArtifactRequest", [ { no: 1, - name: "value", + name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ - } + }, + { + no: 2, + name: "workflow_job_run_backend_id", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "size", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 5, name: "hash", kind: "message", T: () => wrappers_2.StringValue } ]); } - /** - * Encode `StringValue` to JSON string. - */ - internalJsonWrite(message, options) { - return message.value; - } - /** - * Decode `StringValue` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 9, void 0, "value"); - return target; - } create(value) { - const message = { value: "" }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", size: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -75451,9 +77535,25 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* string value */ + case /* string workflow_run_backend_id */ 1: - message.value = reader.string(); + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ + 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* string name */ + 3: + message.name = reader.string(); + break; + case /* int64 size */ + 4: + message.size = reader.int64().toString(); + break; + case /* google.protobuf.StringValue hash */ + 5: + message.hash = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.hash); break; default: let u = options.readUnknownField; @@ -75461,53 +77561,53 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value !== "") - writer.tag(1, runtime_3.WireType.LengthDelimited).string(message.value); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.name !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.size !== "0") + writer.tag(4, runtime_1.WireType.Varint).int64(message.size); + if (message.hash) + wrappers_2.StringValue.internalBinaryWrite(message.hash, writer.tag(5, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.StringValue = new StringValue$Type(); - var BytesValue$Type = class extends runtime_7.MessageType { + exports2.FinalizeArtifactRequest = new FinalizeArtifactRequest$Type(); + var FinalizeArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("google.protobuf.BytesValue", [ + super("github.actions.results.api.v1.FinalizeArtifactResponse", [ { no: 1, - name: "value", + name: "ok", kind: "scalar", - T: 12 - /*ScalarType.BYTES*/ + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "artifact_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ } ]); } - /** - * Encode `BytesValue` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(12, message.value, "value", false, true); - } - /** - * Decode `BytesValue` from JSON string. - */ - internalJsonRead(json2, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json2, 12, void 0, "value"); - return target; - } create(value) { - const message = { value: new Uint8Array(0) }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + const message = { ok: false, artifactId: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) - (0, runtime_5.reflectionMergePartial)(this, message, value); + (0, runtime_3.reflectionMergePartial)(this, message, value); return message; } internalBinaryRead(reader, length, options, target) { @@ -75515,9 +77615,13 @@ var require_wrappers = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bytes value */ + case /* bool ok */ 1: - message.value = reader.bytes(); + message.ok = reader.bool(); + break; + case /* int64 artifact_id */ + 2: + message.artifactId = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -75525,42 +77629,26 @@ var require_wrappers = __commonJS({ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { - if (message.value.length) - writer.tag(1, runtime_3.WireType.LengthDelimited).bytes(message.value); + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); let u = options.writeUnknownFields; if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.BytesValue = new BytesValue$Type(); - } -}); - -// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js -var require_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArtifactService = exports2.DeleteArtifactResponse = exports2.DeleteArtifactRequest = exports2.GetSignedArtifactURLResponse = exports2.GetSignedArtifactURLRequest = exports2.ListArtifactsResponse_MonolithArtifact = exports2.ListArtifactsResponse = exports2.ListArtifactsRequest = exports2.FinalizeArtifactResponse = exports2.FinalizeArtifactRequest = exports2.CreateArtifactResponse = exports2.CreateArtifactRequest = exports2.FinalizeMigratedArtifactResponse = exports2.FinalizeMigratedArtifactRequest = exports2.MigrateArtifactResponse = exports2.MigrateArtifactRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var wrappers_1 = require_wrappers(); - var wrappers_2 = require_wrappers(); - var timestamp_1 = require_timestamp(); - var MigrateArtifactRequest$Type = class extends runtime_5.MessageType { + exports2.FinalizeArtifactResponse = new FinalizeArtifactResponse$Type(); + var ListArtifactsRequest$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.MigrateArtifactRequest", [ + super("github.actions.results.api.v1.ListArtifactsRequest", [ { no: 1, name: "workflow_run_backend_id", @@ -75570,16 +77658,17 @@ var require_artifact = __commonJS({ }, { no: 2, - name: "name", + name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 3, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp } + { no: 3, name: "name_filter", kind: "message", T: () => wrappers_2.StringValue }, + { no: 4, name: "id_filter", kind: "message", T: () => wrappers_1.Int64Value } ]); } create(value) { - const message = { workflowRunBackendId: "", name: "" }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -75594,13 +77683,17 @@ var require_artifact = __commonJS({ 1: message.workflowRunBackendId = reader.string(); break; - case /* string name */ + case /* string workflow_job_run_backend_id */ 2: - message.name = reader.string(); + message.workflowJobRunBackendId = reader.string(); break; - case /* google.protobuf.Timestamp expires_at */ + case /* google.protobuf.StringValue name_filter */ 3: - message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + message.nameFilter = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.nameFilter); + break; + case /* google.protobuf.Int64Value id_filter */ + 4: + message.idFilter = wrappers_1.Int64Value.internalBinaryRead(reader, reader.uint32(), options, message.idFilter); break; default: let u = options.readUnknownField; @@ -75616,38 +77709,106 @@ var require_artifact = __commonJS({ internalBinaryWrite(message, writer, options) { if (message.workflowRunBackendId !== "") writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.name !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.expiresAt) - timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.nameFilter) + wrappers_2.StringValue.internalBinaryWrite(message.nameFilter, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.idFilter) + wrappers_1.Int64Value.internalBinaryWrite(message.idFilter, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.ListArtifactsRequest = new ListArtifactsRequest$Type(); + var ListArtifactsResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.ListArtifactsResponse", [ + { no: 1, name: "artifacts", kind: "message", repeat: 1, T: () => exports2.ListArtifactsResponse_MonolithArtifact } + ]); + } + create(value) { + const message = { artifacts: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts */ + 1: + message.artifacts.push(exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + for (let i = 0; i < message.artifacts.length; i++) + exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryWrite(message.artifacts[i], writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.MigrateArtifactRequest = new MigrateArtifactRequest$Type(); - var MigrateArtifactResponse$Type = class extends runtime_5.MessageType { + exports2.ListArtifactsResponse = new ListArtifactsResponse$Type(); + var ListArtifactsResponse_MonolithArtifact$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.MigrateArtifactResponse", [ + super("github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact", [ { no: 1, - name: "ok", + name: "workflow_run_backend_id", kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ + T: 9 + /*ScalarType.STRING*/ }, { no: 2, - name: "signed_upload_url", + name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ - } + }, + { + no: 3, + name: "database_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "name", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 5, + name: "size", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 6, name: "created_at", kind: "message", T: () => timestamp_1.Timestamp }, + { no: 7, name: "digest", kind: "message", T: () => wrappers_2.StringValue } ]); } create(value) { - const message = { ok: false, signedUploadUrl: "" }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", databaseId: "0", name: "", size: "0" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -75658,13 +77819,33 @@ var require_artifact = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bool ok */ + case /* string workflow_run_backend_id */ 1: - message.ok = reader.bool(); + message.workflowRunBackendId = reader.string(); break; - case /* string signed_upload_url */ + case /* string workflow_job_run_backend_id */ 2: - message.signedUploadUrl = reader.string(); + message.workflowJobRunBackendId = reader.string(); + break; + case /* int64 database_id */ + 3: + message.databaseId = reader.int64().toString(); + break; + case /* string name */ + 4: + message.name = reader.string(); + break; + case /* int64 size */ + 5: + message.size = reader.int64().toString(); + break; + case /* google.protobuf.Timestamp created_at */ + 6: + message.createdAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.createdAt); + break; + case /* google.protobuf.StringValue digest */ + 7: + message.digest = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.digest); break; default: let u = options.readUnknownField; @@ -75678,20 +77859,30 @@ var require_artifact = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + if (message.databaseId !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.databaseId); + if (message.name !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.name); + if (message.size !== "0") + writer.tag(5, runtime_1.WireType.Varint).int64(message.size); + if (message.createdAt) + timestamp_1.Timestamp.internalBinaryWrite(message.createdAt, writer.tag(6, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.digest) + wrappers_2.StringValue.internalBinaryWrite(message.digest, writer.tag(7, runtime_1.WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.MigrateArtifactResponse = new MigrateArtifactResponse$Type(); - var FinalizeMigratedArtifactRequest$Type = class extends runtime_5.MessageType { + exports2.ListArtifactsResponse_MonolithArtifact = new ListArtifactsResponse_MonolithArtifact$Type(); + var GetSignedArtifactURLRequest$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.FinalizeMigratedArtifactRequest", [ + super("github.actions.results.api.v1.GetSignedArtifactURLRequest", [ { no: 1, name: "workflow_run_backend_id", @@ -75701,22 +77892,22 @@ var require_artifact = __commonJS({ }, { no: 2, - name: "name", + name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, - name: "size", + name: "name", kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + T: 9 + /*ScalarType.STRING*/ } ]); } create(value) { - const message = { workflowRunBackendId: "", name: "", size: "0" }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -75731,13 +77922,13 @@ var require_artifact = __commonJS({ 1: message.workflowRunBackendId = reader.string(); break; - case /* string name */ + case /* string workflow_job_run_backend_id */ 2: - message.name = reader.string(); + message.workflowJobRunBackendId = reader.string(); break; - case /* int64 size */ + case /* string name */ 3: - message.size = reader.int64().toString(); + message.name = reader.string(); break; default: let u = options.readUnknownField; @@ -75753,38 +77944,31 @@ var require_artifact = __commonJS({ internalBinaryWrite(message, writer, options) { if (message.workflowRunBackendId !== "") writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); if (message.name !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.size !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.size); + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.FinalizeMigratedArtifactRequest = new FinalizeMigratedArtifactRequest$Type(); - var FinalizeMigratedArtifactResponse$Type = class extends runtime_5.MessageType { + exports2.GetSignedArtifactURLRequest = new GetSignedArtifactURLRequest$Type(); + var GetSignedArtifactURLResponse$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.FinalizeMigratedArtifactResponse", [ + super("github.actions.results.api.v1.GetSignedArtifactURLResponse", [ { no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "artifact_id", + name: "signed_url", kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + T: 9 + /*ScalarType.STRING*/ } ]); } create(value) { - const message = { ok: false, artifactId: "0" }; + const message = { signedUrl: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -75795,13 +77979,9 @@ var require_artifact = __commonJS({ while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { - case /* bool ok */ + case /* string signed_url */ 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ - 2: - message.artifactId = reader.int64().toString(); + message.signedUrl = reader.string(); break; default: let u = options.readUnknownField; @@ -75815,20 +77995,18 @@ var require_artifact = __commonJS({ return message; } internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); + if (message.signedUrl !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.signedUrl); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.FinalizeMigratedArtifactResponse = new FinalizeMigratedArtifactResponse$Type(); - var CreateArtifactRequest$Type = class extends runtime_5.MessageType { + exports2.GetSignedArtifactURLResponse = new GetSignedArtifactURLResponse$Type(); + var DeleteArtifactRequest$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.CreateArtifactRequest", [ + super("github.actions.results.api.v1.DeleteArtifactRequest", [ { no: 1, name: "workflow_run_backend_id", @@ -75849,19 +78027,11 @@ var require_artifact = __commonJS({ kind: "scalar", T: 9 /*ScalarType.STRING*/ - }, - { no: 4, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp }, - { - no: 5, - name: "version", - kind: "scalar", - T: 5 - /*ScalarType.INT32*/ } ]); } create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", version: 0 }; + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -75884,14 +78054,6 @@ var require_artifact = __commonJS({ 3: message.name = reader.string(); break; - case /* google.protobuf.Timestamp expires_at */ - 4: - message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); - break; - case /* int32 version */ - 5: - message.version = reader.int32(); - break; default: let u = options.readUnknownField; if (u === "throw") @@ -75910,20 +78072,16 @@ var require_artifact = __commonJS({ writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); if (message.name !== "") writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.expiresAt) - timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.version !== 0) - writer.tag(5, runtime_1.WireType.Varint).int32(message.version); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.CreateArtifactRequest = new CreateArtifactRequest$Type(); - var CreateArtifactResponse$Type = class extends runtime_5.MessageType { + exports2.DeleteArtifactRequest = new DeleteArtifactRequest$Type(); + var DeleteArtifactResponse$Type = class extends runtime_5.MessageType { constructor() { - super("github.actions.results.api.v1.CreateArtifactResponse", [ + super("github.actions.results.api.v1.DeleteArtifactResponse", [ { no: 1, name: "ok", @@ -75933,15 +78091,15 @@ var require_artifact = __commonJS({ }, { no: 2, - name: "signed_upload_url", + name: "artifact_id", kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + T: 3 + /*ScalarType.INT64*/ } ]); } create(value) { - const message = { ok: false, signedUploadUrl: "" }; + const message = { ok: false, artifactId: "0" }; globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== void 0) (0, runtime_3.reflectionMergePartial)(this, message, value); @@ -75956,9 +78114,9 @@ var require_artifact = __commonJS({ 1: message.ok = reader.bool(); break; - case /* string signed_upload_url */ + case /* int64 artifact_id */ 2: - message.signedUploadUrl = reader.string(); + message.artifactId = reader.int64().toString(); break; default: let u = options.readUnknownField; @@ -75974,938 +78132,1091 @@ var require_artifact = __commonJS({ internalBinaryWrite(message, writer, options) { if (message.ok !== false) writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); let u = options.writeUnknownFields; if (u !== false) (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } }; - exports2.CreateArtifactResponse = new CreateArtifactResponse$Type(); - var FinalizeArtifactRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeArtifactRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "size", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 5, name: "hash", kind: "message", T: () => wrappers_2.StringValue } - ]); + exports2.DeleteArtifactResponse = new DeleteArtifactResponse$Type(); + exports2.ArtifactService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.ArtifactService", [ + { name: "CreateArtifact", options: {}, I: exports2.CreateArtifactRequest, O: exports2.CreateArtifactResponse }, + { name: "FinalizeArtifact", options: {}, I: exports2.FinalizeArtifactRequest, O: exports2.FinalizeArtifactResponse }, + { name: "ListArtifacts", options: {}, I: exports2.ListArtifactsRequest, O: exports2.ListArtifactsResponse }, + { name: "GetSignedArtifactURL", options: {}, I: exports2.GetSignedArtifactURLRequest, O: exports2.GetSignedArtifactURLResponse }, + { name: "DeleteArtifact", options: {}, I: exports2.DeleteArtifactRequest, O: exports2.DeleteArtifactResponse }, + { name: "MigrateArtifact", options: {}, I: exports2.MigrateArtifactRequest, O: exports2.MigrateArtifactResponse }, + { name: "FinalizeMigratedArtifact", options: {}, I: exports2.FinalizeMigratedArtifactRequest, O: exports2.FinalizeMigratedArtifactResponse } + ]); + } +}); + +// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js +var require_artifact_twirp_client = __commonJS({ + "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArtifactServiceClientProtobuf = exports2.ArtifactServiceClientJSON = void 0; + var artifact_1 = require_artifact(); + var ArtifactServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateArtifact.bind(this); + this.FinalizeArtifact.bind(this); + this.ListArtifacts.bind(this); + this.GetSignedArtifactURL.bind(this); + this.DeleteArtifact.bind(this); } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", size: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + CreateArtifact(request) { + const data = artifact_1.CreateArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/json", data); + return promise.then((data2) => artifact_1.CreateArtifactResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ - 3: - message.name = reader.string(); - break; - case /* int64 size */ - 4: - message.size = reader.int64().toString(); - break; - case /* google.protobuf.StringValue hash */ - 5: - message.hash = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.hash); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + FinalizeArtifact(request) { + const data = artifact_1.FinalizeArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/json", data); + return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + ListArtifacts(request) { + const data = artifact_1.ListArtifactsRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/json", data); + return promise.then((data2) => artifact_1.ListArtifactsResponse.fromJson(data2, { ignoreUnknownFields: true })); + } + GetSignedArtifactURL(request) { + const data = artifact_1.GetSignedArtifactURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/json", data); + return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + DeleteArtifact(request) { + const data = artifact_1.DeleteArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/json", data); + return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromJson(data2, { + ignoreUnknownFields: true + })); + } + }; + exports2.ArtifactServiceClientJSON = ArtifactServiceClientJSON; + var ArtifactServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateArtifact.bind(this); + this.FinalizeArtifact.bind(this); + this.ListArtifacts.bind(this); + this.GetSignedArtifactURL.bind(this); + this.DeleteArtifact.bind(this); + } + CreateArtifact(request) { + const data = artifact_1.CreateArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/protobuf", data); + return promise.then((data2) => artifact_1.CreateArtifactResponse.fromBinary(data2)); + } + FinalizeArtifact(request) { + const data = artifact_1.FinalizeArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/protobuf", data); + return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromBinary(data2)); + } + ListArtifacts(request) { + const data = artifact_1.ListArtifactsRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/protobuf", data); + return promise.then((data2) => artifact_1.ListArtifactsResponse.fromBinary(data2)); + } + GetSignedArtifactURL(request) { + const data = artifact_1.GetSignedArtifactURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/protobuf", data); + return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromBinary(data2)); + } + DeleteArtifact(request) { + const data = artifact_1.DeleteArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/protobuf", data); + return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromBinary(data2)); + } + }; + exports2.ArtifactServiceClientProtobuf = ArtifactServiceClientProtobuf; + } +}); + +// node_modules/@actions/artifact/lib/generated/index.js +var require_generated = __commonJS({ + "node_modules/@actions/artifact/lib/generated/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar4(require_timestamp(), exports2); + __exportStar4(require_wrappers(), exports2); + __exportStar4(require_artifact(), exports2); + __exportStar4(require_artifact_twirp_client(), exports2); + } +}); + +// node_modules/@actions/artifact/lib/internal/upload/retention.js +var require_retention = __commonJS({ + "node_modules/@actions/artifact/lib/internal/upload/retention.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getExpiration = getExpiration; + var generated_1 = require_generated(); + var core14 = __importStar4(require_core()); + function getExpiration(retentionDays) { + if (!retentionDays) { + return void 0; + } + const maxRetentionDays = getRetentionDays(); + if (maxRetentionDays && maxRetentionDays < retentionDays) { + core14.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); + retentionDays = maxRetentionDays; + } + const expirationDate = /* @__PURE__ */ new Date(); + expirationDate.setDate(expirationDate.getDate() + retentionDays); + return generated_1.Timestamp.fromDate(expirationDate); + } + function getRetentionDays() { + const retentionDays = process.env["GITHUB_RETENTION_DAYS"]; + if (!retentionDays) { + return void 0; + } + const days = parseInt(retentionDays); + if (isNaN(days)) { + return void 0; + } + return days; + } + } +}); + +// node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js +var require_path_and_artifact_name_validation = __commonJS({ + "node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.validateArtifactName = validateArtifactName; + exports2.validateFilePath = validateFilePath; + var core_1 = require_core(); + var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ + ['"', ' Double quote "'], + [":", " Colon :"], + ["<", " Less than <"], + [">", " Greater than >"], + ["|", " Vertical bar |"], + ["*", " Asterisk *"], + ["?", " Question mark ?"], + ["\r", " Carriage return \\r"], + ["\n", " Line feed \\n"] + ]); + var invalidArtifactNameCharacters = new Map([ + ...invalidArtifactFilePathCharacters, + ["\\", " Backslash \\"], + ["/", " Forward slash /"] + ]); + function validateArtifactName(name) { + if (!name) { + throw new Error(`Provided artifact name input during validation is empty`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { + if (name.includes(invalidCharacterKey)) { + throw new Error(`The artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} + +These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.size !== "0") - writer.tag(4, runtime_1.WireType.Varint).int64(message.size); - if (message.hash) - wrappers_2.StringValue.internalBinaryWrite(message.hash, writer.tag(5, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + (0, core_1.info)(`Artifact name is valid!`); + } + function validateFilePath(path2) { + if (!path2) { + throw new Error(`Provided file path input during validation is empty`); } - }; - exports2.FinalizeArtifactRequest = new FinalizeArtifactRequest$Type(); - var FinalizeArtifactResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeArtifactResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "artifact_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - } - ]); + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { + if (path2.includes(invalidCharacterKey)) { + throw new Error(`The path for one of the files in artifact is not valid: ${path2}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} + +The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. + `); + } } - create(value) { - const message = { ok: false, artifactId: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + } + } +}); + +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ - 2: - message.artifactId = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - return message; + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - }; - exports2.FinalizeArtifactResponse = new FinalizeArtifactResponse$Type(); - var ListArtifactsRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { no: 3, name: "name_filter", kind: "message", T: () => wrappers_2.StringValue }, - { no: 4, name: "id_filter", kind: "message", T: () => wrappers_1.Int64Value } - ]); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* google.protobuf.StringValue name_filter */ - 3: - message.nameFilter = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.nameFilter); - break; - case /* google.protobuf.Int64Value id_filter */ - 4: - message.idFilter = wrappers_1.Int64Value.internalBinaryRead(reader, reader.uint32(), options, message.idFilter); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.nameFilter) - wrappers_2.StringValue.internalBinaryWrite(message.nameFilter, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.idFilter) - wrappers_1.Int64Value.internalBinaryWrite(message.idFilter, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - }; - exports2.ListArtifactsRequest = new ListArtifactsRequest$Type(); - var ListArtifactsResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsResponse", [ - { no: 1, name: "artifacts", kind: "message", repeat: 1, T: () => exports2.ListArtifactsResponse_MonolithArtifact } - ]); + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } } - create(value) { - const message = { artifacts: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts */ - 1: - message.artifacts.push(exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryRead(reader, reader.uint32(), options)); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + get username() { + return this._decodedUsername; } - internalBinaryWrite(message, writer, options) { - for (let i = 0; i < message.artifacts.length; i++) - exports2.ListArtifactsResponse_MonolithArtifact.internalBinaryWrite(message.artifacts[i], writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + get password() { + return this._decodedPassword; } }; - exports2.ListArtifactsResponse = new ListArtifactsResponse$Type(); - var ListArtifactsResponse_MonolithArtifact$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "database_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 5, - name: "size", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 6, name: "created_at", kind: "message", T: () => timestamp_1.Timestamp }, - { no: 7, name: "digest", kind: "message", T: () => wrappers_2.StringValue } - ]); + } +}); + +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", databaseId: "0", name: "", size: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* int64 database_id */ - 3: - message.databaseId = reader.int64().toString(); - break; - case /* string name */ - 4: - message.name = reader.string(); - break; - case /* int64 size */ - 5: - message.size = reader.int64().toString(); - break; - case /* google.protobuf.Timestamp created_at */ - 6: - message.createdAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.createdAt); - break; - case /* google.protobuf.StringValue digest */ - 7: - message.digest = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.digest); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.databaseId !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.databaseId); - if (message.name !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.name); - if (message.size !== "0") - writer.tag(5, runtime_1.WireType.Varint).int64(message.size); - if (message.createdAt) - timestamp_1.Timestamp.internalBinaryWrite(message.createdAt, writer.tag(6, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.digest) - wrappers_2.StringValue.internalBinaryWrite(message.digest, writer.tag(7, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.ListArtifactsResponse_MonolithArtifact = new ListArtifactsResponse_MonolithArtifact$Type(); - var GetSignedArtifactURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetSignedArtifactURLRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); - } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ - 3: - message.name = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); + }); } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); + }); } }; - exports2.GetSignedArtifactURLRequest = new GetSignedArtifactURLRequest$Type(); - var GetSignedArtifactURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetSignedArtifactURLResponse", [ - { - no: 1, - name: "signed_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - ]); - } - create(value) { - const message = { signedUrl: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string signed_url */ - 1: - message.signedUrl = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.signedUrl !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.signedUrl); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.GetSignedArtifactURLResponse = new GetSignedArtifactURLResponse$Type(); - var DeleteArtifactRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.DeleteArtifactRequest", [ - { - no: 1, - name: "workflow_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "workflow_job_run_backend_id", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "name", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ - 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ - 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ - 3: - message.name = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - internalBinaryWrite(message, writer, options) { - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - }; - exports2.DeleteArtifactRequest = new DeleteArtifactRequest$Type(); - var DeleteArtifactResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.DeleteArtifactResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "artifact_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - } - ]); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - create(value) { - const message = { ok: false, artifactId: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ - 2: - message.artifactId = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - }; - exports2.DeleteArtifactResponse = new DeleteArtifactResponse$Type(); - exports2.ArtifactService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.ArtifactService", [ - { name: "CreateArtifact", options: {}, I: exports2.CreateArtifactRequest, O: exports2.CreateArtifactResponse }, - { name: "FinalizeArtifact", options: {}, I: exports2.FinalizeArtifactRequest, O: exports2.FinalizeArtifactResponse }, - { name: "ListArtifacts", options: {}, I: exports2.ListArtifactsRequest, O: exports2.ListArtifactsResponse }, - { name: "GetSignedArtifactURL", options: {}, I: exports2.GetSignedArtifactURLRequest, O: exports2.GetSignedArtifactURLResponse }, - { name: "DeleteArtifact", options: {}, I: exports2.DeleteArtifactRequest, O: exports2.DeleteArtifactResponse }, - { name: "MigrateArtifact", options: {}, I: exports2.MigrateArtifactRequest, O: exports2.MigrateArtifactResponse }, - { name: "FinalizeMigratedArtifact", options: {}, I: exports2.FinalizeMigratedArtifactRequest, O: exports2.FinalizeMigratedArtifactResponse } - ]); - } -}); - -// node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js -var require_artifact_twirp_client = __commonJS({ - "node_modules/@actions/artifact/lib/generated/results/api/v1/artifact.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArtifactServiceClientProtobuf = exports2.ArtifactServiceClientJSON = void 0; - var artifact_1 = require_artifact(); - var ArtifactServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateArtifact.bind(this); - this.FinalizeArtifact.bind(this); - this.ListArtifacts.bind(this); - this.GetSignedArtifactURL.bind(this); - this.DeleteArtifact.bind(this); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - CreateArtifact(request) { - const data = artifact_1.CreateArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/json", data); - return promise.then((data2) => artifact_1.CreateArtifactResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - FinalizeArtifact(request) { - const data = artifact_1.FinalizeArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/json", data); - return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - ListArtifacts(request) { - const data = artifact_1.ListArtifactsRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/json", data); - return promise.then((data2) => artifact_1.ListArtifactsResponse.fromJson(data2, { ignoreUnknownFields: true })); - } - GetSignedArtifactURL(request) { - const data = artifact_1.GetSignedArtifactURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + let socket; + req.on("socket", (sock) => { + socket = sock; }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/json", data); - return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); - } - DeleteArtifact(request) { - const data = artifact_1.DeleteArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/json", data); - return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromJson(data2, { - ignoreUnknownFields: true - })); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } - }; - exports2.ArtifactServiceClientJSON = ArtifactServiceClientJSON; - var ArtifactServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateArtifact.bind(this); - this.FinalizeArtifact.bind(this); - this.ListArtifacts.bind(this); - this.GetSignedArtifactURL.bind(this); - this.DeleteArtifact.bind(this); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - CreateArtifact(request) { - const data = artifact_1.CreateArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/protobuf", data); - return promise.then((data2) => artifact_1.CreateArtifactResponse.fromBinary(data2)); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - FinalizeArtifact(request) { - const data = artifact_1.FinalizeArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/protobuf", data); - return promise.then((data2) => artifact_1.FinalizeArtifactResponse.fromBinary(data2)); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; } - ListArtifacts(request) { - const data = artifact_1.ListArtifactsRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/protobuf", data); - return promise.then((data2) => artifact_1.ListArtifactsResponse.fromBinary(data2)); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - GetSignedArtifactURL(request) { - const data = artifact_1.GetSignedArtifactURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/protobuf", data); - return promise.then((data2) => artifact_1.GetSignedArtifactURLResponse.fromBinary(data2)); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - DeleteArtifact(request) { - const data = artifact_1.DeleteArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/protobuf", data); - return promise.then((data2) => artifact_1.DeleteArtifactResponse.fromBinary(data2)); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - }; - exports2.ArtifactServiceClientProtobuf = ArtifactServiceClientProtobuf; - } -}); - -// node_modules/@actions/artifact/lib/generated/index.js -var require_generated = __commonJS({ - "node_modules/@actions/artifact/lib/generated/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar4(require_timestamp(), exports2); - __exportStar4(require_wrappers(), exports2); - __exportStar4(require_artifact(), exports2); - __exportStar4(require_artifact_twirp_client(), exports2); + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/artifact/lib/internal/upload/retention.js -var require_retention = __commonJS({ - "node_modules/@actions/artifact/lib/internal/upload/retention.js"(exports2) { +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/auth.js +var require_auth3 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - __setModuleDefault4(result, mod); - return result; - }; - })(); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getExpiration = getExpiration; - var generated_1 = require_generated(); - var core14 = __importStar4(require_core()); - function getExpiration(retentionDays) { - if (!retentionDays) { - return void 0; + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - const maxRetentionDays = getRetentionDays(); - if (maxRetentionDays && maxRetentionDays < retentionDays) { - core14.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); - retentionDays = maxRetentionDays; + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; } - const expirationDate = /* @__PURE__ */ new Date(); - expirationDate.setDate(expirationDate.getDate() + retentionDays); - return generated_1.Timestamp.fromDate(expirationDate); - } - function getRetentionDays() { - const retentionDays = process.env["GITHUB_RETENTION_DAYS"]; - if (!retentionDays) { - return void 0; + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - const days = parseInt(retentionDays); - if (isNaN(days)) { - return void 0; + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - return days; - } - } -}); - -// node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js -var require_path_and_artifact_name_validation = __commonJS({ - "node_modules/@actions/artifact/lib/internal/upload/path-and-artifact-name-validation.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.validateArtifactName = validateArtifactName; - exports2.validateFilePath = validateFilePath; - var core_1 = require_core(); - var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ - ['"', ' Double quote "'], - [":", " Colon :"], - ["<", " Less than <"], - [">", " Greater than >"], - ["|", " Vertical bar |"], - ["*", " Asterisk *"], - ["?", " Question mark ?"], - ["\r", " Carriage return \\r"], - ["\n", " Line feed \\n"] - ]); - var invalidArtifactNameCharacters = new Map([ - ...invalidArtifactFilePathCharacters, - ["\\", " Backslash \\"], - ["/", " Forward slash /"] - ]); - function validateArtifactName(name) { - if (!name) { - throw new Error(`Provided artifact name input during validation is empty`); + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { - if (name.includes(invalidCharacterKey)) { - throw new Error(`The artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} - -These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } + options.headers["Authorization"] = `Bearer ${this.token}`; } - (0, core_1.info)(`Artifact name is valid!`); - } - function validateFilePath(path2) { - if (!path2) { - throw new Error(`Provided file path input during validation is empty`); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path2.includes(invalidCharacterKey)) { - throw new Error(`The path for one of the files in artifact is not valid: ${path2}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} - -The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. - `); + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; } - } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); @@ -77274,8 +79585,8 @@ var require_artifact_twirp_client2 = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.internalArtifactTwirpClient = internalArtifactTwirpClient; - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib5(); + var auth_1 = require_auth3(); var core_1 = require_core(); var generated_1 = require_generated(); var config_1 = require_config2(); @@ -99295,7 +101606,7 @@ var require_deflate_crc32_stream = __commonJS({ }); // node_modules/crc32-stream/lib/index.js -var require_lib3 = __commonJS({ +var require_lib6 = __commonJS({ "node_modules/crc32-stream/lib/index.js"(exports2, module2) { "use strict"; module2.exports = { @@ -99310,8 +101621,8 @@ var require_zip_archive_output_stream = __commonJS({ "node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js"(exports2, module2) { var inherits = require("util").inherits; var crc32 = require_crc32(); - var { CRC32Stream } = require_lib3(); - var { DeflateCRC32Stream } = require_lib3(); + var { CRC32Stream } = require_lib6(); + var { DeflateCRC32Stream } = require_lib6(); var ArchiveOutputStream = require_archive_output_stream(); var ZipArchiveEntry = require_zip_archive_entry(); var GeneralPurposeBit = require_general_purpose_bit(); @@ -104691,7 +107002,7 @@ var require_download_artifact = __commonJS({ var stream = __importStar4(require("stream")); var github2 = __importStar4(require_github()); var core14 = __importStar4(require_core()); - var httpClient = __importStar4(require_lib()); + var httpClient = __importStar4(require_lib5()); var unzip_stream_1 = __importDefault4(require_unzip()); var user_agent_1 = require_user_agent2(); var config_1 = require_config2(); @@ -105181,525 +107492,1083 @@ var require_get_artifact = __commonJS({ } }); -// node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js -var require_delete_artifact = __commonJS({ - "node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js"(exports2) { +// node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js +var require_delete_artifact = __commonJS({ + "node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.deleteArtifactPublic = deleteArtifactPublic; + exports2.deleteArtifactInternal = deleteArtifactInternal; + var core_1 = require_core(); + var github_1 = require_github(); + var user_agent_1 = require_user_agent2(); + var retry_options_1 = require_retry_options(); + var utils_1 = require_utils4(); + var plugin_request_log_1 = require_dist_node16(); + var plugin_retry_1 = require_dist_node17(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var util_1 = require_util11(); + var generated_1 = require_generated(); + var get_artifact_1 = require_get_artifact(); + var errors_1 = require_errors3(); + function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { + return __awaiter4(this, void 0, void 0, function* () { + var _a; + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: void 0, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: void 0, + retry: retryOpts, + request: requestOpts + }; + const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + const getArtifactResp = yield (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + const deleteArtifactResp = yield github2.rest.actions.deleteArtifact({ + owner: repositoryOwner, + repo: repositoryName, + artifact_id: getArtifactResp.artifact.id + }); + if (deleteArtifactResp.status !== 204) { + throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); + } + return { + id: getArtifactResp.artifact.id + }; + }); + } + function deleteArtifactInternal(artifactName) { + return __awaiter4(this, void 0, void 0, function* () { + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const listReq = { + workflowRunBackendId, + workflowJobRunBackendId, + nameFilter: generated_1.StringValue.create({ value: artifactName }) + }; + const listRes = yield artifactClient.ListArtifacts(listReq); + if (listRes.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); + } + let artifact2 = listRes.artifacts[0]; + if (listRes.artifacts.length > 1) { + artifact2 = listRes.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; + (0, core_1.debug)(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); + } + const req = { + workflowRunBackendId: artifact2.workflowRunBackendId, + workflowJobRunBackendId: artifact2.workflowJobRunBackendId, + name: artifact2.name + }; + const res = yield artifactClient.DeleteArtifact(req); + (0, core_1.info)(`Artifact '${artifactName}' (ID: ${res.artifactId}) deleted`); + return { + id: Number(res.artifactId) + }; + }); + } + } +}); + +// node_modules/@actions/artifact/lib/internal/find/list-artifacts.js +var require_list_artifacts = __commonJS({ + "node_modules/@actions/artifact/lib/internal/find/list-artifacts.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.listArtifactsPublic = listArtifactsPublic; + exports2.listArtifactsInternal = listArtifactsInternal; + var core_1 = require_core(); + var github_1 = require_github(); + var user_agent_1 = require_user_agent2(); + var retry_options_1 = require_retry_options(); + var utils_1 = require_utils4(); + var plugin_request_log_1 = require_dist_node16(); + var plugin_retry_1 = require_dist_node17(); + var artifact_twirp_client_1 = require_artifact_twirp_client2(); + var util_1 = require_util11(); + var config_1 = require_config2(); + var generated_1 = require_generated(); + var maximumArtifactCount = (0, config_1.getMaxArtifactListCount)(); + var paginationCount = 100; + var maxNumberOfPages = Math.ceil(maximumArtifactCount / paginationCount); + function listArtifactsPublic(workflowRunId_1, repositoryOwner_1, repositoryName_1, token_1) { + return __awaiter4(this, arguments, void 0, function* (workflowRunId, repositoryOwner, repositoryName, token, latest = false) { + (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`); + let artifacts = []; + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: void 0, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: void 0, + retry: retryOpts, + request: requestOpts + }; + const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + let currentPageNumber = 1; + const { data: listArtifactResponse } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + per_page: paginationCount, + page: currentPageNumber + }); + let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount); + const totalArtifactCount = listArtifactResponse.total_count; + if (totalArtifactCount > maximumArtifactCount) { + (0, core_1.warning)(`Workflow run ${workflowRunId} has ${totalArtifactCount} artifacts, exceeding the limit of ${maximumArtifactCount}. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`); + numberOfPages = maxNumberOfPages; + } + for (const artifact2 of listArtifactResponse.artifacts) { + artifacts.push({ + name: artifact2.name, + id: artifact2.id, + size: artifact2.size_in_bytes, + createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, + digest: artifact2.digest + }); + } + currentPageNumber++; + for (currentPageNumber; currentPageNumber <= numberOfPages; currentPageNumber++) { + (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`); + const { data: listArtifactResponse2 } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + per_page: paginationCount, + page: currentPageNumber + }); + for (const artifact2 of listArtifactResponse2.artifacts) { + artifacts.push({ + name: artifact2.name, + id: artifact2.id, + size: artifact2.size_in_bytes, + createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, + digest: artifact2.digest + }); + } + } + if (latest) { + artifacts = filterLatest(artifacts); + } + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; + }); + } + function listArtifactsInternal() { + return __awaiter4(this, arguments, void 0, function* (latest = false) { + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const req = { + workflowRunBackendId, + workflowJobRunBackendId + }; + const res = yield artifactClient.ListArtifacts(req); + let artifacts = res.artifacts.map((artifact2) => { + var _a; + return { + name: artifact2.name, + id: Number(artifact2.databaseId), + size: Number(artifact2.size), + createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, + digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value + }; + }); + if (latest) { + artifacts = filterLatest(artifacts); + } + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; + }); + } + function filterLatest(artifacts) { + artifacts.sort((a, b) => b.id - a.id); + const latestArtifacts = []; + const seenArtifactNames = /* @__PURE__ */ new Set(); + for (const artifact2 of artifacts) { + if (!seenArtifactNames.has(artifact2.name)) { + latestArtifacts.push(artifact2); + seenArtifactNames.add(artifact2.name); + } + } + return latestArtifacts; + } + } +}); + +// node_modules/@actions/artifact/lib/internal/client.js +var require_client2 = __commonJS({ + "node_modules/@actions/artifact/lib/internal/client.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __rest4 = exports2 && exports2.__rest || function(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DefaultArtifactClient = void 0; + var core_1 = require_core(); + var config_1 = require_config2(); + var upload_artifact_1 = require_upload_artifact(); + var download_artifact_1 = require_download_artifact(); + var delete_artifact_1 = require_delete_artifact(); + var get_artifact_1 = require_get_artifact(); + var list_artifacts_1 = require_list_artifacts(); + var errors_1 = require_errors3(); + var DefaultArtifactClient2 = class { + uploadArtifact(name, files, rootDirectory, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options); + } catch (error4) { + (0, core_1.warning)(`Artifact upload failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); + } + downloadArtifact(artifactId, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest4(options, ["findBy"]); + return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions); + } + return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options); + } catch (error4) { + (0, core_1.warning)(`Download Artifact failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); + } + listArtifacts(options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; + return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest); + } + return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest); + } catch (error4) { + (0, core_1.warning)(`Listing Artifacts failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); + } + getArtifact(artifactName, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; + return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + } + return (0, get_artifact_1.getArtifactInternal)(artifactName); + } catch (error4) { + (0, core_1.warning)(`Get Artifact failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); + } + deleteArtifact(artifactName, options) { + return __awaiter4(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { repositoryOwner, repositoryName, workflowRunId, token } } = options; + return (0, delete_artifact_1.deleteArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + } + return (0, delete_artifact_1.deleteArtifactInternal)(artifactName); + } catch (error4) { + (0, core_1.warning)(`Delete Artifact failed with error: ${error4}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error4; + } + }); + } + }; + exports2.DefaultArtifactClient = DefaultArtifactClient2; + } +}); + +// node_modules/@actions/artifact/lib/internal/shared/interfaces.js +var require_interfaces2 = __commonJS({ + "node_modules/@actions/artifact/lib/internal/shared/interfaces.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@actions/artifact/lib/artifact.js +var require_artifact2 = __commonJS({ + "node_modules/@actions/artifact/lib/artifact.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + var client_1 = require_client2(); + __exportStar4(require_interfaces2(), exports2); + __exportStar4(require_errors3(), exports2); + __exportStar4(require_client2(), exports2); + var client = new client_1.DefaultArtifactClient(); + exports2.default = client; + } +}); + +// node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js +var require_path_and_artifact_name_validation2 = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js"(exports2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); - }); - } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.deleteArtifactPublic = deleteArtifactPublic; - exports2.deleteArtifactInternal = deleteArtifactInternal; + exports2.checkArtifactFilePath = exports2.checkArtifactName = void 0; var core_1 = require_core(); - var github_1 = require_github(); - var user_agent_1 = require_user_agent2(); - var retry_options_1 = require_retry_options(); - var utils_1 = require_utils4(); - var plugin_request_log_1 = require_dist_node16(); - var plugin_retry_1 = require_dist_node17(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var util_1 = require_util11(); - var generated_1 = require_generated(); - var get_artifact_1 = require_get_artifact(); - var errors_1 = require_errors3(); - function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { - return __awaiter4(this, void 0, void 0, function* () { - var _a; - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: void 0, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: void 0, - retry: retryOpts, - request: requestOpts - }; - const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - const getArtifactResp = yield (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - const deleteArtifactResp = yield github2.rest.actions.deleteArtifact({ - owner: repositoryOwner, - repo: repositoryName, - artifact_id: getArtifactResp.artifact.id - }); - if (deleteArtifactResp.status !== 204) { - throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`); + var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ + ['"', ' Double quote "'], + [":", " Colon :"], + ["<", " Less than <"], + [">", " Greater than >"], + ["|", " Vertical bar |"], + ["*", " Asterisk *"], + ["?", " Question mark ?"], + ["\r", " Carriage return \\r"], + ["\n", " Line feed \\n"] + ]); + var invalidArtifactNameCharacters = new Map([ + ...invalidArtifactFilePathCharacters, + ["\\", " Backslash \\"], + ["/", " Forward slash /"] + ]); + function checkArtifactName(name) { + if (!name) { + throw new Error(`Artifact name: ${name}, is incorrectly provided`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { + if (name.includes(invalidCharacterKey)) { + throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} + +These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); } - return { - id: getArtifactResp.artifact.id - }; - }); + } + (0, core_1.info)(`Artifact name is valid!`); } - function deleteArtifactInternal(artifactName) { - return __awaiter4(this, void 0, void 0, function* () { - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const listReq = { - workflowRunBackendId, - workflowJobRunBackendId, - nameFilter: generated_1.StringValue.create({ value: artifactName }) - }; - const listRes = yield artifactClient.ListArtifacts(listReq); - if (listRes.artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); - } - let artifact2 = listRes.artifacts[0]; - if (listRes.artifacts.length > 1) { - artifact2 = listRes.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; - (0, core_1.debug)(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`); + exports2.checkArtifactName = checkArtifactName; + function checkArtifactFilePath(path2) { + if (!path2) { + throw new Error(`Artifact path: ${path2}, is incorrectly provided`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { + if (path2.includes(invalidCharacterKey)) { + throw new Error(`Artifact path is not valid: ${path2}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} + +The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. + `); } - const req = { - workflowRunBackendId: artifact2.workflowRunBackendId, - workflowJobRunBackendId: artifact2.workflowJobRunBackendId, - name: artifact2.name - }; - const res = yield artifactClient.DeleteArtifact(req); - (0, core_1.info)(`Artifact '${artifactName}' (ID: ${res.artifactId}) deleted`); - return { - id: Number(res.artifactId) - }; - }); + } } + exports2.checkArtifactFilePath = checkArtifactFilePath; } }); -// node_modules/@actions/artifact/lib/internal/find/list-artifacts.js -var require_list_artifacts = __commonJS({ - "node_modules/@actions/artifact/lib/internal/find/list-artifacts.js"(exports2) { +// node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js +var require_upload_specification = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js"(exports2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); - }); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listArtifactsPublic = listArtifactsPublic; - exports2.listArtifactsInternal = listArtifactsInternal; + exports2.getUploadSpecification = void 0; + var fs2 = __importStar4(require("fs")); var core_1 = require_core(); - var github_1 = require_github(); - var user_agent_1 = require_user_agent2(); - var retry_options_1 = require_retry_options(); - var utils_1 = require_utils4(); - var plugin_request_log_1 = require_dist_node16(); - var plugin_retry_1 = require_dist_node17(); - var artifact_twirp_client_1 = require_artifact_twirp_client2(); - var util_1 = require_util11(); - var config_1 = require_config2(); - var generated_1 = require_generated(); - var maximumArtifactCount = (0, config_1.getMaxArtifactListCount)(); - var paginationCount = 100; - var maxNumberOfPages = Math.ceil(maximumArtifactCount / paginationCount); - function listArtifactsPublic(workflowRunId_1, repositoryOwner_1, repositoryName_1, token_1) { - return __awaiter4(this, arguments, void 0, function* (workflowRunId, repositoryOwner, repositoryName, token, latest = false) { - (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`); - let artifacts = []; - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: void 0, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: void 0, - retry: retryOpts, - request: requestOpts - }; - const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - let currentPageNumber = 1; - const { data: listArtifactResponse } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - per_page: paginationCount, - page: currentPageNumber - }); - let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount); - const totalArtifactCount = listArtifactResponse.total_count; - if (totalArtifactCount > maximumArtifactCount) { - (0, core_1.warning)(`Workflow run ${workflowRunId} has ${totalArtifactCount} artifacts, exceeding the limit of ${maximumArtifactCount}. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`); - numberOfPages = maxNumberOfPages; + var path_1 = require("path"); + var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); + function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { + const specifications = []; + if (!fs2.existsSync(rootDirectory)) { + throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); + } + if (!fs2.statSync(rootDirectory).isDirectory()) { + throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); + } + rootDirectory = (0, path_1.normalize)(rootDirectory); + rootDirectory = (0, path_1.resolve)(rootDirectory); + for (let file of artifactFiles) { + if (!fs2.existsSync(file)) { + throw new Error(`File ${file} does not exist`); } - for (const artifact2 of listArtifactResponse.artifacts) { - artifacts.push({ - name: artifact2.name, - id: artifact2.id, - size: artifact2.size_in_bytes, - createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, - digest: artifact2.digest + if (!fs2.statSync(file).isDirectory()) { + file = (0, path_1.normalize)(file); + file = (0, path_1.resolve)(file); + if (!file.startsWith(rootDirectory)) { + throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); + } + const uploadPath = file.replace(rootDirectory, ""); + (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath); + specifications.push({ + absoluteFilePath: file, + uploadFilePath: (0, path_1.join)(artifactName, uploadPath) }); + } else { + (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`); } - currentPageNumber++; - for (currentPageNumber; currentPageNumber <= numberOfPages; currentPageNumber++) { - (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`); - const { data: listArtifactResponse2 } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - per_page: paginationCount, - page: currentPageNumber - }); - for (const artifact2 of listArtifactResponse2.artifacts) { - artifacts.push({ - name: artifact2.name, - id: artifact2.id, - size: artifact2.size_in_bytes, - createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0, - digest: artifact2.digest + } + return specifications; + } + exports2.getUploadSpecification = getUploadSpecification; + } +}); + +// node_modules/tmp/lib/tmp.js +var require_tmp = __commonJS({ + "node_modules/tmp/lib/tmp.js"(exports2, module2) { + var fs2 = require("fs"); + var os = require("os"); + var path2 = require("path"); + var crypto = require("crypto"); + var _c = { fs: fs2.constants, os: os.constants }; + var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + var TEMPLATE_PATTERN = /XXXXXX/; + var DEFAULT_TRIES = 3; + var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR); + var IS_WIN32 = os.platform() === "win32"; + var EBADF = _c.EBADF || _c.os.errno.EBADF; + var ENOENT = _c.ENOENT || _c.os.errno.ENOENT; + var DIR_MODE = 448; + var FILE_MODE = 384; + var EXIT = "exit"; + var _removeObjects = []; + var FN_RMDIR_SYNC = fs2.rmdirSync.bind(fs2); + var _gracefulCleanup = false; + function rimraf(dirPath, callback) { + return fs2.rm(dirPath, { recursive: true }, callback); + } + function FN_RIMRAF_SYNC(dirPath) { + return fs2.rmSync(dirPath, { recursive: true }); + } + function tmpName(options, callback) { + const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; + _assertAndSanitizeOptions(opts, function(err, sanitizedOptions) { + if (err) return cb(err); + let tries = sanitizedOptions.tries; + (function _getUniqueName() { + try { + const name = _generateTmpName(sanitizedOptions); + fs2.stat(name, function(err2) { + if (!err2) { + if (tries-- > 0) return _getUniqueName(); + return cb(new Error("Could not get a unique tmp filename, max tries reached " + name)); + } + cb(null, name); }); + } catch (err2) { + cb(err2); } + })(); + }); + } + function tmpNameSync(options) { + const args = _parseArguments(options), opts = args[0]; + const sanitizedOptions = _assertAndSanitizeOptionsSync(opts); + let tries = sanitizedOptions.tries; + do { + const name = _generateTmpName(sanitizedOptions); + try { + fs2.statSync(name); + } catch (e) { + return name; } - if (latest) { - artifacts = filterLatest(artifacts); - } - (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); - return { - artifacts - }; + } while (tries-- > 0); + throw new Error("Could not get a unique tmp filename, max tries reached"); + } + function file(options, callback) { + const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; + tmpName(opts, function _tmpNameCreated(err, name) { + if (err) return cb(err); + fs2.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { + if (err2) return cb(err2); + if (opts.discardDescriptor) { + return fs2.close(fd, function _discardCallback(possibleErr) { + return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false)); + }); + } else { + const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; + cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); + } + }); }); } - function listArtifactsInternal() { - return __awaiter4(this, arguments, void 0, function* (latest = false) { - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const req = { - workflowRunBackendId, - workflowJobRunBackendId - }; - const res = yield artifactClient.ListArtifacts(req); - let artifacts = res.artifacts.map((artifact2) => { - var _a; - return { - name: artifact2.name, - id: Number(artifact2.databaseId), - size: Number(artifact2.size), - createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0, - digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value - }; + function fileSync(options) { + const args = _parseArguments(options), opts = args[0]; + const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; + const name = tmpNameSync(opts); + let fd = fs2.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); + if (opts.discardDescriptor) { + fs2.closeSync(fd); + fd = void 0; + } + return { + name, + fd, + removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) + }; + } + function dir(options, callback) { + const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; + tmpName(opts, function _tmpNameCreated(err, name) { + if (err) return cb(err); + fs2.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { + if (err2) return cb(err2); + cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); - if (latest) { - artifacts = filterLatest(artifacts); + }); + } + function dirSync(options) { + const args = _parseArguments(options), opts = args[0]; + const name = tmpNameSync(opts); + fs2.mkdirSync(name, opts.mode || DIR_MODE); + return { + name, + removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) + }; + } + function _removeFileAsync(fdPath, next) { + const _handler = function(err) { + if (err && !_isENOENT(err)) { + return next(err); + } + next(); + }; + if (0 <= fdPath[0]) + fs2.close(fdPath[0], function() { + fs2.unlink(fdPath[1], _handler); + }); + else fs2.unlink(fdPath[1], _handler); + } + function _removeFileSync(fdPath) { + let rethrownException = null; + try { + if (0 <= fdPath[0]) fs2.closeSync(fdPath[0]); + } catch (e) { + if (!_isEBADF(e) && !_isENOENT(e)) throw e; + } finally { + try { + fs2.unlinkSync(fdPath[1]); + } catch (e) { + if (!_isENOENT(e)) rethrownException = e; + } + } + if (rethrownException !== null) { + throw rethrownException; + } + } + function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { + const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); + const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + return sync ? removeCallbackSync : removeCallback; + } + function _prepareTmpDirRemoveCallback(name, opts, sync) { + const removeFunction = opts.unsafeCleanup ? rimraf : fs2.rmdir.bind(fs2); + const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; + const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); + const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + return sync ? removeCallbackSync : removeCallback; + } + function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { + let called = false; + return function _cleanupCallback(next) { + if (!called) { + const toRemove = cleanupCallbackSync || _cleanupCallback; + const index = _removeObjects.indexOf(toRemove); + if (index >= 0) _removeObjects.splice(index, 1); + called = true; + if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { + return removeFunction(fileOrDirName); + } else { + return removeFunction(fileOrDirName, next || function() { + }); + } } - (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); - return { - artifacts - }; - }); + }; } - function filterLatest(artifacts) { - artifacts.sort((a, b) => b.id - a.id); - const latestArtifacts = []; - const seenArtifactNames = /* @__PURE__ */ new Set(); - for (const artifact2 of artifacts) { - if (!seenArtifactNames.has(artifact2.name)) { - latestArtifacts.push(artifact2); - seenArtifactNames.add(artifact2.name); + function _garbageCollector() { + if (!_gracefulCleanup) return; + while (_removeObjects.length) { + try { + _removeObjects[0](); + } catch (e) { } } - return latestArtifacts; } - } -}); - -// node_modules/@actions/artifact/lib/internal/client.js -var require_client2 = __commonJS({ - "node_modules/@actions/artifact/lib/internal/client.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); - }); + function _randomChars(howMany) { + let value = [], rnd = null; + try { + rnd = crypto.randomBytes(howMany); + } catch (e) { + rnd = crypto.pseudoRandomBytes(howMany); } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + for (let i = 0; i < howMany; i++) { + value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); + } + return value.join(""); + } + function _isUndefined(obj) { + return typeof obj === "undefined"; + } + function _parseArguments(options, callback) { + if (typeof options === "function") { + return [{}, options]; + } + if (_isUndefined(options)) { + return [{}, callback]; + } + const actualOptions = {}; + for (const key of Object.getOwnPropertyNames(options)) { + actualOptions[key] = options[key]; + } + return [actualOptions, callback]; + } + function _resolvePath(name, tmpDir, cb) { + const pathToResolve = path2.isAbsolute(name) ? name : path2.join(tmpDir, name); + fs2.stat(pathToResolve, function(err) { + if (err) { + fs2.realpath(path2.dirname(pathToResolve), function(err2, parentDir) { + if (err2) return cb(err2); + cb(null, path2.join(parentDir, path2.basename(pathToResolve))); + }); + } else { + fs2.realpath(path2, cb); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - }; - var __rest4 = exports2 && exports2.__rest || function(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DefaultArtifactClient = void 0; - var core_1 = require_core(); - var config_1 = require_config2(); - var upload_artifact_1 = require_upload_artifact(); - var download_artifact_1 = require_download_artifact(); - var delete_artifact_1 = require_delete_artifact(); - var get_artifact_1 = require_get_artifact(); - var list_artifacts_1 = require_list_artifacts(); - var errors_1 = require_errors3(); - var DefaultArtifactClient2 = class { - uploadArtifact(name, files, rootDirectory, options) { - return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options); - } catch (error4) { - (0, core_1.warning)(`Artifact upload failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } - }); + } + function _resolvePathSync(name, tmpDir) { + const pathToResolve = path2.isAbsolute(name) ? name : path2.join(tmpDir, name); + try { + fs2.statSync(pathToResolve); + return fs2.realpathSync(pathToResolve); + } catch (_err) { + const parentDir = fs2.realpathSync(path2.dirname(pathToResolve)); + return path2.join(parentDir, path2.basename(pathToResolve)); } - downloadArtifact(artifactId, options) { - return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest4(options, ["findBy"]); - return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions); - } - return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options); - } catch (error4) { - (0, core_1.warning)(`Download Artifact failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } - }); + } + function _generateTmpName(opts) { + const tmpDir = opts.tmpdir; + if (!_isUndefined(opts.name)) { + return path2.join(tmpDir, opts.dir, opts.name); } - listArtifacts(options) { - return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; - return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest); - } - return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest); - } catch (error4) { - (0, core_1.warning)(`Listing Artifacts failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } - }); + if (!_isUndefined(opts.template)) { + return path2.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); } - getArtifact(artifactName, options) { - return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; - return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - } - return (0, get_artifact_1.getArtifactInternal)(artifactName); - } catch (error4) { - (0, core_1.warning)(`Get Artifact failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } - }); + const name = [ + opts.prefix ? opts.prefix : "tmp", + "-", + process.pid, + "-", + _randomChars(12), + opts.postfix ? "-" + opts.postfix : "" + ].join(""); + return path2.join(tmpDir, opts.dir, name); + } + function _assertOptionsBase(options) { + if (!_isUndefined(options.name)) { + const name = options.name; + if (path2.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`); + const basename = path2.basename(name); + if (basename === ".." || basename === "." || basename !== name) + throw new Error(`name option must not contain a path, found "${name}".`); } - deleteArtifact(artifactName, options) { - return __awaiter4(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { repositoryOwner, repositoryName, workflowRunId, token } } = options; - return (0, delete_artifact_1.deleteArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - } - return (0, delete_artifact_1.deleteArtifactInternal)(artifactName); - } catch (error4) { - (0, core_1.warning)(`Delete Artifact failed with error: ${error4}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error4; - } + if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) { + throw new Error(`Invalid template, found "${options.template}".`); + } + if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) { + throw new Error(`Invalid tries, found "${options.tries}".`); + } + options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; + options.keep = !!options.keep; + options.detachDescriptor = !!options.detachDescriptor; + options.discardDescriptor = !!options.discardDescriptor; + options.unsafeCleanup = !!options.unsafeCleanup; + options.prefix = _isUndefined(options.prefix) ? "" : options.prefix; + options.postfix = _isUndefined(options.postfix) ? "" : options.postfix; + } + function _getRelativePath(option, name, tmpDir, cb) { + if (_isUndefined(name)) return cb(null); + _resolvePath(name, tmpDir, function(err, resolvedPath) { + if (err) return cb(err); + const relativePath = path2.relative(tmpDir, resolvedPath); + if (!resolvedPath.startsWith(tmpDir)) { + return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`)); + } + cb(null, relativePath); + }); + } + function _getRelativePathSync(option, name, tmpDir) { + if (_isUndefined(name)) return; + const resolvedPath = _resolvePathSync(name, tmpDir); + const relativePath = path2.relative(tmpDir, resolvedPath); + if (!resolvedPath.startsWith(tmpDir)) { + throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`); + } + return relativePath; + } + function _assertAndSanitizeOptions(options, cb) { + _getTmpDir(options, function(err, tmpDir) { + if (err) return cb(err); + options.tmpdir = tmpDir; + try { + _assertOptionsBase(options, tmpDir); + } catch (err2) { + return cb(err2); + } + _getRelativePath("dir", options.dir, tmpDir, function(err2, dir2) { + if (err2) return cb(err2); + options.dir = _isUndefined(dir2) ? "" : dir2; + _getRelativePath("template", options.template, tmpDir, function(err3, template) { + if (err3) return cb(err3); + options.template = template; + cb(null, options); + }); }); + }); + } + function _assertAndSanitizeOptionsSync(options) { + const tmpDir = options.tmpdir = _getTmpDirSync(options); + _assertOptionsBase(options, tmpDir); + const dir2 = _getRelativePathSync("dir", options.dir, tmpDir); + options.dir = _isUndefined(dir2) ? "" : dir2; + options.template = _getRelativePathSync("template", options.template, tmpDir); + return options; + } + function _isEBADF(error4) { + return _isExpectedError(error4, -EBADF, "EBADF"); + } + function _isENOENT(error4) { + return _isExpectedError(error4, -ENOENT, "ENOENT"); + } + function _isExpectedError(error4, errno, code) { + return IS_WIN32 ? error4.code === code : error4.code === code && error4.errno === errno; + } + function setGracefulCleanup() { + _gracefulCleanup = true; + } + function _getTmpDir(options, cb) { + return fs2.realpath(options && options.tmpdir || os.tmpdir(), cb); + } + function _getTmpDirSync(options) { + return fs2.realpathSync(options && options.tmpdir || os.tmpdir()); + } + process.addListener(EXIT, _garbageCollector); + Object.defineProperty(module2.exports, "tmpdir", { + enumerable: true, + configurable: false, + get: function() { + return _getTmpDirSync(); } - }; - exports2.DefaultArtifactClient = DefaultArtifactClient2; - } -}); - -// node_modules/@actions/artifact/lib/internal/shared/interfaces.js -var require_interfaces2 = __commonJS({ - "node_modules/@actions/artifact/lib/internal/shared/interfaces.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); + }); + module2.exports.dir = dir; + module2.exports.dirSync = dirSync; + module2.exports.file = file; + module2.exports.fileSync = fileSync; + module2.exports.tmpName = tmpName; + module2.exports.tmpNameSync = tmpNameSync; + module2.exports.setGracefulCleanup = setGracefulCleanup; } }); -// node_modules/@actions/artifact/lib/artifact.js -var require_artifact2 = __commonJS({ - "node_modules/@actions/artifact/lib/artifact.js"(exports2) { +// node_modules/tmp-promise/index.js +var require_tmp_promise = __commonJS({ + "node_modules/tmp-promise/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + var { promisify } = require("util"); + var tmp = require_tmp(); + module2.exports.fileSync = tmp.fileSync; + var fileWithOptions = promisify( + (options, cb) => tmp.file( + options, + (err, path2, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path2, fd, cleanup: promisify(cleanup) }) + ) + ); + module2.exports.file = async (options) => fileWithOptions(options); + module2.exports.withFile = async function withFile(fn, options) { + const { path: path2, fd, cleanup } = await module2.exports.file(options); + try { + return await fn({ path: path2, fd }); + } finally { + await cleanup(); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); }; - Object.defineProperty(exports2, "__esModule", { value: true }); - var client_1 = require_client2(); - __exportStar4(require_interfaces2(), exports2); - __exportStar4(require_errors3(), exports2); - __exportStar4(require_client2(), exports2); - var client = new client_1.DefaultArtifactClient(); - exports2.default = client; + module2.exports.dirSync = tmp.dirSync; + var dirWithOptions = promisify( + (options, cb) => tmp.dir( + options, + (err, path2, cleanup) => err ? cb(err) : cb(void 0, { path: path2, cleanup: promisify(cleanup) }) + ) + ); + module2.exports.dir = async (options) => dirWithOptions(options); + module2.exports.withDir = async function withDir(fn, options) { + const { path: path2, cleanup } = await module2.exports.dir(options); + try { + return await fn({ path: path2 }); + } finally { + await cleanup(); + } + }; + module2.exports.tmpNameSync = tmp.tmpNameSync; + module2.exports.tmpName = promisify(tmp.tmpName); + module2.exports.tmpdir = tmp.tmpdir; + module2.exports.setGracefulCleanup = tmp.setGracefulCleanup; } }); -// node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js -var require_path_and_artifact_name_validation2 = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js"(exports2) { +// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/proxy.js +var require_proxy5 = __commonJS({ + "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.checkArtifactFilePath = exports2.checkArtifactName = void 0; - var core_1 = require_core(); - var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([ - ['"', ' Double quote "'], - [":", " Colon :"], - ["<", " Less than <"], - [">", " Greater than >"], - ["|", " Vertical bar |"], - ["*", " Asterisk *"], - ["?", " Question mark ?"], - ["\r", " Carriage return \\r"], - ["\n", " Line feed \\n"] - ]); - var invalidArtifactNameCharacters = new Map([ - ...invalidArtifactFilePathCharacters, - ["\\", " Backslash \\"], - ["/", " Forward slash /"] - ]); - function checkArtifactName(name) { - if (!name) { - throw new Error(`Artifact name: ${name}, is incorrectly provided`); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { - if (name.includes(invalidCharacterKey)) { - throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} - -These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } + } else { + return void 0; } - (0, core_1.info)(`Artifact name is valid!`); } - exports2.checkArtifactName = checkArtifactName; - function checkArtifactFilePath(path2) { - if (!path2) { - throw new Error(`Artifact path: ${path2}, is incorrectly provided`); + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path2.includes(invalidCharacterKey)) { - throw new Error(`Artifact path is not valid: ${path2}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} - -The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. - `); - } + get password() { + return this._decodedPassword; } - } - exports2.checkArtifactFilePath = checkArtifactFilePath; + }; } }); -// node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js -var require_upload_specification = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js"(exports2) { +// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/index.js +var require_lib7 = __commonJS({ + "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -105728,448 +108597,695 @@ var require_upload_specification = __commonJS({ __setModuleDefault4(result, mod); return result; }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUploadSpecification = void 0; - var fs2 = __importStar4(require("fs")); - var core_1 = require_core(); - var path_1 = require("path"); - var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); - function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { - const specifications = []; - if (!fs2.existsSync(rootDirectory)) { - throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy5()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - if (!fs2.statSync(rootDirectory).isDirectory()) { - throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - rootDirectory = (0, path_1.normalize)(rootDirectory); - rootDirectory = (0, path_1.resolve)(rootDirectory); - for (let file of artifactFiles) { - if (!fs2.existsSync(file)) { - throw new Error(`File ${file} does not exist`); + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); + }); + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } } - if (!fs2.statSync(file).isDirectory()) { - file = (0, path_1.normalize)(file); - file = (0, path_1.resolve)(file); - if (!file.startsWith(rootDirectory)) { - throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - const uploadPath = file.replace(rootDirectory, ""); - (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath); - specifications.push({ - absoluteFilePath: file, - uploadFilePath: (0, path_1.join)(artifactName, uploadPath) - }); - } else { - (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`); + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return specifications; - } - exports2.getUploadSpecification = getUploadSpecification; - } -}); - -// node_modules/tmp/lib/tmp.js -var require_tmp = __commonJS({ - "node_modules/tmp/lib/tmp.js"(exports2, module2) { - var fs2 = require("fs"); - var os = require("os"); - var path2 = require("path"); - var crypto = require("crypto"); - var _c = { fs: fs2.constants, os: os.constants }; - var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - var TEMPLATE_PATTERN = /XXXXXX/; - var DEFAULT_TRIES = 3; - var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR); - var IS_WIN32 = os.platform() === "win32"; - var EBADF = _c.EBADF || _c.os.errno.EBADF; - var ENOENT = _c.ENOENT || _c.os.errno.ENOENT; - var DIR_MODE = 448; - var FILE_MODE = 384; - var EXIT = "exit"; - var _removeObjects = []; - var FN_RMDIR_SYNC = fs2.rmdirSync.bind(fs2); - var _gracefulCleanup = false; - function rimraf(dirPath, callback) { - return fs2.rm(dirPath, { recursive: true }, callback); - } - function FN_RIMRAF_SYNC(dirPath) { - return fs2.rmSync(dirPath, { recursive: true }); - } - function tmpName(options, callback) { - const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; - _assertAndSanitizeOptions(opts, function(err, sanitizedOptions) { - if (err) return cb(err); - let tries = sanitizedOptions.tries; - (function _getUniqueName() { - try { - const name = _generateTmpName(sanitizedOptions); - fs2.stat(name, function(err2) { - if (!err2) { - if (tries-- > 0) return _getUniqueName(); - return cb(new Error("Could not get a unique tmp filename, max tries reached " + name)); + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); } - cb(null, name); - }); - } catch (err2) { - cb(err2); + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; } - })(); - }); - } - function tmpNameSync(options) { - const args = _parseArguments(options), opts = args[0]; - const sanitizedOptions = _assertAndSanitizeOptionsSync(opts); - let tries = sanitizedOptions.tries; - do { - const name = _generateTmpName(sanitizedOptions); - try { - fs2.statSync(name); - } catch (e) { - return name; + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - } while (tries-- > 0); - throw new Error("Could not get a unique tmp filename, max tries reached"); - } - function file(options, callback) { - const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; - tmpName(opts, function _tmpNameCreated(err, name) { - if (err) return cb(err); - fs2.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { - if (err2) return cb(err2); - if (opts.discardDescriptor) { - return fs2.close(fd, function _discardCallback(possibleErr) { - return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false)); - }); - } else { - const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; - cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); - } - }); - }); - } - function fileSync(options) { - const args = _parseArguments(options), opts = args[0]; - const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; - const name = tmpNameSync(opts); - let fd = fs2.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); - if (opts.discardDescriptor) { - fs2.closeSync(fd); - fd = void 0; + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return { - name, - fd, - removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) - }; - } - function dir(options, callback) { - const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; - tmpName(opts, function _tmpNameCreated(err, name) { - if (err) return cb(err); - fs2.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { - if (err2) return cb(err2); - cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); - }); - }); - } - function dirSync(options) { - const args = _parseArguments(options), opts = args[0]; - const name = tmpNameSync(opts); - fs2.mkdirSync(name, opts.mode || DIR_MODE); - return { - name, - removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) - }; - } - function _removeFileAsync(fdPath, next) { - const _handler = function(err) { - if (err && !_isENOENT(err)) { - return next(err); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; } - next(); - }; - if (0 <= fdPath[0]) - fs2.close(fdPath[0], function() { - fs2.unlink(fdPath[1], _handler); - }); - else fs2.unlink(fdPath[1], _handler); - } - function _removeFileSync(fdPath) { - let rethrownException = null; - try { - if (0 <= fdPath[0]) fs2.closeSync(fdPath[0]); - } catch (e) { - if (!_isEBADF(e) && !_isENOENT(e)) throw e; - } finally { - try { - fs2.unlinkSync(fdPath[1]); - } catch (e) { - if (!_isENOENT(e)) rethrownException = e; + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } } + return info7; } - if (rethrownException !== null) { - throw rethrownException; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - } - function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { - const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); - const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); - return sync ? removeCallbackSync : removeCallback; - } - function _prepareTmpDirRemoveCallback(name, opts, sync) { - const removeFunction = opts.unsafeCleanup ? rimraf : fs2.rmdir.bind(fs2); - const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; - const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); - const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); - if (!opts.keep) _removeObjects.unshift(removeCallbackSync); - return sync ? removeCallbackSync : removeCallback; - } - function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { - let called = false; - return function _cleanupCallback(next) { - if (!called) { - const toRemove = cleanupCallbackSync || _cleanupCallback; - const index = _removeObjects.indexOf(toRemove); - if (index >= 0) _removeObjects.splice(index, 1); - called = true; - if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { - return removeFunction(fileOrDirName); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - return removeFunction(fileOrDirName, next || function() { - }); + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - }; - } - function _garbageCollector() { - if (!_gracefulCleanup) return; - while (_removeObjects.length) { - try { - _removeObjects[0](); - } catch (e) { + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - } - function _randomChars(howMany) { - let value = [], rnd = null; - try { - rnd = crypto.randomBytes(howMany); - } catch (e) { - rnd = crypto.pseudoRandomBytes(howMany); - } - for (let i = 0; i < howMany; i++) { - value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - return value.join(""); - } - function _isUndefined(obj) { - return typeof obj === "undefined"; - } - function _parseArguments(options, callback) { - if (typeof options === "function") { - return [{}, options]; + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); } - if (_isUndefined(options)) { - return [{}, callback]; + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); } - const actualOptions = {}; - for (const key of Object.getOwnPropertyNames(options)) { - actualOptions[key] = options[key]; + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/auth.js +var require_auth4 = __commonJS({ + "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/auth.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); } - return [actualOptions, callback]; - } - function _resolvePath(name, tmpDir, cb) { - const pathToResolve = path2.isAbsolute(name) ? name : path2.join(tmpDir, name); - fs2.stat(pathToResolve, function(err) { - if (err) { - fs2.realpath(path2.dirname(pathToResolve), function(err2, parentDir) { - if (err2) return cb(err2); - cb(null, path2.join(parentDir, path2.basename(pathToResolve))); - }); - } else { - fs2.realpath(path2, cb); + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - } - function _resolvePathSync(name, tmpDir) { - const pathToResolve = path2.isAbsolute(name) ? name : path2.join(tmpDir, name); - try { - fs2.statSync(pathToResolve); - return fs2.realpathSync(pathToResolve); - } catch (_err) { - const parentDir = fs2.realpathSync(path2.dirname(pathToResolve)); - return path2.join(parentDir, path2.basename(pathToResolve)); - } - } - function _generateTmpName(opts) { - const tmpDir = opts.tmpdir; - if (!_isUndefined(opts.name)) { - return path2.join(tmpDir, opts.dir, opts.name); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - if (!_isUndefined(opts.template)) { - return path2.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; } - const name = [ - opts.prefix ? opts.prefix : "tmp", - "-", - process.pid, - "-", - _randomChars(12), - opts.postfix ? "-" + opts.postfix : "" - ].join(""); - return path2.join(tmpDir, opts.dir, name); - } - function _assertOptionsBase(options) { - if (!_isUndefined(options.name)) { - const name = options.name; - if (path2.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`); - const basename = path2.basename(name); - if (basename === ".." || basename === "." || basename !== name) - throw new Error(`name option must not contain a path, found "${name}".`); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) { - throw new Error(`Invalid template, found "${options.template}".`); + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } - if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) { - throw new Error(`Invalid tries, found "${options.tries}".`); + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; } - options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; - options.keep = !!options.keep; - options.detachDescriptor = !!options.detachDescriptor; - options.discardDescriptor = !!options.discardDescriptor; - options.unsafeCleanup = !!options.unsafeCleanup; - options.prefix = _isUndefined(options.prefix) ? "" : options.prefix; - options.postfix = _isUndefined(options.postfix) ? "" : options.postfix; - } - function _getRelativePath(option, name, tmpDir, cb) { - if (_isUndefined(name)) return cb(null); - _resolvePath(name, tmpDir, function(err, resolvedPath) { - if (err) return cb(err); - const relativePath = path2.relative(tmpDir, resolvedPath); - if (!resolvedPath.startsWith(tmpDir)) { - return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`)); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } - cb(null, relativePath); - }); - } - function _getRelativePathSync(option, name, tmpDir) { - if (_isUndefined(name)) return; - const resolvedPath = _resolvePathSync(name, tmpDir); - const relativePath = path2.relative(tmpDir, resolvedPath); - if (!resolvedPath.startsWith(tmpDir)) { - throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`); + options.headers["Authorization"] = `Bearer ${this.token}`; } - return relativePath; - } - function _assertAndSanitizeOptions(options, cb) { - _getTmpDir(options, function(err, tmpDir) { - if (err) return cb(err); - options.tmpdir = tmpDir; - try { - _assertOptionsBase(options, tmpDir); - } catch (err2) { - return cb(err2); - } - _getRelativePath("dir", options.dir, tmpDir, function(err2, dir2) { - if (err2) return cb(err2); - options.dir = _isUndefined(dir2) ? "" : dir2; - _getRelativePath("template", options.template, tmpDir, function(err3, template) { - if (err3) return cb(err3); - options.template = template; - cb(null, options); - }); - }); - }); - } - function _assertAndSanitizeOptionsSync(options) { - const tmpDir = options.tmpdir = _getTmpDirSync(options); - _assertOptionsBase(options, tmpDir); - const dir2 = _getRelativePathSync("dir", options.dir, tmpDir); - options.dir = _isUndefined(dir2) ? "" : dir2; - options.template = _getRelativePathSync("template", options.template, tmpDir); - return options; - } - function _isEBADF(error4) { - return _isExpectedError(error4, -EBADF, "EBADF"); - } - function _isENOENT(error4) { - return _isExpectedError(error4, -ENOENT, "ENOENT"); - } - function _isExpectedError(error4, errno, code) { - return IS_WIN32 ? error4.code === code : error4.code === code && error4.errno === errno; - } - function setGracefulCleanup() { - _gracefulCleanup = true; - } - function _getTmpDir(options, cb) { - return fs2.realpath(options && options.tmpdir || os.tmpdir(), cb); - } - function _getTmpDirSync(options) { - return fs2.realpathSync(options && options.tmpdir || os.tmpdir()); - } - process.addListener(EXIT, _garbageCollector); - Object.defineProperty(module2.exports, "tmpdir", { - enumerable: true, - configurable: false, - get: function() { - return _getTmpDirSync(); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - }); - module2.exports.dir = dir; - module2.exports.dirSync = dirSync; - module2.exports.file = file; - module2.exports.fileSync = fileSync; - module2.exports.tmpName = tmpName; - module2.exports.tmpNameSync = tmpNameSync; - module2.exports.setGracefulCleanup = setGracefulCleanup; - } -}); - -// node_modules/tmp-promise/index.js -var require_tmp_promise = __commonJS({ - "node_modules/tmp-promise/index.js"(exports2, module2) { - "use strict"; - var { promisify } = require("util"); - var tmp = require_tmp(); - module2.exports.fileSync = tmp.fileSync; - var fileWithOptions = promisify( - (options, cb) => tmp.file( - options, - (err, path2, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path2, fd, cleanup: promisify(cleanup) }) - ) - ); - module2.exports.file = async (options) => fileWithOptions(options); - module2.exports.withFile = async function withFile(fn, options) { - const { path: path2, fd, cleanup } = await module2.exports.file(options); - try { - return await fn({ path: path2, fd }); - } finally { - await cleanup(); + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } }; - module2.exports.dirSync = tmp.dirSync; - var dirWithOptions = promisify( - (options, cb) => tmp.dir( - options, - (err, path2, cleanup) => err ? cb(err) : cb(void 0, { path: path2, cleanup: promisify(cleanup) }) - ) - ); - module2.exports.dir = async (options) => dirWithOptions(options); - module2.exports.withDir = async function withDir(fn, options) { - const { path: path2, cleanup } = await module2.exports.dir(options); - try { - return await fn({ path: path2 }); - } finally { - await cleanup(); + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } }; - module2.exports.tmpNameSync = tmp.tmpNameSync; - module2.exports.tmpName = promisify(tmp.tmpName); - module2.exports.tmpdir = tmp.tmpdir; - module2.exports.setGracefulCleanup = tmp.setGracefulCleanup; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); @@ -106583,8 +109699,8 @@ var require_utils7 = __commonJS({ var crypto_1 = __importDefault4(require("crypto")); var fs_1 = require("fs"); var core_1 = require_core(); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib7(); + var auth_1 = require_auth4(); var config_variables_1 = require_config_variables(); var crc64_1 = __importDefault4(require_crc64()); function getExponentialRetryTimeInMilliseconds(retryCount) { @@ -106864,28 +109980,704 @@ var require_http_manager = __commonJS({ this.userAgent = userAgent; this.clients = new Array(clientCount).fill((0, utils_1.createHttpClient)(userAgent)); } - getClient(index) { - return this.clients[index]; + getClient(index) { + return this.clients[index]; + } + // client disposal is necessary if a keep-alive connection is used to properly close the connection + // for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292 + disposeAndReplaceClient(index) { + this.clients[index].dispose(); + this.clients[index] = (0, utils_1.createHttpClient)(this.userAgent); + } + disposeAndReplaceAllClients() { + for (const [index] of this.clients.entries()) { + this.disposeAndReplaceClient(index); + } + } + }; + exports2.HttpManager = HttpManager; + } +}); + +// node_modules/@actions/artifact-legacy/lib/internal/upload-gzip.js +var require_upload_gzip = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/upload-gzip.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); + }); + }; + } + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createGZipFileInBuffer = exports2.createGZipFileOnDisk = void 0; + var fs2 = __importStar4(require("fs")); + var zlib = __importStar4(require("zlib")); + var util_1 = require("util"); + var stat = (0, util_1.promisify)(fs2.stat); + var gzipExemptFileExtensions = [ + ".gz", + ".gzip", + ".tgz", + ".taz", + ".Z", + ".taZ", + ".bz2", + ".tbz", + ".tbz2", + ".tz2", + ".lz", + ".lzma", + ".tlz", + ".lzo", + ".xz", + ".txz", + ".zst", + ".zstd", + ".tzst", + ".zip", + ".7z" + // 7ZIP + ]; + function createGZipFileOnDisk(originalFilePath, tempFilePath) { + return __awaiter4(this, void 0, void 0, function* () { + for (const gzipExemptExtension of gzipExemptFileExtensions) { + if (originalFilePath.endsWith(gzipExemptExtension)) { + return Number.MAX_SAFE_INTEGER; + } + } + return new Promise((resolve2, reject) => { + const inputStream = fs2.createReadStream(originalFilePath); + const gzip = zlib.createGzip(); + const outputStream = fs2.createWriteStream(tempFilePath); + inputStream.pipe(gzip).pipe(outputStream); + outputStream.on("finish", () => __awaiter4(this, void 0, void 0, function* () { + const size = (yield stat(tempFilePath)).size; + resolve2(size); + })); + outputStream.on("error", (error4) => { + console.log(error4); + reject(error4); + }); + }); + }); + } + exports2.createGZipFileOnDisk = createGZipFileOnDisk; + function createGZipFileInBuffer(originalFilePath) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + var _a, e_1, _b, _c; + const inputStream = fs2.createReadStream(originalFilePath); + const gzip = zlib.createGzip(); + inputStream.pipe(gzip); + const chunks = []; + try { + for (var _d = true, gzip_1 = __asyncValues4(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), _a = gzip_1_1.done, !_a; ) { + _c = gzip_1_1.value; + _d = false; + try { + const chunk = _c; + chunks.push(chunk); + } finally { + _d = true; + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = gzip_1.return)) yield _b.call(gzip_1); + } finally { + if (e_1) throw e_1.error; + } + } + resolve2(Buffer.concat(chunks)); + })); + }); + } + exports2.createGZipFileInBuffer = createGZipFileInBuffer; + } +}); + +// node_modules/@actions/artifact-legacy/lib/internal/requestUtils.js +var require_requestUtils2 = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/requestUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.retryHttpClientRequest = exports2.retry = void 0; + var utils_1 = require_utils7(); + var core14 = __importStar4(require_core()); + var config_variables_1 = require_config_variables(); + function retry3(name, operation, customErrorMessages, maxAttempts) { + return __awaiter4(this, void 0, void 0, function* () { + let response = void 0; + let statusCode = void 0; + let isRetryable = false; + let errorMessage = ""; + let customErrorInformation = void 0; + let attempt = 1; + while (attempt <= maxAttempts) { + try { + response = yield operation(); + statusCode = response.message.statusCode; + if ((0, utils_1.isSuccessStatusCode)(statusCode)) { + return response; + } + if (statusCode) { + customErrorInformation = customErrorMessages.get(statusCode); + } + isRetryable = (0, utils_1.isRetryableStatusCode)(statusCode); + errorMessage = `Artifact service responded with ${statusCode}`; + } catch (error4) { + isRetryable = true; + errorMessage = error4.message; + } + if (!isRetryable) { + core14.info(`${name} - Error is not retryable`); + if (response) { + (0, utils_1.displayHttpDiagnostics)(response); + } + break; + } + core14.info(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); + yield (0, utils_1.sleep)((0, utils_1.getExponentialRetryTimeInMilliseconds)(attempt)); + attempt++; + } + if (response) { + (0, utils_1.displayHttpDiagnostics)(response); + } + if (customErrorInformation) { + throw Error(`${name} failed: ${customErrorInformation}`); + } + throw Error(`${name} failed: ${errorMessage}`); + }); + } + exports2.retry = retry3; + function retryHttpClientRequest(name, method, customErrorMessages = /* @__PURE__ */ new Map(), maxAttempts = (0, config_variables_1.getRetryLimit)()) { + return __awaiter4(this, void 0, void 0, function* () { + return yield retry3(name, method, customErrorMessages, maxAttempts); + }); + } + exports2.retryHttpClientRequest = retryHttpClientRequest; + } +}); + +// node_modules/@actions/artifact-legacy/lib/internal/upload-http-client.js +var require_upload_http_client = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/upload-http-client.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UploadHttpClient = void 0; + var fs2 = __importStar4(require("fs")); + var core14 = __importStar4(require_core()); + var tmp = __importStar4(require_tmp_promise()); + var stream = __importStar4(require("stream")); + var utils_1 = require_utils7(); + var config_variables_1 = require_config_variables(); + var util_1 = require("util"); + var url_1 = require("url"); + var perf_hooks_1 = require("perf_hooks"); + var status_reporter_1 = require_status_reporter(); + var http_client_1 = require_lib7(); + var http_manager_1 = require_http_manager(); + var upload_gzip_1 = require_upload_gzip(); + var requestUtils_1 = require_requestUtils2(); + var stat = (0, util_1.promisify)(fs2.stat); + var UploadHttpClient = class { + constructor() { + this.uploadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getUploadFileConcurrency)(), "@actions/artifact-upload"); + this.statusReporter = new status_reporter_1.StatusReporter(1e4); + } + /** + * Creates a file container for the new artifact in the remote blob storage/file service + * @param {string} artifactName Name of the artifact being created + * @returns The response from the Artifact Service if the file container was successfully created + */ + createArtifactInFileContainer(artifactName, options) { + return __awaiter4(this, void 0, void 0, function* () { + const parameters = { + Type: "actions_storage", + Name: artifactName + }; + if (options && options.retentionDays) { + const maxRetentionStr = (0, config_variables_1.getRetentionDays)(); + parameters.RetentionDays = (0, utils_1.getProperRetention)(options.retentionDays, maxRetentionStr); + } + const data = JSON.stringify(parameters, null, 2); + const artifactUrl = (0, utils_1.getArtifactUrl)(); + const client = this.uploadHttpManager.getClient(0); + const headers = (0, utils_1.getUploadHeaders)("application/json", false); + const customErrorMessages = /* @__PURE__ */ new Map([ + [ + http_client_1.HttpCodes.Forbidden, + (0, config_variables_1.isGhes)() ? "Please reference [Enabling GitHub Actions for GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@3.8/admin/github-actions/enabling-github-actions-for-github-enterprise-server) to ensure Actions storage is configured correctly." : "Artifact storage quota has been hit. Unable to upload any new artifacts" + ], + [ + http_client_1.HttpCodes.BadRequest, + `The artifact name ${artifactName} is not valid. Request URL ${artifactUrl}` + ] + ]); + const response = yield (0, requestUtils_1.retryHttpClientRequest)("Create Artifact Container", () => __awaiter4(this, void 0, void 0, function* () { + return client.post(artifactUrl, data, headers); + }), customErrorMessages); + const body = yield response.readBody(); + return JSON.parse(body); + }); + } + /** + * Concurrently upload all of the files in chunks + * @param {string} uploadUrl Base Url for the artifact that was created + * @param {SearchResult[]} filesToUpload A list of information about the files being uploaded + * @returns The size of all the files uploaded in bytes + */ + uploadArtifactToFileContainer(uploadUrl, filesToUpload, options) { + return __awaiter4(this, void 0, void 0, function* () { + const FILE_CONCURRENCY = (0, config_variables_1.getUploadFileConcurrency)(); + const MAX_CHUNK_SIZE = (0, config_variables_1.getUploadChunkSize)(); + core14.debug(`File Concurrency: ${FILE_CONCURRENCY}, and Chunk Size: ${MAX_CHUNK_SIZE}`); + const parameters = []; + let continueOnError = true; + if (options) { + if (options.continueOnError === false) { + continueOnError = false; + } + } + for (const file of filesToUpload) { + const resourceUrl = new url_1.URL(uploadUrl); + resourceUrl.searchParams.append("itemPath", file.uploadFilePath); + parameters.push({ + file: file.absoluteFilePath, + resourceUrl: resourceUrl.toString(), + maxChunkSize: MAX_CHUNK_SIZE, + continueOnError + }); + } + const parallelUploads = [...new Array(FILE_CONCURRENCY).keys()]; + const failedItemsToReport = []; + let currentFile = 0; + let completedFiles = 0; + let uploadFileSize = 0; + let totalFileSize = 0; + let abortPendingFileUploads = false; + this.statusReporter.setTotalNumberOfFilesToProcess(filesToUpload.length); + this.statusReporter.start(); + yield Promise.all(parallelUploads.map((index) => __awaiter4(this, void 0, void 0, function* () { + while (currentFile < filesToUpload.length) { + const currentFileParameters = parameters[currentFile]; + currentFile += 1; + if (abortPendingFileUploads) { + failedItemsToReport.push(currentFileParameters.file); + continue; + } + const startTime = perf_hooks_1.performance.now(); + const uploadFileResult = yield this.uploadFileAsync(index, currentFileParameters); + if (core14.isDebug()) { + core14.debug(`File: ${++completedFiles}/${filesToUpload.length}. ${currentFileParameters.file} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish upload`); + } + uploadFileSize += uploadFileResult.successfulUploadSize; + totalFileSize += uploadFileResult.totalSize; + if (uploadFileResult.isSuccess === false) { + failedItemsToReport.push(currentFileParameters.file); + if (!continueOnError) { + core14.error(`aborting artifact upload`); + abortPendingFileUploads = true; + } + } + this.statusReporter.incrementProcessedCount(); + } + }))); + this.statusReporter.stop(); + this.uploadHttpManager.disposeAndReplaceAllClients(); + core14.info(`Total size of all the files uploaded is ${uploadFileSize} bytes`); + return { + uploadSize: uploadFileSize, + totalSize: totalFileSize, + failedItems: failedItemsToReport + }; + }); + } + /** + * Asynchronously uploads a file. The file is compressed and uploaded using GZip if it is determined to save space. + * If the upload file is bigger than the max chunk size it will be uploaded via multiple calls + * @param {number} httpClientIndex The index of the httpClient that is being used to make all of the calls + * @param {UploadFileParameters} parameters Information about the file that needs to be uploaded + * @returns The size of the file that was uploaded in bytes along with any failed uploads + */ + uploadFileAsync(httpClientIndex, parameters) { + return __awaiter4(this, void 0, void 0, function* () { + const fileStat = yield stat(parameters.file); + const totalFileSize = fileStat.size; + const isFIFO = fileStat.isFIFO(); + let offset = 0; + let isUploadSuccessful = true; + let failedChunkSizes = 0; + let uploadFileSize = 0; + let isGzip = true; + if (!isFIFO && totalFileSize < 65536) { + core14.debug(`${parameters.file} is less than 64k in size. Creating a gzip file in-memory to potentially reduce the upload size`); + const buffer = yield (0, upload_gzip_1.createGZipFileInBuffer)(parameters.file); + let openUploadStream; + if (totalFileSize < buffer.byteLength) { + core14.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); + openUploadStream = () => fs2.createReadStream(parameters.file); + isGzip = false; + uploadFileSize = totalFileSize; + } else { + core14.debug(`A gzip file created for ${parameters.file} helped with reducing the size of the original file. The file will be uploaded using gzip.`); + openUploadStream = () => { + const passThrough = new stream.PassThrough(); + passThrough.end(buffer); + return passThrough; + }; + uploadFileSize = buffer.byteLength; + } + const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, openUploadStream, 0, uploadFileSize - 1, uploadFileSize, isGzip, totalFileSize); + if (!result) { + isUploadSuccessful = false; + failedChunkSizes += uploadFileSize; + core14.warning(`Aborting upload for ${parameters.file} due to failure`); + } + return { + isSuccess: isUploadSuccessful, + successfulUploadSize: uploadFileSize - failedChunkSizes, + totalSize: totalFileSize + }; + } else { + const tempFile = yield tmp.file(); + core14.debug(`${parameters.file} is greater than 64k in size. Creating a gzip file on-disk ${tempFile.path} to potentially reduce the upload size`); + uploadFileSize = yield (0, upload_gzip_1.createGZipFileOnDisk)(parameters.file, tempFile.path); + let uploadFilePath = tempFile.path; + if (!isFIFO && totalFileSize < uploadFileSize) { + core14.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); + uploadFileSize = totalFileSize; + uploadFilePath = parameters.file; + isGzip = false; + } else { + core14.debug(`The gzip file created for ${parameters.file} is smaller than the original file. The file will be uploaded using gzip.`); + } + let abortFileUpload = false; + while (offset < uploadFileSize) { + const chunkSize = Math.min(uploadFileSize - offset, parameters.maxChunkSize); + const startChunkIndex = offset; + const endChunkIndex = offset + chunkSize - 1; + offset += parameters.maxChunkSize; + if (abortFileUpload) { + failedChunkSizes += chunkSize; + continue; + } + const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs2.createReadStream(uploadFilePath, { + start: startChunkIndex, + end: endChunkIndex, + autoClose: false + }), startChunkIndex, endChunkIndex, uploadFileSize, isGzip, totalFileSize); + if (!result) { + isUploadSuccessful = false; + failedChunkSizes += chunkSize; + core14.warning(`Aborting upload for ${parameters.file} due to failure`); + abortFileUpload = true; + } else { + if (uploadFileSize > 8388608) { + this.statusReporter.updateLargeFileStatus(parameters.file, startChunkIndex, endChunkIndex, uploadFileSize); + } + } + } + core14.debug(`deleting temporary gzip file ${tempFile.path}`); + yield tempFile.cleanup(); + return { + isSuccess: isUploadSuccessful, + successfulUploadSize: uploadFileSize - failedChunkSizes, + totalSize: totalFileSize + }; + } + }); } - // client disposal is necessary if a keep-alive connection is used to properly close the connection - // for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292 - disposeAndReplaceClient(index) { - this.clients[index].dispose(); - this.clients[index] = (0, utils_1.createHttpClient)(this.userAgent); + /** + * Uploads a chunk of an individual file to the specified resourceUrl. If the upload fails and the status code + * indicates a retryable status, we try to upload the chunk as well + * @param {number} httpClientIndex The index of the httpClient being used to make all the necessary calls + * @param {string} resourceUrl Url of the resource that the chunk will be uploaded to + * @param {NodeJS.ReadableStream} openStream Stream of the file that will be uploaded + * @param {number} start Starting byte index of file that the chunk belongs to + * @param {number} end Ending byte index of file that the chunk belongs to + * @param {number} uploadFileSize Total size of the file in bytes that is being uploaded + * @param {boolean} isGzip Denotes if we are uploading a Gzip compressed stream + * @param {number} totalFileSize Original total size of the file that is being uploaded + * @returns if the chunk was successfully uploaded + */ + uploadChunk(httpClientIndex, resourceUrl, openStream, start, end, uploadFileSize, isGzip, totalFileSize) { + return __awaiter4(this, void 0, void 0, function* () { + const digest = yield (0, utils_1.digestForStream)(openStream()); + const headers = (0, utils_1.getUploadHeaders)("application/octet-stream", true, isGzip, totalFileSize, end - start + 1, (0, utils_1.getContentRange)(start, end, uploadFileSize), digest); + const uploadChunkRequest = () => __awaiter4(this, void 0, void 0, function* () { + const client = this.uploadHttpManager.getClient(httpClientIndex); + return yield client.sendStream("PUT", resourceUrl, openStream(), headers); + }); + let retryCount = 0; + const retryLimit = (0, config_variables_1.getRetryLimit)(); + const incrementAndCheckRetryLimit = (response) => { + retryCount++; + if (retryCount > retryLimit) { + if (response) { + (0, utils_1.displayHttpDiagnostics)(response); + } + core14.info(`Retry limit has been reached for chunk at offset ${start} to ${resourceUrl}`); + return true; + } + return false; + }; + const backOff = (retryAfterValue) => __awaiter4(this, void 0, void 0, function* () { + this.uploadHttpManager.disposeAndReplaceClient(httpClientIndex); + if (retryAfterValue) { + core14.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the upload`); + yield (0, utils_1.sleep)(retryAfterValue); + } else { + const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount); + core14.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the upload at offset ${start}`); + yield (0, utils_1.sleep)(backoffTime); + } + core14.info(`Finished backoff for retry #${retryCount}, continuing with upload`); + return; + }); + while (retryCount <= retryLimit) { + let response; + try { + response = yield uploadChunkRequest(); + } catch (error4) { + core14.info(`An error has been caught http-client index ${httpClientIndex}, retrying the upload`); + console.log(error4); + if (incrementAndCheckRetryLimit()) { + return false; + } + yield backOff(); + continue; + } + yield response.readBody(); + if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) { + return true; + } else if ((0, utils_1.isRetryableStatusCode)(response.message.statusCode)) { + core14.info(`A ${response.message.statusCode} status code has been received, will attempt to retry the upload`); + if (incrementAndCheckRetryLimit(response)) { + return false; + } + (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff(); + } else { + core14.error(`Unexpected response. Unable to upload chunk to ${resourceUrl}`); + (0, utils_1.displayHttpDiagnostics)(response); + return false; + } + } + return false; + }); } - disposeAndReplaceAllClients() { - for (const [index] of this.clients.entries()) { - this.disposeAndReplaceClient(index); - } + /** + * Updates the size of the artifact from -1 which was initially set when the container was first created for the artifact. + * Updating the size indicates that we are done uploading all the contents of the artifact + */ + patchArtifactSize(size, artifactName) { + return __awaiter4(this, void 0, void 0, function* () { + const resourceUrl = new url_1.URL((0, utils_1.getArtifactUrl)()); + resourceUrl.searchParams.append("artifactName", artifactName); + const parameters = { Size: size }; + const data = JSON.stringify(parameters, null, 2); + core14.debug(`URL is ${resourceUrl.toString()}`); + const client = this.uploadHttpManager.getClient(0); + const headers = (0, utils_1.getUploadHeaders)("application/json", false); + const customErrorMessages = /* @__PURE__ */ new Map([ + [ + http_client_1.HttpCodes.NotFound, + `An Artifact with the name ${artifactName} was not found` + ] + ]); + const response = yield (0, requestUtils_1.retryHttpClientRequest)("Finalize artifact upload", () => __awaiter4(this, void 0, void 0, function* () { + return client.patch(resourceUrl.toString(), data, headers); + }), customErrorMessages); + yield response.readBody(); + core14.debug(`Artifact ${artifactName} has been successfully uploaded, total size in bytes: ${size}`); + }); } }; - exports2.HttpManager = HttpManager; + exports2.UploadHttpClient = UploadHttpClient; } }); -// node_modules/@actions/artifact-legacy/lib/internal/upload-gzip.js -var require_upload_gzip = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/upload-gzip.js"(exports2) { +// node_modules/@actions/artifact-legacy/lib/internal/download-http-client.js +var require_download_http_client = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/download-http-client.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -106941,118 +110733,228 @@ var require_upload_gzip = __commonJS({ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve2, reject) { - v = o[n](v), settle(resolve2, reject, v.done, v.value); - }); - }; - } - function settle(resolve2, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve2({ value: v2, done: d }); - }, reject); - } - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createGZipFileInBuffer = exports2.createGZipFileOnDisk = void 0; + exports2.DownloadHttpClient = void 0; var fs2 = __importStar4(require("fs")); + var core14 = __importStar4(require_core()); var zlib = __importStar4(require("zlib")); - var util_1 = require("util"); - var stat = (0, util_1.promisify)(fs2.stat); - var gzipExemptFileExtensions = [ - ".gz", - ".gzip", - ".tgz", - ".taz", - ".Z", - ".taZ", - ".bz2", - ".tbz", - ".tbz2", - ".tz2", - ".lz", - ".lzma", - ".tlz", - ".lzo", - ".xz", - ".txz", - ".zst", - ".zstd", - ".tzst", - ".zip", - ".7z" - // 7ZIP - ]; - function createGZipFileOnDisk(originalFilePath, tempFilePath) { - return __awaiter4(this, void 0, void 0, function* () { - for (const gzipExemptExtension of gzipExemptFileExtensions) { - if (originalFilePath.endsWith(gzipExemptExtension)) { - return Number.MAX_SAFE_INTEGER; - } - } - return new Promise((resolve2, reject) => { - const inputStream = fs2.createReadStream(originalFilePath); - const gzip = zlib.createGzip(); - const outputStream = fs2.createWriteStream(tempFilePath); - inputStream.pipe(gzip).pipe(outputStream); - outputStream.on("finish", () => __awaiter4(this, void 0, void 0, function* () { - const size = (yield stat(tempFilePath)).size; - resolve2(size); + var utils_1 = require_utils7(); + var url_1 = require("url"); + var status_reporter_1 = require_status_reporter(); + var perf_hooks_1 = require("perf_hooks"); + var http_manager_1 = require_http_manager(); + var config_variables_1 = require_config_variables(); + var requestUtils_1 = require_requestUtils2(); + var DownloadHttpClient = class { + constructor() { + this.downloadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getDownloadFileConcurrency)(), "@actions/artifact-download"); + this.statusReporter = new status_reporter_1.StatusReporter(1e3); + } + /** + * Gets a list of all artifacts that are in a specific container + */ + listArtifacts() { + return __awaiter4(this, void 0, void 0, function* () { + const artifactUrl = (0, utils_1.getArtifactUrl)(); + const client = this.downloadHttpManager.getClient(0); + const headers = (0, utils_1.getDownloadHeaders)("application/json"); + const response = yield (0, requestUtils_1.retryHttpClientRequest)("List Artifacts", () => __awaiter4(this, void 0, void 0, function* () { + return client.get(artifactUrl, headers); })); - outputStream.on("error", (error4) => { - console.log(error4); - reject(error4); + const body = yield response.readBody(); + return JSON.parse(body); + }); + } + /** + * Fetches a set of container items that describe the contents of an artifact + * @param artifactName the name of the artifact + * @param containerUrl the artifact container URL for the run + */ + getContainerItems(artifactName, containerUrl) { + return __awaiter4(this, void 0, void 0, function* () { + const resourceUrl = new url_1.URL(containerUrl); + resourceUrl.searchParams.append("itemPath", artifactName); + const client = this.downloadHttpManager.getClient(0); + const headers = (0, utils_1.getDownloadHeaders)("application/json"); + const response = yield (0, requestUtils_1.retryHttpClientRequest)("Get Container Items", () => __awaiter4(this, void 0, void 0, function* () { + return client.get(resourceUrl.toString(), headers); + })); + const body = yield response.readBody(); + return JSON.parse(body); + }); + } + /** + * Concurrently downloads all the files that are part of an artifact + * @param downloadItems information about what items to download and where to save them + */ + downloadSingleArtifact(downloadItems) { + return __awaiter4(this, void 0, void 0, function* () { + const DOWNLOAD_CONCURRENCY = (0, config_variables_1.getDownloadFileConcurrency)(); + core14.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`); + const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()]; + let currentFile = 0; + let downloadedFiles = 0; + core14.info(`Total number of files that will be downloaded: ${downloadItems.length}`); + this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length); + this.statusReporter.start(); + yield Promise.all(parallelDownloads.map((index) => __awaiter4(this, void 0, void 0, function* () { + while (currentFile < downloadItems.length) { + const currentFileToDownload = downloadItems[currentFile]; + currentFile += 1; + const startTime = perf_hooks_1.performance.now(); + yield this.downloadIndividualFile(index, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath); + if (core14.isDebug()) { + core14.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`); + } + this.statusReporter.incrementProcessedCount(); + } + }))).catch((error4) => { + throw new Error(`Unable to download the artifact: ${error4}`); + }).finally(() => { + this.statusReporter.stop(); + this.downloadHttpManager.disposeAndReplaceAllClients(); }); }); - }); - } - exports2.createGZipFileOnDisk = createGZipFileOnDisk; - function createGZipFileInBuffer(originalFilePath) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { - var _a, e_1, _b, _c; - const inputStream = fs2.createReadStream(originalFilePath); - const gzip = zlib.createGzip(); - inputStream.pipe(gzip); - const chunks = []; - try { - for (var _d = true, gzip_1 = __asyncValues4(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), _a = gzip_1_1.done, !_a; ) { - _c = gzip_1_1.value; - _d = false; - try { - const chunk = _c; - chunks.push(chunk); - } finally { - _d = true; + } + /** + * Downloads an individual file + * @param httpClientIndex the index of the http client that is used to make all of the calls + * @param artifactLocation origin location where a file will be downloaded from + * @param downloadPath destination location for the file being downloaded + */ + downloadIndividualFile(httpClientIndex, artifactLocation, downloadPath) { + return __awaiter4(this, void 0, void 0, function* () { + let retryCount = 0; + const retryLimit = (0, config_variables_1.getRetryLimit)(); + let destinationStream = fs2.createWriteStream(downloadPath); + const headers = (0, utils_1.getDownloadHeaders)("application/json", true, true); + const makeDownloadRequest = () => __awaiter4(this, void 0, void 0, function* () { + const client = this.downloadHttpManager.getClient(httpClientIndex); + return yield client.get(artifactLocation, headers); + }); + const isGzip = (incomingHeaders) => { + return "content-encoding" in incomingHeaders && incomingHeaders["content-encoding"] === "gzip"; + }; + const backOff = (retryAfterValue) => __awaiter4(this, void 0, void 0, function* () { + retryCount++; + if (retryCount > retryLimit) { + return Promise.reject(new Error(`Retry limit has been reached. Unable to download ${artifactLocation}`)); + } else { + this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex); + if (retryAfterValue) { + core14.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`); + yield (0, utils_1.sleep)(retryAfterValue); + } else { + const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount); + core14.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`); + yield (0, utils_1.sleep)(backoffTime); } + core14.info(`Finished backoff for retry #${retryCount}, continuing with download`); } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { + }); + const isAllBytesReceived = (expected, received) => { + if (!expected || !received || process.env["ACTIONS_ARTIFACT_SKIP_DOWNLOAD_VALIDATION"]) { + core14.info("Skipping download validation."); + return true; + } + return parseInt(expected) === received; + }; + const resetDestinationStream = (fileDownloadPath) => __awaiter4(this, void 0, void 0, function* () { + destinationStream.close(); + yield new Promise((resolve2) => { + destinationStream.on("close", resolve2); + if (destinationStream.writableFinished) { + resolve2(); + } + }); + yield (0, utils_1.rmFile)(fileDownloadPath); + destinationStream = fs2.createWriteStream(fileDownloadPath); + }); + while (retryCount <= retryLimit) { + let response; try { - if (!_d && !_a && (_b = gzip_1.return)) yield _b.call(gzip_1); - } finally { - if (e_1) throw e_1.error; + response = yield makeDownloadRequest(); + } catch (error4) { + core14.info("An error occurred while attempting to download a file"); + console.log(error4); + yield backOff(); + continue; + } + let forceRetry = false; + if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) { + try { + const isGzipped = isGzip(response.message.headers); + yield this.pipeResponseToFile(response, destinationStream, isGzipped); + if (isGzipped || isAllBytesReceived(response.message.headers["content-length"], yield (0, utils_1.getFileSize)(downloadPath))) { + return; + } else { + forceRetry = true; + } + } catch (error4) { + forceRetry = true; + } + } + if (forceRetry || (0, utils_1.isRetryableStatusCode)(response.message.statusCode)) { + core14.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`); + resetDestinationStream(downloadPath); + (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff(); + } else { + (0, utils_1.displayHttpDiagnostics)(response); + return Promise.reject(new Error(`Unexpected http ${response.message.statusCode} during download for ${artifactLocation}`)); + } + } + }); + } + /** + * Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary + * @param response the http response received when downloading a file + * @param destinationStream the stream where the file should be written to + * @param isGzip a boolean denoting if the content is compressed using gzip and if we need to decode it + */ + pipeResponseToFile(response, destinationStream, isGzip) { + return __awaiter4(this, void 0, void 0, function* () { + yield new Promise((resolve2, reject) => { + if (isGzip) { + const gunzip = zlib.createGunzip(); + response.message.on("error", (error4) => { + core14.info(`An error occurred while attempting to read the response stream`); + gunzip.close(); + destinationStream.close(); + reject(error4); + }).pipe(gunzip).on("error", (error4) => { + core14.info(`An error occurred while attempting to decompress the response stream`); + destinationStream.close(); + reject(error4); + }).pipe(destinationStream).on("close", () => { + resolve2(); + }).on("error", (error4) => { + core14.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); + reject(error4); + }); + } else { + response.message.on("error", (error4) => { + core14.info(`An error occurred while attempting to read the response stream`); + destinationStream.close(); + reject(error4); + }).pipe(destinationStream).on("close", () => { + resolve2(); + }).on("error", (error4) => { + core14.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); + reject(error4); + }); } - } - resolve2(Buffer.concat(chunks)); - })); - }); - } - exports2.createGZipFileInBuffer = createGZipFileInBuffer; + }); + return; + }); + } + }; + exports2.DownloadHttpClient = DownloadHttpClient; } }); -// node_modules/@actions/artifact-legacy/lib/internal/requestUtils.js -var require_requestUtils2 = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/requestUtils.js"(exports2) { +// node_modules/@actions/artifact-legacy/lib/internal/download-specification.js +var require_download_specification = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/download-specification.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -107081,95 +110983,44 @@ var require_requestUtils2 = __commonJS({ __setModuleDefault4(result, mod); return result; }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); - }); - } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.retryHttpClientRequest = exports2.retry = void 0; - var utils_1 = require_utils7(); - var core14 = __importStar4(require_core()); - var config_variables_1 = require_config_variables(); - function retry3(name, operation, customErrorMessages, maxAttempts) { - return __awaiter4(this, void 0, void 0, function* () { - let response = void 0; - let statusCode = void 0; - let isRetryable = false; - let errorMessage = ""; - let customErrorInformation = void 0; - let attempt = 1; - while (attempt <= maxAttempts) { - try { - response = yield operation(); - statusCode = response.message.statusCode; - if ((0, utils_1.isSuccessStatusCode)(statusCode)) { - return response; - } - if (statusCode) { - customErrorInformation = customErrorMessages.get(statusCode); - } - isRetryable = (0, utils_1.isRetryableStatusCode)(statusCode); - errorMessage = `Artifact service responded with ${statusCode}`; - } catch (error4) { - isRetryable = true; - errorMessage = error4.message; - } - if (!isRetryable) { - core14.info(`${name} - Error is not retryable`); - if (response) { - (0, utils_1.displayHttpDiagnostics)(response); + exports2.getDownloadSpecification = void 0; + var path2 = __importStar4(require("path")); + function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) { + const directories = /* @__PURE__ */ new Set(); + const specifications = { + rootDownloadLocation: includeRootDirectory ? path2.join(downloadPath, artifactName) : downloadPath, + directoryStructure: [], + emptyFilesToCreate: [], + filesToDownload: [] + }; + for (const entry of artifactEntries) { + if (entry.path.startsWith(`${artifactName}/`) || entry.path.startsWith(`${artifactName}\\`)) { + const normalizedPathEntry = path2.normalize(entry.path); + const filePath = path2.join(downloadPath, includeRootDirectory ? normalizedPathEntry : normalizedPathEntry.replace(artifactName, "")); + if (entry.itemType === "file") { + directories.add(path2.dirname(filePath)); + if (entry.fileLength === 0) { + specifications.emptyFilesToCreate.push(filePath); + } else { + specifications.filesToDownload.push({ + sourceLocation: entry.contentLocation, + targetPath: filePath + }); } - break; } - core14.info(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); - yield (0, utils_1.sleep)((0, utils_1.getExponentialRetryTimeInMilliseconds)(attempt)); - attempt++; - } - if (response) { - (0, utils_1.displayHttpDiagnostics)(response); } - if (customErrorInformation) { - throw Error(`${name} failed: ${customErrorInformation}`); - } - throw Error(`${name} failed: ${errorMessage}`); - }); - } - exports2.retry = retry3; - function retryHttpClientRequest(name, method, customErrorMessages = /* @__PURE__ */ new Map(), maxAttempts = (0, config_variables_1.getRetryLimit)()) { - return __awaiter4(this, void 0, void 0, function* () { - return yield retry3(name, method, customErrorMessages, maxAttempts); - }); + } + specifications.directoryStructure = Array.from(directories); + return specifications; } - exports2.retryHttpClientRequest = retryHttpClientRequest; + exports2.getDownloadSpecification = getDownloadSpecification; } }); -// node_modules/@actions/artifact-legacy/lib/internal/upload-http-client.js -var require_upload_http_client = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/upload-http-client.js"(exports2) { +// node_modules/@actions/artifact-legacy/lib/internal/artifact-client.js +var require_artifact_client = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/internal/artifact-client.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -107226,342 +111077,383 @@ var require_upload_http_client = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UploadHttpClient = void 0; - var fs2 = __importStar4(require("fs")); + exports2.DefaultArtifactClient = void 0; var core14 = __importStar4(require_core()); - var tmp = __importStar4(require_tmp_promise()); - var stream = __importStar4(require("stream")); + var upload_specification_1 = require_upload_specification(); + var upload_http_client_1 = require_upload_http_client(); var utils_1 = require_utils7(); + var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); + var download_http_client_1 = require_download_http_client(); + var download_specification_1 = require_download_specification(); var config_variables_1 = require_config_variables(); - var util_1 = require("util"); - var url_1 = require("url"); - var perf_hooks_1 = require("perf_hooks"); - var status_reporter_1 = require_status_reporter(); - var http_client_1 = require_lib(); - var http_manager_1 = require_http_manager(); - var upload_gzip_1 = require_upload_gzip(); - var requestUtils_1 = require_requestUtils2(); - var stat = (0, util_1.promisify)(fs2.stat); - var UploadHttpClient = class { - constructor() { - this.uploadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getUploadFileConcurrency)(), "@actions/artifact-upload"); - this.statusReporter = new status_reporter_1.StatusReporter(1e4); + var path_1 = require("path"); + var DefaultArtifactClient2 = class _DefaultArtifactClient { + /** + * Constructs a DefaultArtifactClient + */ + static create() { + return new _DefaultArtifactClient(); } /** - * Creates a file container for the new artifact in the remote blob storage/file service - * @param {string} artifactName Name of the artifact being created - * @returns The response from the Artifact Service if the file container was successfully created + * Uploads an artifact */ - createArtifactInFileContainer(artifactName, options) { + uploadArtifact(name, files, rootDirectory, options) { return __awaiter4(this, void 0, void 0, function* () { - const parameters = { - Type: "actions_storage", - Name: artifactName + core14.info(`Starting artifact upload +For more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging`); + (0, path_and_artifact_name_validation_1.checkArtifactName)(name); + const uploadSpecification = (0, upload_specification_1.getUploadSpecification)(name, rootDirectory, files); + const uploadResponse = { + artifactName: name, + artifactItems: [], + size: 0, + failedItems: [] }; - if (options && options.retentionDays) { - const maxRetentionStr = (0, config_variables_1.getRetentionDays)(); - parameters.RetentionDays = (0, utils_1.getProperRetention)(options.retentionDays, maxRetentionStr); + const uploadHttpClient = new upload_http_client_1.UploadHttpClient(); + if (uploadSpecification.length === 0) { + core14.warning(`No files found that can be uploaded`); + } else { + const response = yield uploadHttpClient.createArtifactInFileContainer(name, options); + if (!response.fileContainerResourceUrl) { + core14.debug(response.toString()); + throw new Error("No URL provided by the Artifact Service to upload an artifact to"); + } + core14.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`); + core14.info(`Container for artifact "${name}" successfully created. Starting upload of file(s)`); + const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options); + core14.info(`File upload process has finished. Finalizing the artifact upload`); + yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name); + if (uploadResult.failedItems.length > 0) { + core14.info(`Upload finished. There were ${uploadResult.failedItems.length} items that failed to upload`); + } else { + core14.info(`Artifact has been finalized. All files have been successfully uploaded!`); + } + core14.info(` +The raw size of all the files that were specified for upload is ${uploadResult.totalSize} bytes +The size of all the files that were uploaded is ${uploadResult.uploadSize} bytes. This takes into account any gzip compression used to reduce the upload size, time and storage + +Note: The size of downloaded zips can differ significantly from the reported size. For more information see: https://github.com/actions/upload-artifact#zipped-artifact-downloads \r +`); + uploadResponse.artifactItems = uploadSpecification.map((item) => item.absoluteFilePath); + uploadResponse.size = uploadResult.uploadSize; + uploadResponse.failedItems = uploadResult.failedItems; } - const data = JSON.stringify(parameters, null, 2); - const artifactUrl = (0, utils_1.getArtifactUrl)(); - const client = this.uploadHttpManager.getClient(0); - const headers = (0, utils_1.getUploadHeaders)("application/json", false); - const customErrorMessages = /* @__PURE__ */ new Map([ - [ - http_client_1.HttpCodes.Forbidden, - (0, config_variables_1.isGhes)() ? "Please reference [Enabling GitHub Actions for GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@3.8/admin/github-actions/enabling-github-actions-for-github-enterprise-server) to ensure Actions storage is configured correctly." : "Artifact storage quota has been hit. Unable to upload any new artifacts" - ], - [ - http_client_1.HttpCodes.BadRequest, - `The artifact name ${artifactName} is not valid. Request URL ${artifactUrl}` - ] - ]); - const response = yield (0, requestUtils_1.retryHttpClientRequest)("Create Artifact Container", () => __awaiter4(this, void 0, void 0, function* () { - return client.post(artifactUrl, data, headers); - }), customErrorMessages); - const body = yield response.readBody(); - return JSON.parse(body); + return uploadResponse; }); } - /** - * Concurrently upload all of the files in chunks - * @param {string} uploadUrl Base Url for the artifact that was created - * @param {SearchResult[]} filesToUpload A list of information about the files being uploaded - * @returns The size of all the files uploaded in bytes - */ - uploadArtifactToFileContainer(uploadUrl, filesToUpload, options) { + downloadArtifact(name, path2, options) { return __awaiter4(this, void 0, void 0, function* () { - const FILE_CONCURRENCY = (0, config_variables_1.getUploadFileConcurrency)(); - const MAX_CHUNK_SIZE = (0, config_variables_1.getUploadChunkSize)(); - core14.debug(`File Concurrency: ${FILE_CONCURRENCY}, and Chunk Size: ${MAX_CHUNK_SIZE}`); - const parameters = []; - let continueOnError = true; - if (options) { - if (options.continueOnError === false) { - continueOnError = false; - } + const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); + const artifacts = yield downloadHttpClient.listArtifacts(); + if (artifacts.count === 0) { + throw new Error(`Unable to find any artifacts for the associated workflow`); } - for (const file of filesToUpload) { - const resourceUrl = new url_1.URL(uploadUrl); - resourceUrl.searchParams.append("itemPath", file.uploadFilePath); - parameters.push({ - file: file.absoluteFilePath, - resourceUrl: resourceUrl.toString(), - maxChunkSize: MAX_CHUNK_SIZE, - continueOnError - }); + const artifactToDownload = artifacts.value.find((artifact2) => { + return artifact2.name === name; + }); + if (!artifactToDownload) { + throw new Error(`Unable to find an artifact with the name: ${name}`); + } + const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl); + if (!path2) { + path2 = (0, config_variables_1.getWorkSpaceDirectory)(); + } + path2 = (0, path_1.normalize)(path2); + path2 = (0, path_1.resolve)(path2); + const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(name, items.value, path2, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false); + if (downloadSpecification.filesToDownload.length === 0) { + core14.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`); + } else { + yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure); + core14.info("Directory structure has been set up for the artifact"); + yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate); + yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); } - const parallelUploads = [...new Array(FILE_CONCURRENCY).keys()]; - const failedItemsToReport = []; - let currentFile = 0; - let completedFiles = 0; - let uploadFileSize = 0; - let totalFileSize = 0; - let abortPendingFileUploads = false; - this.statusReporter.setTotalNumberOfFilesToProcess(filesToUpload.length); - this.statusReporter.start(); - yield Promise.all(parallelUploads.map((index) => __awaiter4(this, void 0, void 0, function* () { - while (currentFile < filesToUpload.length) { - const currentFileParameters = parameters[currentFile]; - currentFile += 1; - if (abortPendingFileUploads) { - failedItemsToReport.push(currentFileParameters.file); - continue; - } - const startTime = perf_hooks_1.performance.now(); - const uploadFileResult = yield this.uploadFileAsync(index, currentFileParameters); - if (core14.isDebug()) { - core14.debug(`File: ${++completedFiles}/${filesToUpload.length}. ${currentFileParameters.file} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish upload`); - } - uploadFileSize += uploadFileResult.successfulUploadSize; - totalFileSize += uploadFileResult.totalSize; - if (uploadFileResult.isSuccess === false) { - failedItemsToReport.push(currentFileParameters.file); - if (!continueOnError) { - core14.error(`aborting artifact upload`); - abortPendingFileUploads = true; - } - } - this.statusReporter.incrementProcessedCount(); - } - }))); - this.statusReporter.stop(); - this.uploadHttpManager.disposeAndReplaceAllClients(); - core14.info(`Total size of all the files uploaded is ${uploadFileSize} bytes`); return { - uploadSize: uploadFileSize, - totalSize: totalFileSize, - failedItems: failedItemsToReport + artifactName: name, + downloadPath: downloadSpecification.rootDownloadLocation }; }); } - /** - * Asynchronously uploads a file. The file is compressed and uploaded using GZip if it is determined to save space. - * If the upload file is bigger than the max chunk size it will be uploaded via multiple calls - * @param {number} httpClientIndex The index of the httpClient that is being used to make all of the calls - * @param {UploadFileParameters} parameters Information about the file that needs to be uploaded - * @returns The size of the file that was uploaded in bytes along with any failed uploads - */ - uploadFileAsync(httpClientIndex, parameters) { + downloadAllArtifacts(path2) { return __awaiter4(this, void 0, void 0, function* () { - const fileStat = yield stat(parameters.file); - const totalFileSize = fileStat.size; - const isFIFO = fileStat.isFIFO(); - let offset = 0; - let isUploadSuccessful = true; - let failedChunkSizes = 0; - let uploadFileSize = 0; - let isGzip = true; - if (!isFIFO && totalFileSize < 65536) { - core14.debug(`${parameters.file} is less than 64k in size. Creating a gzip file in-memory to potentially reduce the upload size`); - const buffer = yield (0, upload_gzip_1.createGZipFileInBuffer)(parameters.file); - let openUploadStream; - if (totalFileSize < buffer.byteLength) { - core14.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); - openUploadStream = () => fs2.createReadStream(parameters.file); - isGzip = false; - uploadFileSize = totalFileSize; - } else { - core14.debug(`A gzip file created for ${parameters.file} helped with reducing the size of the original file. The file will be uploaded using gzip.`); - openUploadStream = () => { - const passThrough = new stream.PassThrough(); - passThrough.end(buffer); - return passThrough; - }; - uploadFileSize = buffer.byteLength; - } - const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, openUploadStream, 0, uploadFileSize - 1, uploadFileSize, isGzip, totalFileSize); - if (!result) { - isUploadSuccessful = false; - failedChunkSizes += uploadFileSize; - core14.warning(`Aborting upload for ${parameters.file} due to failure`); - } - return { - isSuccess: isUploadSuccessful, - successfulUploadSize: uploadFileSize - failedChunkSizes, - totalSize: totalFileSize - }; - } else { - const tempFile = yield tmp.file(); - core14.debug(`${parameters.file} is greater than 64k in size. Creating a gzip file on-disk ${tempFile.path} to potentially reduce the upload size`); - uploadFileSize = yield (0, upload_gzip_1.createGZipFileOnDisk)(parameters.file, tempFile.path); - let uploadFilePath = tempFile.path; - if (!isFIFO && totalFileSize < uploadFileSize) { - core14.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); - uploadFileSize = totalFileSize; - uploadFilePath = parameters.file; - isGzip = false; + const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); + const response = []; + const artifacts = yield downloadHttpClient.listArtifacts(); + if (artifacts.count === 0) { + core14.info("Unable to find any artifacts for the associated workflow"); + return response; + } + if (!path2) { + path2 = (0, config_variables_1.getWorkSpaceDirectory)(); + } + path2 = (0, path_1.normalize)(path2); + path2 = (0, path_1.resolve)(path2); + let downloadedArtifacts = 0; + while (downloadedArtifacts < artifacts.count) { + const currentArtifactToDownload = artifacts.value[downloadedArtifacts]; + downloadedArtifacts += 1; + core14.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`); + const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl); + const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(currentArtifactToDownload.name, items.value, path2, true); + if (downloadSpecification.filesToDownload.length === 0) { + core14.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`); } else { - core14.debug(`The gzip file created for ${parameters.file} is smaller than the original file. The file will be uploaded using gzip.`); - } - let abortFileUpload = false; - while (offset < uploadFileSize) { - const chunkSize = Math.min(uploadFileSize - offset, parameters.maxChunkSize); - const startChunkIndex = offset; - const endChunkIndex = offset + chunkSize - 1; - offset += parameters.maxChunkSize; - if (abortFileUpload) { - failedChunkSizes += chunkSize; - continue; - } - const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs2.createReadStream(uploadFilePath, { - start: startChunkIndex, - end: endChunkIndex, - autoClose: false - }), startChunkIndex, endChunkIndex, uploadFileSize, isGzip, totalFileSize); - if (!result) { - isUploadSuccessful = false; - failedChunkSizes += chunkSize; - core14.warning(`Aborting upload for ${parameters.file} due to failure`); - abortFileUpload = true; - } else { - if (uploadFileSize > 8388608) { - this.statusReporter.updateLargeFileStatus(parameters.file, startChunkIndex, endChunkIndex, uploadFileSize); - } - } + yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure); + yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate); + yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); } - core14.debug(`deleting temporary gzip file ${tempFile.path}`); - yield tempFile.cleanup(); - return { - isSuccess: isUploadSuccessful, - successfulUploadSize: uploadFileSize - failedChunkSizes, - totalSize: totalFileSize - }; + response.push({ + artifactName: currentArtifactToDownload.name, + downloadPath: downloadSpecification.rootDownloadLocation + }); } + return response; + }); + } + }; + exports2.DefaultArtifactClient = DefaultArtifactClient2; + } +}); + +// node_modules/@actions/artifact-legacy/lib/artifact-client.js +var require_artifact_client2 = __commonJS({ + "node_modules/@actions/artifact-legacy/lib/artifact-client.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.create = void 0; + var artifact_client_1 = require_artifact_client(); + function create3() { + return artifact_client_1.DefaultArtifactClient.create(); + } + exports2.create = create3; + } +}); + +// node_modules/@actions/tool-cache/lib/manifest.js +var require_manifest = __commonJS({ + "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); }); } - /** - * Uploads a chunk of an individual file to the specified resourceUrl. If the upload fails and the status code - * indicates a retryable status, we try to upload the chunk as well - * @param {number} httpClientIndex The index of the httpClient being used to make all the necessary calls - * @param {string} resourceUrl Url of the resource that the chunk will be uploaded to - * @param {NodeJS.ReadableStream} openStream Stream of the file that will be uploaded - * @param {number} start Starting byte index of file that the chunk belongs to - * @param {number} end Ending byte index of file that the chunk belongs to - * @param {number} uploadFileSize Total size of the file in bytes that is being uploaded - * @param {boolean} isGzip Denotes if we are uploading a Gzip compressed stream - * @param {number} totalFileSize Original total size of the file that is being uploaded - * @returns if the chunk was successfully uploaded - */ - uploadChunk(httpClientIndex, resourceUrl, openStream, start, end, uploadFileSize, isGzip, totalFileSize) { - return __awaiter4(this, void 0, void 0, function* () { - const digest = yield (0, utils_1.digestForStream)(openStream()); - const headers = (0, utils_1.getUploadHeaders)("application/octet-stream", true, isGzip, totalFileSize, end - start + 1, (0, utils_1.getContentRange)(start, end, uploadFileSize), digest); - const uploadChunkRequest = () => __awaiter4(this, void 0, void 0, function* () { - const client = this.uploadHttpManager.getClient(httpClientIndex); - return yield client.sendStream("PUT", resourceUrl, openStream(), headers); - }); - let retryCount = 0; - const retryLimit = (0, config_variables_1.getRetryLimit)(); - const incrementAndCheckRetryLimit = (response) => { - retryCount++; - if (retryCount > retryLimit) { - if (response) { - (0, utils_1.displayHttpDiagnostics)(response); - } - core14.info(`Retry limit has been reached for chunk at offset ${start} to ${resourceUrl}`); - return true; - } - return false; - }; - const backOff = (retryAfterValue) => __awaiter4(this, void 0, void 0, function* () { - this.uploadHttpManager.disposeAndReplaceClient(httpClientIndex); - if (retryAfterValue) { - core14.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the upload`); - yield (0, utils_1.sleep)(retryAfterValue); - } else { - const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount); - core14.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the upload at offset ${start}`); - yield (0, utils_1.sleep)(backoffTime); - } - core14.info(`Finished backoff for retry #${retryCount}, continuing with upload`); - return; - }); - while (retryCount <= retryLimit) { - let response; - try { - response = yield uploadChunkRequest(); - } catch (error4) { - core14.info(`An error has been caught http-client index ${httpClientIndex}, retrying the upload`); - console.log(error4); - if (incrementAndCheckRetryLimit()) { - return false; + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; + var semver8 = __importStar4(require_semver2()); + var core_1 = require_core(); + var os = require("os"); + var cp = require("child_process"); + var fs2 = require("fs"); + function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); + if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + file = candidate.files.find((item) => { + (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module2.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } else { + chk = semver8.satisfies(osVersion, item.platform_version); + } } - yield backOff(); - continue; + return chk; + }); + if (file) { + (0, core_1.debug)(`matched ${candidate.version}`); + match = candidate; + break; } - yield response.readBody(); - if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) { - return true; - } else if ((0, utils_1.isRetryableStatusCode)(response.message.statusCode)) { - core14.info(`A ${response.message.statusCode} status code has been received, will attempt to retry the upload`); - if (incrementAndCheckRetryLimit(response)) { - return false; - } - (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff(); - } else { - core14.error(`Unexpected response. Unable to upload chunk to ${resourceUrl}`); - (0, utils_1.displayHttpDiagnostics)(response); - return false; + } + } + if (match && file) { + result = Object.assign({}, match); + result.files = [file]; + } + return result; + }); + } + exports2._findMatch = _findMatch; + function _getOsVersion() { + const plat = os.platform(); + let version = ""; + if (plat === "darwin") { + version = cp.execSync("sw_vers -productVersion").toString(); + } else if (plat === "linux") { + const lsbContents = module2.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split("\n"); + for (const line of lines) { + const parts = line.split("="); + if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { + version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); + break; } } - return false; - }); + } } - /** - * Updates the size of the artifact from -1 which was initially set when the container was first created for the artifact. - * Updating the size indicates that we are done uploading all the contents of the artifact - */ - patchArtifactSize(size, artifactName) { - return __awaiter4(this, void 0, void 0, function* () { - const resourceUrl = new url_1.URL((0, utils_1.getArtifactUrl)()); - resourceUrl.searchParams.append("artifactName", artifactName); - const parameters = { Size: size }; - const data = JSON.stringify(parameters, null, 2); - core14.debug(`URL is ${resourceUrl.toString()}`); - const client = this.uploadHttpManager.getClient(0); - const headers = (0, utils_1.getUploadHeaders)("application/json", false); - const customErrorMessages = /* @__PURE__ */ new Map([ - [ - http_client_1.HttpCodes.NotFound, - `An Artifact with the name ${artifactName} was not found` - ] - ]); - const response = yield (0, requestUtils_1.retryHttpClientRequest)("Finalize artifact upload", () => __awaiter4(this, void 0, void 0, function* () { - return client.patch(resourceUrl.toString(), data, headers); - }), customErrorMessages); - yield response.readBody(); - core14.debug(`Artifact ${artifactName} has been successfully uploaded, total size in bytes: ${size}`); - }); + return version; + } + exports2._getOsVersion = _getOsVersion; + function _readLinuxVersionFile() { + const lsbReleaseFile = "/etc/lsb-release"; + const osReleaseFile = "/etc/os-release"; + let contents = ""; + if (fs2.existsSync(lsbReleaseFile)) { + contents = fs2.readFileSync(lsbReleaseFile).toString(); + } else if (fs2.existsSync(osReleaseFile)) { + contents = fs2.readFileSync(osReleaseFile).toString(); + } + return contents; + } + exports2._readLinuxVersionFile = _readLinuxVersionFile; + } +}); + +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy6 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; } }; - exports2.UploadHttpClient = UploadHttpClient; } }); -// node_modules/@actions/artifact-legacy/lib/internal/download-http-client.js -var require_download_http_client = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/download-http-client.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib8 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -107587,258 +111479,600 @@ var require_download_http_client = __commonJS({ if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy6()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); + } + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); + }); + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DownloadHttpClient = void 0; - var fs2 = __importStar4(require("fs")); - var core14 = __importStar4(require_core()); - var zlib = __importStar4(require("zlib")); - var utils_1 = require_utils7(); - var url_1 = require("url"); - var status_reporter_1 = require_status_reporter(); - var perf_hooks_1 = require("perf_hooks"); - var http_manager_1 = require_http_manager(); - var config_variables_1 = require_config_variables(); - var requestUtils_1 = require_requestUtils2(); - var DownloadHttpClient = class { - constructor() { - this.downloadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getDownloadFileConcurrency)(), "@actions/artifact-download"); - this.statusReporter = new status_reporter_1.StatusReporter(1e3); + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } /** - * Gets a list of all artifacts that are in a specific container + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch */ - listArtifacts() { + request(verb, requestUrl, data, headers) { return __awaiter4(this, void 0, void 0, function* () { - const artifactUrl = (0, utils_1.getArtifactUrl)(); - const client = this.downloadHttpManager.getClient(0); - const headers = (0, utils_1.getDownloadHeaders)("application/json"); - const response = yield (0, requestUtils_1.retryHttpClientRequest)("List Artifacts", () => __awaiter4(this, void 0, void 0, function* () { - return client.get(artifactUrl, headers); - })); - const body = yield response.readBody(); - return JSON.parse(body); + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); } /** - * Fetches a set of container items that describe the contents of an artifact - * @param artifactName the name of the artifact - * @param containerUrl the artifact container URL for the run + * Needs to be called if keepAlive is set to true in request options. */ - getContainerItems(artifactName, containerUrl) { - return __awaiter4(this, void 0, void 0, function* () { - const resourceUrl = new url_1.URL(containerUrl); - resourceUrl.searchParams.append("itemPath", artifactName); - const client = this.downloadHttpManager.getClient(0); - const headers = (0, utils_1.getDownloadHeaders)("application/json"); - const response = yield (0, requestUtils_1.retryHttpClientRequest)("Get Container Items", () => __awaiter4(this, void 0, void 0, function* () { - return client.get(resourceUrl.toString(), headers); - })); - const body = yield response.readBody(); - return JSON.parse(body); - }); + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; } /** - * Concurrently downloads all the files that are part of an artifact - * @param downloadItems information about what items to download and where to save them + * Raw request. + * @param info + * @param data */ - downloadSingleArtifact(downloadItems) { + requestRaw(info7, data) { return __awaiter4(this, void 0, void 0, function* () { - const DOWNLOAD_CONCURRENCY = (0, config_variables_1.getDownloadFileConcurrency)(); - core14.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`); - const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()]; - let currentFile = 0; - let downloadedFiles = 0; - core14.info(`Total number of files that will be downloaded: ${downloadItems.length}`); - this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length); - this.statusReporter.start(); - yield Promise.all(parallelDownloads.map((index) => __awaiter4(this, void 0, void 0, function* () { - while (currentFile < downloadItems.length) { - const currentFileToDownload = downloadItems[currentFile]; - currentFile += 1; - const startTime = perf_hooks_1.performance.now(); - yield this.downloadIndividualFile(index, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath); - if (core14.isDebug()) { - core14.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`); + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); } - this.statusReporter.incrementProcessedCount(); } - }))).catch((error4) => { - throw new Error(`Unable to download the artifact: ${error4}`); - }).finally(() => { - this.statusReporter.stop(); - this.downloadHttpManager.disposeAndReplaceAllClients(); + this.requestRawWithCallback(info7, data, callbackForResult); }); }); } /** - * Downloads an individual file - * @param httpClientIndex the index of the http client that is used to make all of the calls - * @param artifactLocation origin location where a file will be downloaded from - * @param downloadPath destination location for the file being downloaded + * Raw request with callback. + * @param info + * @param data + * @param onResult */ - downloadIndividualFile(httpClientIndex, artifactLocation, downloadPath) { - return __awaiter4(this, void 0, void 0, function* () { - let retryCount = 0; - const retryLimit = (0, config_variables_1.getRetryLimit)(); - let destinationStream = fs2.createWriteStream(downloadPath); - const headers = (0, utils_1.getDownloadHeaders)("application/json", true, true); - const makeDownloadRequest = () => __awaiter4(this, void 0, void 0, function* () { - const client = this.downloadHttpManager.getClient(httpClientIndex); - return yield client.get(artifactLocation, headers); + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); }); - const isGzip = (incomingHeaders) => { - return "content-encoding" in incomingHeaders && incomingHeaders["content-encoding"] === "gzip"; + data.pipe(req); + } else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; + } + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) }; - const backOff = (retryAfterValue) => __awaiter4(this, void 0, void 0, function* () { - retryCount++; - if (retryCount > retryLimit) { - return Promise.reject(new Error(`Retry limit has been reached. Unable to download ${artifactLocation}`)); - } else { - this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex); - if (retryAfterValue) { - core14.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`); - yield (0, utils_1.sleep)(retryAfterValue); - } else { - const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount); - core14.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`); - yield (0, utils_1.sleep)(backoffTime); - } - core14.info(`Finished backoff for retry #${retryCount}, continuing with download`); - } + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false }); - const isAllBytesReceived = (expected, received) => { - if (!expected || !received || process.env["ACTIONS_ARTIFACT_SKIP_DOWNLOAD_VALIDATION"]) { - core14.info("Skipping download validation."); - return true; + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); } - return parseInt(expected) === received; - }; - const resetDestinationStream = (fileDownloadPath) => __awaiter4(this, void 0, void 0, function* () { - destinationStream.close(); - yield new Promise((resolve2) => { - destinationStream.on("close", resolve2); - if (destinationStream.writableFinished) { - resolve2(); + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } } - }); - yield (0, utils_1.rmFile)(fileDownloadPath); - destinationStream = fs2.createWriteStream(fileDownloadPath); - }); - while (retryCount <= retryLimit) { - let response; - try { - response = yield makeDownloadRequest(); - } catch (error4) { - core14.info("An error occurred while attempting to download a file"); - console.log(error4); - yield backOff(); - continue; + return value; } - let forceRetry = false; - if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) { - try { - const isGzipped = isGzip(response.message.headers); - yield this.pipeResponseToFile(response, destinationStream, isGzipped); - if (isGzipped || isAllBytesReceived(response.message.headers["content-length"], yield (0, utils_1.getFileSize)(downloadPath))) { - return; + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); } else { - forceRetry = true; + obj = JSON.parse(contents); } - } catch (error4) { - forceRetry = true; + response.result = obj; } + response.headers = res.message.headers; + } catch (err) { } - if (forceRetry || (0, utils_1.isRetryableStatusCode)(response.message.statusCode)) { - core14.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`); - resetDestinationStream(downloadPath); - (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff(); - } else { - (0, utils_1.displayHttpDiagnostics)(response); - return Promise.reject(new Error(`Unexpected http ${response.message.statusCode} during download for ${artifactLocation}`)); - } - } - }); - } - /** - * Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary - * @param response the http response received when downloading a file - * @param destinationStream the stream where the file should be written to - * @param isGzip a boolean denoting if the content is compressed using gzip and if we need to decode it - */ - pipeResponseToFile(response, destinationStream, isGzip) { - return __awaiter4(this, void 0, void 0, function* () { - yield new Promise((resolve2, reject) => { - if (isGzip) { - const gunzip = zlib.createGunzip(); - response.message.on("error", (error4) => { - core14.info(`An error occurred while attempting to read the response stream`); - gunzip.close(); - destinationStream.close(); - reject(error4); - }).pipe(gunzip).on("error", (error4) => { - core14.info(`An error occurred while attempting to decompress the response stream`); - destinationStream.close(); - reject(error4); - }).pipe(destinationStream).on("close", () => { - resolve2(); - }).on("error", (error4) => { - core14.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); - reject(error4); - }); - } else { - response.message.on("error", (error4) => { - core14.info(`An error occurred while attempting to read the response stream`); - destinationStream.close(); - reject(error4); - }).pipe(destinationStream).on("close", () => { - resolve2(); - }).on("error", (error4) => { - core14.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); - reject(error4); - }); + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); } - }); - return; + })); }); } }; - exports2.DownloadHttpClient = DownloadHttpClient; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/artifact-legacy/lib/internal/download-specification.js -var require_download_specification = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/download-specification.js"(exports2) { +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -107867,44 +112101,84 @@ var require_download_specification = __commonJS({ __setModuleDefault4(result, mod); return result; }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getDownloadSpecification = void 0; - var path2 = __importStar4(require("path")); - function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) { - const directories = /* @__PURE__ */ new Set(); - const specifications = { - rootDownloadLocation: includeRootDirectory ? path2.join(downloadPath, artifactName) : downloadPath, - directoryStructure: [], - emptyFilesToCreate: [], - filesToDownload: [] - }; - for (const entry of artifactEntries) { - if (entry.path.startsWith(`${artifactName}/`) || entry.path.startsWith(`${artifactName}\\`)) { - const normalizedPathEntry = path2.normalize(entry.path); - const filePath = path2.join(downloadPath, includeRootDirectory ? normalizedPathEntry : normalizedPathEntry.replace(artifactName, "")); - if (entry.itemType === "file") { - directories.add(path2.dirname(filePath)); - if (entry.fileLength === 0) { - specifications.emptyFilesToCreate.push(filePath); - } else { - specifications.filesToDownload.push({ - sourceLocation: entry.contentLocation, - targetPath: filePath - }); + exports2.RetryHelper = void 0; + var core14 = __importStar4(require_core()); + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); + } + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); + } + } + execute(action, isRetryable) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 1; + while (attempt < this.maxAttempts) { + try { + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; + } + core14.info(err.message); } + const seconds = this.getSleepAmount(); + core14.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); + attempt++; } - } + return yield action(); + }); } - specifications.directoryStructure = Array.from(directories); - return specifications; - } - exports2.getDownloadSpecification = getDownloadSpecification; + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + } + sleep(seconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => setTimeout(resolve2, seconds * 1e3)); + }); + } + }; + exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/artifact-legacy/lib/internal/artifact-client.js -var require_artifact_client = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/internal/artifact-client.js"(exports2) { +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -107961,407 +112235,610 @@ var require_artifact_client = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DefaultArtifactClient = void 0; + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; var core14 = __importStar4(require_core()); - var upload_specification_1 = require_upload_specification(); - var upload_http_client_1 = require_upload_http_client(); - var utils_1 = require_utils7(); - var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); - var download_http_client_1 = require_download_http_client(); - var download_specification_1 = require_download_specification(); - var config_variables_1 = require_config_variables(); - var path_1 = require("path"); - var DefaultArtifactClient2 = class _DefaultArtifactClient { - /** - * Constructs a DefaultArtifactClient - */ - static create() { - return new _DefaultArtifactClient(); + var io6 = __importStar4(require_io()); + var crypto = __importStar4(require("crypto")); + var fs2 = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os = __importStar4(require("os")); + var path2 = __importStar4(require("path")); + var httpm = __importStar4(require_lib8()); + var semver8 = __importStar4(require_semver2()); + var stream = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); } - /** - * Uploads an artifact - */ - uploadArtifact(name, files, rootDirectory, options) { - return __awaiter4(this, void 0, void 0, function* () { - core14.info(`Starting artifact upload -For more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging`); - (0, path_and_artifact_name_validation_1.checkArtifactName)(name); - const uploadSpecification = (0, upload_specification_1.getUploadSpecification)(name, rootDirectory, files); - const uploadResponse = { - artifactName: name, - artifactItems: [], - size: 0, - failedItems: [] - }; - const uploadHttpClient = new upload_http_client_1.UploadHttpClient(); - if (uploadSpecification.length === 0) { - core14.warning(`No files found that can be uploaded`); - } else { - const response = yield uploadHttpClient.createArtifactInFileContainer(name, options); - if (!response.fileContainerResourceUrl) { - core14.debug(response.toString()); - throw new Error("No URL provided by the Artifact Service to upload an artifact to"); - } - core14.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`); - core14.info(`Container for artifact "${name}" successfully created. Starting upload of file(s)`); - const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options); - core14.info(`File upload process has finished. Finalizing the artifact upload`); - yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name); - if (uploadResult.failedItems.length > 0) { - core14.info(`Upload finished. There were ${uploadResult.failedItems.length} items that failed to upload`); - } else { - core14.info(`Artifact has been finalized. All files have been successfully uploaded!`); + }; + exports2.HTTPError = HTTPError; + var IS_WINDOWS = process.platform === "win32"; + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url, dest, auth, headers) { + return __awaiter4(this, void 0, void 0, function* () { + dest = dest || path2.join(_getTempDirectory(), crypto.randomUUID()); + yield io6.mkdirP(path2.dirname(dest)); + core14.debug(`Downloading ${url}`); + core14.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; } - core14.info(` -The raw size of all the files that were specified for upload is ${uploadResult.totalSize} bytes -The size of all the files that were uploaded is ${uploadResult.uploadSize} bytes. This takes into account any gzip compression used to reduce the upload size, time and storage - -Note: The size of downloaded zips can differ significantly from the reported size. For more information see: https://github.com/actions/upload-artifact#zipped-artifact-downloads \r -`); - uploadResponse.artifactItems = uploadSpecification.map((item) => item.absoluteFilePath); - uploadResponse.size = uploadResult.uploadSize; - uploadResponse.failedItems = uploadResult.failedItems; } - return uploadResponse; + return true; }); - } - downloadArtifact(name, path2, options) { - return __awaiter4(this, void 0, void 0, function* () { - const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); - const artifacts = yield downloadHttpClient.listArtifacts(); - if (artifacts.count === 0) { - throw new Error(`Unable to find any artifacts for the associated workflow`); - } - const artifactToDownload = artifacts.value.find((artifact2) => { - return artifact2.name === name; - }); - if (!artifactToDownload) { - throw new Error(`Unable to find an artifact with the name: ${name}`); + }); + } + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url, dest, auth, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (fs2.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); + } + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core14.debug("set auth"); + if (headers === void 0) { + headers = {}; } - const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl); - if (!path2) { - path2 = (0, config_variables_1.getWorkSpaceDirectory)(); + headers.authorization = auth; + } + const response = yield http.get(url, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError(response.message.statusCode); + core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; + } + const pipeline = util.promisify(stream.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; + try { + yield pipeline(readStream, fs2.createWriteStream(dest)); + core14.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core14.debug("download failed"); + try { + yield io6.rmRF(dest); + } catch (err) { + core14.debug(`Failed to delete '${dest}'. ${err.message}`); + } } - path2 = (0, path_1.normalize)(path2); - path2 = (0, path_1.resolve)(path2); - const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(name, items.value, path2, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false); - if (downloadSpecification.filesToDownload.length === 0) { - core14.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`); - } else { - yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure); - core14.info("Directory structure has been set up for the artifact"); - yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate); - yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); + } + }); + } + function extract7z(file, dest, _7zPath) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { + try { + const logLevel = core14.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file + ]; + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); } - return { - artifactName: name, - downloadPath: downloadSpecification.rootDownloadLocation + } else { + const escapedScript = path2.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true }; + try { + const powershellPath = yield io6.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } + return dest; + }); + } + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + core14.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } }); + core14.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + if (core14.isDebug() && !flags.includes("v")) { + args.push("-v"); + } + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); + } + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); + } + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; + }); + } + exports2.extractTar = extractTar2; + function extractXar(file, dest, flags = []) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + args.push("-x", "-C", dest, "-f", file); + if (core14.isDebug()) { + args.push("-v"); + } + const xarPath = yield io6.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; + }); + } + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } else { + yield extractZipNix(file, dest); + } + return dest; + }); + } + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io6.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core14.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io6.which("powershell", true); + core14.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); + } + }); + } + function extractZipNix(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const unzipPath = yield io6.which("unzip", true); + const args = [file]; + if (!core14.isDebug()) { + args.unshift("-q"); + } + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); + }); + } + function cacheDir(sourceDir, tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver8.clean(version) || version; + arch = arch || os.arch(); + core14.debug(`Caching tool ${tool} ${version} ${arch}`); + core14.debug(`source dir: ${sourceDir}`); + if (!fs2.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); + } + const destPath = yield _createToolPath(tool, version, arch); + for (const itemName of fs2.readdirSync(sourceDir)) { + const s = path2.join(sourceDir, itemName); + yield io6.cp(s, destPath, { recursive: true }); + } + _completeToolPath(tool, version, arch); + return destPath; + }); + } + exports2.cacheDir = cacheDir; + function cacheFile(sourceFile, targetFile, tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver8.clean(version) || version; + arch = arch || os.arch(); + core14.debug(`Caching tool ${tool} ${version} ${arch}`); + core14.debug(`source file: ${sourceFile}`); + if (!fs2.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); + } + const destFolder = yield _createToolPath(tool, version, arch); + const destPath = path2.join(destFolder, targetFile); + core14.debug(`destination file ${destPath}`); + yield io6.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch); + return destFolder; + }); + } + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch) { + if (!toolName) { + throw new Error("toolName parameter is required"); } - downloadAllArtifacts(path2) { - return __awaiter4(this, void 0, void 0, function* () { - const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); - const response = []; - const artifacts = yield downloadHttpClient.listArtifacts(); - if (artifacts.count === 0) { - core14.info("Unable to find any artifacts for the associated workflow"); - return response; - } - if (!path2) { - path2 = (0, config_variables_1.getWorkSpaceDirectory)(); - } - path2 = (0, path_1.normalize)(path2); - path2 = (0, path_1.resolve)(path2); - let downloadedArtifacts = 0; - while (downloadedArtifacts < artifacts.count) { - const currentArtifactToDownload = artifacts.value[downloadedArtifacts]; - downloadedArtifacts += 1; - core14.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`); - const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl); - const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(currentArtifactToDownload.name, items.value, path2, true); - if (downloadSpecification.filesToDownload.length === 0) { - core14.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`); - } else { - yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure); - yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate); - yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); - } - response.push({ - artifactName: currentArtifactToDownload.name, - downloadPath: downloadSpecification.rootDownloadLocation - }); - } - return response; - }); + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); } - }; - exports2.DefaultArtifactClient = DefaultArtifactClient2; - } -}); - -// node_modules/@actions/artifact-legacy/lib/artifact-client.js -var require_artifact_client2 = __commonJS({ - "node_modules/@actions/artifact-legacy/lib/artifact-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.create = void 0; - var artifact_client_1 = require_artifact_client(); - function create3() { - return artifact_client_1.DefaultArtifactClient.create(); - } - exports2.create = create3; - } -}); - -// node_modules/@actions/tool-cache/lib/manifest.js -var require_manifest = __commonJS({ - "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + arch = arch || os.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions2(toolName, arch); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + let toolPath = ""; + if (versionSpec) { + versionSpec = semver8.clean(versionSpec) || ""; + const cachePath = path2.join(_getCacheDirectory(), toolName, versionSpec, arch); + core14.debug(`checking cache: ${cachePath}`); + if (fs2.existsSync(cachePath) && fs2.existsSync(`${cachePath}.complete`)) { + core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); + toolPath = cachePath; + } else { + core14.debug("not found"); + } } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); - }); + return toolPath; + } + exports2.find = find2; + function findAllVersions2(toolName, arch) { + const versions = []; + arch = arch || os.arch(); + const toolPath = path2.join(_getCacheDirectory(), toolName); + if (fs2.existsSync(toolPath)) { + const children = fs2.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path2.join(toolPath, child, arch || ""); + if (fs2.existsSync(fullPath) && fs2.existsSync(`${fullPath}.complete`)) { + versions.push(child); + } + } + } } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + return versions; + } + exports2.findAllVersions = findAllVersions2; + function getManifestFromRepo(owner, repo, auth, branch = "master") { + return __awaiter4(this, void 0, void 0, function* () { + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core14.debug("set auth"); + headers.authorization = auth; + } + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; + } + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; } } - function rejected(value) { + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + releases = JSON.parse(versionsRaw); + } catch (_a) { + core14.debug("Invalid json"); } } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return releases; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver8 = __importStar4(require_semver2()); - var core_1 = require_core(); - var os = require("os"); - var cp = require("child_process"); - var fs2 = require("fs"); - function _findMatch(versionSpec, stable, candidates, archFilter) { + } + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) { return __awaiter4(this, void 0, void 0, function* () { - const platFilter = os.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { - file = candidate.files.find((item) => { - (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module2.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } else { - chk = semver8.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - (0, core_1.debug)(`matched ${candidate.version}`); - match = candidate; - break; - } - } - } - if (match && file) { - result = Object.assign({}, match); - result.files = [file]; + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; + }); + } + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!dest) { + dest = path2.join(_getTempDirectory(), crypto.randomUUID()); } - return result; + yield io6.mkdirP(dest); + return dest; }); } - exports2._findMatch = _findMatch; - function _getOsVersion() { - const plat = os.platform(); + function _createToolPath(tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + const folderPath = path2.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); + core14.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io6.rmRF(folderPath); + yield io6.rmRF(markerPath); + yield io6.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch) { + const folderPath = path2.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); + const markerPath = `${folderPath}.complete`; + fs2.writeFileSync(markerPath, ""); + core14.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver8.clean(versionSpec) || ""; + core14.debug(`isExplicit: ${c}`); + const valid3 = semver8.valid(c) != null; + core14.debug(`explicit? ${valid3}`); + return valid3; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { let version = ""; - if (plat === "darwin") { - version = cp.execSync("sw_vers -productVersion").toString(); - } else if (plat === "linux") { - const lsbContents = module2.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split("\n"); - for (const line of lines) { - const parts = line.split("="); - if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { - version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); - break; - } - } + core14.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver8.gt(a, b)) { + return 1; + } + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver8.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; } } + if (version) { + core14.debug(`matched: ${version}`); + } else { + core14.debug("match not found"); + } return version; } - exports2._getOsVersion = _getOsVersion; - function _readLinuxVersionFile() { - const lsbReleaseFile = "/etc/lsb-release"; - const osReleaseFile = "/etc/os-release"; - let contents = ""; - if (fs2.existsSync(lsbReleaseFile)) { - contents = fs2.readFileSync(lsbReleaseFile).toString(); - } else if (fs2.existsSync(osReleaseFile)) { - contents = fs2.readFileSync(osReleaseFile).toString(); - } - return contents; + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); } - exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); - }); - } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + module2.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return true; + } + return a !== a && b !== b; }; + } +}); + +// node_modules/@actions/http-client/lib/proxy.js +var require_proxy7 = __commonJS({ + "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core14 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); + exports2.getProxyUrl = getProxyUrl; + exports2.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } + } else { + return void 0; } - execute(action, isRetryable) { - return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core14.info(err.message); - } - const seconds = this.getSleepAmount(); - core14.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - return yield action(); - }); + } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - sleep(seconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve2) => setTimeout(resolve2, seconds * 1e3)); - }); + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; } }; - exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib9 = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -108381,15 +112858,25 @@ var require_tool_cache = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { @@ -108418,523 +112905,616 @@ var require_tool_cache = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core14 = __importStar4(require_core()); - var io6 = __importStar4(require_io()); - var crypto = __importStar4(require("crypto")); - var fs2 = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os = __importStar4(require("os")); - var path2 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver8 = __importStar4(require_semver2()); - var stream = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy7()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.HTTPError = HTTPError; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path2.join(_getTempDirectory(), crypto.randomUUID()); - yield io6.mkdirP(path2.dirname(dest)); - core14.debug(`Downloading ${url}`); - core14.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs2.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); }); - if (auth) { - core14.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - headers.authorization = auth; - } - const response = yield http.get(url, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError(response.message.statusCode); - core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; - } - const pipeline = util.promisify(stream.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs2.createWriteStream(dest)); - core14.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core14.debug("download failed"); - try { - yield io6.rmRF(dest); - } catch (err) { - core14.debug(`Failed to delete '${dest}'. ${err.message}`); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core14.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } else { - const escapedScript = path2.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io6.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core14.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - core14.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core14.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - args.push("-x", "-C", dest, "-f", file); - if (core14.isDebug()) { - args.push("-v"); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - const xarPath = yield io6.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io6.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core14.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io6.which("powershell", true); - core14.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); - } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io6.which("unzip", true); - const args = [file]; - if (!core14.isDebug()) { - args.unshift("-q"); + req.end(); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir(sourceDir, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch = arch || os.arch(); - core14.debug(`Caching tool ${tool} ${version} ${arch}`); - core14.debug(`source dir: ${sourceDir}`); - if (!fs2.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const destPath = yield _createToolPath(tool, version, arch); - for (const itemName of fs2.readdirSync(sourceDir)) { - const s = path2.join(sourceDir, itemName); - yield io6.cp(s, destPath, { recursive: true }); + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; } - _completeToolPath(tool, version, arch); - return destPath; - }); - } - exports2.cacheDir = cacheDir; - function cacheFile(sourceFile, targetFile, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch = arch || os.arch(); - core14.debug(`Caching tool ${tool} ${version} ${arch}`); - core14.debug(`source file: ${sourceFile}`); - if (!fs2.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } } - const destFolder = yield _createToolPath(tool, version, arch); - const destPath = path2.join(destFolder, targetFile); - core14.debug(`destination file ${destPath}`); - yield io6.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); + return info7; } - arch = arch || os.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions2(toolName, arch); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver8.clean(versionSpec) || ""; - const cachePath = path2.join(_getCacheDirectory(), toolName, versionSpec, arch); - core14.debug(`checking cache: ${cachePath}`); - if (fs2.existsSync(cachePath) && fs2.existsSync(`${cachePath}.complete`)) { - core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); - toolPath = cachePath; - } else { - core14.debug("not found"); + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return toolPath; - } - exports2.find = find2; - function findAllVersions2(toolName, arch) { - const versions = []; - arch = arch || os.arch(); - const toolPath = path2.join(_getCacheDirectory(), toolName); - if (fs2.existsSync(toolPath)) { - const children = fs2.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path2.join(toolPath, child, arch || ""); - if (fs2.existsSync(fullPath) && fs2.existsSync(`${fullPath}.complete`)) { - versions.push(child); + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; } } } + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; + } + } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return versions; - } - exports2.findAllVersions = findAllVersions2; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core14.debug("set auth"); - headers.authorization = auth; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + if (!useProxy) { + agent = this._agent; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; - } + if (agent) { + return agent; } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core14.debug("Invalid json"); - } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path2.join(_getTempDirectory(), crypto.randomUUID()); + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - yield io6.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path2.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); - core14.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io6.rmRF(folderPath); - yield io6.rmRF(markerPath); - yield io6.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch) { - const folderPath = path2.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || ""); - const markerPath = `${folderPath}.complete`; - fs2.writeFileSync(markerPath, ""); - core14.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver8.clean(versionSpec) || ""; - core14.debug(`isExplicit: ${c}`); - const valid3 = semver8.valid(c) != null; - core14.debug(`explicit? ${valid3}`); - return valid3; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core14.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver8.gt(a, b)) { - return 1; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver8.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } + return agent; } - if (version) { - core14.debug(`matched: ${version}`); - } else { - core14.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; + if (proxyAgent) { + return proxyAgent; } - return true; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); } - return a !== a && b !== b; }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -113388,7 +117968,7 @@ var supportedAnalysisKinds = new Set(Object.values(AnalysisKind)); var core6 = __toESM(require_core()); // src/config/db-config.ts -var jsonschema = __toESM(require_lib2()); +var jsonschema = __toESM(require_lib3()); var semver2 = __toESM(require_semver2()); var PACK_IDENTIFIER_PATTERN = (function() { const alphaNumeric = "[a-z0-9]"; @@ -113839,7 +118419,7 @@ var semver5 = __toESM(require_semver2()); // src/tools-download.ts var core9 = __toESM(require_core()); -var import_http_client = __toESM(require_lib()); +var import_http_client = __toESM(require_lib9()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); var semver6 = __toESM(require_semver2()); diff --git a/lib/start-proxy-action.js b/lib/start-proxy-action.js index a6ba8e88a4..1b448b2f31 100644 --- a/lib/start-proxy-action.js +++ b/lib/start-proxy-action.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -21885,115 +21885,91 @@ var require_manifest = __commonJS({ } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); - }); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core12 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - execute(action, isRetryable) { - return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core12.info(err.message); - } - const seconds = this.getSleepAmount(); - core12.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - return yield action(); - }); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + get username() { + return this._decodedUsername; } - sleep(seconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve2) => setTimeout(resolve2, seconds * 1e3)); - }); + get password() { + return this._decodedPassword; } }; - exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -22050,4522 +22026,3509 @@ var require_tool_cache = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core12 = __importStar4(require_core()); - var io4 = __importStar4(require_io()); - var crypto = __importStar4(require("crypto")); - var fs = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os2 = __importStar4(require("os")); - var path2 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver5 = __importStar4(require_semver2()); - var stream = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError2 = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.HTTPError = HTTPError2; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path2.join(_getTempDirectory(), crypto.randomUUID()); - yield io4.mkdirP(path2.dirname(dest)); - core12.debug(`Downloading ${url}`); - core12.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError2 && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); }); - if (auth) { - core12.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - headers.authorization = auth; - } - const response = yield http.get(url, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError2(response.message.statusCode); - core12.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; - } - const pipeline = util.promisify(stream.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs.createWriteStream(dest)); - core12.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core12.debug("download failed"); - try { - yield io4.rmRF(dest); - } catch (err) { - core12.debug(`Failed to delete '${dest}'. ${err.message}`); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core12.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } else { - const escapedScript = path2.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io4.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } - } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core12.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } - }); - core12.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core12.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - args.push("-x", "-C", dest, "-f", file); - if (core12.isDebug()) { - args.push("-v"); - } - const xarPath = yield io4.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io4.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core12.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); - } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io4.which("powershell", true); - core12.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io4.which("unzip", true); - const args = [file]; - if (!core12.isDebug()) { - args.unshift("-q"); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir2(sourceDir, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver5.clean(version) || version; - arch = arch || os2.arch(); - core12.debug(`Caching tool ${tool} ${version} ${arch}`); - core12.debug(`source dir: ${sourceDir}`); - if (!fs.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - const destPath = yield _createToolPath(tool, version, arch); - for (const itemName of fs.readdirSync(sourceDir)) { - const s = path2.join(sourceDir, itemName); - yield io4.cp(s, destPath, { recursive: true }); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - _completeToolPath(tool, version, arch); - return destPath; - }); - } - exports2.cacheDir = cacheDir2; - function cacheFile(sourceFile, targetFile, tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver5.clean(version) || version; - arch = arch || os2.arch(); - core12.debug(`Caching tool ${tool} ${version} ${arch}`); - core12.debug(`source file: ${sourceFile}`); - if (!fs.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); } - const destFolder = yield _createToolPath(tool, version, arch); - const destPath = path2.join(destFolder, targetFile); - core12.debug(`destination file ${destPath}`); - yield io4.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); } - arch = arch || os2.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions(toolName, arch); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver5.clean(versionSpec) || ""; - const cachePath = path2.join(_getCacheDirectory(), toolName, versionSpec, arch); - core12.debug(`checking cache: ${cachePath}`); - if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { - core12.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); - toolPath = cachePath; - } else { - core12.debug("not found"); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return toolPath; - } - exports2.find = find2; - function findAllVersions(toolName, arch) { - const versions = []; - arch = arch || os2.arch(); - const toolPath = path2.join(_getCacheDirectory(), toolName); - if (fs.existsSync(toolPath)) { - const children = fs.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path2.join(toolPath, child, arch || ""); - if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) { - versions.push(child); - } + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } } + return info6; } - return versions; - } - exports2.findAllVersions = findAllVersions; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core12.debug("set auth"); - headers.authorization = auth; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; - } + return additionalHeaders[header] || clientHeader || _default2; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core12.debug("Invalid json"); - } + if (!useProxy) { + agent = this._agent; } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os2.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path2.join(_getTempDirectory(), crypto.randomUUID()); + if (agent) { + return agent; } - yield io4.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path2.join(_getCacheDirectory(), tool, semver5.clean(version) || version, arch || ""); - core12.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io4.rmRF(folderPath); - yield io4.rmRF(markerPath); - yield io4.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch) { - const folderPath = path2.join(_getCacheDirectory(), tool, semver5.clean(version) || version, arch || ""); - const markerPath = `${folderPath}.complete`; - fs.writeFileSync(markerPath, ""); - core12.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver5.clean(versionSpec) || ""; - core12.debug(`isExplicit: ${c}`); - const valid2 = semver5.valid(c) != null; - core12.debug(`explicit? ${valid2}`); - return valid2; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core12.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver5.gt(a, b)) { - return 1; + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver5.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - if (version) { - core12.debug(`matched: ${version}`); - } else { - core12.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/node-forge/lib/forge.js -var require_forge = __commonJS({ - "node_modules/node-forge/lib/forge.js"(exports2, module2) { - module2.exports = { - // default options - options: { - usePureJavaScript: false - } - }; - } -}); - -// node_modules/node-forge/lib/baseN.js -var require_baseN = __commonJS({ - "node_modules/node-forge/lib/baseN.js"(exports2, module2) { - var api = {}; - module2.exports = api; - var _reverseAlphabets = {}; - api.encode = function(input, alphabet, maxline) { - if (typeof alphabet !== "string") { - throw new TypeError('"alphabet" must be a string.'); - } - if (maxline !== void 0 && typeof maxline !== "number") { - throw new TypeError('"maxline" must be a number.'); - } - var output = ""; - if (!(input instanceof Uint8Array)) { - output = _encodeWithByteBuffer(input, alphabet); - } else { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for (i = 0; i < input.length; ++i) { - for (var j = 0, carry = input[i]; j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = carry / base | 0; - } - while (carry > 0) { - digits.push(carry % base); - carry = carry / base | 0; - } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - for (i = 0; input[i] === 0 && i < input.length - 1; ++i) { - output += first; + if (proxyAgent) { + return proxyAgent; } - for (i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); } + return proxyAgent; } - if (maxline) { - var regex = new RegExp(".{1," + maxline + "}", "g"); - output = output.match(regex).join("\r\n"); + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); } - return output; }; - api.decode = function(input, alphabet) { - if (typeof input !== "string") { - throw new TypeError('"input" must be a string.'); + exports2.HttpClient = HttpClient; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - if (typeof alphabet !== "string") { - throw new TypeError('"alphabet" must be a string.'); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - var table = _reverseAlphabets[alphabet]; - if (!table) { - table = _reverseAlphabets[alphabet] = []; - for (var i = 0; i < alphabet.length; ++i) { - table[alphabet.charCodeAt(i)] = i; - } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); } - input = input.replace(/\s/g, ""); - var base = alphabet.length; - var first = alphabet.charAt(0); - var bytes = [0]; - for (var i = 0; i < input.length; i++) { - var value = table[input.charCodeAt(i)]; - if (value === void 0) { - return; + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - for (var j = 0, carry = value; j < bytes.length; ++j) { - carry += bytes[j] * base; - bytes[j] = carry & 255; - carry >>= 8; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - while (carry > 0) { - bytes.push(carry & 255); - carry >>= 8; + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); } - } - for (var k = 0; input[k] === first && k < input.length - 1; ++k) { - bytes.push(0); - } - if (typeof Buffer !== "undefined") { - return Buffer.from(bytes.reverse()); - } - return new Uint8Array(bytes.reverse()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - function _encodeWithByteBuffer(input, alphabet) { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for (i = 0; i < input.length(); ++i) { - for (var j = 0, carry = input.at(i); j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = carry / base | 0; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RetryHelper = void 0; + var core12 = __importStar4(require_core()); + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); } - while (carry > 0) { - digits.push(carry % base); - carry = carry / base | 0; + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); } } - var output = ""; - for (i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { - output += first; + execute(action, isRetryable) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 1; + while (attempt < this.maxAttempts) { + try { + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; + } + core12.info(err.message); + } + const seconds = this.getSleepAmount(); + core12.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); + attempt++; + } + return yield action(); + }); } - for (i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; } - return output; - } + sleep(seconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => setTimeout(resolve2, seconds * 1e3)); + }); + } + }; + exports2.RetryHelper = RetryHelper; } }); -// node_modules/node-forge/lib/util.js -var require_util8 = __commonJS({ - "node_modules/node-forge/lib/util.js"(exports2, module2) { - var forge = require_forge(); - var baseN = require_baseN(); - var util = module2.exports = forge.util = forge.util || {}; - (function() { - if (typeof process !== "undefined" && process.nextTick && !process.browser) { - util.nextTick = process.nextTick; - if (typeof setImmediate === "function") { - util.setImmediate = setImmediate; - } else { - util.setImmediate = util.nextTick; - } - return; - } - if (typeof setImmediate === "function") { - util.setImmediate = function() { - return setImmediate.apply(void 0, arguments); - }; - util.nextTick = function(callback) { - return setImmediate(callback); - }; - return; - } - util.setImmediate = function(callback) { - setTimeout(callback, 0); - }; - if (typeof window !== "undefined" && typeof window.postMessage === "function") { - let handler2 = function(event) { - if (event.source === window && event.data === msg) { - event.stopPropagation(); - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - } - }; - var handler = handler2; - var msg = "forge.setImmediate"; - var callbacks = []; - util.setImmediate = function(callback) { - callbacks.push(callback); - if (callbacks.length === 1) { - window.postMessage(msg, "*"); - } - }; - window.addEventListener("message", handler2, true); - } - if (typeof MutationObserver !== "undefined") { - var now = Date.now(); - var attr = true; - var div = document.createElement("div"); - var callbacks = []; - new MutationObserver(function() { - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - }).observe(div, { attributes: true }); - var oldSetImmediate = util.setImmediate; - util.setImmediate = function(callback) { - if (Date.now() - now > 15) { - now = Date.now(); - oldSetImmediate(callback); - } else { - callbacks.push(callback); - if (callbacks.length === 1) { - div.setAttribute("a", attr = !attr); - } - } - }; +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - util.nextTick = util.setImmediate; - })(); - util.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node; - util.globalScope = (function() { - if (util.isNodejs) { - return global; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - return typeof self === "undefined" ? window : self; - })(); - util.isArray = Array.isArray || function(x) { - return Object.prototype.toString.call(x) === "[object Array]"; - }; - util.isArrayBuffer = function(x) { - return typeof ArrayBuffer !== "undefined" && x instanceof ArrayBuffer; - }; - util.isArrayBufferView = function(x) { - return x && util.isArrayBuffer(x.buffer) && x.byteLength !== void 0; + __setModuleDefault4(result, mod); + return result; }; - function _checkBitsParam(n) { - if (!(n === 8 || n === 16 || n === 24 || n === 32)) { - throw new Error("Only 8, 16, 24, or 32 bits supported: " + n); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); } - } - util.ByteBuffer = ByteStringBuffer; - function ByteStringBuffer(b) { - this.data = ""; - this.read = 0; - if (typeof b === "string") { - this.data = b; - } else if (util.isArrayBuffer(b) || util.isArrayBufferView(b)) { - if (typeof Buffer !== "undefined" && b instanceof Buffer) { - this.data = b.toString("binary"); - } else { - var arr = new Uint8Array(b); + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { try { - this.data = String.fromCharCode.apply(null, arr); + step(generator.next(value)); } catch (e) { - for (var i = 0; i < arr.length; ++i) { - this.putByte(arr[i]); - } + reject(e); } } - } else if (b instanceof ByteStringBuffer || typeof b === "object" && typeof b.data === "string" && typeof b.read === "number") { - this.data = b.data; - this.read = b.read; - } - this._constructedStringLength = 0; - } - util.ByteStringBuffer = ByteStringBuffer; - var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; - util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { - this._constructedStringLength += x; - if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { - this.data.substr(0, 1); - this._constructedStringLength = 0; - } - }; - util.ByteStringBuffer.prototype.length = function() { - return this.data.length - this.read; - }; - util.ByteStringBuffer.prototype.isEmpty = function() { - return this.length() <= 0; - }; - util.ByteStringBuffer.prototype.putByte = function(b) { - return this.putBytes(String.fromCharCode(b)); - }; - util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { - b = String.fromCharCode(b); - var d = this.data; - while (n > 0) { - if (n & 1) { - d += b; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - n >>>= 1; - if (n > 0) { - b += b; + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); } - } - this.data = d; - this._optimizeConstructedString(n); - return this; - }; - util.ByteStringBuffer.prototype.putBytes = function(bytes) { - this.data += bytes; - this._optimizeConstructedString(bytes.length); - return this; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - util.ByteStringBuffer.prototype.putString = function(str2) { - return this.putBytes(util.encodeUtf8(str2)); - }; - util.ByteStringBuffer.prototype.putInt16 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt24 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt32 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt16Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt24Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt32Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 24 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - var bytes = ""; - do { - n -= 8; - bytes += String.fromCharCode(i >> n & 255); - } while (n > 0); - return this.putBytes(bytes); - }; - util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { - if (i < 0) { - i += 2 << n - 1; - } - return this.putInt(i, n); - }; - util.ByteStringBuffer.prototype.putBuffer = function(buffer) { - return this.putBytes(buffer.getBytes()); - }; - util.ByteStringBuffer.prototype.getByte = function() { - return this.data.charCodeAt(this.read++); - }; - util.ByteStringBuffer.prototype.getInt16 = function() { - var rval = this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1); - this.read += 2; - return rval; - }; - util.ByteStringBuffer.prototype.getInt24 = function() { - var rval = this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2); - this.read += 3; - return rval; - }; - util.ByteStringBuffer.prototype.getInt32 = function() { - var rval = this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3); - this.read += 4; - return rval; - }; - util.ByteStringBuffer.prototype.getInt16Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8; - this.read += 2; - return rval; - }; - util.ByteStringBuffer.prototype.getInt24Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16; - this.read += 3; - return rval; - }; - util.ByteStringBuffer.prototype.getInt32Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24; - this.read += 4; - return rval; - }; - util.ByteStringBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - rval = (rval << 8) + this.data.charCodeAt(this.read++); - n -= 8; - } while (n > 0); - return rval; - }; - util.ByteStringBuffer.prototype.getSignedInt = function(n) { - var x = this.getInt(n); - var max = 2 << n - 2; - if (x >= max) { - x -= max << 1; - } - return x; - }; - util.ByteStringBuffer.prototype.getBytes = function(count) { - var rval; - if (count) { - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if (count === 0) { - rval = ""; - } else { - rval = this.read === 0 ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; - }; - util.ByteStringBuffer.prototype.bytes = function(count) { - return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); - }; - util.ByteStringBuffer.prototype.at = function(i) { - return this.data.charCodeAt(this.read + i); - }; - util.ByteStringBuffer.prototype.setAt = function(i, b) { - this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); - return this; - }; - util.ByteStringBuffer.prototype.last = function() { - return this.data.charCodeAt(this.data.length - 1); - }; - util.ByteStringBuffer.prototype.copy = function() { - var c = util.createBuffer(this.data); - c.read = this.read; - return c; - }; - util.ByteStringBuffer.prototype.compact = function() { - if (this.read > 0) { - this.data = this.data.slice(this.read); - this.read = 0; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; + var core12 = __importStar4(require_core()); + var io4 = __importStar4(require_io()); + var crypto = __importStar4(require("crypto")); + var fs = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os2 = __importStar4(require("os")); + var path2 = __importStar4(require("path")); + var httpm = __importStar4(require_lib2()); + var semver5 = __importStar4(require_semver2()); + var stream = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError2 = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); } - return this; - }; - util.ByteStringBuffer.prototype.clear = function() { - this.data = ""; - this.read = 0; - return this; - }; - util.ByteStringBuffer.prototype.truncate = function(count) { - var len = Math.max(0, this.length() - count); - this.data = this.data.substr(this.read, len); - this.read = 0; - return this; }; - util.ByteStringBuffer.prototype.toHex = function() { - var rval = ""; - for (var i = this.read; i < this.data.length; ++i) { - var b = this.data.charCodeAt(i); - if (b < 16) { - rval += "0"; + exports2.HTTPError = HTTPError2; + var IS_WINDOWS = process.platform === "win32"; + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url, dest, auth, headers) { + return __awaiter4(this, void 0, void 0, function* () { + dest = dest || path2.join(_getTempDirectory(), crypto.randomUUID()); + yield io4.mkdirP(path2.dirname(dest)); + core12.debug(`Downloading ${url}`); + core12.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError2 && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; + } + } + return true; + }); + }); + } + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url, dest, auth, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (fs.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); } - rval += b.toString(16); - } - return rval; - }; - util.ByteStringBuffer.prototype.toString = function() { - return util.decodeUtf8(this.bytes()); - }; - function DataBuffer(b, options) { - options = options || {}; - this.read = options.readOffset || 0; - this.growSize = options.growSize || 1024; - var isArrayBuffer = util.isArrayBuffer(b); - var isArrayBufferView = util.isArrayBufferView(b); - if (isArrayBuffer || isArrayBufferView) { - if (isArrayBuffer) { - this.data = new DataView(b); + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core12.debug("set auth"); + if (headers === void 0) { + headers = {}; + } + headers.authorization = auth; + } + const response = yield http.get(url, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError2(response.message.statusCode); + core12.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; + } + const pipeline = util.promisify(stream.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; + try { + yield pipeline(readStream, fs.createWriteStream(dest)); + core12.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core12.debug("download failed"); + try { + yield io4.rmRF(dest); + } catch (err) { + core12.debug(`Failed to delete '${dest}'. ${err.message}`); + } + } + } + }); + } + function extract7z(file, dest, _7zPath) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { + try { + const logLevel = core12.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file + ]; + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } } else { - this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); + const escapedScript = path2.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true + }; + try { + const powershellPath = yield io4.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } } - this.write = "writeOffset" in options ? options.writeOffset : this.data.byteLength; - return; - } - this.data = new DataView(new ArrayBuffer(0)); - this.write = 0; - if (b !== null && b !== void 0) { - this.putBytes(b); - } - if ("writeOffset" in options) { - this.write = options.writeOffset; - } + return dest; + }); } - util.DataBuffer = DataBuffer; - util.DataBuffer.prototype.length = function() { - return this.write - this.read; - }; - util.DataBuffer.prototype.isEmpty = function() { - return this.length() <= 0; - }; - util.DataBuffer.prototype.accommodate = function(amount, growSize) { - if (this.length() >= amount) { - return this; - } - growSize = Math.max(growSize || this.growSize, amount); - var src = new Uint8Array( - this.data.buffer, - this.data.byteOffset, - this.data.byteLength - ); - var dst = new Uint8Array(this.length() + growSize); - dst.set(src); - this.data = new DataView(dst.buffer); - return this; - }; - util.DataBuffer.prototype.putByte = function(b) { - this.accommodate(1); - this.data.setUint8(this.write++, b); - return this; - }; - util.DataBuffer.prototype.fillWithByte = function(b, n) { - this.accommodate(n); - for (var i = 0; i < n; ++i) { - this.data.setUint8(b); - } - return this; - }; - util.DataBuffer.prototype.putBytes = function(bytes, encoding) { - if (util.isArrayBufferView(bytes)) { - var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); - var len = src.byteLength - src.byteOffset; - this.accommodate(len); - var dst = new Uint8Array(this.data.buffer, this.write); - dst.set(src); - this.write += len; - return this; - } - if (util.isArrayBuffer(bytes)) { - var src = new Uint8Array(bytes); - this.accommodate(src.byteLength); - var dst = new Uint8Array(this.data.buffer); - dst.set(src, this.write); - this.write += src.byteLength; - return this; - } - if (bytes instanceof util.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util.isArrayBufferView(bytes.data)) { - var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); - this.accommodate(src.byteLength); - var dst = new Uint8Array(bytes.data.byteLength, this.write); - dst.set(src); - this.write += src.byteLength; - return this; - } - if (bytes instanceof util.ByteStringBuffer) { - bytes = bytes.data; - encoding = "binary"; - } - encoding = encoding || "binary"; - if (typeof bytes === "string") { - var view; - if (encoding === "hex") { - this.accommodate(Math.ceil(bytes.length / 2)); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.hex.decode(bytes, view, this.write); - return this; + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); } - if (encoding === "base64") { - this.accommodate(Math.ceil(bytes.length / 4) * 3); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.base64.decode(bytes, view, this.write); - return this; + dest = yield _createExtractFolder(dest); + core12.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + core12.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; } - if (encoding === "utf8") { - bytes = util.encodeUtf8(bytes); - encoding = "binary"; + if (core12.isDebug() && !flags.includes("v")) { + args.push("-v"); } - if (encoding === "binary" || encoding === "raw") { - this.accommodate(bytes.length); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.raw.decode(view); - return this; + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); } - if (encoding === "utf16") { - this.accommodate(bytes.length * 2); - view = new Uint16Array(this.data.buffer, this.write); - this.write += util.text.utf16.encode(view); - return this; + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); } - throw new Error("Invalid encoding: " + encoding); - } - throw Error("Invalid parameter: " + bytes); - }; - util.DataBuffer.prototype.putBuffer = function(buffer) { - this.putBytes(buffer); - buffer.clear(); - return this; - }; - util.DataBuffer.prototype.putString = function(str2) { - return this.putBytes(str2, "utf16"); - }; - util.DataBuffer.prototype.putInt16 = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i); - this.write += 2; - return this; - }; - util.DataBuffer.prototype.putInt24 = function(i) { - this.accommodate(3); - this.data.setInt16(this.write, i >> 8 & 65535); - this.data.setInt8(this.write, i >> 16 & 255); - this.write += 3; - return this; - }; - util.DataBuffer.prototype.putInt32 = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i); - this.write += 4; - return this; - }; - util.DataBuffer.prototype.putInt16Le = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i, true); - this.write += 2; - return this; - }; - util.DataBuffer.prototype.putInt24Le = function(i) { - this.accommodate(3); - this.data.setInt8(this.write, i >> 16 & 255); - this.data.setInt16(this.write, i >> 8 & 65535, true); - this.write += 3; - return this; - }; - util.DataBuffer.prototype.putInt32Le = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i, true); - this.write += 4; - return this; - }; - util.DataBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - do { - n -= 8; - this.data.setInt8(this.write++, i >> n & 255); - } while (n > 0); - return this; - }; - util.DataBuffer.prototype.putSignedInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - if (i < 0) { - i += 2 << n - 1; - } - return this.putInt(i, n); - }; - util.DataBuffer.prototype.getByte = function() { - return this.data.getInt8(this.read++); - }; - util.DataBuffer.prototype.getInt16 = function() { - var rval = this.data.getInt16(this.read); - this.read += 2; - return rval; - }; - util.DataBuffer.prototype.getInt24 = function() { - var rval = this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2); - this.read += 3; - return rval; - }; - util.DataBuffer.prototype.getInt32 = function() { - var rval = this.data.getInt32(this.read); - this.read += 4; - return rval; - }; - util.DataBuffer.prototype.getInt16Le = function() { - var rval = this.data.getInt16(this.read, true); - this.read += 2; - return rval; - }; - util.DataBuffer.prototype.getInt24Le = function() { - var rval = this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8; - this.read += 3; - return rval; - }; - util.DataBuffer.prototype.getInt32Le = function() { - var rval = this.data.getInt32(this.read, true); - this.read += 4; - return rval; - }; - util.DataBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - rval = (rval << 8) + this.data.getInt8(this.read++); - n -= 8; - } while (n > 0); - return rval; - }; - util.DataBuffer.prototype.getSignedInt = function(n) { - var x = this.getInt(n); - var max = 2 << n - 2; - if (x >= max) { - x -= max << 1; + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; + }); + } + exports2.extractTar = extractTar2; + function extractXar(file, dest, flags = []) { + return __awaiter4(this, void 0, void 0, function* () { + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + args.push("-x", "-C", dest, "-f", file); + if (core12.isDebug()) { + args.push("-v"); + } + const xarPath = yield io4.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; + }); + } + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } else { + yield extractZipNix(file, dest); + } + return dest; + }); + } + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io4.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core12.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io4.which("powershell", true); + core12.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); + } + }); + } + function extractZipNix(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + const unzipPath = yield io4.which("unzip", true); + const args = [file]; + if (!core12.isDebug()) { + args.unshift("-q"); + } + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); + }); + } + function cacheDir2(sourceDir, tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver5.clean(version) || version; + arch = arch || os2.arch(); + core12.debug(`Caching tool ${tool} ${version} ${arch}`); + core12.debug(`source dir: ${sourceDir}`); + if (!fs.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); + } + const destPath = yield _createToolPath(tool, version, arch); + for (const itemName of fs.readdirSync(sourceDir)) { + const s = path2.join(sourceDir, itemName); + yield io4.cp(s, destPath, { recursive: true }); + } + _completeToolPath(tool, version, arch); + return destPath; + }); + } + exports2.cacheDir = cacheDir2; + function cacheFile(sourceFile, targetFile, tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + version = semver5.clean(version) || version; + arch = arch || os2.arch(); + core12.debug(`Caching tool ${tool} ${version} ${arch}`); + core12.debug(`source file: ${sourceFile}`); + if (!fs.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); + } + const destFolder = yield _createToolPath(tool, version, arch); + const destPath = path2.join(destFolder, targetFile); + core12.debug(`destination file ${destPath}`); + yield io4.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch); + return destFolder; + }); + } + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch) { + if (!toolName) { + throw new Error("toolName parameter is required"); } - return x; - }; - util.DataBuffer.prototype.getBytes = function(count) { - var rval; - if (count) { - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if (count === 0) { - rval = ""; - } else { - rval = this.read === 0 ? this.data : this.data.slice(this.read); - this.clear(); + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); } - return rval; - }; - util.DataBuffer.prototype.bytes = function(count) { - return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); - }; - util.DataBuffer.prototype.at = function(i) { - return this.data.getUint8(this.read + i); - }; - util.DataBuffer.prototype.setAt = function(i, b) { - this.data.setUint8(i, b); - return this; - }; - util.DataBuffer.prototype.last = function() { - return this.data.getUint8(this.write - 1); - }; - util.DataBuffer.prototype.copy = function() { - return new util.DataBuffer(this); - }; - util.DataBuffer.prototype.compact = function() { - if (this.read > 0) { - var src = new Uint8Array(this.data.buffer, this.read); - var dst = new Uint8Array(src.byteLength); - dst.set(src); - this.data = new DataView(dst); - this.write -= this.read; - this.read = 0; + arch = arch || os2.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions(toolName, arch); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; } - return this; - }; - util.DataBuffer.prototype.clear = function() { - this.data = new DataView(new ArrayBuffer(0)); - this.read = this.write = 0; - return this; - }; - util.DataBuffer.prototype.truncate = function(count) { - this.write = Math.max(0, this.length() - count); - this.read = Math.min(this.read, this.write); - return this; - }; - util.DataBuffer.prototype.toHex = function() { - var rval = ""; - for (var i = this.read; i < this.data.byteLength; ++i) { - var b = this.data.getUint8(i); - if (b < 16) { - rval += "0"; + let toolPath = ""; + if (versionSpec) { + versionSpec = semver5.clean(versionSpec) || ""; + const cachePath = path2.join(_getCacheDirectory(), toolName, versionSpec, arch); + core12.debug(`checking cache: ${cachePath}`); + if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { + core12.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); + toolPath = cachePath; + } else { + core12.debug("not found"); } - rval += b.toString(16); - } - return rval; - }; - util.DataBuffer.prototype.toString = function(encoding) { - var view = new Uint8Array(this.data, this.read, this.length()); - encoding = encoding || "utf8"; - if (encoding === "binary" || encoding === "raw") { - return util.binary.raw.encode(view); } - if (encoding === "hex") { - return util.binary.hex.encode(view); + return toolPath; + } + exports2.find = find2; + function findAllVersions(toolName, arch) { + const versions = []; + arch = arch || os2.arch(); + const toolPath = path2.join(_getCacheDirectory(), toolName); + if (fs.existsSync(toolPath)) { + const children = fs.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path2.join(toolPath, child, arch || ""); + if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) { + versions.push(child); + } + } + } } - if (encoding === "base64") { - return util.binary.base64.encode(view); + return versions; + } + exports2.findAllVersions = findAllVersions; + function getManifestFromRepo(owner, repo, auth, branch = "master") { + return __awaiter4(this, void 0, void 0, function* () { + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core12.debug("set auth"); + headers.authorization = auth; + } + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; + } + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; + } + } + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); + try { + releases = JSON.parse(versionsRaw); + } catch (_a) { + core12.debug("Invalid json"); + } + } + return releases; + }); + } + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os2.arch()) { + return __awaiter4(this, void 0, void 0, function* () { + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; + }); + } + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!dest) { + dest = path2.join(_getTempDirectory(), crypto.randomUUID()); + } + yield io4.mkdirP(dest); + return dest; + }); + } + function _createToolPath(tool, version, arch) { + return __awaiter4(this, void 0, void 0, function* () { + const folderPath = path2.join(_getCacheDirectory(), tool, semver5.clean(version) || version, arch || ""); + core12.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io4.rmRF(folderPath); + yield io4.rmRF(markerPath); + yield io4.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch) { + const folderPath = path2.join(_getCacheDirectory(), tool, semver5.clean(version) || version, arch || ""); + const markerPath = `${folderPath}.complete`; + fs.writeFileSync(markerPath, ""); + core12.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver5.clean(versionSpec) || ""; + core12.debug(`isExplicit: ${c}`); + const valid2 = semver5.valid(c) != null; + core12.debug(`explicit? ${valid2}`); + return valid2; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { + let version = ""; + core12.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver5.gt(a, b)) { + return 1; + } + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver5.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; + } } - if (encoding === "utf8") { - return util.text.utf8.decode(view); + if (version) { + core12.debug(`matched: ${version}`); + } else { + core12.debug("match not found"); } - if (encoding === "utf16") { - return util.text.utf16.decode(view); + return version; + } + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); + } + } +}); + +// node_modules/node-forge/lib/forge.js +var require_forge = __commonJS({ + "node_modules/node-forge/lib/forge.js"(exports2, module2) { + module2.exports = { + // default options + options: { + usePureJavaScript: false } - throw new Error("Invalid encoding: " + encoding); }; - util.createBuffer = function(input, encoding) { - encoding = encoding || "raw"; - if (input !== void 0 && encoding === "utf8") { - input = util.encodeUtf8(input); + } +}); + +// node_modules/node-forge/lib/baseN.js +var require_baseN = __commonJS({ + "node_modules/node-forge/lib/baseN.js"(exports2, module2) { + var api = {}; + module2.exports = api; + var _reverseAlphabets = {}; + api.encode = function(input, alphabet, maxline) { + if (typeof alphabet !== "string") { + throw new TypeError('"alphabet" must be a string.'); } - return new util.ByteBuffer(input); - }; - util.fillString = function(c, n) { - var s = ""; - while (n > 0) { - if (n & 1) { - s += c; + if (maxline !== void 0 && typeof maxline !== "number") { + throw new TypeError('"maxline" must be a number.'); + } + var output = ""; + if (!(input instanceof Uint8Array)) { + output = _encodeWithByteBuffer(input, alphabet); + } else { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for (i = 0; i < input.length; ++i) { + for (var j = 0, carry = input[i]; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = carry / base | 0; + } + while (carry > 0) { + digits.push(carry % base); + carry = carry / base | 0; + } } - n >>>= 1; - if (n > 0) { - c += c; + for (i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; } - } - return s; - }; - util.xorBytes = function(s1, s2, n) { - var s3 = ""; - var b = ""; - var t = ""; - var i = 0; - var c = 0; - for (; n > 0; --n, ++i) { - b = s1.charCodeAt(i) ^ s2.charCodeAt(i); - if (c >= 10) { - s3 += t; - t = ""; - c = 0; + for (i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; } - t += String.fromCharCode(b); - ++c; } - s3 += t; - return s3; + if (maxline) { + var regex = new RegExp(".{1," + maxline + "}", "g"); + output = output.match(regex).join("\r\n"); + } + return output; }; - util.hexToBytes = function(hex) { - var rval = ""; - var i = 0; - if (hex.length & true) { - i = 1; - rval += String.fromCharCode(parseInt(hex[0], 16)); + api.decode = function(input, alphabet) { + if (typeof input !== "string") { + throw new TypeError('"input" must be a string.'); } - for (; i < hex.length; i += 2) { - rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + if (typeof alphabet !== "string") { + throw new TypeError('"alphabet" must be a string.'); } - return rval; - }; - util.bytesToHex = function(bytes) { - return util.createBuffer(bytes).toHex(); - }; - util.int32ToBytes = function(i) { - return String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255); - }; - var _base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var _base64Idx = [ - /*43 -43 = 0*/ - /*'+', 1, 2, 3,'/' */ - 62, - -1, - -1, - -1, - 63, - /*'0','1','2','3','4','5','6','7','8','9' */ - 52, - 53, - 54, - 55, - 56, - 57, - 58, - 59, - 60, - 61, - /*15, 16, 17,'=', 19, 20, 21 */ - -1, - -1, - -1, - 64, - -1, - -1, - -1, - /*65 - 43 = 22*/ - /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - /*91 - 43 = 48 */ - /*48, 49, 50, 51, 52, 53 */ - -1, - -1, - -1, - -1, - -1, - -1, - /*97 - 43 = 54*/ - /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, - 37, - 38, - /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, - 51 - ]; - var _base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; - util.encode64 = function(input, maxline) { - var line = ""; - var output = ""; - var chr1, chr2, chr3; - var i = 0; - while (i < input.length) { - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); - if (isNaN(chr2)) { - line += "=="; - } else { - line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); - line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); + var table = _reverseAlphabets[alphabet]; + if (!table) { + table = _reverseAlphabets[alphabet] = []; + for (var i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; } - if (maxline && line.length > maxline) { - output += line.substr(0, maxline) + "\r\n"; - line = line.substr(maxline); + } + input = input.replace(/\s/g, ""); + var base = alphabet.length; + var first = alphabet.charAt(0); + var bytes = [0]; + for (var i = 0; i < input.length; i++) { + var value = table[input.charCodeAt(i)]; + if (value === void 0) { + return; + } + for (var j = 0, carry = value; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 255; + carry >>= 8; + } + while (carry > 0) { + bytes.push(carry & 255); + carry >>= 8; } } - output += line; - return output; + for (var k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + if (typeof Buffer !== "undefined") { + return Buffer.from(bytes.reverse()); + } + return new Uint8Array(bytes.reverse()); }; - util.decode64 = function(input) { - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - var output = ""; - var enc1, enc2, enc3, enc4; + function _encodeWithByteBuffer(input, alphabet) { var i = 0; - while (i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - output += String.fromCharCode(enc1 << 2 | enc2 >> 4); - if (enc3 !== 64) { - output += String.fromCharCode((enc2 & 15) << 4 | enc3 >> 2); - if (enc4 !== 64) { - output += String.fromCharCode((enc3 & 3) << 6 | enc4); - } + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for (i = 0; i < input.length(); ++i) { + for (var j = 0, carry = input.at(i); j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = carry / base | 0; + } + while (carry > 0) { + digits.push(carry % base); + carry = carry / base | 0; } } - return output; - }; - util.encodeUtf8 = function(str2) { - return unescape(encodeURIComponent(str2)); - }; - util.decodeUtf8 = function(str2) { - return decodeURIComponent(escape(str2)); - }; - util.binary = { - raw: {}, - hex: {}, - base64: {}, - base58: {}, - baseN: { - encode: baseN.encode, - decode: baseN.decode + var output = ""; + for (i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { + output += first; } - }; - util.binary.raw.encode = function(bytes) { - return String.fromCharCode.apply(null, bytes); - }; - util.binary.raw.decode = function(str2, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(str2.length); + for (i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; } - offset = offset || 0; - var j = offset; - for (var i = 0; i < str2.length; ++i) { - out[j++] = str2.charCodeAt(i); + return output; + } + } +}); + +// node_modules/node-forge/lib/util.js +var require_util8 = __commonJS({ + "node_modules/node-forge/lib/util.js"(exports2, module2) { + var forge = require_forge(); + var baseN = require_baseN(); + var util = module2.exports = forge.util = forge.util || {}; + (function() { + if (typeof process !== "undefined" && process.nextTick && !process.browser) { + util.nextTick = process.nextTick; + if (typeof setImmediate === "function") { + util.setImmediate = setImmediate; + } else { + util.setImmediate = util.nextTick; + } + return; } - return output ? j - offset : out; - }; - util.binary.hex.encode = util.bytesToHex; - util.binary.hex.decode = function(hex, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(Math.ceil(hex.length / 2)); + if (typeof setImmediate === "function") { + util.setImmediate = function() { + return setImmediate.apply(void 0, arguments); + }; + util.nextTick = function(callback) { + return setImmediate(callback); + }; + return; } - offset = offset || 0; - var i = 0, j = offset; - if (hex.length & 1) { - i = 1; - out[j++] = parseInt(hex[0], 16); + util.setImmediate = function(callback) { + setTimeout(callback, 0); + }; + if (typeof window !== "undefined" && typeof window.postMessage === "function") { + let handler2 = function(event) { + if (event.source === window && event.data === msg) { + event.stopPropagation(); + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + } + }; + var handler = handler2; + var msg = "forge.setImmediate"; + var callbacks = []; + util.setImmediate = function(callback) { + callbacks.push(callback); + if (callbacks.length === 1) { + window.postMessage(msg, "*"); + } + }; + window.addEventListener("message", handler2, true); } - for (; i < hex.length; i += 2) { - out[j++] = parseInt(hex.substr(i, 2), 16); + if (typeof MutationObserver !== "undefined") { + var now = Date.now(); + var attr = true; + var div = document.createElement("div"); + var callbacks = []; + new MutationObserver(function() { + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + }).observe(div, { attributes: true }); + var oldSetImmediate = util.setImmediate; + util.setImmediate = function(callback) { + if (Date.now() - now > 15) { + now = Date.now(); + oldSetImmediate(callback); + } else { + callbacks.push(callback); + if (callbacks.length === 1) { + div.setAttribute("a", attr = !attr); + } + } + }; } - return output ? j - offset : out; - }; - util.binary.base64.encode = function(input, maxline) { - var line = ""; - var output = ""; - var chr1, chr2, chr3; - var i = 0; - while (i < input.byteLength) { - chr1 = input[i++]; - chr2 = input[i++]; - chr3 = input[i++]; - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); - if (isNaN(chr2)) { - line += "=="; - } else { - line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); - line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); - } - if (maxline && line.length > maxline) { - output += line.substr(0, maxline) + "\r\n"; - line = line.substr(maxline); - } + util.nextTick = util.setImmediate; + })(); + util.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node; + util.globalScope = (function() { + if (util.isNodejs) { + return global; } - output += line; - return output; + return typeof self === "undefined" ? window : self; + })(); + util.isArray = Array.isArray || function(x) { + return Object.prototype.toString.call(x) === "[object Array]"; }; - util.binary.base64.decode = function(input, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(Math.ceil(input.length / 4) * 3); + util.isArrayBuffer = function(x) { + return typeof ArrayBuffer !== "undefined" && x instanceof ArrayBuffer; + }; + util.isArrayBufferView = function(x) { + return x && util.isArrayBuffer(x.buffer) && x.byteLength !== void 0; + }; + function _checkBitsParam(n) { + if (!(n === 8 || n === 16 || n === 24 || n === 32)) { + throw new Error("Only 8, 16, 24, or 32 bits supported: " + n); } - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - offset = offset || 0; - var enc1, enc2, enc3, enc4; - var i = 0, j = offset; - while (i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - out[j++] = enc1 << 2 | enc2 >> 4; - if (enc3 !== 64) { - out[j++] = (enc2 & 15) << 4 | enc3 >> 2; - if (enc4 !== 64) { - out[j++] = (enc3 & 3) << 6 | enc4; + } + util.ByteBuffer = ByteStringBuffer; + function ByteStringBuffer(b) { + this.data = ""; + this.read = 0; + if (typeof b === "string") { + this.data = b; + } else if (util.isArrayBuffer(b) || util.isArrayBufferView(b)) { + if (typeof Buffer !== "undefined" && b instanceof Buffer) { + this.data = b.toString("binary"); + } else { + var arr = new Uint8Array(b); + try { + this.data = String.fromCharCode.apply(null, arr); + } catch (e) { + for (var i = 0; i < arr.length; ++i) { + this.putByte(arr[i]); + } } } + } else if (b instanceof ByteStringBuffer || typeof b === "object" && typeof b.data === "string" && typeof b.read === "number") { + this.data = b.data; + this.read = b.read; + } + this._constructedStringLength = 0; + } + util.ByteStringBuffer = ByteStringBuffer; + var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; + util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { + this._constructedStringLength += x; + if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { + this.data.substr(0, 1); + this._constructedStringLength = 0; } - return output ? j - offset : out.subarray(0, j); }; - util.binary.base58.encode = function(input, maxline) { - return util.binary.baseN.encode(input, _base58, maxline); + util.ByteStringBuffer.prototype.length = function() { + return this.data.length - this.read; }; - util.binary.base58.decode = function(input, maxline) { - return util.binary.baseN.decode(input, _base58, maxline); + util.ByteStringBuffer.prototype.isEmpty = function() { + return this.length() <= 0; }; - util.text = { - utf8: {}, - utf16: {} + util.ByteStringBuffer.prototype.putByte = function(b) { + return this.putBytes(String.fromCharCode(b)); }; - util.text.utf8.encode = function(str2, output, offset) { - str2 = util.encodeUtf8(str2); - var out = output; - if (!out) { - out = new Uint8Array(str2.length); - } - offset = offset || 0; - var j = offset; - for (var i = 0; i < str2.length; ++i) { - out[j++] = str2.charCodeAt(i); + util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { + b = String.fromCharCode(b); + var d = this.data; + while (n > 0) { + if (n & 1) { + d += b; + } + n >>>= 1; + if (n > 0) { + b += b; + } } - return output ? j - offset : out; + this.data = d; + this._optimizeConstructedString(n); + return this; }; - util.text.utf8.decode = function(bytes) { - return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); + util.ByteStringBuffer.prototype.putBytes = function(bytes) { + this.data += bytes; + this._optimizeConstructedString(bytes.length); + return this; }; - util.text.utf16.encode = function(str2, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(str2.length * 2); - } - var view = new Uint16Array(out.buffer); - offset = offset || 0; - var j = offset; - var k = offset; - for (var i = 0; i < str2.length; ++i) { - view[k++] = str2.charCodeAt(i); - j += 2; - } - return output ? j - offset : out; + util.ByteStringBuffer.prototype.putString = function(str2) { + return this.putBytes(util.encodeUtf8(str2)); }; - util.text.utf16.decode = function(bytes) { - return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); + util.ByteStringBuffer.prototype.putInt16 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) + ); }; - util.deflate = function(api, bytes, raw) { - bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); - if (raw) { - var start = 2; - var flg = bytes.charCodeAt(1); - if (flg & 32) { - start = 6; - } - bytes = bytes.substring(start, bytes.length - 4); - } - return bytes; + util.ByteStringBuffer.prototype.putInt24 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) + ); }; - util.inflate = function(api, bytes, raw) { - var rval = api.inflate(util.encode64(bytes)).rval; - return rval === null ? null : util.decode64(rval); + util.ByteStringBuffer.prototype.putInt32 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) + ); }; - var _setStorageObject = function(api, id, obj) { - if (!api) { - throw new Error("WebStorage not available."); - } - var rval; - if (obj === null) { - rval = api.removeItem(id); - } else { - obj = util.encode64(JSON.stringify(obj)); - rval = api.setItem(id, obj); - } - if (typeof rval !== "undefined" && rval.rval !== true) { - var error4 = new Error(rval.error.message); - error4.id = rval.error.id; - error4.name = rval.error.name; - throw error4; - } + util.ByteStringBuffer.prototype.putInt16Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + ); }; - var _getStorageObject = function(api, id) { - if (!api) { - throw new Error("WebStorage not available."); - } - var rval = api.getItem(id); - if (api.init) { - if (rval.rval === null) { - if (rval.error) { - var error4 = new Error(rval.error.message); - error4.id = rval.error.id; - error4.name = rval.error.name; - throw error4; - } - rval = null; - } else { - rval = rval.rval; - } - } - if (rval !== null) { - rval = JSON.parse(util.decode64(rval)); + util.ByteStringBuffer.prototype.putInt24Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) + ); + }; + util.ByteStringBuffer.prototype.putInt32Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 24 & 255) + ); + }; + util.ByteStringBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + var bytes = ""; + do { + n -= 8; + bytes += String.fromCharCode(i >> n & 255); + } while (n > 0); + return this.putBytes(bytes); + }; + util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { + if (i < 0) { + i += 2 << n - 1; } + return this.putInt(i, n); + }; + util.ByteStringBuffer.prototype.putBuffer = function(buffer) { + return this.putBytes(buffer.getBytes()); + }; + util.ByteStringBuffer.prototype.getByte = function() { + return this.data.charCodeAt(this.read++); + }; + util.ByteStringBuffer.prototype.getInt16 = function() { + var rval = this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1); + this.read += 2; return rval; }; - var _setItem = function(api, id, key, data) { - var obj = _getStorageObject(api, id); - if (obj === null) { - obj = {}; - } - obj[key] = data; - _setStorageObject(api, id, obj); + util.ByteStringBuffer.prototype.getInt24 = function() { + var rval = this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2); + this.read += 3; + return rval; }; - var _getItem = function(api, id, key) { - var rval = _getStorageObject(api, id); - if (rval !== null) { - rval = key in rval ? rval[key] : null; - } + util.ByteStringBuffer.prototype.getInt32 = function() { + var rval = this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3); + this.read += 4; return rval; }; - var _removeItem = function(api, id, key) { - var obj = _getStorageObject(api, id); - if (obj !== null && key in obj) { - delete obj[key]; - var empty = true; - for (var prop in obj) { - empty = false; - break; - } - if (empty) { - obj = null; - } - _setStorageObject(api, id, obj); - } + util.ByteStringBuffer.prototype.getInt16Le = function() { + var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8; + this.read += 2; + return rval; }; - var _clearItems = function(api, id) { - _setStorageObject(api, id, null); + util.ByteStringBuffer.prototype.getInt24Le = function() { + var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16; + this.read += 3; + return rval; }; - var _callStorageFunction = function(func, args, location) { - var rval = null; - if (typeof location === "undefined") { - location = ["web", "flash"]; - } - var type2; - var done = false; - var exception2 = null; - for (var idx in location) { - type2 = location[idx]; - try { - if (type2 === "flash" || type2 === "both") { - if (args[0] === null) { - throw new Error("Flash local storage not available."); - } - rval = func.apply(this, args); - done = type2 === "flash"; - } - if (type2 === "web" || type2 === "both") { - args[0] = localStorage; - rval = func.apply(this, args); - done = true; - } - } catch (ex) { - exception2 = ex; - } - if (done) { - break; - } + util.ByteStringBuffer.prototype.getInt32Le = function() { + var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24; + this.read += 4; + return rval; + }; + util.ByteStringBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + rval = (rval << 8) + this.data.charCodeAt(this.read++); + n -= 8; + } while (n > 0); + return rval; + }; + util.ByteStringBuffer.prototype.getSignedInt = function(n) { + var x = this.getInt(n); + var max = 2 << n - 2; + if (x >= max) { + x -= max << 1; } - if (!done) { - throw exception2; + return x; + }; + util.ByteStringBuffer.prototype.getBytes = function(count) { + var rval; + if (count) { + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if (count === 0) { + rval = ""; + } else { + rval = this.read === 0 ? this.data : this.data.slice(this.read); + this.clear(); } return rval; }; - util.setItem = function(api, id, key, data, location) { - _callStorageFunction(_setItem, arguments, location); + util.ByteStringBuffer.prototype.bytes = function(count) { + return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); }; - util.getItem = function(api, id, key, location) { - return _callStorageFunction(_getItem, arguments, location); + util.ByteStringBuffer.prototype.at = function(i) { + return this.data.charCodeAt(this.read + i); }; - util.removeItem = function(api, id, key, location) { - _callStorageFunction(_removeItem, arguments, location); + util.ByteStringBuffer.prototype.setAt = function(i, b) { + this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); + return this; }; - util.clearItems = function(api, id, location) { - _callStorageFunction(_clearItems, arguments, location); + util.ByteStringBuffer.prototype.last = function() { + return this.data.charCodeAt(this.data.length - 1); }; - util.isEmpty = function(obj) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - return false; - } - } - return true; + util.ByteStringBuffer.prototype.copy = function() { + var c = util.createBuffer(this.data); + c.read = this.read; + return c; }; - util.format = function(format) { - var re = /%./g; - var match; - var part; - var argi = 0; - var parts = []; - var last = 0; - while (match = re.exec(format)) { - part = format.substring(last, re.lastIndex - 2); - if (part.length > 0) { - parts.push(part); - } - last = re.lastIndex; - var code = match[0][1]; - switch (code) { - case "s": - case "o": - if (argi < arguments.length) { - parts.push(arguments[argi++ + 1]); - } else { - parts.push(""); - } - break; - // FIXME: do proper formating for numbers, etc - //case 'f': - //case 'd': - case "%": - parts.push("%"); - break; - default: - parts.push("<%" + code + "?>"); - } + util.ByteStringBuffer.prototype.compact = function() { + if (this.read > 0) { + this.data = this.data.slice(this.read); + this.read = 0; } - parts.push(format.substring(last)); - return parts.join(""); - }; - util.formatNumber = function(number, decimals, dec_point, thousands_sep) { - var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; - var d = dec_point === void 0 ? "," : dec_point; - var t = thousands_sep === void 0 ? "." : thousands_sep, s = n < 0 ? "-" : ""; - var i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + ""; - var j = i.length > 3 ? i.length % 3 : 0; - return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); + return this; }; - util.formatSize = function(size) { - if (size >= 1073741824) { - size = util.formatNumber(size / 1073741824, 2, ".", "") + " GiB"; - } else if (size >= 1048576) { - size = util.formatNumber(size / 1048576, 2, ".", "") + " MiB"; - } else if (size >= 1024) { - size = util.formatNumber(size / 1024, 0) + " KiB"; - } else { - size = util.formatNumber(size, 0) + " bytes"; - } - return size; + util.ByteStringBuffer.prototype.clear = function() { + this.data = ""; + this.read = 0; + return this; }; - util.bytesFromIP = function(ip) { - if (ip.indexOf(".") !== -1) { - return util.bytesFromIPv4(ip); - } - if (ip.indexOf(":") !== -1) { - return util.bytesFromIPv6(ip); - } - return null; + util.ByteStringBuffer.prototype.truncate = function(count) { + var len = Math.max(0, this.length() - count); + this.data = this.data.substr(this.read, len); + this.read = 0; + return this; }; - util.bytesFromIPv4 = function(ip) { - ip = ip.split("."); - if (ip.length !== 4) { - return null; - } - var b = util.createBuffer(); - for (var i = 0; i < ip.length; ++i) { - var num = parseInt(ip[i], 10); - if (isNaN(num)) { - return null; + util.ByteStringBuffer.prototype.toHex = function() { + var rval = ""; + for (var i = this.read; i < this.data.length; ++i) { + var b = this.data.charCodeAt(i); + if (b < 16) { + rval += "0"; } - b.putByte(num); + rval += b.toString(16); } - return b.getBytes(); + return rval; }; - util.bytesFromIPv6 = function(ip) { - var blanks = 0; - ip = ip.split(":").filter(function(e) { - if (e.length === 0) ++blanks; - return true; - }); - var zeros = (8 - ip.length + blanks) * 2; - var b = util.createBuffer(); - for (var i = 0; i < 8; ++i) { - if (!ip[i] || ip[i].length === 0) { - b.fillWithByte(0, zeros); - zeros = 0; - continue; - } - var bytes = util.hexToBytes(ip[i]); - if (bytes.length < 2) { - b.putByte(0); + util.ByteStringBuffer.prototype.toString = function() { + return util.decodeUtf8(this.bytes()); + }; + function DataBuffer(b, options) { + options = options || {}; + this.read = options.readOffset || 0; + this.growSize = options.growSize || 1024; + var isArrayBuffer = util.isArrayBuffer(b); + var isArrayBufferView = util.isArrayBufferView(b); + if (isArrayBuffer || isArrayBufferView) { + if (isArrayBuffer) { + this.data = new DataView(b); + } else { + this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); } - b.putBytes(bytes); + this.write = "writeOffset" in options ? options.writeOffset : this.data.byteLength; + return; } - return b.getBytes(); - }; - util.bytesToIP = function(bytes) { - if (bytes.length === 4) { - return util.bytesToIPv4(bytes); + this.data = new DataView(new ArrayBuffer(0)); + this.write = 0; + if (b !== null && b !== void 0) { + this.putBytes(b); } - if (bytes.length === 16) { - return util.bytesToIPv6(bytes); + if ("writeOffset" in options) { + this.write = options.writeOffset; } - return null; + } + util.DataBuffer = DataBuffer; + util.DataBuffer.prototype.length = function() { + return this.write - this.read; }; - util.bytesToIPv4 = function(bytes) { - if (bytes.length !== 4) { - return null; - } - var ip = []; - for (var i = 0; i < bytes.length; ++i) { - ip.push(bytes.charCodeAt(i)); - } - return ip.join("."); + util.DataBuffer.prototype.isEmpty = function() { + return this.length() <= 0; }; - util.bytesToIPv6 = function(bytes) { - if (bytes.length !== 16) { - return null; - } - var ip = []; - var zeroGroups = []; - var zeroMaxGroup = 0; - for (var i = 0; i < bytes.length; i += 2) { - var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); - while (hex[0] === "0" && hex !== "0") { - hex = hex.substr(1); - } - if (hex === "0") { - var last = zeroGroups[zeroGroups.length - 1]; - var idx = ip.length; - if (!last || idx !== last.end + 1) { - zeroGroups.push({ start: idx, end: idx }); - } else { - last.end = idx; - if (last.end - last.start > zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start) { - zeroMaxGroup = zeroGroups.length - 1; - } - } - } - ip.push(hex); - } - if (zeroGroups.length > 0) { - var group = zeroGroups[zeroMaxGroup]; - if (group.end - group.start > 0) { - ip.splice(group.start, group.end - group.start + 1, ""); - if (group.start === 0) { - ip.unshift(""); - } - if (group.end === 7) { - ip.push(""); - } - } + util.DataBuffer.prototype.accommodate = function(amount, growSize) { + if (this.length() >= amount) { + return this; } - return ip.join(":"); + growSize = Math.max(growSize || this.growSize, amount); + var src = new Uint8Array( + this.data.buffer, + this.data.byteOffset, + this.data.byteLength + ); + var dst = new Uint8Array(this.length() + growSize); + dst.set(src); + this.data = new DataView(dst.buffer); + return this; }; - util.estimateCores = function(options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; + util.DataBuffer.prototype.putByte = function(b) { + this.accommodate(1); + this.data.setUint8(this.write++, b); + return this; + }; + util.DataBuffer.prototype.fillWithByte = function(b, n) { + this.accommodate(n); + for (var i = 0; i < n; ++i) { + this.data.setUint8(b); } - options = options || {}; - if ("cores" in util && !options.update) { - return callback(null, util.cores); + return this; + }; + util.DataBuffer.prototype.putBytes = function(bytes, encoding) { + if (util.isArrayBufferView(bytes)) { + var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var len = src.byteLength - src.byteOffset; + this.accommodate(len); + var dst = new Uint8Array(this.data.buffer, this.write); + dst.set(src); + this.write += len; + return this; } - if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency > 0) { - util.cores = navigator.hardwareConcurrency; - return callback(null, util.cores); + if (util.isArrayBuffer(bytes)) { + var src = new Uint8Array(bytes); + this.accommodate(src.byteLength); + var dst = new Uint8Array(this.data.buffer); + dst.set(src, this.write); + this.write += src.byteLength; + return this; } - if (typeof Worker === "undefined") { - util.cores = 1; - return callback(null, util.cores); + if (bytes instanceof util.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util.isArrayBufferView(bytes.data)) { + var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); + this.accommodate(src.byteLength); + var dst = new Uint8Array(bytes.data.byteLength, this.write); + dst.set(src); + this.write += src.byteLength; + return this; } - if (typeof Blob === "undefined") { - util.cores = 2; - return callback(null, util.cores); + if (bytes instanceof util.ByteStringBuffer) { + bytes = bytes.data; + encoding = "binary"; } - var blobUrl = URL.createObjectURL(new Blob([ - "(", - function() { - self.addEventListener("message", function(e) { - var st = Date.now(); - var et = st + 4; - while (Date.now() < et) ; - self.postMessage({ st, et }); - }); - }.toString(), - ")()" - ], { type: "application/javascript" })); - sample([], 5, 16); - function sample(max, samples, numWorkers) { - if (samples === 0) { - var avg = Math.floor(max.reduce(function(avg2, x) { - return avg2 + x; - }, 0) / max.length); - util.cores = Math.max(1, avg); - URL.revokeObjectURL(blobUrl); - return callback(null, util.cores); + encoding = encoding || "binary"; + if (typeof bytes === "string") { + var view; + if (encoding === "hex") { + this.accommodate(Math.ceil(bytes.length / 2)); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.hex.decode(bytes, view, this.write); + return this; } - map2(numWorkers, function(err, results) { - max.push(reduce(numWorkers, results)); - sample(max, samples - 1, numWorkers); - }); - } - function map2(numWorkers, callback2) { - var workers = []; - var results = []; - for (var i = 0; i < numWorkers; ++i) { - var worker = new Worker(blobUrl); - worker.addEventListener("message", function(e) { - results.push(e.data); - if (results.length === numWorkers) { - for (var i2 = 0; i2 < numWorkers; ++i2) { - workers[i2].terminate(); - } - callback2(null, results); - } - }); - workers.push(worker); + if (encoding === "base64") { + this.accommodate(Math.ceil(bytes.length / 4) * 3); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.base64.decode(bytes, view, this.write); + return this; } - for (var i = 0; i < numWorkers; ++i) { - workers[i].postMessage(i); + if (encoding === "utf8") { + bytes = util.encodeUtf8(bytes); + encoding = "binary"; } - } - function reduce(numWorkers, results) { - var overlaps = []; - for (var n = 0; n < numWorkers; ++n) { - var r1 = results[n]; - var overlap = overlaps[n] = []; - for (var i = 0; i < numWorkers; ++i) { - if (n === i) { - continue; - } - var r2 = results[i]; - if (r1.st > r2.st && r1.st < r2.et || r2.st > r1.st && r2.st < r1.et) { - overlap.push(i); - } - } + if (encoding === "binary" || encoding === "raw") { + this.accommodate(bytes.length); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.raw.decode(view); + return this; } - return overlaps.reduce(function(max, overlap2) { - return Math.max(max, overlap2.length); - }, 0); - } - }; - } -}); - -// node_modules/node-forge/lib/cipher.js -var require_cipher = __commonJS({ - "node_modules/node-forge/lib/cipher.js"(exports2, module2) { - var forge = require_forge(); - require_util8(); - module2.exports = forge.cipher = forge.cipher || {}; - forge.cipher.algorithms = forge.cipher.algorithms || {}; - forge.cipher.createCipher = function(algorithm, key) { - var api = algorithm; - if (typeof api === "string") { - api = forge.cipher.getAlgorithm(api); - if (api) { - api = api(); + if (encoding === "utf16") { + this.accommodate(bytes.length * 2); + view = new Uint16Array(this.data.buffer, this.write); + this.write += util.text.utf16.encode(view); + return this; } + throw new Error("Invalid encoding: " + encoding); } - if (!api) { - throw new Error("Unsupported algorithm: " + algorithm); - } - return new forge.cipher.BlockCipher({ - algorithm: api, - key, - decrypt: false - }); + throw Error("Invalid parameter: " + bytes); }; - forge.cipher.createDecipher = function(algorithm, key) { - var api = algorithm; - if (typeof api === "string") { - api = forge.cipher.getAlgorithm(api); - if (api) { - api = api(); - } - } - if (!api) { - throw new Error("Unsupported algorithm: " + algorithm); - } - return new forge.cipher.BlockCipher({ - algorithm: api, - key, - decrypt: true - }); + util.DataBuffer.prototype.putBuffer = function(buffer) { + this.putBytes(buffer); + buffer.clear(); + return this; }; - forge.cipher.registerAlgorithm = function(name, algorithm) { - name = name.toUpperCase(); - forge.cipher.algorithms[name] = algorithm; + util.DataBuffer.prototype.putString = function(str2) { + return this.putBytes(str2, "utf16"); }; - forge.cipher.getAlgorithm = function(name) { - name = name.toUpperCase(); - if (name in forge.cipher.algorithms) { - return forge.cipher.algorithms[name]; - } - return null; + util.DataBuffer.prototype.putInt16 = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i); + this.write += 2; + return this; }; - var BlockCipher = forge.cipher.BlockCipher = function(options) { - this.algorithm = options.algorithm; - this.mode = this.algorithm.mode; - this.blockSize = this.mode.blockSize; - this._finish = false; - this._input = null; - this.output = null; - this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; - this._decrypt = options.decrypt; - this.algorithm.initialize(options); + util.DataBuffer.prototype.putInt24 = function(i) { + this.accommodate(3); + this.data.setInt16(this.write, i >> 8 & 65535); + this.data.setInt8(this.write, i >> 16 & 255); + this.write += 3; + return this; }; - BlockCipher.prototype.start = function(options) { - options = options || {}; - var opts = {}; - for (var key in options) { - opts[key] = options[key]; - } - opts.decrypt = this._decrypt; - this._finish = false; - this._input = forge.util.createBuffer(); - this.output = options.output || forge.util.createBuffer(); - this.mode.start(opts); + util.DataBuffer.prototype.putInt32 = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i); + this.write += 4; + return this; }; - BlockCipher.prototype.update = function(input) { - if (input) { - this._input.putBuffer(input); - } - while (!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) { - } - this._input.compact(); + util.DataBuffer.prototype.putInt16Le = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i, true); + this.write += 2; + return this; }; - BlockCipher.prototype.finish = function(pad) { - if (pad && (this.mode.name === "ECB" || this.mode.name === "CBC")) { - this.mode.pad = function(input) { - return pad(this.blockSize, input, false); - }; - this.mode.unpad = function(output) { - return pad(this.blockSize, output, true); - }; - } - var options = {}; - options.decrypt = this._decrypt; - options.overflow = this._input.length() % this.blockSize; - if (!this._decrypt && this.mode.pad) { - if (!this.mode.pad(this._input, options)) { - return false; - } - } - this._finish = true; - this.update(); - if (this._decrypt && this.mode.unpad) { - if (!this.mode.unpad(this.output, options)) { - return false; - } - } - if (this.mode.afterFinish) { - if (!this.mode.afterFinish(this.output, options)) { - return false; - } - } - return true; + util.DataBuffer.prototype.putInt24Le = function(i) { + this.accommodate(3); + this.data.setInt8(this.write, i >> 16 & 255); + this.data.setInt16(this.write, i >> 8 & 65535, true); + this.write += 3; + return this; }; - } -}); - -// node_modules/node-forge/lib/cipherModes.js -var require_cipherModes = __commonJS({ - "node_modules/node-forge/lib/cipherModes.js"(exports2, module2) { - var forge = require_forge(); - require_util8(); - forge.cipher = forge.cipher || {}; - var modes = module2.exports = forge.cipher.modes = forge.cipher.modes || {}; - modes.ecb = function(options) { - options = options || {}; - this.name = "ECB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); + util.DataBuffer.prototype.putInt32Le = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i, true); + this.write += 4; + return this; }; - modes.ecb.prototype.start = function(options) { + util.DataBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + do { + n -= 8; + this.data.setInt8(this.write++, i >> n & 255); + } while (n > 0); + return this; }; - modes.ecb.prototype.encrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.encrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); + util.DataBuffer.prototype.putSignedInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + if (i < 0) { + i += 2 << n - 1; } + return this.putInt(i, n); }; - modes.ecb.prototype.decrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.decrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } + util.DataBuffer.prototype.getByte = function() { + return this.data.getInt8(this.read++); }; - modes.ecb.prototype.pad = function(input, options) { - var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); - input.fillWithByte(padding, padding); - return true; + util.DataBuffer.prototype.getInt16 = function() { + var rval = this.data.getInt16(this.read); + this.read += 2; + return rval; }; - modes.ecb.prototype.unpad = function(output, options) { - if (options.overflow > 0) { - return false; - } - var len = output.length(); - var count = output.at(len - 1); - if (count > this.blockSize << 2) { - return false; - } - output.truncate(count); - return true; + util.DataBuffer.prototype.getInt24 = function() { + var rval = this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2); + this.read += 3; + return rval; }; - modes.cbc = function(options) { - options = options || {}; - this.name = "CBC"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); + util.DataBuffer.prototype.getInt32 = function() { + var rval = this.data.getInt32(this.read); + this.read += 4; + return rval; }; - modes.cbc.prototype.start = function(options) { - if (options.iv === null) { - if (!this._prev) { - throw new Error("Invalid IV parameter."); - } - this._iv = this._prev.slice(0); - } else if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } else { - this._iv = transformIV(options.iv, this.blockSize); - this._prev = this._iv.slice(0); - } + util.DataBuffer.prototype.getInt16Le = function() { + var rval = this.data.getInt16(this.read, true); + this.read += 2; + return rval; }; - modes.cbc.prototype.encrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._prev[i] ^ input.getInt32(); - } - this.cipher.encrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - this._prev = this._outBlock; + util.DataBuffer.prototype.getInt24Le = function() { + var rval = this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8; + this.read += 3; + return rval; }; - modes.cbc.prototype.decrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.decrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._prev[i] ^ this._outBlock[i]); - } - this._prev = this._inBlock.slice(0); + util.DataBuffer.prototype.getInt32Le = function() { + var rval = this.data.getInt32(this.read, true); + this.read += 4; + return rval; }; - modes.cbc.prototype.pad = function(input, options) { - var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); - input.fillWithByte(padding, padding); - return true; + util.DataBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + rval = (rval << 8) + this.data.getInt8(this.read++); + n -= 8; + } while (n > 0); + return rval; }; - modes.cbc.prototype.unpad = function(output, options) { - if (options.overflow > 0) { - return false; + util.DataBuffer.prototype.getSignedInt = function(n) { + var x = this.getInt(n); + var max = 2 << n - 2; + if (x >= max) { + x -= max << 1; } - var len = output.length(); - var count = output.at(len - 1); - if (count > this.blockSize << 2) { - return false; + return x; + }; + util.DataBuffer.prototype.getBytes = function(count) { + var rval; + if (count) { + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if (count === 0) { + rval = ""; + } else { + rval = this.read === 0 ? this.data : this.data.slice(this.read); + this.clear(); } - output.truncate(count); - return true; + return rval; }; - modes.cfb = function(options) { - options = options || {}; - this.name = "CFB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; + util.DataBuffer.prototype.bytes = function(count) { + return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); }; - modes.cfb.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; + util.DataBuffer.prototype.at = function(i) { + return this.data.getUint8(this.read + i); }; - modes.cfb.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; + util.DataBuffer.prototype.setAt = function(i, b) { + this.data.setUint8(i, b); + return this; + }; + util.DataBuffer.prototype.last = function() { + return this.data.getUint8(this.write - 1); + }; + util.DataBuffer.prototype.copy = function() { + return new util.DataBuffer(this); + }; + util.DataBuffer.prototype.compact = function() { + if (this.read > 0) { + var src = new Uint8Array(this.data.buffer, this.read); + var dst = new Uint8Array(src.byteLength); + dst.set(src); + this.data = new DataView(dst); + this.write -= this.read; + this.read = 0; } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; - output.putInt32(this._inBlock[i]); + return this; + }; + util.DataBuffer.prototype.clear = function() { + this.data = new DataView(new ArrayBuffer(0)); + this.read = this.write = 0; + return this; + }; + util.DataBuffer.prototype.truncate = function(count) { + this.write = Math.max(0, this.length() - count); + this.read = Math.min(this.read, this.write); + return this; + }; + util.DataBuffer.prototype.toHex = function() { + var rval = ""; + for (var i = this.read; i < this.data.byteLength; ++i) { + var b = this.data.getUint8(i); + if (b < 16) { + rval += "0"; } - return; + rval += b.toString(16); } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; + return rval; + }; + util.DataBuffer.prototype.toString = function(encoding) { + var view = new Uint8Array(this.data, this.read, this.length()); + encoding = encoding || "utf8"; + if (encoding === "binary" || encoding === "raw") { + return util.binary.raw.encode(view); } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; - this._partialOutput.putInt32(this._partialBlock[i]); + if (encoding === "hex") { + return util.binary.hex.encode(view); } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } + if (encoding === "base64") { + return util.binary.base64.encode(view); } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); + if (encoding === "utf8") { + return util.text.utf8.decode(view); } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; + if (encoding === "utf16") { + return util.text.utf16.decode(view); } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; + throw new Error("Invalid encoding: " + encoding); }; - modes.cfb.prototype.decrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; + util.createBuffer = function(input, encoding) { + encoding = encoding || "raw"; + if (input !== void 0 && encoding === "utf8") { + input = util.encodeUtf8(input); } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - output.putInt32(this._inBlock[i] ^ this._outBlock[i]); + return new util.ByteBuffer(input); + }; + util.fillString = function(c, n) { + var s = ""; + while (n > 0) { + if (n & 1) { + s += c; } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32(); - this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; + n >>>= 1; + if (n > 0) { + c += c; } } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; + return s; }; - modes.ofb = function(options) { - options = options || {}; - this.name = "OFB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; - }; - modes.ofb.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.ofb.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (input.length() === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - this._inBlock[i] = this._outBlock[i]; - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._outBlock[i]; + util.xorBytes = function(s1, s2, n) { + var s3 = ""; + var b = ""; + var t = ""; + var i = 0; + var c = 0; + for (; n > 0; --n, ++i) { + b = s1.charCodeAt(i) ^ s2.charCodeAt(i); + if (c >= 10) { + s3 += t; + t = ""; + c = 0; } + t += String.fromCharCode(b); + ++c; } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); + s3 += t; + return s3; + }; + util.hexToBytes = function(hex) { + var rval = ""; + var i = 0; + if (hex.length & true) { + i = 1; + rval += String.fromCharCode(parseInt(hex[0], 16)); } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; + for (; i < hex.length; i += 2) { + rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; + return rval; }; - modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; - modes.ctr = function(options) { - options = options || {}; - this.name = "CTR"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; + util.bytesToHex = function(bytes) { + return util.createBuffer(bytes).toHex(); }; - modes.ctr.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; + util.int32ToBytes = function(i) { + return String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255); }; - modes.ctr.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - } - } else { - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; + var _base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + var _base64Idx = [ + /*43 -43 = 0*/ + /*'+', 1, 2, 3,'/' */ + 62, + -1, + -1, + -1, + 63, + /*'0','1','2','3','4','5','6','7','8','9' */ + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + /*15, 16, 17,'=', 19, 20, 21 */ + -1, + -1, + -1, + 64, + -1, + -1, + -1, + /*65 - 43 = 22*/ + /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + /*91 - 43 = 48 */ + /*48, 49, 50, 51, 52, 53 */ + -1, + -1, + -1, + -1, + -1, + -1, + /*97 - 43 = 54*/ + /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51 + ]; + var _base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + util.encode64 = function(input, maxline) { + var line = ""; + var output = ""; + var chr1, chr2, chr3; + var i = 0; + while (i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); + if (isNaN(chr2)) { + line += "=="; + } else { + line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); + line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); + if (maxline && line.length > maxline) { + output += line.substr(0, maxline) + "\r\n"; + line = line.substr(maxline); } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; + } + output += line; + return output; + }; + util.decode64 = function(input) { + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + var output = ""; + var enc1, enc2, enc3, enc4; + var i = 0; + while (i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + output += String.fromCharCode(enc1 << 2 | enc2 >> 4); + if (enc3 !== 64) { + output += String.fromCharCode((enc2 & 15) << 4 | enc3 >> 2); + if (enc4 !== 64) { + output += String.fromCharCode((enc3 & 3) << 6 | enc4); + } } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; } - inc32(this._inBlock); + return output; }; - modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; - modes.gcm = function(options) { - options = options || {}; - this.name = "GCM"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - this._partialOutput = forge.util.createBuffer(); - this._partialBytes = 0; - this._R = 3774873600; + util.encodeUtf8 = function(str2) { + return unescape(encodeURIComponent(str2)); }; - modes.gcm.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - var iv = forge.util.createBuffer(options.iv); - this._cipherLength = 0; - var additionalData; - if ("additionalData" in options) { - additionalData = forge.util.createBuffer(options.additionalData); - } else { - additionalData = forge.util.createBuffer(); + util.decodeUtf8 = function(str2) { + return decodeURIComponent(escape(str2)); + }; + util.binary = { + raw: {}, + hex: {}, + base64: {}, + base58: {}, + baseN: { + encode: baseN.encode, + decode: baseN.decode } - if ("tagLength" in options) { - this._tagLength = options.tagLength; - } else { - this._tagLength = 128; + }; + util.binary.raw.encode = function(bytes) { + return String.fromCharCode.apply(null, bytes); + }; + util.binary.raw.decode = function(str2, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(str2.length); } - this._tag = null; - if (options.decrypt) { - this._tag = forge.util.createBuffer(options.tag).getBytes(); - if (this._tag.length !== this._tagLength / 8) { - throw new Error("Authentication tag does not match tag length."); - } + offset = offset || 0; + var j = offset; + for (var i = 0; i < str2.length; ++i) { + out[j++] = str2.charCodeAt(i); } - this._hashBlock = new Array(this._ints); - this.tag = null; - this._hashSubkey = new Array(this._ints); - this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); - this.componentBits = 4; - this._m = this.generateHashTable(this._hashSubkey, this.componentBits); - var ivLength = iv.length(); - if (ivLength === 12) { - this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; - } else { - this._j0 = [0, 0, 0, 0]; - while (iv.length() > 0) { - this._j0 = this.ghash( - this._hashSubkey, - this._j0, - [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()] - ); - } - this._j0 = this.ghash( - this._hashSubkey, - this._j0, - [0, 0].concat(from64To32(ivLength * 8)) - ); + return output ? j - offset : out; + }; + util.binary.hex.encode = util.bytesToHex; + util.binary.hex.decode = function(hex, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(Math.ceil(hex.length / 2)); } - this._inBlock = this._j0.slice(0); - inc32(this._inBlock); - this._partialBytes = 0; - additionalData = forge.util.createBuffer(additionalData); - this._aDataLength = from64To32(additionalData.length() * 8); - var overflow = additionalData.length() % this.blockSize; - if (overflow) { - additionalData.fillWithByte(0, this.blockSize - overflow); + offset = offset || 0; + var i = 0, j = offset; + if (hex.length & 1) { + i = 1; + out[j++] = parseInt(hex[0], 16); } - this._s = [0, 0, 0, 0]; - while (additionalData.length() > 0) { - this._s = this.ghash(this._hashSubkey, this._s, [ - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32() - ]); + for (; i < hex.length; i += 2) { + out[j++] = parseInt(hex.substr(i, 2), 16); } + return output ? j - offset : out; }; - modes.gcm.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^= input.getInt32()); - } - this._cipherLength += this.blockSize; - } else { - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; + util.binary.base64.encode = function(input, maxline) { + var line = ""; + var output = ""; + var chr1, chr2, chr3; + var i = 0; + while (i < input.byteLength) { + chr1 = input[i++]; + chr2 = input[i++]; + chr3 = input[i++]; + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); + if (isNaN(chr2)) { + line += "=="; + } else { + line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); + line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + if (maxline && line.length > maxline) { + output += line.substr(0, maxline) + "\r\n"; + line = line.substr(maxline); } - if (partialBytes <= 0 || finish) { - if (finish) { - var overflow = inputLength % this.blockSize; - this._cipherLength += overflow; - this._partialOutput.truncate(this.blockSize - overflow); - } else { - this._cipherLength += this.blockSize; - } - for (var i = 0; i < this._ints; ++i) { - this._outBlock[i] = this._partialOutput.getInt32(); + } + output += line; + return output; + }; + util.binary.base64.decode = function(input, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(Math.ceil(input.length / 4) * 3); + } + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + offset = offset || 0; + var enc1, enc2, enc3, enc4; + var i = 0, j = offset; + while (i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + out[j++] = enc1 << 2 | enc2 >> 4; + if (enc3 !== 64) { + out[j++] = (enc2 & 15) << 4 | enc3 >> 2; + if (enc4 !== 64) { + out[j++] = (enc3 & 3) << 6 | enc4; } - this._partialOutput.read -= this.blockSize; - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - input.read -= this.blockSize; - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; } - this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); - inc32(this._inBlock); + return output ? j - offset : out.subarray(0, j); }; - modes.gcm.prototype.decrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength < this.blockSize && !(finish && inputLength > 0)) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - inc32(this._inBlock); - this._hashBlock[0] = input.getInt32(); - this._hashBlock[1] = input.getInt32(); - this._hashBlock[2] = input.getInt32(); - this._hashBlock[3] = input.getInt32(); - this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); + util.binary.base58.encode = function(input, maxline) { + return util.binary.baseN.encode(input, _base58, maxline); + }; + util.binary.base58.decode = function(input, maxline) { + return util.binary.baseN.decode(input, _base58, maxline); + }; + util.text = { + utf8: {}, + utf16: {} + }; + util.text.utf8.encode = function(str2, output, offset) { + str2 = util.encodeUtf8(str2); + var out = output; + if (!out) { + out = new Uint8Array(str2.length); } - if (inputLength < this.blockSize) { - this._cipherLength += inputLength % this.blockSize; - } else { - this._cipherLength += this.blockSize; + offset = offset || 0; + var j = offset; + for (var i = 0; i < str2.length; ++i) { + out[j++] = str2.charCodeAt(i); } + return output ? j - offset : out; }; - modes.gcm.prototype.afterFinish = function(output, options) { - var rval = true; - if (options.decrypt && options.overflow) { - output.truncate(this.blockSize - options.overflow); - } - this.tag = forge.util.createBuffer(); - var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); - this._s = this.ghash(this._hashSubkey, this._s, lengths); - var tag = []; - this.cipher.encrypt(this._j0, tag); - for (var i = 0; i < this._ints; ++i) { - this.tag.putInt32(this._s[i] ^ tag[i]); + util.text.utf8.decode = function(bytes) { + return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); + }; + util.text.utf16.encode = function(str2, output, offset) { + var out = output; + if (!out) { + out = new Uint8Array(str2.length * 2); } - this.tag.truncate(this.tag.length() % (this._tagLength / 8)); - if (options.decrypt && this.tag.bytes() !== this._tag) { - rval = false; + var view = new Uint16Array(out.buffer); + offset = offset || 0; + var j = offset; + var k = offset; + for (var i = 0; i < str2.length; ++i) { + view[k++] = str2.charCodeAt(i); + j += 2; } - return rval; + return output ? j - offset : out; }; - modes.gcm.prototype.multiply = function(x, y) { - var z_i = [0, 0, 0, 0]; - var v_i = y.slice(0); - for (var i = 0; i < 128; ++i) { - var x_i = x[i / 32 | 0] & 1 << 31 - i % 32; - if (x_i) { - z_i[0] ^= v_i[0]; - z_i[1] ^= v_i[1]; - z_i[2] ^= v_i[2]; - z_i[3] ^= v_i[3]; + util.text.utf16.decode = function(bytes) { + return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); + }; + util.deflate = function(api, bytes, raw) { + bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); + if (raw) { + var start = 2; + var flg = bytes.charCodeAt(1); + if (flg & 32) { + start = 6; } - this.pow(v_i, v_i); + bytes = bytes.substring(start, bytes.length - 4); } - return z_i; + return bytes; }; - modes.gcm.prototype.pow = function(x, out) { - var lsb = x[3] & 1; - for (var i = 3; i > 0; --i) { - out[i] = x[i] >>> 1 | (x[i - 1] & 1) << 31; - } - out[0] = x[0] >>> 1; - if (lsb) { - out[0] ^= this._R; - } + util.inflate = function(api, bytes, raw) { + var rval = api.inflate(util.encode64(bytes)).rval; + return rval === null ? null : util.decode64(rval); }; - modes.gcm.prototype.tableMultiply = function(x) { - var z = [0, 0, 0, 0]; - for (var i = 0; i < 32; ++i) { - var idx = i / 8 | 0; - var x_i = x[idx] >>> (7 - i % 8) * 4 & 15; - var ah = this._m[i][x_i]; - z[0] ^= ah[0]; - z[1] ^= ah[1]; - z[2] ^= ah[2]; - z[3] ^= ah[3]; + var _setStorageObject = function(api, id, obj) { + if (!api) { + throw new Error("WebStorage not available."); } - return z; - }; - modes.gcm.prototype.ghash = function(h, y, x) { - y[0] ^= x[0]; - y[1] ^= x[1]; - y[2] ^= x[2]; - y[3] ^= x[3]; - return this.tableMultiply(y); - }; - modes.gcm.prototype.generateHashTable = function(h, bits) { - var multiplier = 8 / bits; - var perInt = 4 * multiplier; - var size = 16 * multiplier; - var m = new Array(size); - for (var i = 0; i < size; ++i) { - var tmp = [0, 0, 0, 0]; - var idx = i / perInt | 0; - var shft = (perInt - 1 - i % perInt) * bits; - tmp[idx] = 1 << bits - 1 << shft; - m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); + var rval; + if (obj === null) { + rval = api.removeItem(id); + } else { + obj = util.encode64(JSON.stringify(obj)); + rval = api.setItem(id, obj); + } + if (typeof rval !== "undefined" && rval.rval !== true) { + var error4 = new Error(rval.error.message); + error4.id = rval.error.id; + error4.name = rval.error.name; + throw error4; } - return m; }; - modes.gcm.prototype.generateSubHashTable = function(mid, bits) { - var size = 1 << bits; - var half = size >>> 1; - var m = new Array(size); - m[half] = mid.slice(0); - var i = half >>> 1; - while (i > 0) { - this.pow(m[2 * i], m[i] = []); - i >>= 1; + var _getStorageObject = function(api, id) { + if (!api) { + throw new Error("WebStorage not available."); } - i = 2; - while (i < half) { - for (var j = 1; j < i; ++j) { - var m_i = m[i]; - var m_j = m[j]; - m[i + j] = [ - m_i[0] ^ m_j[0], - m_i[1] ^ m_j[1], - m_i[2] ^ m_j[2], - m_i[3] ^ m_j[3] - ]; + var rval = api.getItem(id); + if (api.init) { + if (rval.rval === null) { + if (rval.error) { + var error4 = new Error(rval.error.message); + error4.id = rval.error.id; + error4.name = rval.error.name; + throw error4; + } + rval = null; + } else { + rval = rval.rval; } - i *= 2; } - m[0] = [0, 0, 0, 0]; - for (i = half + 1; i < size; ++i) { - var c = m[i ^ half]; - m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; + if (rval !== null) { + rval = JSON.parse(util.decode64(rval)); } - return m; + return rval; }; - function transformIV(iv, blockSize) { - if (typeof iv === "string") { - iv = forge.util.createBuffer(iv); + var _setItem = function(api, id, key, data) { + var obj = _getStorageObject(api, id); + if (obj === null) { + obj = {}; } - if (forge.util.isArray(iv) && iv.length > 4) { - var tmp = iv; - iv = forge.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - iv.putByte(tmp[i]); + obj[key] = data; + _setStorageObject(api, id, obj); + }; + var _getItem = function(api, id, key) { + var rval = _getStorageObject(api, id); + if (rval !== null) { + rval = key in rval ? rval[key] : null; + } + return rval; + }; + var _removeItem = function(api, id, key) { + var obj = _getStorageObject(api, id); + if (obj !== null && key in obj) { + delete obj[key]; + var empty = true; + for (var prop in obj) { + empty = false; + break; + } + if (empty) { + obj = null; } + _setStorageObject(api, id, obj); } - if (iv.length() < blockSize) { - throw new Error( - "Invalid IV length; got " + iv.length() + " bytes and expected " + blockSize + " bytes." - ); + }; + var _clearItems = function(api, id) { + _setStorageObject(api, id, null); + }; + var _callStorageFunction = function(func, args, location) { + var rval = null; + if (typeof location === "undefined") { + location = ["web", "flash"]; } - if (!forge.util.isArray(iv)) { - var ints = []; - var blocks = blockSize / 4; - for (var i = 0; i < blocks; ++i) { - ints.push(iv.getInt32()); + var type2; + var done = false; + var exception2 = null; + for (var idx in location) { + type2 = location[idx]; + try { + if (type2 === "flash" || type2 === "both") { + if (args[0] === null) { + throw new Error("Flash local storage not available."); + } + rval = func.apply(this, args); + done = type2 === "flash"; + } + if (type2 === "web" || type2 === "both") { + args[0] = localStorage; + rval = func.apply(this, args); + done = true; + } + } catch (ex) { + exception2 = ex; + } + if (done) { + break; } - iv = ints; } - return iv; - } - function inc32(block) { - block[block.length - 1] = block[block.length - 1] + 1 & 4294967295; - } - function from64To32(num) { - return [num / 4294967296 | 0, num & 4294967295]; - } - } -}); - -// node_modules/node-forge/lib/aes.js -var require_aes = __commonJS({ - "node_modules/node-forge/lib/aes.js"(exports2, module2) { - var forge = require_forge(); - require_cipher(); - require_cipherModes(); - require_util8(); - module2.exports = forge.aes = forge.aes || {}; - forge.aes.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: false, - mode - }); - cipher.start(iv); - return cipher; + if (!done) { + throw exception2; + } + return rval; }; - forge.aes.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: false, - mode - }); + util.setItem = function(api, id, key, data, location) { + _callStorageFunction(_setItem, arguments, location); }; - forge.aes.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: true, - mode - }); - cipher.start(iv); - return cipher; + util.getItem = function(api, id, key, location) { + return _callStorageFunction(_getItem, arguments, location); }; - forge.aes.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: true, - mode - }); + util.removeItem = function(api, id, key, location) { + _callStorageFunction(_removeItem, arguments, location); }; - forge.aes.Algorithm = function(name, mode) { - if (!init) { - initialize(); - } - var self2 = this; - self2.name = name; - self2.mode = new mode({ - blockSize: 16, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self2._w, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self2._w, inBlock, outBlock, true); - } - } - }); - self2._init = false; + util.clearItems = function(api, id, location) { + _callStorageFunction(_clearItems, arguments, location); }; - forge.aes.Algorithm.prototype.initialize = function(options) { - if (this._init) { - return; - } - var key = options.key; - var tmp; - if (typeof key === "string" && (key.length === 16 || key.length === 24 || key.length === 32)) { - key = forge.util.createBuffer(key); - } else if (forge.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { - tmp = key; - key = forge.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); + util.isEmpty = function(obj) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + return false; } } - if (!forge.util.isArray(key)) { - tmp = key; - key = []; - var len = tmp.length(); - if (len === 16 || len === 24 || len === 32) { - len = len >>> 2; - for (var i = 0; i < len; ++i) { - key.push(tmp.getInt32()); - } + return true; + }; + util.format = function(format) { + var re = /%./g; + var match; + var part; + var argi = 0; + var parts = []; + var last = 0; + while (match = re.exec(format)) { + part = format.substring(last, re.lastIndex - 2); + if (part.length > 0) { + parts.push(part); + } + last = re.lastIndex; + var code = match[0][1]; + switch (code) { + case "s": + case "o": + if (argi < arguments.length) { + parts.push(arguments[argi++ + 1]); + } else { + parts.push(""); + } + break; + // FIXME: do proper formating for numbers, etc + //case 'f': + //case 'd': + case "%": + parts.push("%"); + break; + default: + parts.push("<%" + code + "?>"); } } - if (!forge.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) { - throw new Error("Invalid key parameter."); + parts.push(format.substring(last)); + return parts.join(""); + }; + util.formatNumber = function(number, decimals, dec_point, thousands_sep) { + var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; + var d = dec_point === void 0 ? "," : dec_point; + var t = thousands_sep === void 0 ? "." : thousands_sep, s = n < 0 ? "-" : ""; + var i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + ""; + var j = i.length > 3 ? i.length % 3 : 0; + return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); + }; + util.formatSize = function(size) { + if (size >= 1073741824) { + size = util.formatNumber(size / 1073741824, 2, ".", "") + " GiB"; + } else if (size >= 1048576) { + size = util.formatNumber(size / 1048576, 2, ".", "") + " MiB"; + } else if (size >= 1024) { + size = util.formatNumber(size / 1024, 0) + " KiB"; + } else { + size = util.formatNumber(size, 0) + " bytes"; } - var mode = this.mode.name; - var encryptOp = ["CFB", "OFB", "CTR", "GCM"].indexOf(mode) !== -1; - this._w = _expandKey(key, options.decrypt && !encryptOp); - this._init = true; + return size; }; - forge.aes._expandKey = function(key, decrypt) { - if (!init) { - initialize(); + util.bytesFromIP = function(ip) { + if (ip.indexOf(".") !== -1) { + return util.bytesFromIPv4(ip); } - return _expandKey(key, decrypt); + if (ip.indexOf(":") !== -1) { + return util.bytesFromIPv6(ip); + } + return null; }; - forge.aes._updateBlock = _updateBlock; - registerAlgorithm("AES-ECB", forge.cipher.modes.ecb); - registerAlgorithm("AES-CBC", forge.cipher.modes.cbc); - registerAlgorithm("AES-CFB", forge.cipher.modes.cfb); - registerAlgorithm("AES-OFB", forge.cipher.modes.ofb); - registerAlgorithm("AES-CTR", forge.cipher.modes.ctr); - registerAlgorithm("AES-GCM", forge.cipher.modes.gcm); - function registerAlgorithm(name, mode) { - var factory = function() { - return new forge.aes.Algorithm(name, mode); - }; - forge.cipher.registerAlgorithm(name, factory); - } - var init = false; - var Nb = 4; - var sbox; - var isbox; - var rcon; - var mix; - var imix; - function initialize() { - init = true; - rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; - var xtime = new Array(256); - for (var i = 0; i < 128; ++i) { - xtime[i] = i << 1; - xtime[i + 128] = i + 128 << 1 ^ 283; + util.bytesFromIPv4 = function(ip) { + ip = ip.split("."); + if (ip.length !== 4) { + return null; } - sbox = new Array(256); - isbox = new Array(256); - mix = new Array(4); - imix = new Array(4); - for (var i = 0; i < 4; ++i) { - mix[i] = new Array(256); - imix[i] = new Array(256); + var b = util.createBuffer(); + for (var i = 0; i < ip.length; ++i) { + var num = parseInt(ip[i], 10); + if (isNaN(num)) { + return null; + } + b.putByte(num); } - var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; - for (var i = 0; i < 256; ++i) { - sx = ei ^ ei << 1 ^ ei << 2 ^ ei << 3 ^ ei << 4; - sx = sx >> 8 ^ sx & 255 ^ 99; - sbox[e] = sx; - isbox[sx] = e; - sx2 = xtime[sx]; - e2 = xtime[e]; - e4 = xtime[e2]; - e8 = xtime[e4]; - me = sx2 << 24 ^ // 2 - sx << 16 ^ // 1 - sx << 8 ^ // 1 - (sx ^ sx2); - ime = (e2 ^ e4 ^ e8) << 24 ^ // E (14) - (e ^ e8) << 16 ^ // 9 - (e ^ e4 ^ e8) << 8 ^ // D (13) - (e ^ e2 ^ e8); - for (var n = 0; n < 4; ++n) { - mix[n][e] = me; - imix[n][sx] = ime; - me = me << 24 | me >>> 8; - ime = ime << 24 | ime >>> 8; + return b.getBytes(); + }; + util.bytesFromIPv6 = function(ip) { + var blanks = 0; + ip = ip.split(":").filter(function(e) { + if (e.length === 0) ++blanks; + return true; + }); + var zeros = (8 - ip.length + blanks) * 2; + var b = util.createBuffer(); + for (var i = 0; i < 8; ++i) { + if (!ip[i] || ip[i].length === 0) { + b.fillWithByte(0, zeros); + zeros = 0; + continue; } - if (e === 0) { - e = ei = 1; - } else { - e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; - ei ^= xtime[xtime[ei]]; + var bytes = util.hexToBytes(ip[i]); + if (bytes.length < 2) { + b.putByte(0); } + b.putBytes(bytes); } - } - function _expandKey(key, decrypt) { - var w = key.slice(0); - var temp, iNk = 1; - var Nk = w.length; - var Nr1 = Nk + 6 + 1; - var end = Nb * Nr1; - for (var i = Nk; i < end; ++i) { - temp = w[i - 1]; - if (i % Nk === 0) { - temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ rcon[iNk] << 24; - iNk++; - } else if (Nk > 6 && i % Nk === 4) { - temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255]; - } - w[i] = w[i - Nk] ^ temp; + return b.getBytes(); + }; + util.bytesToIP = function(bytes) { + if (bytes.length === 4) { + return util.bytesToIPv4(bytes); } - if (decrypt) { - var tmp; - var m0 = imix[0]; - var m1 = imix[1]; - var m2 = imix[2]; - var m3 = imix[3]; - var wnew = w.slice(0); - end = w.length; - for (var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { - if (i === 0 || i === end - Nb) { - wnew[i] = w[wi]; - wnew[i + 1] = w[wi + 3]; - wnew[i + 2] = w[wi + 2]; - wnew[i + 3] = w[wi + 1]; + if (bytes.length === 16) { + return util.bytesToIPv6(bytes); + } + return null; + }; + util.bytesToIPv4 = function(bytes) { + if (bytes.length !== 4) { + return null; + } + var ip = []; + for (var i = 0; i < bytes.length; ++i) { + ip.push(bytes.charCodeAt(i)); + } + return ip.join("."); + }; + util.bytesToIPv6 = function(bytes) { + if (bytes.length !== 16) { + return null; + } + var ip = []; + var zeroGroups = []; + var zeroMaxGroup = 0; + for (var i = 0; i < bytes.length; i += 2) { + var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); + while (hex[0] === "0" && hex !== "0") { + hex = hex.substr(1); + } + if (hex === "0") { + var last = zeroGroups[zeroGroups.length - 1]; + var idx = ip.length; + if (!last || idx !== last.end + 1) { + zeroGroups.push({ start: idx, end: idx }); } else { - for (var n = 0; n < Nb; ++n) { - tmp = w[wi + n]; - wnew[i + (3 & -n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; + last.end = idx; + if (last.end - last.start > zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start) { + zeroMaxGroup = zeroGroups.length - 1; } } } - w = wnew; + ip.push(hex); } - return w; - } - function _updateBlock(w, input, output, decrypt) { - var Nr = w.length / 4 - 1; - var m0, m1, m2, m3, sub; - if (decrypt) { - m0 = imix[0]; - m1 = imix[1]; - m2 = imix[2]; - m3 = imix[3]; - sub = isbox; - } else { - m0 = mix[0]; - m1 = mix[1]; - m2 = mix[2]; - m3 = mix[3]; - sub = sbox; + if (zeroGroups.length > 0) { + var group = zeroGroups[zeroMaxGroup]; + if (group.end - group.start > 0) { + ip.splice(group.start, group.end - group.start + 1, ""); + if (group.start === 0) { + ip.unshift(""); + } + if (group.end === 7) { + ip.push(""); + } + } } - var a, b, c, d, a2, b2, c2; - a = input[0] ^ w[0]; - b = input[decrypt ? 3 : 1] ^ w[1]; - c = input[2] ^ w[2]; - d = input[decrypt ? 1 : 3] ^ w[3]; - var i = 3; - for (var round = 1; round < Nr; ++round) { - a2 = m0[a >>> 24] ^ m1[b >>> 16 & 255] ^ m2[c >>> 8 & 255] ^ m3[d & 255] ^ w[++i]; - b2 = m0[b >>> 24] ^ m1[c >>> 16 & 255] ^ m2[d >>> 8 & 255] ^ m3[a & 255] ^ w[++i]; - c2 = m0[c >>> 24] ^ m1[d >>> 16 & 255] ^ m2[a >>> 8 & 255] ^ m3[b & 255] ^ w[++i]; - d = m0[d >>> 24] ^ m1[a >>> 16 & 255] ^ m2[b >>> 8 & 255] ^ m3[c & 255] ^ w[++i]; - a = a2; - b = b2; - c = c2; + return ip.join(":"); + }; + util.estimateCores = function(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; } - output[0] = sub[a >>> 24] << 24 ^ sub[b >>> 16 & 255] << 16 ^ sub[c >>> 8 & 255] << 8 ^ sub[d & 255] ^ w[++i]; - output[decrypt ? 3 : 1] = sub[b >>> 24] << 24 ^ sub[c >>> 16 & 255] << 16 ^ sub[d >>> 8 & 255] << 8 ^ sub[a & 255] ^ w[++i]; - output[2] = sub[c >>> 24] << 24 ^ sub[d >>> 16 & 255] << 16 ^ sub[a >>> 8 & 255] << 8 ^ sub[b & 255] ^ w[++i]; - output[decrypt ? 1 : 3] = sub[d >>> 24] << 24 ^ sub[a >>> 16 & 255] << 16 ^ sub[b >>> 8 & 255] << 8 ^ sub[c & 255] ^ w[++i]; - } - function _createCipher(options) { options = options || {}; - var mode = (options.mode || "CBC").toUpperCase(); - var algorithm = "AES-" + mode; - var cipher; - if (options.decrypt) { - cipher = forge.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge.cipher.createCipher(algorithm, options.key); + if ("cores" in util && !options.update) { + return callback(null, util.cores); } - var start = cipher.start; - cipher.start = function(iv, options2) { - var output = null; - if (options2 instanceof forge.util.ByteBuffer) { - output = options2; - options2 = {}; + if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency > 0) { + util.cores = navigator.hardwareConcurrency; + return callback(null, util.cores); + } + if (typeof Worker === "undefined") { + util.cores = 1; + return callback(null, util.cores); + } + if (typeof Blob === "undefined") { + util.cores = 2; + return callback(null, util.cores); + } + var blobUrl = URL.createObjectURL(new Blob([ + "(", + function() { + self.addEventListener("message", function(e) { + var st = Date.now(); + var et = st + 4; + while (Date.now() < et) ; + self.postMessage({ st, et }); + }); + }.toString(), + ")()" + ], { type: "application/javascript" })); + sample([], 5, 16); + function sample(max, samples, numWorkers) { + if (samples === 0) { + var avg = Math.floor(max.reduce(function(avg2, x) { + return avg2 + x; + }, 0) / max.length); + util.cores = Math.max(1, avg); + URL.revokeObjectURL(blobUrl); + return callback(null, util.cores); } - options2 = options2 || {}; - options2.output = output; - options2.iv = iv; - start.call(cipher, options2); - }; - return cipher; - } - } -}); - -// node_modules/node-forge/lib/oids.js -var require_oids = __commonJS({ - "node_modules/node-forge/lib/oids.js"(exports2, module2) { - var forge = require_forge(); - forge.pki = forge.pki || {}; - var oids = module2.exports = forge.pki.oids = forge.oids = forge.oids || {}; - function _IN(id, name) { - oids[id] = name; - oids[name] = id; - } - function _I_(id, name) { - oids[id] = name; - } - _IN("1.2.840.113549.1.1.1", "rsaEncryption"); - _IN("1.2.840.113549.1.1.4", "md5WithRSAEncryption"); - _IN("1.2.840.113549.1.1.5", "sha1WithRSAEncryption"); - _IN("1.2.840.113549.1.1.7", "RSAES-OAEP"); - _IN("1.2.840.113549.1.1.8", "mgf1"); - _IN("1.2.840.113549.1.1.9", "pSpecified"); - _IN("1.2.840.113549.1.1.10", "RSASSA-PSS"); - _IN("1.2.840.113549.1.1.11", "sha256WithRSAEncryption"); - _IN("1.2.840.113549.1.1.12", "sha384WithRSAEncryption"); - _IN("1.2.840.113549.1.1.13", "sha512WithRSAEncryption"); - _IN("1.3.101.112", "EdDSA25519"); - _IN("1.2.840.10040.4.3", "dsa-with-sha1"); - _IN("1.3.14.3.2.7", "desCBC"); - _IN("1.3.14.3.2.26", "sha1"); - _IN("1.3.14.3.2.29", "sha1WithRSASignature"); - _IN("2.16.840.1.101.3.4.2.1", "sha256"); - _IN("2.16.840.1.101.3.4.2.2", "sha384"); - _IN("2.16.840.1.101.3.4.2.3", "sha512"); - _IN("2.16.840.1.101.3.4.2.4", "sha224"); - _IN("2.16.840.1.101.3.4.2.5", "sha512-224"); - _IN("2.16.840.1.101.3.4.2.6", "sha512-256"); - _IN("1.2.840.113549.2.2", "md2"); - _IN("1.2.840.113549.2.5", "md5"); - _IN("1.2.840.113549.1.7.1", "data"); - _IN("1.2.840.113549.1.7.2", "signedData"); - _IN("1.2.840.113549.1.7.3", "envelopedData"); - _IN("1.2.840.113549.1.7.4", "signedAndEnvelopedData"); - _IN("1.2.840.113549.1.7.5", "digestedData"); - _IN("1.2.840.113549.1.7.6", "encryptedData"); - _IN("1.2.840.113549.1.9.1", "emailAddress"); - _IN("1.2.840.113549.1.9.2", "unstructuredName"); - _IN("1.2.840.113549.1.9.3", "contentType"); - _IN("1.2.840.113549.1.9.4", "messageDigest"); - _IN("1.2.840.113549.1.9.5", "signingTime"); - _IN("1.2.840.113549.1.9.6", "counterSignature"); - _IN("1.2.840.113549.1.9.7", "challengePassword"); - _IN("1.2.840.113549.1.9.8", "unstructuredAddress"); - _IN("1.2.840.113549.1.9.14", "extensionRequest"); - _IN("1.2.840.113549.1.9.20", "friendlyName"); - _IN("1.2.840.113549.1.9.21", "localKeyId"); - _IN("1.2.840.113549.1.9.22.1", "x509Certificate"); - _IN("1.2.840.113549.1.12.10.1.1", "keyBag"); - _IN("1.2.840.113549.1.12.10.1.2", "pkcs8ShroudedKeyBag"); - _IN("1.2.840.113549.1.12.10.1.3", "certBag"); - _IN("1.2.840.113549.1.12.10.1.4", "crlBag"); - _IN("1.2.840.113549.1.12.10.1.5", "secretBag"); - _IN("1.2.840.113549.1.12.10.1.6", "safeContentsBag"); - _IN("1.2.840.113549.1.5.13", "pkcs5PBES2"); - _IN("1.2.840.113549.1.5.12", "pkcs5PBKDF2"); - _IN("1.2.840.113549.1.12.1.1", "pbeWithSHAAnd128BitRC4"); - _IN("1.2.840.113549.1.12.1.2", "pbeWithSHAAnd40BitRC4"); - _IN("1.2.840.113549.1.12.1.3", "pbeWithSHAAnd3-KeyTripleDES-CBC"); - _IN("1.2.840.113549.1.12.1.4", "pbeWithSHAAnd2-KeyTripleDES-CBC"); - _IN("1.2.840.113549.1.12.1.5", "pbeWithSHAAnd128BitRC2-CBC"); - _IN("1.2.840.113549.1.12.1.6", "pbewithSHAAnd40BitRC2-CBC"); - _IN("1.2.840.113549.2.7", "hmacWithSHA1"); - _IN("1.2.840.113549.2.8", "hmacWithSHA224"); - _IN("1.2.840.113549.2.9", "hmacWithSHA256"); - _IN("1.2.840.113549.2.10", "hmacWithSHA384"); - _IN("1.2.840.113549.2.11", "hmacWithSHA512"); - _IN("1.2.840.113549.3.7", "des-EDE3-CBC"); - _IN("2.16.840.1.101.3.4.1.2", "aes128-CBC"); - _IN("2.16.840.1.101.3.4.1.22", "aes192-CBC"); - _IN("2.16.840.1.101.3.4.1.42", "aes256-CBC"); - _IN("2.5.4.3", "commonName"); - _IN("2.5.4.4", "surname"); - _IN("2.5.4.5", "serialNumber"); - _IN("2.5.4.6", "countryName"); - _IN("2.5.4.7", "localityName"); - _IN("2.5.4.8", "stateOrProvinceName"); - _IN("2.5.4.9", "streetAddress"); - _IN("2.5.4.10", "organizationName"); - _IN("2.5.4.11", "organizationalUnitName"); - _IN("2.5.4.12", "title"); - _IN("2.5.4.13", "description"); - _IN("2.5.4.15", "businessCategory"); - _IN("2.5.4.17", "postalCode"); - _IN("2.5.4.42", "givenName"); - _IN("1.3.6.1.4.1.311.60.2.1.2", "jurisdictionOfIncorporationStateOrProvinceName"); - _IN("1.3.6.1.4.1.311.60.2.1.3", "jurisdictionOfIncorporationCountryName"); - _IN("2.16.840.1.113730.1.1", "nsCertType"); - _IN("2.16.840.1.113730.1.13", "nsComment"); - _I_("2.5.29.1", "authorityKeyIdentifier"); - _I_("2.5.29.2", "keyAttributes"); - _I_("2.5.29.3", "certificatePolicies"); - _I_("2.5.29.4", "keyUsageRestriction"); - _I_("2.5.29.5", "policyMapping"); - _I_("2.5.29.6", "subtreesConstraint"); - _I_("2.5.29.7", "subjectAltName"); - _I_("2.5.29.8", "issuerAltName"); - _I_("2.5.29.9", "subjectDirectoryAttributes"); - _I_("2.5.29.10", "basicConstraints"); - _I_("2.5.29.11", "nameConstraints"); - _I_("2.5.29.12", "policyConstraints"); - _I_("2.5.29.13", "basicConstraints"); - _IN("2.5.29.14", "subjectKeyIdentifier"); - _IN("2.5.29.15", "keyUsage"); - _I_("2.5.29.16", "privateKeyUsagePeriod"); - _IN("2.5.29.17", "subjectAltName"); - _IN("2.5.29.18", "issuerAltName"); - _IN("2.5.29.19", "basicConstraints"); - _I_("2.5.29.20", "cRLNumber"); - _I_("2.5.29.21", "cRLReason"); - _I_("2.5.29.22", "expirationDate"); - _I_("2.5.29.23", "instructionCode"); - _I_("2.5.29.24", "invalidityDate"); - _I_("2.5.29.25", "cRLDistributionPoints"); - _I_("2.5.29.26", "issuingDistributionPoint"); - _I_("2.5.29.27", "deltaCRLIndicator"); - _I_("2.5.29.28", "issuingDistributionPoint"); - _I_("2.5.29.29", "certificateIssuer"); - _I_("2.5.29.30", "nameConstraints"); - _IN("2.5.29.31", "cRLDistributionPoints"); - _IN("2.5.29.32", "certificatePolicies"); - _I_("2.5.29.33", "policyMappings"); - _I_("2.5.29.34", "policyConstraints"); - _IN("2.5.29.35", "authorityKeyIdentifier"); - _I_("2.5.29.36", "policyConstraints"); - _IN("2.5.29.37", "extKeyUsage"); - _I_("2.5.29.46", "freshestCRL"); - _I_("2.5.29.54", "inhibitAnyPolicy"); - _IN("1.3.6.1.4.1.11129.2.4.2", "timestampList"); - _IN("1.3.6.1.5.5.7.1.1", "authorityInfoAccess"); - _IN("1.3.6.1.5.5.7.3.1", "serverAuth"); - _IN("1.3.6.1.5.5.7.3.2", "clientAuth"); - _IN("1.3.6.1.5.5.7.3.3", "codeSigning"); - _IN("1.3.6.1.5.5.7.3.4", "emailProtection"); - _IN("1.3.6.1.5.5.7.3.8", "timeStamping"); + map2(numWorkers, function(err, results) { + max.push(reduce(numWorkers, results)); + sample(max, samples - 1, numWorkers); + }); + } + function map2(numWorkers, callback2) { + var workers = []; + var results = []; + for (var i = 0; i < numWorkers; ++i) { + var worker = new Worker(blobUrl); + worker.addEventListener("message", function(e) { + results.push(e.data); + if (results.length === numWorkers) { + for (var i2 = 0; i2 < numWorkers; ++i2) { + workers[i2].terminate(); + } + callback2(null, results); + } + }); + workers.push(worker); + } + for (var i = 0; i < numWorkers; ++i) { + workers[i].postMessage(i); + } + } + function reduce(numWorkers, results) { + var overlaps = []; + for (var n = 0; n < numWorkers; ++n) { + var r1 = results[n]; + var overlap = overlaps[n] = []; + for (var i = 0; i < numWorkers; ++i) { + if (n === i) { + continue; + } + var r2 = results[i]; + if (r1.st > r2.st && r1.st < r2.et || r2.st > r1.st && r2.st < r1.et) { + overlap.push(i); + } + } + } + return overlaps.reduce(function(max, overlap2) { + return Math.max(max, overlap2.length); + }, 0); + } + }; } }); -// node_modules/node-forge/lib/asn1.js -var require_asn1 = __commonJS({ - "node_modules/node-forge/lib/asn1.js"(exports2, module2) { +// node_modules/node-forge/lib/cipher.js +var require_cipher = __commonJS({ + "node_modules/node-forge/lib/cipher.js"(exports2, module2) { var forge = require_forge(); require_util8(); - require_oids(); - var asn1 = module2.exports = forge.asn1 = forge.asn1 || {}; - asn1.Class = { - UNIVERSAL: 0, - APPLICATION: 64, - CONTEXT_SPECIFIC: 128, - PRIVATE: 192 - }; - asn1.Type = { - NONE: 0, - BOOLEAN: 1, - INTEGER: 2, - BITSTRING: 3, - OCTETSTRING: 4, - NULL: 5, - OID: 6, - ODESC: 7, - EXTERNAL: 8, - REAL: 9, - ENUMERATED: 10, - EMBEDDED: 11, - UTF8: 12, - ROID: 13, - SEQUENCE: 16, - SET: 17, - PRINTABLESTRING: 19, - IA5STRING: 22, - UTCTIME: 23, - GENERALIZEDTIME: 24, - BMPSTRING: 30 - }; - asn1.create = function(tagClass, type2, constructed, value, options) { - if (forge.util.isArray(value)) { - var tmp = []; - for (var i = 0; i < value.length; ++i) { - if (value[i] !== void 0) { - tmp.push(value[i]); - } + module2.exports = forge.cipher = forge.cipher || {}; + forge.cipher.algorithms = forge.cipher.algorithms || {}; + forge.cipher.createCipher = function(algorithm, key) { + var api = algorithm; + if (typeof api === "string") { + api = forge.cipher.getAlgorithm(api); + if (api) { + api = api(); } - value = tmp; } - var obj = { - tagClass, - type: type2, - constructed, - composed: constructed || forge.util.isArray(value), - value - }; - if (options && "bitStringContents" in options) { - obj.bitStringContents = options.bitStringContents; - obj.original = asn1.copy(obj); + if (!api) { + throw new Error("Unsupported algorithm: " + algorithm); } - return obj; + return new forge.cipher.BlockCipher({ + algorithm: api, + key, + decrypt: false + }); }; - asn1.copy = function(obj, options) { - var copy; - if (forge.util.isArray(obj)) { - copy = []; - for (var i = 0; i < obj.length; ++i) { - copy.push(asn1.copy(obj[i], options)); + forge.cipher.createDecipher = function(algorithm, key) { + var api = algorithm; + if (typeof api === "string") { + api = forge.cipher.getAlgorithm(api); + if (api) { + api = api(); } - return copy; - } - if (typeof obj === "string") { - return obj; } - copy = { - tagClass: obj.tagClass, - type: obj.type, - constructed: obj.constructed, - composed: obj.composed, - value: asn1.copy(obj.value, options) - }; - if (options && !options.excludeBitStringContents) { - copy.bitStringContents = obj.bitStringContents; + if (!api) { + throw new Error("Unsupported algorithm: " + algorithm); } - return copy; + return new forge.cipher.BlockCipher({ + algorithm: api, + key, + decrypt: true + }); }; - asn1.equals = function(obj1, obj2, options) { - if (forge.util.isArray(obj1)) { - if (!forge.util.isArray(obj2)) { - return false; - } - if (obj1.length !== obj2.length) { - return false; - } - for (var i = 0; i < obj1.length; ++i) { - if (!asn1.equals(obj1[i], obj2[i])) { - return false; - } - } - return true; - } - if (typeof obj1 !== typeof obj2) { - return false; - } - if (typeof obj1 === "string") { - return obj1 === obj2; - } - var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value); - if (options && options.includeBitStringContents) { - equal = equal && obj1.bitStringContents === obj2.bitStringContents; - } - return equal; + forge.cipher.registerAlgorithm = function(name, algorithm) { + name = name.toUpperCase(); + forge.cipher.algorithms[name] = algorithm; }; - asn1.getBerValueLength = function(b) { - var b2 = b.getByte(); - if (b2 === 128) { - return void 0; - } - var length; - var longForm = b2 & 128; - if (!longForm) { - length = b2; - } else { - length = b.getInt((b2 & 127) << 3); + forge.cipher.getAlgorithm = function(name) { + name = name.toUpperCase(); + if (name in forge.cipher.algorithms) { + return forge.cipher.algorithms[name]; } - return length; + return null; }; - function _checkBufferLength(bytes, remaining, n) { - if (n > remaining) { - var error4 = new Error("Too few bytes to parse DER."); - error4.available = bytes.length(); - error4.remaining = remaining; - error4.requested = n; - throw error4; - } - } - var _getValueLength = function(bytes, remaining) { - var b2 = bytes.getByte(); - remaining--; - if (b2 === 128) { - return void 0; + var BlockCipher = forge.cipher.BlockCipher = function(options) { + this.algorithm = options.algorithm; + this.mode = this.algorithm.mode; + this.blockSize = this.mode.blockSize; + this._finish = false; + this._input = null; + this.output = null; + this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; + this._decrypt = options.decrypt; + this.algorithm.initialize(options); + }; + BlockCipher.prototype.start = function(options) { + options = options || {}; + var opts = {}; + for (var key in options) { + opts[key] = options[key]; } - var length; - var longForm = b2 & 128; - if (!longForm) { - length = b2; - } else { - var longFormBytes = b2 & 127; - _checkBufferLength(bytes, remaining, longFormBytes); - length = bytes.getInt(longFormBytes << 3); + opts.decrypt = this._decrypt; + this._finish = false; + this._input = forge.util.createBuffer(); + this.output = options.output || forge.util.createBuffer(); + this.mode.start(opts); + }; + BlockCipher.prototype.update = function(input) { + if (input) { + this._input.putBuffer(input); } - if (length < 0) { - throw new Error("Negative length: " + length); + while (!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) { } - return length; + this._input.compact(); }; - asn1.fromDer = function(bytes, options) { - if (options === void 0) { - options = { - strict: true, - parseAllBytes: true, - decodeBitStrings: true + BlockCipher.prototype.finish = function(pad) { + if (pad && (this.mode.name === "ECB" || this.mode.name === "CBC")) { + this.mode.pad = function(input) { + return pad(this.blockSize, input, false); }; - } - if (typeof options === "boolean") { - options = { - strict: options, - parseAllBytes: true, - decodeBitStrings: true + this.mode.unpad = function(output) { + return pad(this.blockSize, output, true); }; } - if (!("strict" in options)) { - options.strict = true; - } - if (!("parseAllBytes" in options)) { - options.parseAllBytes = true; - } - if (!("decodeBitStrings" in options)) { - options.decodeBitStrings = true; - } - if (typeof bytes === "string") { - bytes = forge.util.createBuffer(bytes); - } - var byteCount = bytes.length(); - var value = _fromDer(bytes, bytes.length(), 0, options); - if (options.parseAllBytes && bytes.length() !== 0) { - var error4 = new Error("Unparsed DER bytes remain after ASN.1 parsing."); - error4.byteCount = byteCount; - error4.remaining = bytes.length(); - throw error4; - } - return value; - }; - function _fromDer(bytes, remaining, depth, options) { - var start; - _checkBufferLength(bytes, remaining, 2); - var b1 = bytes.getByte(); - remaining--; - var tagClass = b1 & 192; - var type2 = b1 & 31; - start = bytes.length(); - var length = _getValueLength(bytes, remaining); - remaining -= start - bytes.length(); - if (length !== void 0 && length > remaining) { - if (options.strict) { - var error4 = new Error("Too few bytes to read ASN.1 value."); - error4.available = bytes.length(); - error4.remaining = remaining; - error4.requested = length; - throw error4; - } - length = remaining; - } - var value; - var bitStringContents; - var constructed = (b1 & 32) === 32; - if (constructed) { - value = []; - if (length === void 0) { - for (; ; ) { - _checkBufferLength(bytes, remaining, 2); - if (bytes.bytes(2) === String.fromCharCode(0, 0)) { - bytes.getBytes(2); - remaining -= 2; - break; - } - start = bytes.length(); - value.push(_fromDer(bytes, remaining, depth + 1, options)); - remaining -= start - bytes.length(); - } - } else { - while (length > 0) { - start = bytes.length(); - value.push(_fromDer(bytes, length, depth + 1, options)); - remaining -= start - bytes.length(); - length -= start - bytes.length(); - } + var options = {}; + options.decrypt = this._decrypt; + options.overflow = this._input.length() % this.blockSize; + if (!this._decrypt && this.mode.pad) { + if (!this.mode.pad(this._input, options)) { + return false; } } - if (value === void 0 && tagClass === asn1.Class.UNIVERSAL && type2 === asn1.Type.BITSTRING) { - bitStringContents = bytes.bytes(length); - } - if (value === void 0 && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && // FIXME: OCTET STRINGs not yet supported here - // .. other parts of forge expect to decode OCTET STRINGs manually - type2 === asn1.Type.BITSTRING && length > 1) { - var savedRead = bytes.read; - var savedRemaining = remaining; - var unused = 0; - if (type2 === asn1.Type.BITSTRING) { - _checkBufferLength(bytes, remaining, 1); - unused = bytes.getByte(); - remaining--; - } - if (unused === 0) { - try { - start = bytes.length(); - var subOptions = { - // enforce strict mode to avoid parsing ASN.1 from plain data - strict: true, - decodeBitStrings: true - }; - var composed = _fromDer(bytes, remaining, depth + 1, subOptions); - var used = start - bytes.length(); - remaining -= used; - if (type2 == asn1.Type.BITSTRING) { - used++; - } - var tc = composed.tagClass; - if (used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { - value = [composed]; - } - } catch (ex) { - } - } - if (value === void 0) { - bytes.read = savedRead; - remaining = savedRemaining; + this._finish = true; + this.update(); + if (this._decrypt && this.mode.unpad) { + if (!this.mode.unpad(this.output, options)) { + return false; } } - if (value === void 0) { - if (length === void 0) { - if (options.strict) { - throw new Error("Non-constructed ASN.1 object of indefinite length."); - } - length = remaining; - } - if (type2 === asn1.Type.BMPSTRING) { - value = ""; - for (; length > 0; length -= 2) { - _checkBufferLength(bytes, remaining, 2); - value += String.fromCharCode(bytes.getInt16()); - remaining -= 2; - } - } else { - value = bytes.getBytes(length); - remaining -= length; + if (this.mode.afterFinish) { + if (!this.mode.afterFinish(this.output, options)) { + return false; } } - var asn1Options = bitStringContents === void 0 ? null : { - bitStringContents - }; - return asn1.create(tagClass, type2, constructed, value, asn1Options); - } - asn1.toDer = function(obj) { - var bytes = forge.util.createBuffer(); - var b1 = obj.tagClass | obj.type; - var value = forge.util.createBuffer(); - var useBitStringContents = false; - if ("bitStringContents" in obj) { - useBitStringContents = true; - if (obj.original) { - useBitStringContents = asn1.equals(obj, obj.original); - } + return true; + }; + } +}); + +// node_modules/node-forge/lib/cipherModes.js +var require_cipherModes = __commonJS({ + "node_modules/node-forge/lib/cipherModes.js"(exports2, module2) { + var forge = require_forge(); + require_util8(); + forge.cipher = forge.cipher || {}; + var modes = module2.exports = forge.cipher.modes = forge.cipher.modes || {}; + modes.ecb = function(options) { + options = options || {}; + this.name = "ECB"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + }; + modes.ecb.prototype.start = function(options) { + }; + modes.ecb.prototype.encrypt = function(input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; } - if (useBitStringContents) { - value.putBytes(obj.bitStringContents); - } else if (obj.composed) { - if (obj.constructed) { - b1 |= 32; - } else { - value.putByte(0); - } - for (var i = 0; i < obj.value.length; ++i) { - if (obj.value[i] !== void 0) { - value.putBuffer(asn1.toDer(obj.value[i])); - } - } - } else { - if (obj.type === asn1.Type.BMPSTRING) { - for (var i = 0; i < obj.value.length; ++i) { - value.putInt16(obj.value.charCodeAt(i)); - } - } else { - if (obj.type === asn1.Type.INTEGER && obj.value.length > 1 && // leading 0x00 for positive integer - (obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer - obj.value.charCodeAt(0) === 255 && (obj.value.charCodeAt(1) & 128) === 128)) { - value.putBytes(obj.value.substr(1)); - } else { - value.putBytes(obj.value); - } - } + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); } - bytes.putByte(b1); - if (value.length() <= 127) { - bytes.putByte(value.length() & 127); - } else { - var len = value.length(); - var lenBytes = ""; - do { - lenBytes += String.fromCharCode(len & 255); - len = len >>> 8; - } while (len > 0); - bytes.putByte(lenBytes.length | 128); - for (var i = lenBytes.length - 1; i >= 0; --i) { - bytes.putByte(lenBytes.charCodeAt(i)); - } + this.cipher.encrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); } - bytes.putBuffer(value); - return bytes; }; - asn1.oidToDer = function(oid) { - var values = oid.split("."); - var bytes = forge.util.createBuffer(); - bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); - var last, valueBytes, value, b; - for (var i = 2; i < values.length; ++i) { - last = true; - valueBytes = []; - value = parseInt(values[i], 10); - do { - b = value & 127; - value = value >>> 7; - if (!last) { - b |= 128; - } - valueBytes.push(b); - last = false; - } while (value > 0); - for (var n = valueBytes.length - 1; n >= 0; --n) { - bytes.putByte(valueBytes[n]); - } + modes.ecb.prototype.decrypt = function(input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; } - return bytes; - }; - asn1.derToOid = function(bytes) { - var oid; - if (typeof bytes === "string") { - bytes = forge.util.createBuffer(bytes); + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); } - var b = bytes.getByte(); - oid = Math.floor(b / 40) + "." + b % 40; - var value = 0; - while (bytes.length() > 0) { - b = bytes.getByte(); - value = value << 7; - if (b & 128) { - value += b & 127; - } else { - oid += "." + (value + b); - value = 0; - } + this.cipher.decrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); } - return oid; }; - asn1.utcTimeToDate = function(utc) { - var date = /* @__PURE__ */ new Date(); - var year = parseInt(utc.substr(0, 2), 10); - year = year >= 50 ? 1900 + year : 2e3 + year; - var MM = parseInt(utc.substr(2, 2), 10) - 1; - var DD = parseInt(utc.substr(4, 2), 10); - var hh = parseInt(utc.substr(6, 2), 10); - var mm = parseInt(utc.substr(8, 2), 10); - var ss = 0; - if (utc.length > 11) { - var c = utc.charAt(10); - var end = 10; - if (c !== "+" && c !== "-") { - ss = parseInt(utc.substr(10, 2), 10); - end += 2; - } + modes.ecb.prototype.pad = function(input, options) { + var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); + input.fillWithByte(padding, padding); + return true; + }; + modes.ecb.prototype.unpad = function(output, options) { + if (options.overflow > 0) { + return false; } - date.setUTCFullYear(year, MM, DD); - date.setUTCHours(hh, mm, ss, 0); - if (end) { - c = utc.charAt(end); - if (c === "+" || c === "-") { - var hhoffset = parseInt(utc.substr(end + 1, 2), 10); - var mmoffset = parseInt(utc.substr(end + 4, 2), 10); - var offset = hhoffset * 60 + mmoffset; - offset *= 6e4; - if (c === "+") { - date.setTime(+date - offset); - } else { - date.setTime(+date + offset); - } - } + var len = output.length(); + var count = output.at(len - 1); + if (count > this.blockSize << 2) { + return false; } - return date; + output.truncate(count); + return true; }; - asn1.generalizedTimeToDate = function(gentime) { - var date = /* @__PURE__ */ new Date(); - var YYYY = parseInt(gentime.substr(0, 4), 10); - var MM = parseInt(gentime.substr(4, 2), 10) - 1; - var DD = parseInt(gentime.substr(6, 2), 10); - var hh = parseInt(gentime.substr(8, 2), 10); - var mm = parseInt(gentime.substr(10, 2), 10); - var ss = parseInt(gentime.substr(12, 2), 10); - var fff = 0; - var offset = 0; - var isUTC = false; - if (gentime.charAt(gentime.length - 1) === "Z") { - isUTC = true; - } - var end = gentime.length - 5, c = gentime.charAt(end); - if (c === "+" || c === "-") { - var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); - var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); - offset = hhoffset * 60 + mmoffset; - offset *= 6e4; - if (c === "+") { - offset *= -1; + modes.cbc = function(options) { + options = options || {}; + this.name = "CBC"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + }; + modes.cbc.prototype.start = function(options) { + if (options.iv === null) { + if (!this._prev) { + throw new Error("Invalid IV parameter."); } - isUTC = true; - } - if (gentime.charAt(14) === ".") { - fff = parseFloat(gentime.substr(14), 10) * 1e3; - } - if (isUTC) { - date.setUTCFullYear(YYYY, MM, DD); - date.setUTCHours(hh, mm, ss, fff); - date.setTime(+date + offset); + this._iv = this._prev.slice(0); + } else if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); } else { - date.setFullYear(YYYY, MM, DD); - date.setHours(hh, mm, ss, fff); + this._iv = transformIV(options.iv, this.blockSize); + this._prev = this._iv.slice(0); } - return date; }; - asn1.dateToUtcTime = function(date) { - if (typeof date === "string") { - return date; - } - var rval = ""; - var format = []; - format.push(("" + date.getUTCFullYear()).substr(2)); - format.push("" + (date.getUTCMonth() + 1)); - format.push("" + date.getUTCDate()); - format.push("" + date.getUTCHours()); - format.push("" + date.getUTCMinutes()); - format.push("" + date.getUTCSeconds()); - for (var i = 0; i < format.length; ++i) { - if (format[i].length < 2) { - rval += "0"; - } - rval += format[i]; + modes.cbc.prototype.encrypt = function(input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; } - rval += "Z"; - return rval; - }; - asn1.dateToGeneralizedTime = function(date) { - if (typeof date === "string") { - return date; + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._prev[i] ^ input.getInt32(); } - var rval = ""; - var format = []; - format.push("" + date.getUTCFullYear()); - format.push("" + (date.getUTCMonth() + 1)); - format.push("" + date.getUTCDate()); - format.push("" + date.getUTCHours()); - format.push("" + date.getUTCMinutes()); - format.push("" + date.getUTCSeconds()); - for (var i = 0; i < format.length; ++i) { - if (format[i].length < 2) { - rval += "0"; - } - rval += format[i]; + this.cipher.encrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); } - rval += "Z"; - return rval; + this._prev = this._outBlock; }; - asn1.integerToDer = function(x) { - var rval = forge.util.createBuffer(); - if (x >= -128 && x < 128) { - return rval.putSignedInt(x, 8); - } - if (x >= -32768 && x < 32768) { - return rval.putSignedInt(x, 16); + modes.cbc.prototype.decrypt = function(input, output, finish) { + if (input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; } - if (x >= -8388608 && x < 8388608) { - return rval.putSignedInt(x, 24); + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); } - if (x >= -2147483648 && x < 2147483648) { - return rval.putSignedInt(x, 32); + this.cipher.decrypt(this._inBlock, this._outBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._prev[i] ^ this._outBlock[i]); } - var error4 = new Error("Integer too large; max is 32-bits."); - error4.integer = x; - throw error4; + this._prev = this._inBlock.slice(0); }; - asn1.derToInteger = function(bytes) { - if (typeof bytes === "string") { - bytes = forge.util.createBuffer(bytes); + modes.cbc.prototype.pad = function(input, options) { + var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); + input.fillWithByte(padding, padding); + return true; + }; + modes.cbc.prototype.unpad = function(output, options) { + if (options.overflow > 0) { + return false; } - var n = bytes.length() * 8; - if (n > 32) { - throw new Error("Integer too large; max is 32-bits."); + var len = output.length(); + var count = output.at(len - 1); + if (count > this.blockSize << 2) { + return false; } - return bytes.getSignedInt(n); + output.truncate(count); + return true; }; - asn1.validate = function(obj, v, capture, errors) { - var rval = false; - if ((obj.tagClass === v.tagClass || typeof v.tagClass === "undefined") && (obj.type === v.type || typeof v.type === "undefined")) { - if (obj.constructed === v.constructed || typeof v.constructed === "undefined") { - rval = true; - if (v.value && forge.util.isArray(v.value)) { - var j = 0; - for (var i = 0; rval && i < v.value.length; ++i) { - rval = v.value[i].optional || false; - if (obj.value[j]) { - rval = asn1.validate(obj.value[j], v.value[i], capture, errors); - if (rval) { - ++j; - } else if (v.value[i].optional) { - rval = true; - } - } - if (!rval && errors) { - errors.push( - "[" + v.name + '] Tag class "' + v.tagClass + '", type "' + v.type + '" expected value length "' + v.value.length + '", got "' + obj.value.length + '"' - ); - } - } - } - if (rval && capture) { - if (v.capture) { - capture[v.capture] = obj.value; - } - if (v.captureAsn1) { - capture[v.captureAsn1] = obj; - } - if (v.captureBitStringContents && "bitStringContents" in obj) { - capture[v.captureBitStringContents] = obj.bitStringContents; - } - if (v.captureBitStringValue && "bitStringContents" in obj) { - var value; - if (obj.bitStringContents.length < 2) { - capture[v.captureBitStringValue] = ""; - } else { - var unused = obj.bitStringContents.charCodeAt(0); - if (unused !== 0) { - throw new Error( - "captureBitStringValue only supported for zero unused bits" - ); - } - capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); - } - } - } - } else if (errors) { - errors.push( - "[" + v.name + '] Expected constructed "' + v.constructed + '", got "' + obj.constructed + '"' - ); - } - } else if (errors) { - if (obj.tagClass !== v.tagClass) { - errors.push( - "[" + v.name + '] Expected tag class "' + v.tagClass + '", got "' + obj.tagClass + '"' - ); + modes.cfb = function(options) { + options = options || {}; + this.name = "CFB"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + }; + modes.cfb.prototype.start = function(options) { + if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); + } + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; + }; + modes.cfb.prototype.encrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; + output.putInt32(this._inBlock[i]); } - if (obj.type !== v.type) { - errors.push( - "[" + v.name + '] Expected type "' + v.type + '", got "' + obj.type + '"' - ); + return; + } + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; + this._partialOutput.putInt32(this._partialBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; + } else { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; } } - return rval; - }; - var _nonLatinRegex = /[^\\u0000-\\u00ff]/; - asn1.prettyPrint = function(obj, level, indentation) { - var rval = ""; - level = level || 0; - indentation = indentation || 2; - if (level > 0) { - rval += "\n"; + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); } - var indent = ""; - for (var i = 0; i < level * indentation; ++i) { - indent += " "; + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; } - rval += indent + "Tag: "; - switch (obj.tagClass) { - case asn1.Class.UNIVERSAL: - rval += "Universal:"; - break; - case asn1.Class.APPLICATION: - rval += "Application:"; - break; - case asn1.Class.CONTEXT_SPECIFIC: - rval += "Context-Specific:"; - break; - case asn1.Class.PRIVATE: - rval += "Private:"; - break; + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; + }; + modes.cfb.prototype.decrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; } - if (obj.tagClass === asn1.Class.UNIVERSAL) { - rval += obj.type; - switch (obj.type) { - case asn1.Type.NONE: - rval += " (None)"; - break; - case asn1.Type.BOOLEAN: - rval += " (Boolean)"; - break; - case asn1.Type.INTEGER: - rval += " (Integer)"; - break; - case asn1.Type.BITSTRING: - rval += " (Bit string)"; - break; - case asn1.Type.OCTETSTRING: - rval += " (Octet string)"; - break; - case asn1.Type.NULL: - rval += " (Null)"; - break; - case asn1.Type.OID: - rval += " (Object Identifier)"; - break; - case asn1.Type.ODESC: - rval += " (Object Descriptor)"; - break; - case asn1.Type.EXTERNAL: - rval += " (External or Instance of)"; - break; - case asn1.Type.REAL: - rval += " (Real)"; - break; - case asn1.Type.ENUMERATED: - rval += " (Enumerated)"; - break; - case asn1.Type.EMBEDDED: - rval += " (Embedded PDV)"; - break; - case asn1.Type.UTF8: - rval += " (UTF8)"; - break; - case asn1.Type.ROID: - rval += " (Relative Object Identifier)"; - break; - case asn1.Type.SEQUENCE: - rval += " (Sequence)"; - break; - case asn1.Type.SET: - rval += " (Set)"; - break; - case asn1.Type.PRINTABLESTRING: - rval += " (Printable String)"; - break; - case asn1.Type.IA5String: - rval += " (IA5String (ASCII))"; - break; - case asn1.Type.UTCTIME: - rval += " (UTC time)"; - break; - case asn1.Type.GENERALIZEDTIME: - rval += " (Generalized time)"; - break; - case asn1.Type.BMPSTRING: - rval += " (BMP String)"; - break; + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + output.putInt32(this._inBlock[i] ^ this._outBlock[i]); } + return; + } + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32(); + this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; } else { - rval += obj.type; + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } } - rval += "\n"; - rval += indent + "Constructed: " + obj.constructed + "\n"; - if (obj.composed) { - var subvalues = 0; - var sub = ""; - for (var i = 0; i < obj.value.length; ++i) { - if (obj.value[i] !== void 0) { - subvalues += 1; - sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); - if (i + 1 < obj.value.length) { - sub += ","; - } - } + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; + }; + modes.ofb = function(options) { + options = options || {}; + this.name = "OFB"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + }; + modes.ofb.prototype.start = function(options) { + if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); + } + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; + }; + modes.ofb.prototype.encrypt = function(input, output, finish) { + var inputLength = input.length(); + if (input.length() === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + this._inBlock[i] = this._outBlock[i]; } - rval += indent + "Sub values: " + subvalues + sub; + return; + } + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + if (partialBytes > 0) { + input.read -= this.blockSize; } else { - rval += indent + "Value: "; - if (obj.type === asn1.Type.OID) { - var oid = asn1.derToOid(obj.value); - rval += oid; - if (forge.pki && forge.pki.oids) { - if (oid in forge.pki.oids) { - rval += " (" + forge.pki.oids[oid] + ") "; - } - } - } - if (obj.type === asn1.Type.INTEGER) { - try { - rval += asn1.derToInteger(obj.value); - } catch (ex) { - rval += "0x" + forge.util.bytesToHex(obj.value); - } - } else if (obj.type === asn1.Type.BITSTRING) { - if (obj.value.length > 1) { - rval += "0x" + forge.util.bytesToHex(obj.value.slice(1)); - } else { - rval += "(none)"; - } - if (obj.value.length > 0) { - var unused = obj.value.charCodeAt(0); - if (unused == 1) { - rval += " (1 unused bit shown)"; - } else if (unused > 1) { - rval += " (" + unused + " unused bits shown)"; - } - } - } else if (obj.type === asn1.Type.OCTETSTRING) { - if (!_nonLatinRegex.test(obj.value)) { - rval += "(" + obj.value + ") "; - } - rval += "0x" + forge.util.bytesToHex(obj.value); - } else if (obj.type === asn1.Type.UTF8) { - try { - rval += forge.util.decodeUtf8(obj.value); - } catch (e) { - if (e.message === "URI malformed") { - rval += "0x" + forge.util.bytesToHex(obj.value) + " (malformed UTF8)"; - } else { - throw e; - } - } - } else if (obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) { - rval += obj.value; - } else if (_nonLatinRegex.test(obj.value)) { - rval += "0x" + forge.util.bytesToHex(obj.value); - } else if (obj.value.length === 0) { - rval += "[null]"; - } else { - rval += obj.value; + for (var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._outBlock[i]; } } - return rval; + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; }; - } -}); - -// node_modules/node-forge/lib/md.js -var require_md = __commonJS({ - "node_modules/node-forge/lib/md.js"(exports2, module2) { - var forge = require_forge(); - module2.exports = forge.md = forge.md || {}; - forge.md.algorithms = forge.md.algorithms || {}; - } -}); - -// node_modules/node-forge/lib/hmac.js -var require_hmac = __commonJS({ - "node_modules/node-forge/lib/hmac.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util8(); - var hmac = module2.exports = forge.hmac = forge.hmac || {}; - hmac.create = function() { - var _key = null; - var _md = null; - var _ipadding = null; - var _opadding = null; - var ctx = {}; - ctx.start = function(md, key) { - if (md !== null) { - if (typeof md === "string") { - md = md.toLowerCase(); - if (md in forge.md.algorithms) { - _md = forge.md.algorithms[md].create(); - } else { - throw new Error('Unknown hash algorithm "' + md + '"'); - } - } else { - _md = md; - } + modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; + modes.ctr = function(options) { + options = options || {}; + this.name = "CTR"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + }; + modes.ctr.prototype.start = function(options) { + if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); + } + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; + }; + modes.ctr.prototype.encrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); } - if (key === null) { - key = _key; - } else { - if (typeof key === "string") { - key = forge.util.createBuffer(key); - } else if (forge.util.isArray(key)) { - var tmp = key; - key = forge.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - var keylen = key.length(); - if (keylen > _md.blockLength) { - _md.start(); - _md.update(key.bytes()); - key = _md.digest(); - } - _ipadding = forge.util.createBuffer(); - _opadding = forge.util.createBuffer(); - keylen = key.length(); - for (var i = 0; i < keylen; ++i) { - var tmp = key.at(i); - _ipadding.putByte(54 ^ tmp); - _opadding.putByte(92 ^ tmp); - } - if (keylen < _md.blockLength) { - var tmp = _md.blockLength - keylen; - for (var i = 0; i < tmp; ++i) { - _ipadding.putByte(54); - _opadding.putByte(92); - } - } - _key = key; - _ipadding = _ipadding.bytes(); - _opadding = _opadding.bytes(); + } else { + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; } - _md.start(); - _md.update(_ipadding); - }; - ctx.update = function(bytes) { - _md.update(bytes); - }; - ctx.getMac = function() { - var inner = _md.digest().bytes(); - _md.start(); - _md.update(_opadding); - _md.update(inner); - return _md.digest(); - }; - ctx.digest = ctx.getMac; - return ctx; - }; - } -}); - -// node_modules/node-forge/lib/md5.js -var require_md5 = __commonJS({ - "node_modules/node-forge/lib/md5.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util8(); - var md5 = module2.exports = forge.md5 = forge.md5 || {}; - forge.md.md5 = forge.md.algorithms.md5 = md5; - md5.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge.util.createBuffer(); - var _w = new Array(16); - var md = { - algorithm: "md5", - blockLength: 64, - digestLength: 16, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge.util.createBuffer(); - _state = { - h0: 1732584193, - h1: 4023233417, - h2: 2562383102, - h3: 271733878 - }; - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var bits, carry = 0; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - bits = md.fullMessageLength[i] * 8 + carry; - carry = bits / 4294967296 >>> 0; - finalBlock.putInt32Le(bits >>> 0); - } - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3 - }; - _update(s2, _w, finalBlock); - var rval = forge.util.createBuffer(); - rval.putInt32Le(s2.h0); - rval.putInt32Le(s2.h1); - rval.putInt32Le(s2.h2); - rval.putInt32Le(s2.h3); - return rval; - }; - return md; - }; - var _padding = null; - var _g = null; - var _r = null; - var _k = null; - var _initialized = false; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0), 64); - _g = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 1, - 6, - 11, - 0, - 5, - 10, - 15, - 4, - 9, - 14, - 3, - 8, - 13, - 2, - 7, - 12, - 5, - 8, - 11, - 14, - 1, - 4, - 7, - 10, - 13, - 0, - 3, - 6, - 9, - 12, - 15, - 2, - 0, - 7, - 14, - 5, - 12, - 3, - 10, - 1, - 8, - 15, - 6, - 13, - 4, - 11, - 2, - 9 - ]; - _r = [ - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21 - ]; - _k = new Array(64); - for (var i = 0; i < 64; ++i) { - _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); - } - _initialized = true; - } - function _update(s, w, bytes) { - var t, a, b, c, d, f, r, i; - var len = bytes.length(); - while (len >= 64) { - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - for (i = 0; i < 16; ++i) { - w[i] = bytes.getInt32Le(); - f = d ^ b & (c ^ d); - t = a + f + _k[i] + w[i]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); } - for (; i < 32; ++i) { - f = c ^ d & (b ^ c); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; + if (partialBytes > 0) { + input.read -= this.blockSize; } - for (; i < 48; ++i) { - f = b ^ c ^ d; - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); } - for (; i < 64; ++i) { - f = c ^ (b | ~d); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; + if (partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - len -= 64; + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; } - } - } -}); - -// node_modules/node-forge/lib/pem.js -var require_pem = __commonJS({ - "node_modules/node-forge/lib/pem.js"(exports2, module2) { - var forge = require_forge(); - require_util8(); - var pem = module2.exports = forge.pem = forge.pem || {}; - pem.encode = function(msg, options) { + inc32(this._inBlock); + }; + modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; + modes.gcm = function(options) { options = options || {}; - var rval = "-----BEGIN " + msg.type + "-----\r\n"; - var header; - if (msg.procType) { - header = { - name: "Proc-Type", - values: [String(msg.procType.version), msg.procType.type] - }; - rval += foldHeader(header); + this.name = "GCM"; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + this._R = 3774873600; + }; + modes.gcm.prototype.start = function(options) { + if (!("iv" in options)) { + throw new Error("Invalid IV parameter."); } - if (msg.contentDomain) { - header = { name: "Content-Domain", values: [msg.contentDomain] }; - rval += foldHeader(header); + var iv = forge.util.createBuffer(options.iv); + this._cipherLength = 0; + var additionalData; + if ("additionalData" in options) { + additionalData = forge.util.createBuffer(options.additionalData); + } else { + additionalData = forge.util.createBuffer(); } - if (msg.dekInfo) { - header = { name: "DEK-Info", values: [msg.dekInfo.algorithm] }; - if (msg.dekInfo.parameters) { - header.values.push(msg.dekInfo.parameters); + if ("tagLength" in options) { + this._tagLength = options.tagLength; + } else { + this._tagLength = 128; + } + this._tag = null; + if (options.decrypt) { + this._tag = forge.util.createBuffer(options.tag).getBytes(); + if (this._tag.length !== this._tagLength / 8) { + throw new Error("Authentication tag does not match tag length."); } - rval += foldHeader(header); } - if (msg.headers) { - for (var i = 0; i < msg.headers.length; ++i) { - rval += foldHeader(msg.headers[i]); + this._hashBlock = new Array(this._ints); + this.tag = null; + this._hashSubkey = new Array(this._ints); + this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); + this.componentBits = 4; + this._m = this.generateHashTable(this._hashSubkey, this.componentBits); + var ivLength = iv.length(); + if (ivLength === 12) { + this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; + } else { + this._j0 = [0, 0, 0, 0]; + while (iv.length() > 0) { + this._j0 = this.ghash( + this._hashSubkey, + this._j0, + [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()] + ); } + this._j0 = this.ghash( + this._hashSubkey, + this._j0, + [0, 0].concat(from64To32(ivLength * 8)) + ); } - if (msg.procType) { - rval += "\r\n"; + this._inBlock = this._j0.slice(0); + inc32(this._inBlock); + this._partialBytes = 0; + additionalData = forge.util.createBuffer(additionalData); + this._aDataLength = from64To32(additionalData.length() * 8); + var overflow = additionalData.length() % this.blockSize; + if (overflow) { + additionalData.fillWithByte(0, this.blockSize - overflow); + } + this._s = [0, 0, 0, 0]; + while (additionalData.length() > 0) { + this._s = this.ghash(this._hashSubkey, this._s, [ + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32() + ]); } - rval += forge.util.encode64(msg.body, options.maxline || 64) + "\r\n"; - rval += "-----END " + msg.type + "-----\r\n"; - return rval; }; - pem.decode = function(str2) { - var rval = []; - var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; - var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; - var rCRLF = /\r?\n/; - var match; - while (true) { - match = rMessage.exec(str2); - if (!match) { - break; + modes.gcm.prototype.encrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength === 0) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + if (this._partialBytes === 0 && inputLength >= this.blockSize) { + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^= input.getInt32()); } - var type2 = match[1]; - if (type2 === "NEW CERTIFICATE REQUEST") { - type2 = "CERTIFICATE REQUEST"; + this._cipherLength += this.blockSize; + } else { + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if (partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; } - var msg = { - type: type2, - procType: null, - contentDomain: null, - dekInfo: null, - headers: [], - body: forge.util.decode64(match[3]) - }; - rval.push(msg); - if (!match[2]) { - continue; + this._partialOutput.clear(); + for (var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); } - var lines = match[2].split(rCRLF); - var li = 0; - while (match && li < lines.length) { - var line = lines[li].replace(/\s+$/, ""); - for (var nl = li + 1; nl < lines.length; ++nl) { - var next = lines[nl]; - if (!/\s/.test(next[0])) { - break; - } - line += next; - li = nl; + if (partialBytes <= 0 || finish) { + if (finish) { + var overflow = inputLength % this.blockSize; + this._cipherLength += overflow; + this._partialOutput.truncate(this.blockSize - overflow); + } else { + this._cipherLength += this.blockSize; } - match = line.match(rHeader); - if (match) { - var header = { name: match[1], values: [] }; - var values = match[2].split(","); - for (var vi = 0; vi < values.length; ++vi) { - header.values.push(ltrim(values[vi])); - } - if (!msg.procType) { - if (header.name !== "Proc-Type") { - throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".'); - } else if (header.values.length !== 2) { - throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.'); - } - msg.procType = { version: values[0], type: values[1] }; - } else if (!msg.contentDomain && header.name === "Content-Domain") { - msg.contentDomain = values[0] || ""; - } else if (!msg.dekInfo && header.name === "DEK-Info") { - if (header.values.length === 0) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.'); - } - msg.dekInfo = { algorithm: values[0], parameters: values[1] || null }; - } else { - msg.headers.push(header); - } + for (var i = 0; i < this._ints; ++i) { + this._outBlock[i] = this._partialOutput.getInt32(); } - ++li; + this._partialOutput.read -= this.blockSize; } - if (msg.procType === "ENCRYPTED" && !msg.dekInfo) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".'); + if (this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); } + if (partialBytes > 0 && !finish) { + input.read -= this.blockSize; + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes + )); + this._partialBytes = partialBytes; + return true; + } + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes + )); + this._partialBytes = 0; } - if (rval.length === 0) { - throw new Error("Invalid PEM formatted message."); + this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); + inc32(this._inBlock); + }; + modes.gcm.prototype.decrypt = function(input, output, finish) { + var inputLength = input.length(); + if (inputLength < this.blockSize && !(finish && inputLength > 0)) { + return true; + } + this.cipher.encrypt(this._inBlock, this._outBlock); + inc32(this._inBlock); + this._hashBlock[0] = input.getInt32(); + this._hashBlock[1] = input.getInt32(); + this._hashBlock[2] = input.getInt32(); + this._hashBlock[3] = input.getInt32(); + this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); + for (var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); + } + if (inputLength < this.blockSize) { + this._cipherLength += inputLength % this.blockSize; + } else { + this._cipherLength += this.blockSize; + } + }; + modes.gcm.prototype.afterFinish = function(output, options) { + var rval = true; + if (options.decrypt && options.overflow) { + output.truncate(this.blockSize - options.overflow); + } + this.tag = forge.util.createBuffer(); + var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); + this._s = this.ghash(this._hashSubkey, this._s, lengths); + var tag = []; + this.cipher.encrypt(this._j0, tag); + for (var i = 0; i < this._ints; ++i) { + this.tag.putInt32(this._s[i] ^ tag[i]); + } + this.tag.truncate(this.tag.length() % (this._tagLength / 8)); + if (options.decrypt && this.tag.bytes() !== this._tag) { + rval = false; } return rval; }; - function foldHeader(header) { - var rval = header.name + ": "; - var values = []; - var insertSpace = function(match, $1) { - return " " + $1; - }; - for (var i = 0; i < header.values.length; ++i) { - values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); + modes.gcm.prototype.multiply = function(x, y) { + var z_i = [0, 0, 0, 0]; + var v_i = y.slice(0); + for (var i = 0; i < 128; ++i) { + var x_i = x[i / 32 | 0] & 1 << 31 - i % 32; + if (x_i) { + z_i[0] ^= v_i[0]; + z_i[1] ^= v_i[1]; + z_i[2] ^= v_i[2]; + z_i[3] ^= v_i[3]; + } + this.pow(v_i, v_i); } - rval += values.join(",") + "\r\n"; - var length = 0; - var candidate = -1; - for (var i = 0; i < rval.length; ++i, ++length) { - if (length > 65 && candidate !== -1) { - var insert = rval[candidate]; - if (insert === ",") { - ++candidate; - rval = rval.substr(0, candidate) + "\r\n " + rval.substr(candidate); - } else { - rval = rval.substr(0, candidate) + "\r\n" + insert + rval.substr(candidate + 1); - } - length = i - candidate - 1; - candidate = -1; - ++i; - } else if (rval[i] === " " || rval[i] === " " || rval[i] === ",") { - candidate = i; + return z_i; + }; + modes.gcm.prototype.pow = function(x, out) { + var lsb = x[3] & 1; + for (var i = 3; i > 0; --i) { + out[i] = x[i] >>> 1 | (x[i - 1] & 1) << 31; + } + out[0] = x[0] >>> 1; + if (lsb) { + out[0] ^= this._R; + } + }; + modes.gcm.prototype.tableMultiply = function(x) { + var z = [0, 0, 0, 0]; + for (var i = 0; i < 32; ++i) { + var idx = i / 8 | 0; + var x_i = x[idx] >>> (7 - i % 8) * 4 & 15; + var ah = this._m[i][x_i]; + z[0] ^= ah[0]; + z[1] ^= ah[1]; + z[2] ^= ah[2]; + z[3] ^= ah[3]; + } + return z; + }; + modes.gcm.prototype.ghash = function(h, y, x) { + y[0] ^= x[0]; + y[1] ^= x[1]; + y[2] ^= x[2]; + y[3] ^= x[3]; + return this.tableMultiply(y); + }; + modes.gcm.prototype.generateHashTable = function(h, bits) { + var multiplier = 8 / bits; + var perInt = 4 * multiplier; + var size = 16 * multiplier; + var m = new Array(size); + for (var i = 0; i < size; ++i) { + var tmp = [0, 0, 0, 0]; + var idx = i / perInt | 0; + var shft = (perInt - 1 - i % perInt) * bits; + tmp[idx] = 1 << bits - 1 << shft; + m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); + } + return m; + }; + modes.gcm.prototype.generateSubHashTable = function(mid, bits) { + var size = 1 << bits; + var half = size >>> 1; + var m = new Array(size); + m[half] = mid.slice(0); + var i = half >>> 1; + while (i > 0) { + this.pow(m[2 * i], m[i] = []); + i >>= 1; + } + i = 2; + while (i < half) { + for (var j = 1; j < i; ++j) { + var m_i = m[i]; + var m_j = m[j]; + m[i + j] = [ + m_i[0] ^ m_j[0], + m_i[1] ^ m_j[1], + m_i[2] ^ m_j[2], + m_i[3] ^ m_j[3] + ]; } + i *= 2; } - return rval; + m[0] = [0, 0, 0, 0]; + for (i = half + 1; i < size; ++i) { + var c = m[i ^ half]; + m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; + } + return m; + }; + function transformIV(iv, blockSize) { + if (typeof iv === "string") { + iv = forge.util.createBuffer(iv); + } + if (forge.util.isArray(iv) && iv.length > 4) { + var tmp = iv; + iv = forge.util.createBuffer(); + for (var i = 0; i < tmp.length; ++i) { + iv.putByte(tmp[i]); + } + } + if (iv.length() < blockSize) { + throw new Error( + "Invalid IV length; got " + iv.length() + " bytes and expected " + blockSize + " bytes." + ); + } + if (!forge.util.isArray(iv)) { + var ints = []; + var blocks = blockSize / 4; + for (var i = 0; i < blocks; ++i) { + ints.push(iv.getInt32()); + } + iv = ints; + } + return iv; } - function ltrim(str2) { - return str2.replace(/^\s+/, ""); + function inc32(block) { + block[block.length - 1] = block[block.length - 1] + 1 & 4294967295; + } + function from64To32(num) { + return [num / 4294967296 | 0, num & 4294967295]; } } }); -// node_modules/node-forge/lib/des.js -var require_des = __commonJS({ - "node_modules/node-forge/lib/des.js"(exports2, module2) { +// node_modules/node-forge/lib/aes.js +var require_aes = __commonJS({ + "node_modules/node-forge/lib/aes.js"(exports2, module2) { var forge = require_forge(); require_cipher(); require_cipherModes(); require_util8(); - module2.exports = forge.des = forge.des || {}; - forge.des.startEncrypting = function(key, iv, output, mode) { + module2.exports = forge.aes = forge.aes || {}; + forge.aes.startEncrypting = function(key, iv, output, mode) { var cipher = _createCipher({ key, output, decrypt: false, - mode: mode || (iv === null ? "ECB" : "CBC") + mode }); cipher.start(iv); return cipher; }; - forge.des.createEncryptionCipher = function(key, mode) { + forge.aes.createEncryptionCipher = function(key, mode) { return _createCipher({ key, output: null, @@ -26573,17 +25536,17 @@ var require_des = __commonJS({ mode }); }; - forge.des.startDecrypting = function(key, iv, output, mode) { + forge.aes.startDecrypting = function(key, iv, output, mode) { var cipher = _createCipher({ key, output, decrypt: true, - mode: mode || (iv === null ? "ECB" : "CBC") + mode }); cipher.start(iv); return cipher; }; - forge.des.createDecryptionCipher = function(key, mode) { + forge.aes.createDecryptionCipher = function(key, mode) { return _createCipher({ key, output: null, @@ -26591,185 +25554,222 @@ var require_des = __commonJS({ mode }); }; - forge.des.Algorithm = function(name, mode) { + forge.aes.Algorithm = function(name, mode) { + if (!init) { + initialize(); + } var self2 = this; self2.name = name; self2.mode = new mode({ - blockSize: 8, + blockSize: 16, cipher: { encrypt: function(inBlock, outBlock) { - return _updateBlock(self2._keys, inBlock, outBlock, false); + return _updateBlock(self2._w, inBlock, outBlock, false); }, decrypt: function(inBlock, outBlock) { - return _updateBlock(self2._keys, inBlock, outBlock, true); + return _updateBlock(self2._w, inBlock, outBlock, true); } } }); self2._init = false; }; - forge.des.Algorithm.prototype.initialize = function(options) { + forge.aes.Algorithm.prototype.initialize = function(options) { if (this._init) { return; } - var key = forge.util.createBuffer(options.key); - if (this.name.indexOf("3DES") === 0) { - if (key.length() !== 24) { - throw new Error("Invalid Triple-DES key size: " + key.length() * 8); + var key = options.key; + var tmp; + if (typeof key === "string" && (key.length === 16 || key.length === 24 || key.length === 32)) { + key = forge.util.createBuffer(key); + } else if (forge.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { + tmp = key; + key = forge.util.createBuffer(); + for (var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); } } - this._keys = _createKeys(key); + if (!forge.util.isArray(key)) { + tmp = key; + key = []; + var len = tmp.length(); + if (len === 16 || len === 24 || len === 32) { + len = len >>> 2; + for (var i = 0; i < len; ++i) { + key.push(tmp.getInt32()); + } + } + } + if (!forge.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) { + throw new Error("Invalid key parameter."); + } + var mode = this.mode.name; + var encryptOp = ["CFB", "OFB", "CTR", "GCM"].indexOf(mode) !== -1; + this._w = _expandKey(key, options.decrypt && !encryptOp); this._init = true; }; - registerAlgorithm("DES-ECB", forge.cipher.modes.ecb); - registerAlgorithm("DES-CBC", forge.cipher.modes.cbc); - registerAlgorithm("DES-CFB", forge.cipher.modes.cfb); - registerAlgorithm("DES-OFB", forge.cipher.modes.ofb); - registerAlgorithm("DES-CTR", forge.cipher.modes.ctr); - registerAlgorithm("3DES-ECB", forge.cipher.modes.ecb); - registerAlgorithm("3DES-CBC", forge.cipher.modes.cbc); - registerAlgorithm("3DES-CFB", forge.cipher.modes.cfb); - registerAlgorithm("3DES-OFB", forge.cipher.modes.ofb); - registerAlgorithm("3DES-CTR", forge.cipher.modes.ctr); + forge.aes._expandKey = function(key, decrypt) { + if (!init) { + initialize(); + } + return _expandKey(key, decrypt); + }; + forge.aes._updateBlock = _updateBlock; + registerAlgorithm("AES-ECB", forge.cipher.modes.ecb); + registerAlgorithm("AES-CBC", forge.cipher.modes.cbc); + registerAlgorithm("AES-CFB", forge.cipher.modes.cfb); + registerAlgorithm("AES-OFB", forge.cipher.modes.ofb); + registerAlgorithm("AES-CTR", forge.cipher.modes.ctr); + registerAlgorithm("AES-GCM", forge.cipher.modes.gcm); function registerAlgorithm(name, mode) { var factory = function() { - return new forge.des.Algorithm(name, mode); + return new forge.aes.Algorithm(name, mode); }; forge.cipher.registerAlgorithm(name, factory); } - var spfunction1 = [16843776, 0, 65536, 16843780, 16842756, 66564, 4, 65536, 1024, 16843776, 16843780, 1024, 16778244, 16842756, 16777216, 4, 1028, 16778240, 16778240, 66560, 66560, 16842752, 16842752, 16778244, 65540, 16777220, 16777220, 65540, 0, 1028, 66564, 16777216, 65536, 16843780, 4, 16842752, 16843776, 16777216, 16777216, 1024, 16842756, 65536, 66560, 16777220, 1024, 4, 16778244, 66564, 16843780, 65540, 16842752, 16778244, 16777220, 1028, 66564, 16843776, 1028, 16778240, 16778240, 0, 65540, 66560, 0, 16842756]; - var spfunction2 = [-2146402272, -2147450880, 32768, 1081376, 1048576, 32, -2146435040, -2147450848, -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 1048576, 32, -2146435040, 1081344, 1048608, -2147450848, 0, -2147483648, 32768, 1081376, -2146435072, 1048608, -2147483616, 0, 1081344, 32800, -2146402304, -2146435072, 32800, 0, 1081376, -2146435040, 1048576, -2147450848, -2146435072, -2146402304, 32768, -2146435072, -2147450880, 32, -2146402272, 1081376, 32, 32768, -2147483648, 32800, -2146402304, 1048576, -2147483616, 1048608, -2147450848, -2147483616, 1048608, 1081344, 0, -2147450880, 32800, -2147483648, -2146435040, -2146402272, 1081344]; - var spfunction3 = [520, 134349312, 0, 134348808, 134218240, 0, 131592, 134218240, 131080, 134217736, 134217736, 131072, 134349320, 131080, 134348800, 520, 134217728, 8, 134349312, 512, 131584, 134348800, 134348808, 131592, 134218248, 131584, 131072, 134218248, 8, 134349320, 512, 134217728, 134349312, 134217728, 131080, 520, 131072, 134349312, 134218240, 0, 512, 131080, 134349320, 134218240, 134217736, 512, 0, 134348808, 134218248, 131072, 134217728, 134349320, 8, 131592, 131584, 134217736, 134348800, 134218248, 520, 134348800, 131592, 8, 134348808, 131584]; - var spfunction4 = [8396801, 8321, 8321, 128, 8396928, 8388737, 8388609, 8193, 0, 8396800, 8396800, 8396929, 129, 0, 8388736, 8388609, 1, 8192, 8388608, 8396801, 128, 8388608, 8193, 8320, 8388737, 1, 8320, 8388736, 8192, 8396928, 8396929, 129, 8388736, 8388609, 8396800, 8396929, 129, 0, 0, 8396800, 8320, 8388736, 8388737, 1, 8396801, 8321, 8321, 128, 8396929, 129, 1, 8192, 8388609, 8193, 8396928, 8388737, 8193, 8320, 8388608, 8396801, 128, 8388608, 8192, 8396928]; - var spfunction5 = [256, 34078976, 34078720, 1107296512, 524288, 256, 1073741824, 34078720, 1074266368, 524288, 33554688, 1074266368, 1107296512, 1107820544, 524544, 1073741824, 33554432, 1074266112, 1074266112, 0, 1073742080, 1107820800, 1107820800, 33554688, 1107820544, 1073742080, 0, 1107296256, 34078976, 33554432, 1107296256, 524544, 524288, 1107296512, 256, 33554432, 1073741824, 34078720, 1107296512, 1074266368, 33554688, 1073741824, 1107820544, 34078976, 1074266368, 256, 33554432, 1107820544, 1107820800, 524544, 1107296256, 1107820800, 34078720, 0, 1074266112, 1107296256, 524544, 33554688, 1073742080, 524288, 0, 1074266112, 34078976, 1073742080]; - var spfunction6 = [536870928, 541065216, 16384, 541081616, 541065216, 16, 541081616, 4194304, 536887296, 4210704, 4194304, 536870928, 4194320, 536887296, 536870912, 16400, 0, 4194320, 536887312, 16384, 4210688, 536887312, 16, 541065232, 541065232, 0, 4210704, 541081600, 16400, 4210688, 541081600, 536870912, 536887296, 16, 541065232, 4210688, 541081616, 4194304, 16400, 536870928, 4194304, 536887296, 536870912, 16400, 536870928, 541081616, 4210688, 541065216, 4210704, 541081600, 0, 541065232, 16, 16384, 541065216, 4210704, 16384, 4194320, 536887312, 0, 541081600, 536870912, 4194320, 536887312]; - var spfunction7 = [2097152, 69206018, 67110914, 0, 2048, 67110914, 2099202, 69208064, 69208066, 2097152, 0, 67108866, 2, 67108864, 69206018, 2050, 67110912, 2099202, 2097154, 67110912, 67108866, 69206016, 69208064, 2097154, 69206016, 2048, 2050, 69208066, 2099200, 2, 67108864, 2099200, 67108864, 2099200, 2097152, 67110914, 67110914, 69206018, 69206018, 2, 2097154, 67108864, 67110912, 2097152, 69208064, 2050, 2099202, 69208064, 2050, 67108866, 69208066, 69206016, 2099200, 0, 2, 69208066, 0, 2099202, 69206016, 2048, 67108866, 67110912, 2048, 2097154]; - var spfunction8 = [268439616, 4096, 262144, 268701760, 268435456, 268439616, 64, 268435456, 262208, 268697600, 268701760, 266240, 268701696, 266304, 4096, 64, 268697600, 268435520, 268439552, 4160, 266240, 262208, 268697664, 268701696, 4160, 0, 0, 268697664, 268435520, 268439552, 266304, 262144, 266304, 262144, 268701696, 4096, 64, 268697664, 4096, 266304, 268439552, 64, 268435520, 268697600, 268697664, 268435456, 262144, 268439616, 0, 268701760, 262208, 268435520, 268697600, 268439552, 268439616, 0, 268701760, 266240, 266240, 4160, 4160, 262208, 268435456, 268701696]; - function _createKeys(key) { - var pc2bytes0 = [0, 4, 536870912, 536870916, 65536, 65540, 536936448, 536936452, 512, 516, 536871424, 536871428, 66048, 66052, 536936960, 536936964], pc2bytes1 = [0, 1, 1048576, 1048577, 67108864, 67108865, 68157440, 68157441, 256, 257, 1048832, 1048833, 67109120, 67109121, 68157696, 68157697], pc2bytes2 = [0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272, 0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272], pc2bytes3 = [0, 2097152, 134217728, 136314880, 8192, 2105344, 134225920, 136323072, 131072, 2228224, 134348800, 136445952, 139264, 2236416, 134356992, 136454144], pc2bytes4 = [0, 262144, 16, 262160, 0, 262144, 16, 262160, 4096, 266240, 4112, 266256, 4096, 266240, 4112, 266256], pc2bytes5 = [0, 1024, 32, 1056, 0, 1024, 32, 1056, 33554432, 33555456, 33554464, 33555488, 33554432, 33555456, 33554464, 33555488], pc2bytes6 = [0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746, 0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746], pc2bytes7 = [0, 65536, 2048, 67584, 536870912, 536936448, 536872960, 536938496, 131072, 196608, 133120, 198656, 537001984, 537067520, 537004032, 537069568], pc2bytes8 = [0, 262144, 0, 262144, 2, 262146, 2, 262146, 33554432, 33816576, 33554432, 33816576, 33554434, 33816578, 33554434, 33816578], pc2bytes9 = [0, 268435456, 8, 268435464, 0, 268435456, 8, 268435464, 1024, 268436480, 1032, 268436488, 1024, 268436480, 1032, 268436488], pc2bytes10 = [0, 32, 0, 32, 1048576, 1048608, 1048576, 1048608, 8192, 8224, 8192, 8224, 1056768, 1056800, 1056768, 1056800], pc2bytes11 = [0, 16777216, 512, 16777728, 2097152, 18874368, 2097664, 18874880, 67108864, 83886080, 67109376, 83886592, 69206016, 85983232, 69206528, 85983744], pc2bytes12 = [0, 4096, 134217728, 134221824, 524288, 528384, 134742016, 134746112, 16, 4112, 134217744, 134221840, 524304, 528400, 134742032, 134746128], pc2bytes13 = [0, 4, 256, 260, 0, 4, 256, 260, 1, 5, 257, 261, 1, 5, 257, 261]; - var iterations = key.length() > 8 ? 3 : 1; - var keys = []; - var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - var n = 0, tmp; - for (var j = 0; j < iterations; j++) { - var left = key.getInt32(); - var right = key.getInt32(); - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 2 ^ right) & 858993459; - right ^= tmp; - left ^= tmp << 2; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = left << 8 | right >>> 20 & 240; - left = right << 24 | right << 8 & 16711680 | right >>> 8 & 65280 | right >>> 24 & 240; - right = tmp; - for (var i = 0; i < shifts.length; ++i) { - if (shifts[i]) { - left = left << 2 | left >>> 26; - right = right << 2 | right >>> 26; - } else { - left = left << 1 | left >>> 27; - right = right << 1 | right >>> 27; - } - left &= -15; - right &= -15; - var lefttmp = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 15] | pc2bytes2[left >>> 20 & 15] | pc2bytes3[left >>> 16 & 15] | pc2bytes4[left >>> 12 & 15] | pc2bytes5[left >>> 8 & 15] | pc2bytes6[left >>> 4 & 15]; - var righttmp = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 15] | pc2bytes9[right >>> 20 & 15] | pc2bytes10[right >>> 16 & 15] | pc2bytes11[right >>> 12 & 15] | pc2bytes12[right >>> 8 & 15] | pc2bytes13[right >>> 4 & 15]; - tmp = (righttmp >>> 16 ^ lefttmp) & 65535; - keys[n++] = lefttmp ^ tmp; - keys[n++] = righttmp ^ tmp << 16; + var init = false; + var Nb = 4; + var sbox; + var isbox; + var rcon; + var mix; + var imix; + function initialize() { + init = true; + rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; + var xtime = new Array(256); + for (var i = 0; i < 128; ++i) { + xtime[i] = i << 1; + xtime[i + 128] = i + 128 << 1 ^ 283; + } + sbox = new Array(256); + isbox = new Array(256); + mix = new Array(4); + imix = new Array(4); + for (var i = 0; i < 4; ++i) { + mix[i] = new Array(256); + imix[i] = new Array(256); + } + var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; + for (var i = 0; i < 256; ++i) { + sx = ei ^ ei << 1 ^ ei << 2 ^ ei << 3 ^ ei << 4; + sx = sx >> 8 ^ sx & 255 ^ 99; + sbox[e] = sx; + isbox[sx] = e; + sx2 = xtime[sx]; + e2 = xtime[e]; + e4 = xtime[e2]; + e8 = xtime[e4]; + me = sx2 << 24 ^ // 2 + sx << 16 ^ // 1 + sx << 8 ^ // 1 + (sx ^ sx2); + ime = (e2 ^ e4 ^ e8) << 24 ^ // E (14) + (e ^ e8) << 16 ^ // 9 + (e ^ e4 ^ e8) << 8 ^ // D (13) + (e ^ e2 ^ e8); + for (var n = 0; n < 4; ++n) { + mix[n][e] = me; + imix[n][sx] = ime; + me = me << 24 | me >>> 8; + ime = ime << 24 | ime >>> 8; + } + if (e === 0) { + e = ei = 1; + } else { + e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; + ei ^= xtime[xtime[ei]]; } } - return keys; } - function _updateBlock(keys, input, output, decrypt) { - var iterations = keys.length === 32 ? 3 : 9; - var looping; - if (iterations === 3) { - looping = decrypt ? [30, -2, -2] : [0, 32, 2]; - } else { - looping = decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2]; + function _expandKey(key, decrypt) { + var w = key.slice(0); + var temp, iNk = 1; + var Nk = w.length; + var Nr1 = Nk + 6 + 1; + var end = Nb * Nr1; + for (var i = Nk; i < end; ++i) { + temp = w[i - 1]; + if (i % Nk === 0) { + temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ rcon[iNk] << 24; + iNk++; + } else if (Nk > 6 && i % Nk === 4) { + temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255]; + } + w[i] = w[i - Nk] ^ temp; } - var tmp; - var left = input[0]; - var right = input[1]; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - left = left << 1 | left >>> 31; - right = right << 1 | right >>> 31; - for (var j = 0; j < iterations; j += 3) { - var endloop = looping[j + 1]; - var loopinc = looping[j + 2]; - for (var i = looping[j]; i != endloop; i += loopinc) { - var right1 = right ^ keys[i]; - var right2 = (right >>> 4 | right << 28) ^ keys[i + 1]; - tmp = left; - left = right; - right = tmp ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right2 >>> 24 & 63] | spfunction3[right2 >>> 16 & 63] | spfunction5[right2 >>> 8 & 63] | spfunction7[right2 & 63]); + if (decrypt) { + var tmp; + var m0 = imix[0]; + var m1 = imix[1]; + var m2 = imix[2]; + var m3 = imix[3]; + var wnew = w.slice(0); + end = w.length; + for (var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { + if (i === 0 || i === end - Nb) { + wnew[i] = w[wi]; + wnew[i + 1] = w[wi + 3]; + wnew[i + 2] = w[wi + 2]; + wnew[i + 3] = w[wi + 1]; + } else { + for (var n = 0; n < Nb; ++n) { + tmp = w[wi + n]; + wnew[i + (3 & -n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; + } + } } - tmp = left; - left = right; - right = tmp; + w = wnew; } - left = left >>> 1 | left << 31; - right = right >>> 1 | right << 31; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - output[0] = left; - output[1] = right; + return w; } - function _createCipher(options) { - options = options || {}; - var mode = (options.mode || "CBC").toUpperCase(); - var algorithm = "DES-" + mode; - var cipher; - if (options.decrypt) { - cipher = forge.cipher.createDecipher(algorithm, options.key); + function _updateBlock(w, input, output, decrypt) { + var Nr = w.length / 4 - 1; + var m0, m1, m2, m3, sub; + if (decrypt) { + m0 = imix[0]; + m1 = imix[1]; + m2 = imix[2]; + m3 = imix[3]; + sub = isbox; } else { - cipher = forge.cipher.createCipher(algorithm, options.key); - } - var start = cipher.start; - cipher.start = function(iv, options2) { + m0 = mix[0]; + m1 = mix[1]; + m2 = mix[2]; + m3 = mix[3]; + sub = sbox; + } + var a, b, c, d, a2, b2, c2; + a = input[0] ^ w[0]; + b = input[decrypt ? 3 : 1] ^ w[1]; + c = input[2] ^ w[2]; + d = input[decrypt ? 1 : 3] ^ w[3]; + var i = 3; + for (var round = 1; round < Nr; ++round) { + a2 = m0[a >>> 24] ^ m1[b >>> 16 & 255] ^ m2[c >>> 8 & 255] ^ m3[d & 255] ^ w[++i]; + b2 = m0[b >>> 24] ^ m1[c >>> 16 & 255] ^ m2[d >>> 8 & 255] ^ m3[a & 255] ^ w[++i]; + c2 = m0[c >>> 24] ^ m1[d >>> 16 & 255] ^ m2[a >>> 8 & 255] ^ m3[b & 255] ^ w[++i]; + d = m0[d >>> 24] ^ m1[a >>> 16 & 255] ^ m2[b >>> 8 & 255] ^ m3[c & 255] ^ w[++i]; + a = a2; + b = b2; + c = c2; + } + output[0] = sub[a >>> 24] << 24 ^ sub[b >>> 16 & 255] << 16 ^ sub[c >>> 8 & 255] << 8 ^ sub[d & 255] ^ w[++i]; + output[decrypt ? 3 : 1] = sub[b >>> 24] << 24 ^ sub[c >>> 16 & 255] << 16 ^ sub[d >>> 8 & 255] << 8 ^ sub[a & 255] ^ w[++i]; + output[2] = sub[c >>> 24] << 24 ^ sub[d >>> 16 & 255] << 16 ^ sub[a >>> 8 & 255] << 8 ^ sub[b & 255] ^ w[++i]; + output[decrypt ? 1 : 3] = sub[d >>> 24] << 24 ^ sub[a >>> 16 & 255] << 16 ^ sub[b >>> 8 & 255] << 8 ^ sub[c & 255] ^ w[++i]; + } + function _createCipher(options) { + options = options || {}; + var mode = (options.mode || "CBC").toUpperCase(); + var algorithm = "AES-" + mode; + var cipher; + if (options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + var start = cipher.start; + cipher.start = function(iv, options2) { var output = null; if (options2 instanceof forge.util.ByteBuffer) { output = options2; @@ -26785,2382 +25785,1865 @@ var require_des = __commonJS({ } }); -// node_modules/node-forge/lib/pbkdf2.js -var require_pbkdf2 = __commonJS({ - "node_modules/node-forge/lib/pbkdf2.js"(exports2, module2) { +// node_modules/node-forge/lib/oids.js +var require_oids = __commonJS({ + "node_modules/node-forge/lib/oids.js"(exports2, module2) { var forge = require_forge(); - require_hmac(); - require_md(); - require_util8(); - var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; - var crypto; - if (forge.util.isNodejs && !forge.options.usePureJavaScript) { - crypto = require("crypto"); + forge.pki = forge.pki || {}; + var oids = module2.exports = forge.pki.oids = forge.oids = forge.oids || {}; + function _IN(id, name) { + oids[id] = name; + oids[name] = id; } - module2.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(p, s, c, dkLen, md, callback) { - if (typeof md === "function") { - callback = md; - md = null; - } - if (forge.util.isNodejs && !forge.options.usePureJavaScript && crypto.pbkdf2 && (md === null || typeof md !== "object") && (crypto.pbkdf2Sync.length > 4 || (!md || md === "sha1"))) { - if (typeof md !== "string") { - md = "sha1"; - } - p = Buffer.from(p, "binary"); - s = Buffer.from(s, "binary"); - if (!callback) { - if (crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2Sync(p, s, c, dkLen).toString("binary"); + function _I_(id, name) { + oids[id] = name; + } + _IN("1.2.840.113549.1.1.1", "rsaEncryption"); + _IN("1.2.840.113549.1.1.4", "md5WithRSAEncryption"); + _IN("1.2.840.113549.1.1.5", "sha1WithRSAEncryption"); + _IN("1.2.840.113549.1.1.7", "RSAES-OAEP"); + _IN("1.2.840.113549.1.1.8", "mgf1"); + _IN("1.2.840.113549.1.1.9", "pSpecified"); + _IN("1.2.840.113549.1.1.10", "RSASSA-PSS"); + _IN("1.2.840.113549.1.1.11", "sha256WithRSAEncryption"); + _IN("1.2.840.113549.1.1.12", "sha384WithRSAEncryption"); + _IN("1.2.840.113549.1.1.13", "sha512WithRSAEncryption"); + _IN("1.3.101.112", "EdDSA25519"); + _IN("1.2.840.10040.4.3", "dsa-with-sha1"); + _IN("1.3.14.3.2.7", "desCBC"); + _IN("1.3.14.3.2.26", "sha1"); + _IN("1.3.14.3.2.29", "sha1WithRSASignature"); + _IN("2.16.840.1.101.3.4.2.1", "sha256"); + _IN("2.16.840.1.101.3.4.2.2", "sha384"); + _IN("2.16.840.1.101.3.4.2.3", "sha512"); + _IN("2.16.840.1.101.3.4.2.4", "sha224"); + _IN("2.16.840.1.101.3.4.2.5", "sha512-224"); + _IN("2.16.840.1.101.3.4.2.6", "sha512-256"); + _IN("1.2.840.113549.2.2", "md2"); + _IN("1.2.840.113549.2.5", "md5"); + _IN("1.2.840.113549.1.7.1", "data"); + _IN("1.2.840.113549.1.7.2", "signedData"); + _IN("1.2.840.113549.1.7.3", "envelopedData"); + _IN("1.2.840.113549.1.7.4", "signedAndEnvelopedData"); + _IN("1.2.840.113549.1.7.5", "digestedData"); + _IN("1.2.840.113549.1.7.6", "encryptedData"); + _IN("1.2.840.113549.1.9.1", "emailAddress"); + _IN("1.2.840.113549.1.9.2", "unstructuredName"); + _IN("1.2.840.113549.1.9.3", "contentType"); + _IN("1.2.840.113549.1.9.4", "messageDigest"); + _IN("1.2.840.113549.1.9.5", "signingTime"); + _IN("1.2.840.113549.1.9.6", "counterSignature"); + _IN("1.2.840.113549.1.9.7", "challengePassword"); + _IN("1.2.840.113549.1.9.8", "unstructuredAddress"); + _IN("1.2.840.113549.1.9.14", "extensionRequest"); + _IN("1.2.840.113549.1.9.20", "friendlyName"); + _IN("1.2.840.113549.1.9.21", "localKeyId"); + _IN("1.2.840.113549.1.9.22.1", "x509Certificate"); + _IN("1.2.840.113549.1.12.10.1.1", "keyBag"); + _IN("1.2.840.113549.1.12.10.1.2", "pkcs8ShroudedKeyBag"); + _IN("1.2.840.113549.1.12.10.1.3", "certBag"); + _IN("1.2.840.113549.1.12.10.1.4", "crlBag"); + _IN("1.2.840.113549.1.12.10.1.5", "secretBag"); + _IN("1.2.840.113549.1.12.10.1.6", "safeContentsBag"); + _IN("1.2.840.113549.1.5.13", "pkcs5PBES2"); + _IN("1.2.840.113549.1.5.12", "pkcs5PBKDF2"); + _IN("1.2.840.113549.1.12.1.1", "pbeWithSHAAnd128BitRC4"); + _IN("1.2.840.113549.1.12.1.2", "pbeWithSHAAnd40BitRC4"); + _IN("1.2.840.113549.1.12.1.3", "pbeWithSHAAnd3-KeyTripleDES-CBC"); + _IN("1.2.840.113549.1.12.1.4", "pbeWithSHAAnd2-KeyTripleDES-CBC"); + _IN("1.2.840.113549.1.12.1.5", "pbeWithSHAAnd128BitRC2-CBC"); + _IN("1.2.840.113549.1.12.1.6", "pbewithSHAAnd40BitRC2-CBC"); + _IN("1.2.840.113549.2.7", "hmacWithSHA1"); + _IN("1.2.840.113549.2.8", "hmacWithSHA224"); + _IN("1.2.840.113549.2.9", "hmacWithSHA256"); + _IN("1.2.840.113549.2.10", "hmacWithSHA384"); + _IN("1.2.840.113549.2.11", "hmacWithSHA512"); + _IN("1.2.840.113549.3.7", "des-EDE3-CBC"); + _IN("2.16.840.1.101.3.4.1.2", "aes128-CBC"); + _IN("2.16.840.1.101.3.4.1.22", "aes192-CBC"); + _IN("2.16.840.1.101.3.4.1.42", "aes256-CBC"); + _IN("2.5.4.3", "commonName"); + _IN("2.5.4.4", "surname"); + _IN("2.5.4.5", "serialNumber"); + _IN("2.5.4.6", "countryName"); + _IN("2.5.4.7", "localityName"); + _IN("2.5.4.8", "stateOrProvinceName"); + _IN("2.5.4.9", "streetAddress"); + _IN("2.5.4.10", "organizationName"); + _IN("2.5.4.11", "organizationalUnitName"); + _IN("2.5.4.12", "title"); + _IN("2.5.4.13", "description"); + _IN("2.5.4.15", "businessCategory"); + _IN("2.5.4.17", "postalCode"); + _IN("2.5.4.42", "givenName"); + _IN("1.3.6.1.4.1.311.60.2.1.2", "jurisdictionOfIncorporationStateOrProvinceName"); + _IN("1.3.6.1.4.1.311.60.2.1.3", "jurisdictionOfIncorporationCountryName"); + _IN("2.16.840.1.113730.1.1", "nsCertType"); + _IN("2.16.840.1.113730.1.13", "nsComment"); + _I_("2.5.29.1", "authorityKeyIdentifier"); + _I_("2.5.29.2", "keyAttributes"); + _I_("2.5.29.3", "certificatePolicies"); + _I_("2.5.29.4", "keyUsageRestriction"); + _I_("2.5.29.5", "policyMapping"); + _I_("2.5.29.6", "subtreesConstraint"); + _I_("2.5.29.7", "subjectAltName"); + _I_("2.5.29.8", "issuerAltName"); + _I_("2.5.29.9", "subjectDirectoryAttributes"); + _I_("2.5.29.10", "basicConstraints"); + _I_("2.5.29.11", "nameConstraints"); + _I_("2.5.29.12", "policyConstraints"); + _I_("2.5.29.13", "basicConstraints"); + _IN("2.5.29.14", "subjectKeyIdentifier"); + _IN("2.5.29.15", "keyUsage"); + _I_("2.5.29.16", "privateKeyUsagePeriod"); + _IN("2.5.29.17", "subjectAltName"); + _IN("2.5.29.18", "issuerAltName"); + _IN("2.5.29.19", "basicConstraints"); + _I_("2.5.29.20", "cRLNumber"); + _I_("2.5.29.21", "cRLReason"); + _I_("2.5.29.22", "expirationDate"); + _I_("2.5.29.23", "instructionCode"); + _I_("2.5.29.24", "invalidityDate"); + _I_("2.5.29.25", "cRLDistributionPoints"); + _I_("2.5.29.26", "issuingDistributionPoint"); + _I_("2.5.29.27", "deltaCRLIndicator"); + _I_("2.5.29.28", "issuingDistributionPoint"); + _I_("2.5.29.29", "certificateIssuer"); + _I_("2.5.29.30", "nameConstraints"); + _IN("2.5.29.31", "cRLDistributionPoints"); + _IN("2.5.29.32", "certificatePolicies"); + _I_("2.5.29.33", "policyMappings"); + _I_("2.5.29.34", "policyConstraints"); + _IN("2.5.29.35", "authorityKeyIdentifier"); + _I_("2.5.29.36", "policyConstraints"); + _IN("2.5.29.37", "extKeyUsage"); + _I_("2.5.29.46", "freshestCRL"); + _I_("2.5.29.54", "inhibitAnyPolicy"); + _IN("1.3.6.1.4.1.11129.2.4.2", "timestampList"); + _IN("1.3.6.1.5.5.7.1.1", "authorityInfoAccess"); + _IN("1.3.6.1.5.5.7.3.1", "serverAuth"); + _IN("1.3.6.1.5.5.7.3.2", "clientAuth"); + _IN("1.3.6.1.5.5.7.3.3", "codeSigning"); + _IN("1.3.6.1.5.5.7.3.4", "emailProtection"); + _IN("1.3.6.1.5.5.7.3.8", "timeStamping"); + } +}); + +// node_modules/node-forge/lib/asn1.js +var require_asn1 = __commonJS({ + "node_modules/node-forge/lib/asn1.js"(exports2, module2) { + var forge = require_forge(); + require_util8(); + require_oids(); + var asn1 = module2.exports = forge.asn1 = forge.asn1 || {}; + asn1.Class = { + UNIVERSAL: 0, + APPLICATION: 64, + CONTEXT_SPECIFIC: 128, + PRIVATE: 192 + }; + asn1.Type = { + NONE: 0, + BOOLEAN: 1, + INTEGER: 2, + BITSTRING: 3, + OCTETSTRING: 4, + NULL: 5, + OID: 6, + ODESC: 7, + EXTERNAL: 8, + REAL: 9, + ENUMERATED: 10, + EMBEDDED: 11, + UTF8: 12, + ROID: 13, + SEQUENCE: 16, + SET: 17, + PRINTABLESTRING: 19, + IA5STRING: 22, + UTCTIME: 23, + GENERALIZEDTIME: 24, + BMPSTRING: 30 + }; + asn1.create = function(tagClass, type2, constructed, value, options) { + if (forge.util.isArray(value)) { + var tmp = []; + for (var i = 0; i < value.length; ++i) { + if (value[i] !== void 0) { + tmp.push(value[i]); } - return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString("binary"); - } - if (crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2(p, s, c, dkLen, function(err2, key) { - if (err2) { - return callback(err2); - } - callback(null, key.toString("binary")); - }); } - return crypto.pbkdf2(p, s, c, dkLen, md, function(err2, key) { - if (err2) { - return callback(err2); - } - callback(null, key.toString("binary")); - }); + value = tmp; } - if (typeof md === "undefined" || md === null) { - md = "sha1"; + var obj = { + tagClass, + type: type2, + constructed, + composed: constructed || forge.util.isArray(value), + value + }; + if (options && "bitStringContents" in options) { + obj.bitStringContents = options.bitStringContents; + obj.original = asn1.copy(obj); } - if (typeof md === "string") { - if (!(md in forge.md.algorithms)) { - throw new Error("Unknown hash algorithm: " + md); + return obj; + }; + asn1.copy = function(obj, options) { + var copy; + if (forge.util.isArray(obj)) { + copy = []; + for (var i = 0; i < obj.length; ++i) { + copy.push(asn1.copy(obj[i], options)); } - md = forge.md[md].create(); + return copy; } - var hLen = md.digestLength; - if (dkLen > 4294967295 * hLen) { - var err = new Error("Derived key is too long."); - if (callback) { - return callback(err); - } - throw err; + if (typeof obj === "string") { + return obj; } - var len = Math.ceil(dkLen / hLen); - var r = dkLen - (len - 1) * hLen; - var prf = forge.hmac.create(); - prf.start(md, p); - var dk = ""; - var xor, u_c, u_c1; - if (!callback) { - for (var i = 1; i <= len; ++i) { - prf.start(null, null); - prf.update(s); - prf.update(forge.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - for (var j = 2; j <= c; ++j) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - xor = forge.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; + copy = { + tagClass: obj.tagClass, + type: obj.type, + constructed: obj.constructed, + composed: obj.composed, + value: asn1.copy(obj.value, options) + }; + if (options && !options.excludeBitStringContents) { + copy.bitStringContents = obj.bitStringContents; + } + return copy; + }; + asn1.equals = function(obj1, obj2, options) { + if (forge.util.isArray(obj1)) { + if (!forge.util.isArray(obj2)) { + return false; + } + if (obj1.length !== obj2.length) { + return false; + } + for (var i = 0; i < obj1.length; ++i) { + if (!asn1.equals(obj1[i], obj2[i])) { + return false; } - dk += i < len ? xor : xor.substr(0, r); } - return dk; + return true; } - var i = 1, j; - function outer() { - if (i > len) { - return callback(null, dk); - } - prf.start(null, null); - prf.update(s); - prf.update(forge.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - j = 2; - inner(); + if (typeof obj1 !== typeof obj2) { + return false; } - function inner() { - if (j <= c) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - xor = forge.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - ++j; - return forge.util.setImmediate(inner); - } - dk += i < len ? xor : xor.substr(0, r); - ++i; - outer(); + if (typeof obj1 === "string") { + return obj1 === obj2; } - outer(); + var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value); + if (options && options.includeBitStringContents) { + equal = equal && obj1.bitStringContents === obj2.bitStringContents; + } + return equal; }; - } -}); - -// node_modules/node-forge/lib/sha256.js -var require_sha256 = __commonJS({ - "node_modules/node-forge/lib/sha256.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util8(); - var sha256 = module2.exports = forge.sha256 = forge.sha256 || {}; - forge.md.sha256 = forge.md.algorithms.sha256 = sha256; - sha256.create = function() { - if (!_initialized) { - _init(); + asn1.getBerValueLength = function(b) { + var b2 = b.getByte(); + if (b2 === 128) { + return void 0; } - var _state = null; - var _input = forge.util.createBuffer(); - var _w = new Array(64); - var md = { - algorithm: "sha256", - blockLength: 64, - digestLength: 32, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge.util.createBuffer(); - _state = { - h0: 1779033703, - h1: 3144134277, - h2: 1013904242, - h3: 2773480762, - h4: 1359893119, - h5: 2600822924, - h6: 528734635, - h7: 1541459225 - }; - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4, - h5: _state.h5, - h6: _state.h6, - h7: _state.h7 - }; - _update(s2, _w, finalBlock); - var rval = forge.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - rval.putInt32(s2.h5); - rval.putInt32(s2.h6); - rval.putInt32(s2.h7); - return rval; - }; - return md; + var length; + var longForm = b2 & 128; + if (!longForm) { + length = b2; + } else { + length = b.getInt((b2 & 127) << 3); + } + return length; }; - var _padding = null; - var _initialized = false; - var _k = null; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0), 64); - _k = [ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 - ]; - _initialized = true; - } - function _update(s, w, bytes) { - var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; - var len = bytes.length(); - while (len >= 64) { - for (i = 0; i < 16; ++i) { - w[i] = bytes.getInt32(); - } - for (; i < 64; ++i) { - t1 = w[i - 2]; - t1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; - t2 = w[i - 15]; - t2 = (t2 >>> 7 | t2 << 25) ^ (t2 >>> 18 | t2 << 14) ^ t2 >>> 3; - w[i] = t1 + w[i - 7] + t2 + w[i - 16] | 0; - } - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - f = s.h5; - g = s.h6; - h = s.h7; - for (i = 0; i < 64; ++i) { - s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); - ch = g ^ e & (f ^ g); - s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); - maj = a & b | c & (a ^ b); - t1 = h + s1 + ch + _k[i] + w[i]; - t2 = s0 + maj; - h = g; - g = f; - f = e; - e = d + t1 >>> 0; - d = c; - c = b; - b = a; - a = t1 + t2 >>> 0; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - s.h4 = s.h4 + e | 0; - s.h5 = s.h5 + f | 0; - s.h6 = s.h6 + g | 0; - s.h7 = s.h7 + h | 0; - len -= 64; + function _checkBufferLength(bytes, remaining, n) { + if (n > remaining) { + var error4 = new Error("Too few bytes to parse DER."); + error4.available = bytes.length(); + error4.remaining = remaining; + error4.requested = n; + throw error4; } } - } -}); - -// node_modules/node-forge/lib/prng.js -var require_prng = __commonJS({ - "node_modules/node-forge/lib/prng.js"(exports2, module2) { - var forge = require_forge(); - require_util8(); - var _crypto = null; - if (forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions["node-webkit"]) { - _crypto = require("crypto"); - } - var prng = module2.exports = forge.prng = forge.prng || {}; - prng.create = function(plugin) { - var ctx = { - plugin, - key: null, - seed: null, - time: null, - // number of reseeds so far - reseeds: 0, - // amount of data generated so far - generated: 0, - // no initial key bytes - keyBytes: "" - }; - var md = plugin.md; - var pools = new Array(32); - for (var i = 0; i < 32; ++i) { - pools[i] = md.create(); + var _getValueLength = function(bytes, remaining) { + var b2 = bytes.getByte(); + remaining--; + if (b2 === 128) { + return void 0; } - ctx.pools = pools; - ctx.pool = 0; - ctx.generate = function(count, callback) { - if (!callback) { - return ctx.generateSync(count); + var length; + var longForm = b2 & 128; + if (!longForm) { + length = b2; + } else { + var longFormBytes = b2 & 127; + _checkBufferLength(bytes, remaining, longFormBytes); + length = bytes.getInt(longFormBytes << 3); + } + if (length < 0) { + throw new Error("Negative length: " + length); + } + return length; + }; + asn1.fromDer = function(bytes, options) { + if (options === void 0) { + options = { + strict: true, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if (typeof options === "boolean") { + options = { + strict: options, + parseAllBytes: true, + decodeBitStrings: true + }; + } + if (!("strict" in options)) { + options.strict = true; + } + if (!("parseAllBytes" in options)) { + options.parseAllBytes = true; + } + if (!("decodeBitStrings" in options)) { + options.decodeBitStrings = true; + } + if (typeof bytes === "string") { + bytes = forge.util.createBuffer(bytes); + } + var byteCount = bytes.length(); + var value = _fromDer(bytes, bytes.length(), 0, options); + if (options.parseAllBytes && bytes.length() !== 0) { + var error4 = new Error("Unparsed DER bytes remain after ASN.1 parsing."); + error4.byteCount = byteCount; + error4.remaining = bytes.length(); + throw error4; + } + return value; + }; + function _fromDer(bytes, remaining, depth, options) { + var start; + _checkBufferLength(bytes, remaining, 2); + var b1 = bytes.getByte(); + remaining--; + var tagClass = b1 & 192; + var type2 = b1 & 31; + start = bytes.length(); + var length = _getValueLength(bytes, remaining); + remaining -= start - bytes.length(); + if (length !== void 0 && length > remaining) { + if (options.strict) { + var error4 = new Error("Too few bytes to read ASN.1 value."); + error4.available = bytes.length(); + error4.remaining = remaining; + error4.requested = length; + throw error4; } - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - var b = forge.util.createBuffer(); - ctx.key = null; - generate(); - function generate(err) { - if (err) { - return callback(err); - } - if (b.length() >= count) { - return callback(null, b.getBytes(count)); - } - if (ctx.generated > 1048575) { - ctx.key = null; + length = remaining; + } + var value; + var bitStringContents; + var constructed = (b1 & 32) === 32; + if (constructed) { + value = []; + if (length === void 0) { + for (; ; ) { + _checkBufferLength(bytes, remaining, 2); + if (bytes.bytes(2) === String.fromCharCode(0, 0)) { + bytes.getBytes(2); + remaining -= 2; + break; + } + start = bytes.length(); + value.push(_fromDer(bytes, remaining, depth + 1, options)); + remaining -= start - bytes.length(); } - if (ctx.key === null) { - return forge.util.nextTick(function() { - _reseed(generate); - }); + } else { + while (length > 0) { + start = bytes.length(); + value.push(_fromDer(bytes, length, depth + 1, options)); + remaining -= start - bytes.length(); + length -= start - bytes.length(); } - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - forge.util.setImmediate(generate); } - }; - ctx.generateSync = function(count) { - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - ctx.key = null; - var b = forge.util.createBuffer(); - while (b.length() < count) { - if (ctx.generated > 1048575) { - ctx.key = null; - } - if (ctx.key === null) { - _reseedSync(); + } + if (value === void 0 && tagClass === asn1.Class.UNIVERSAL && type2 === asn1.Type.BITSTRING) { + bitStringContents = bytes.bytes(length); + } + if (value === void 0 && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && // FIXME: OCTET STRINGs not yet supported here + // .. other parts of forge expect to decode OCTET STRINGs manually + type2 === asn1.Type.BITSTRING && length > 1) { + var savedRead = bytes.read; + var savedRemaining = remaining; + var unused = 0; + if (type2 === asn1.Type.BITSTRING) { + _checkBufferLength(bytes, remaining, 1); + unused = bytes.getByte(); + remaining--; + } + if (unused === 0) { + try { + start = bytes.length(); + var subOptions = { + // enforce strict mode to avoid parsing ASN.1 from plain data + strict: true, + decodeBitStrings: true + }; + var composed = _fromDer(bytes, remaining, depth + 1, subOptions); + var used = start - bytes.length(); + remaining -= used; + if (type2 == asn1.Type.BITSTRING) { + used++; + } + var tc = composed.tagClass; + if (used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { + value = [composed]; + } + } catch (ex) { } - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); } - return b.getBytes(count); - }; - function _reseed(callback) { - if (ctx.pools[0].messageLength >= 32) { - _seed(); - return callback(); + if (value === void 0) { + bytes.read = savedRead; + remaining = savedRemaining; } - var needed = 32 - ctx.pools[0].messageLength << 5; - ctx.seedFile(needed, function(err, bytes) { - if (err) { - return callback(err); - } - ctx.collect(bytes); - _seed(); - callback(); - }); } - function _reseedSync() { - if (ctx.pools[0].messageLength >= 32) { - return _seed(); + if (value === void 0) { + if (length === void 0) { + if (options.strict) { + throw new Error("Non-constructed ASN.1 object of indefinite length."); + } + length = remaining; } - var needed = 32 - ctx.pools[0].messageLength << 5; - ctx.collect(ctx.seedFileSync(needed)); - _seed(); - } - function _seed() { - ctx.reseeds = ctx.reseeds === 4294967295 ? 0 : ctx.reseeds + 1; - var md2 = ctx.plugin.md.create(); - md2.update(ctx.keyBytes); - var _2powK = 1; - for (var k = 0; k < 32; ++k) { - if (ctx.reseeds % _2powK === 0) { - md2.update(ctx.pools[k].digest().getBytes()); - ctx.pools[k].start(); + if (type2 === asn1.Type.BMPSTRING) { + value = ""; + for (; length > 0; length -= 2) { + _checkBufferLength(bytes, remaining, 2); + value += String.fromCharCode(bytes.getInt16()); + remaining -= 2; } - _2powK = _2powK << 1; + } else { + value = bytes.getBytes(length); + remaining -= length; } - ctx.keyBytes = md2.digest().getBytes(); - md2.start(); - md2.update(ctx.keyBytes); - var seedBytes = md2.digest().getBytes(); - ctx.key = ctx.plugin.formatKey(ctx.keyBytes); - ctx.seed = ctx.plugin.formatSeed(seedBytes); - ctx.generated = 0; } - function defaultSeedFile(needed) { - var getRandomValues = null; - var globalScope = forge.util.globalScope; - var _crypto2 = globalScope.crypto || globalScope.msCrypto; - if (_crypto2 && _crypto2.getRandomValues) { - getRandomValues = function(arr) { - return _crypto2.getRandomValues(arr); - }; + var asn1Options = bitStringContents === void 0 ? null : { + bitStringContents + }; + return asn1.create(tagClass, type2, constructed, value, asn1Options); + } + asn1.toDer = function(obj) { + var bytes = forge.util.createBuffer(); + var b1 = obj.tagClass | obj.type; + var value = forge.util.createBuffer(); + var useBitStringContents = false; + if ("bitStringContents" in obj) { + useBitStringContents = true; + if (obj.original) { + useBitStringContents = asn1.equals(obj, obj.original); } - var b = forge.util.createBuffer(); - if (getRandomValues) { - while (b.length() < needed) { - var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); - var entropy = new Uint32Array(Math.floor(count)); - try { - getRandomValues(entropy); - for (var i2 = 0; i2 < entropy.length; ++i2) { - b.putInt32(entropy[i2]); - } - } catch (e) { - if (!(typeof QuotaExceededError !== "undefined" && e instanceof QuotaExceededError)) { - throw e; - } - } + } + if (useBitStringContents) { + value.putBytes(obj.bitStringContents); + } else if (obj.composed) { + if (obj.constructed) { + b1 |= 32; + } else { + value.putByte(0); + } + for (var i = 0; i < obj.value.length; ++i) { + if (obj.value[i] !== void 0) { + value.putBuffer(asn1.toDer(obj.value[i])); } } - if (b.length() < needed) { - var hi, lo, next; - var seed = Math.floor(Math.random() * 65536); - while (b.length() < needed) { - lo = 16807 * (seed & 65535); - hi = 16807 * (seed >> 16); - lo += (hi & 32767) << 16; - lo += hi >> 15; - lo = (lo & 2147483647) + (lo >> 31); - seed = lo & 4294967295; - for (var i2 = 0; i2 < 3; ++i2) { - next = seed >>> (i2 << 3); - next ^= Math.floor(Math.random() * 256); - b.putByte(next & 255); - } + } else { + if (obj.type === asn1.Type.BMPSTRING) { + for (var i = 0; i < obj.value.length; ++i) { + value.putInt16(obj.value.charCodeAt(i)); + } + } else { + if (obj.type === asn1.Type.INTEGER && obj.value.length > 1 && // leading 0x00 for positive integer + (obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer + obj.value.charCodeAt(0) === 255 && (obj.value.charCodeAt(1) & 128) === 128)) { + value.putBytes(obj.value.substr(1)); + } else { + value.putBytes(obj.value); } } - return b.getBytes(needed); } - if (_crypto) { - ctx.seedFile = function(needed, callback) { - _crypto.randomBytes(needed, function(err, bytes) { - if (err) { - return callback(err); - } - callback(null, bytes.toString()); - }); - }; - ctx.seedFileSync = function(needed) { - return _crypto.randomBytes(needed).toString(); - }; + bytes.putByte(b1); + if (value.length() <= 127) { + bytes.putByte(value.length() & 127); } else { - ctx.seedFile = function(needed, callback) { - try { - callback(null, defaultSeedFile(needed)); - } catch (e) { - callback(e); + var len = value.length(); + var lenBytes = ""; + do { + lenBytes += String.fromCharCode(len & 255); + len = len >>> 8; + } while (len > 0); + bytes.putByte(lenBytes.length | 128); + for (var i = lenBytes.length - 1; i >= 0; --i) { + bytes.putByte(lenBytes.charCodeAt(i)); + } + } + bytes.putBuffer(value); + return bytes; + }; + asn1.oidToDer = function(oid) { + var values = oid.split("."); + var bytes = forge.util.createBuffer(); + bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); + var last, valueBytes, value, b; + for (var i = 2; i < values.length; ++i) { + last = true; + valueBytes = []; + value = parseInt(values[i], 10); + do { + b = value & 127; + value = value >>> 7; + if (!last) { + b |= 128; } - }; - ctx.seedFileSync = defaultSeedFile; + valueBytes.push(b); + last = false; + } while (value > 0); + for (var n = valueBytes.length - 1; n >= 0; --n) { + bytes.putByte(valueBytes[n]); + } } - ctx.collect = function(bytes) { - var count = bytes.length; - for (var i2 = 0; i2 < count; ++i2) { - ctx.pools[ctx.pool].update(bytes.substr(i2, 1)); - ctx.pool = ctx.pool === 31 ? 0 : ctx.pool + 1; + return bytes; + }; + asn1.derToOid = function(bytes) { + var oid; + if (typeof bytes === "string") { + bytes = forge.util.createBuffer(bytes); + } + var b = bytes.getByte(); + oid = Math.floor(b / 40) + "." + b % 40; + var value = 0; + while (bytes.length() > 0) { + b = bytes.getByte(); + value = value << 7; + if (b & 128) { + value += b & 127; + } else { + oid += "." + (value + b); + value = 0; } - }; - ctx.collectInt = function(i2, n) { - var bytes = ""; - for (var x = 0; x < n; x += 8) { - bytes += String.fromCharCode(i2 >> x & 255); + } + return oid; + }; + asn1.utcTimeToDate = function(utc) { + var date = /* @__PURE__ */ new Date(); + var year = parseInt(utc.substr(0, 2), 10); + year = year >= 50 ? 1900 + year : 2e3 + year; + var MM = parseInt(utc.substr(2, 2), 10) - 1; + var DD = parseInt(utc.substr(4, 2), 10); + var hh = parseInt(utc.substr(6, 2), 10); + var mm = parseInt(utc.substr(8, 2), 10); + var ss = 0; + if (utc.length > 11) { + var c = utc.charAt(10); + var end = 10; + if (c !== "+" && c !== "-") { + ss = parseInt(utc.substr(10, 2), 10); + end += 2; } - ctx.collect(bytes); - }; - ctx.registerWorker = function(worker) { - if (worker === self) { - ctx.seedFile = function(needed, callback) { - function listener2(e) { - var data = e.data; - if (data.forge && data.forge.prng) { - self.removeEventListener("message", listener2); - callback(data.forge.prng.err, data.forge.prng.bytes); - } - } - self.addEventListener("message", listener2); - self.postMessage({ forge: { prng: { needed } } }); - }; - } else { - var listener = function(e) { - var data = e.data; - if (data.forge && data.forge.prng) { - ctx.seedFile(data.forge.prng.needed, function(err, bytes) { - worker.postMessage({ forge: { prng: { err, bytes } } }); - }); - } - }; - worker.addEventListener("message", listener); + } + date.setUTCFullYear(year, MM, DD); + date.setUTCHours(hh, mm, ss, 0); + if (end) { + c = utc.charAt(end); + if (c === "+" || c === "-") { + var hhoffset = parseInt(utc.substr(end + 1, 2), 10); + var mmoffset = parseInt(utc.substr(end + 4, 2), 10); + var offset = hhoffset * 60 + mmoffset; + offset *= 6e4; + if (c === "+") { + date.setTime(+date - offset); + } else { + date.setTime(+date + offset); + } } - }; - return ctx; + } + return date; }; - } -}); - -// node_modules/node-forge/lib/random.js -var require_random = __commonJS({ - "node_modules/node-forge/lib/random.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_sha256(); - require_prng(); - require_util8(); - (function() { - if (forge.random && forge.random.getBytes) { - module2.exports = forge.random; - return; + asn1.generalizedTimeToDate = function(gentime) { + var date = /* @__PURE__ */ new Date(); + var YYYY = parseInt(gentime.substr(0, 4), 10); + var MM = parseInt(gentime.substr(4, 2), 10) - 1; + var DD = parseInt(gentime.substr(6, 2), 10); + var hh = parseInt(gentime.substr(8, 2), 10); + var mm = parseInt(gentime.substr(10, 2), 10); + var ss = parseInt(gentime.substr(12, 2), 10); + var fff = 0; + var offset = 0; + var isUTC = false; + if (gentime.charAt(gentime.length - 1) === "Z") { + isUTC = true; } - (function(jQuery2) { - var prng_aes = {}; - var _prng_aes_output = new Array(4); - var _prng_aes_buffer = forge.util.createBuffer(); - prng_aes.formatKey = function(key2) { - var tmp = forge.util.createBuffer(key2); - key2 = new Array(4); - key2[0] = tmp.getInt32(); - key2[1] = tmp.getInt32(); - key2[2] = tmp.getInt32(); - key2[3] = tmp.getInt32(); - return forge.aes._expandKey(key2, false); - }; - prng_aes.formatSeed = function(seed) { - var tmp = forge.util.createBuffer(seed); - seed = new Array(4); - seed[0] = tmp.getInt32(); - seed[1] = tmp.getInt32(); - seed[2] = tmp.getInt32(); - seed[3] = tmp.getInt32(); - return seed; - }; - prng_aes.cipher = function(key2, seed) { - forge.aes._updateBlock(key2, seed, _prng_aes_output, false); - _prng_aes_buffer.putInt32(_prng_aes_output[0]); - _prng_aes_buffer.putInt32(_prng_aes_output[1]); - _prng_aes_buffer.putInt32(_prng_aes_output[2]); - _prng_aes_buffer.putInt32(_prng_aes_output[3]); - return _prng_aes_buffer.getBytes(); - }; - prng_aes.increment = function(seed) { - ++seed[3]; - return seed; - }; - prng_aes.md = forge.md.sha256; - function spawnPrng() { - var ctx = forge.prng.create(prng_aes); - ctx.getBytes = function(count, callback) { - return ctx.generate(count, callback); - }; - ctx.getBytesSync = function(count) { - return ctx.generate(count); - }; - return ctx; + var end = gentime.length - 5, c = gentime.charAt(end); + if (c === "+" || c === "-") { + var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); + var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); + offset = hhoffset * 60 + mmoffset; + offset *= 6e4; + if (c === "+") { + offset *= -1; } - var _ctx = spawnPrng(); - var getRandomValues = null; - var globalScope = forge.util.globalScope; - var _crypto = globalScope.crypto || globalScope.msCrypto; - if (_crypto && _crypto.getRandomValues) { - getRandomValues = function(arr) { - return _crypto.getRandomValues(arr); - }; + isUTC = true; + } + if (gentime.charAt(14) === ".") { + fff = parseFloat(gentime.substr(14), 10) * 1e3; + } + if (isUTC) { + date.setUTCFullYear(YYYY, MM, DD); + date.setUTCHours(hh, mm, ss, fff); + date.setTime(+date + offset); + } else { + date.setFullYear(YYYY, MM, DD); + date.setHours(hh, mm, ss, fff); + } + return date; + }; + asn1.dateToUtcTime = function(date) { + if (typeof date === "string") { + return date; + } + var rval = ""; + var format = []; + format.push(("" + date.getUTCFullYear()).substr(2)); + format.push("" + (date.getUTCMonth() + 1)); + format.push("" + date.getUTCDate()); + format.push("" + date.getUTCHours()); + format.push("" + date.getUTCMinutes()); + format.push("" + date.getUTCSeconds()); + for (var i = 0; i < format.length; ++i) { + if (format[i].length < 2) { + rval += "0"; } - if (forge.options.usePureJavaScript || !forge.util.isNodejs && !getRandomValues) { - if (typeof window === "undefined" || window.document === void 0) { + rval += format[i]; + } + rval += "Z"; + return rval; + }; + asn1.dateToGeneralizedTime = function(date) { + if (typeof date === "string") { + return date; + } + var rval = ""; + var format = []; + format.push("" + date.getUTCFullYear()); + format.push("" + (date.getUTCMonth() + 1)); + format.push("" + date.getUTCDate()); + format.push("" + date.getUTCHours()); + format.push("" + date.getUTCMinutes()); + format.push("" + date.getUTCSeconds()); + for (var i = 0; i < format.length; ++i) { + if (format[i].length < 2) { + rval += "0"; + } + rval += format[i]; + } + rval += "Z"; + return rval; + }; + asn1.integerToDer = function(x) { + var rval = forge.util.createBuffer(); + if (x >= -128 && x < 128) { + return rval.putSignedInt(x, 8); + } + if (x >= -32768 && x < 32768) { + return rval.putSignedInt(x, 16); + } + if (x >= -8388608 && x < 8388608) { + return rval.putSignedInt(x, 24); + } + if (x >= -2147483648 && x < 2147483648) { + return rval.putSignedInt(x, 32); + } + var error4 = new Error("Integer too large; max is 32-bits."); + error4.integer = x; + throw error4; + }; + asn1.derToInteger = function(bytes) { + if (typeof bytes === "string") { + bytes = forge.util.createBuffer(bytes); + } + var n = bytes.length() * 8; + if (n > 32) { + throw new Error("Integer too large; max is 32-bits."); + } + return bytes.getSignedInt(n); + }; + asn1.validate = function(obj, v, capture, errors) { + var rval = false; + if ((obj.tagClass === v.tagClass || typeof v.tagClass === "undefined") && (obj.type === v.type || typeof v.type === "undefined")) { + if (obj.constructed === v.constructed || typeof v.constructed === "undefined") { + rval = true; + if (v.value && forge.util.isArray(v.value)) { + var j = 0; + for (var i = 0; rval && i < v.value.length; ++i) { + rval = v.value[i].optional || false; + if (obj.value[j]) { + rval = asn1.validate(obj.value[j], v.value[i], capture, errors); + if (rval) { + ++j; + } else if (v.value[i].optional) { + rval = true; + } + } + if (!rval && errors) { + errors.push( + "[" + v.name + '] Tag class "' + v.tagClass + '", type "' + v.type + '" expected value length "' + v.value.length + '", got "' + obj.value.length + '"' + ); + } + } } - _ctx.collectInt(+/* @__PURE__ */ new Date(), 32); - if (typeof navigator !== "undefined") { - var _navBytes = ""; - for (var key in navigator) { - try { - if (typeof navigator[key] == "string") { - _navBytes += navigator[key]; + if (rval && capture) { + if (v.capture) { + capture[v.capture] = obj.value; + } + if (v.captureAsn1) { + capture[v.captureAsn1] = obj; + } + if (v.captureBitStringContents && "bitStringContents" in obj) { + capture[v.captureBitStringContents] = obj.bitStringContents; + } + if (v.captureBitStringValue && "bitStringContents" in obj) { + var value; + if (obj.bitStringContents.length < 2) { + capture[v.captureBitStringValue] = ""; + } else { + var unused = obj.bitStringContents.charCodeAt(0); + if (unused !== 0) { + throw new Error( + "captureBitStringValue only supported for zero unused bits" + ); } - } catch (e) { + capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); } } - _ctx.collect(_navBytes); - _navBytes = null; } - if (jQuery2) { - jQuery2().mousemove(function(e) { - _ctx.collectInt(e.clientX, 16); - _ctx.collectInt(e.clientY, 16); - }); - jQuery2().keypress(function(e) { - _ctx.collectInt(e.charCode, 8); - }); + } else if (errors) { + errors.push( + "[" + v.name + '] Expected constructed "' + v.constructed + '", got "' + obj.constructed + '"' + ); + } + } else if (errors) { + if (obj.tagClass !== v.tagClass) { + errors.push( + "[" + v.name + '] Expected tag class "' + v.tagClass + '", got "' + obj.tagClass + '"' + ); + } + if (obj.type !== v.type) { + errors.push( + "[" + v.name + '] Expected type "' + v.type + '", got "' + obj.type + '"' + ); + } + } + return rval; + }; + var _nonLatinRegex = /[^\\u0000-\\u00ff]/; + asn1.prettyPrint = function(obj, level, indentation) { + var rval = ""; + level = level || 0; + indentation = indentation || 2; + if (level > 0) { + rval += "\n"; + } + var indent = ""; + for (var i = 0; i < level * indentation; ++i) { + indent += " "; + } + rval += indent + "Tag: "; + switch (obj.tagClass) { + case asn1.Class.UNIVERSAL: + rval += "Universal:"; + break; + case asn1.Class.APPLICATION: + rval += "Application:"; + break; + case asn1.Class.CONTEXT_SPECIFIC: + rval += "Context-Specific:"; + break; + case asn1.Class.PRIVATE: + rval += "Private:"; + break; + } + if (obj.tagClass === asn1.Class.UNIVERSAL) { + rval += obj.type; + switch (obj.type) { + case asn1.Type.NONE: + rval += " (None)"; + break; + case asn1.Type.BOOLEAN: + rval += " (Boolean)"; + break; + case asn1.Type.INTEGER: + rval += " (Integer)"; + break; + case asn1.Type.BITSTRING: + rval += " (Bit string)"; + break; + case asn1.Type.OCTETSTRING: + rval += " (Octet string)"; + break; + case asn1.Type.NULL: + rval += " (Null)"; + break; + case asn1.Type.OID: + rval += " (Object Identifier)"; + break; + case asn1.Type.ODESC: + rval += " (Object Descriptor)"; + break; + case asn1.Type.EXTERNAL: + rval += " (External or Instance of)"; + break; + case asn1.Type.REAL: + rval += " (Real)"; + break; + case asn1.Type.ENUMERATED: + rval += " (Enumerated)"; + break; + case asn1.Type.EMBEDDED: + rval += " (Embedded PDV)"; + break; + case asn1.Type.UTF8: + rval += " (UTF8)"; + break; + case asn1.Type.ROID: + rval += " (Relative Object Identifier)"; + break; + case asn1.Type.SEQUENCE: + rval += " (Sequence)"; + break; + case asn1.Type.SET: + rval += " (Set)"; + break; + case asn1.Type.PRINTABLESTRING: + rval += " (Printable String)"; + break; + case asn1.Type.IA5String: + rval += " (IA5String (ASCII))"; + break; + case asn1.Type.UTCTIME: + rval += " (UTC time)"; + break; + case asn1.Type.GENERALIZEDTIME: + rval += " (Generalized time)"; + break; + case asn1.Type.BMPSTRING: + rval += " (BMP String)"; + break; + } + } else { + rval += obj.type; + } + rval += "\n"; + rval += indent + "Constructed: " + obj.constructed + "\n"; + if (obj.composed) { + var subvalues = 0; + var sub = ""; + for (var i = 0; i < obj.value.length; ++i) { + if (obj.value[i] !== void 0) { + subvalues += 1; + sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); + if (i + 1 < obj.value.length) { + sub += ","; + } } } - if (!forge.random) { - forge.random = _ctx; - } else { - for (var key in _ctx) { - forge.random[key] = _ctx[key]; + rval += indent + "Sub values: " + subvalues + sub; + } else { + rval += indent + "Value: "; + if (obj.type === asn1.Type.OID) { + var oid = asn1.derToOid(obj.value); + rval += oid; + if (forge.pki && forge.pki.oids) { + if (oid in forge.pki.oids) { + rval += " (" + forge.pki.oids[oid] + ") "; + } } } - forge.random.createInstance = spawnPrng; - module2.exports = forge.random; - })(typeof jQuery !== "undefined" ? jQuery : null); - })(); - } -}); - -// node_modules/node-forge/lib/rc2.js -var require_rc2 = __commonJS({ - "node_modules/node-forge/lib/rc2.js"(exports2, module2) { - var forge = require_forge(); - require_util8(); - var piTable = [ - 217, - 120, - 249, - 196, - 25, - 221, - 181, - 237, - 40, - 233, - 253, - 121, - 74, - 160, - 216, - 157, - 198, - 126, - 55, - 131, - 43, - 118, - 83, - 142, - 98, - 76, - 100, - 136, - 68, - 139, - 251, - 162, - 23, - 154, - 89, - 245, - 135, - 179, - 79, - 19, - 97, - 69, - 109, - 141, - 9, - 129, - 125, - 50, - 189, - 143, - 64, - 235, - 134, - 183, - 123, - 11, - 240, - 149, - 33, - 34, - 92, - 107, - 78, - 130, - 84, - 214, - 101, - 147, - 206, - 96, - 178, - 28, - 115, - 86, - 192, - 20, - 167, - 140, - 241, - 220, - 18, - 117, - 202, - 31, - 59, - 190, - 228, - 209, - 66, - 61, - 212, - 48, - 163, - 60, - 182, - 38, - 111, - 191, - 14, - 218, - 70, - 105, - 7, - 87, - 39, - 242, - 29, - 155, - 188, - 148, - 67, - 3, - 248, - 17, - 199, - 246, - 144, - 239, - 62, - 231, - 6, - 195, - 213, - 47, - 200, - 102, - 30, - 215, - 8, - 232, - 234, - 222, - 128, - 82, - 238, - 247, - 132, - 170, - 114, - 172, - 53, - 77, - 106, - 42, - 150, - 26, - 210, - 113, - 90, - 21, - 73, - 116, - 75, - 159, - 208, - 94, - 4, - 24, - 164, - 236, - 194, - 224, - 65, - 110, - 15, - 81, - 203, - 204, - 36, - 145, - 175, - 80, - 161, - 244, - 112, - 57, - 153, - 124, - 58, - 133, - 35, - 184, - 180, - 122, - 252, - 2, - 54, - 91, - 37, - 85, - 151, - 49, - 45, - 93, - 250, - 152, - 227, - 138, - 146, - 174, - 5, - 223, - 41, - 16, - 103, - 108, - 186, - 201, - 211, - 0, - 230, - 207, - 225, - 158, - 168, - 44, - 99, - 22, - 1, - 63, - 88, - 226, - 137, - 169, - 13, - 56, - 52, - 27, - 171, - 51, - 255, - 176, - 187, - 72, - 12, - 95, - 185, - 177, - 205, - 46, - 197, - 243, - 219, - 71, - 229, - 165, - 156, - 119, - 10, - 166, - 32, - 104, - 254, - 127, - 193, - 173 - ]; - var s = [1, 2, 3, 5]; - var rol = function(word, bits) { - return word << bits & 65535 | (word & 65535) >> 16 - bits; - }; - var ror = function(word, bits) { - return (word & 65535) >> bits | word << 16 - bits & 65535; - }; - module2.exports = forge.rc2 = forge.rc2 || {}; - forge.rc2.expandKey = function(key, effKeyBits) { - if (typeof key === "string") { - key = forge.util.createBuffer(key); - } - effKeyBits = effKeyBits || 128; - var L = key; - var T = key.length(); - var T1 = effKeyBits; - var T8 = Math.ceil(T1 / 8); - var TM = 255 >> (T1 & 7); - var i; - for (i = T; i < 128; i++) { - L.putByte(piTable[L.at(i - 1) + L.at(i - T) & 255]); - } - L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); - for (i = 127 - T8; i >= 0; i--) { - L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); - } - return L; - }; - var createCipher = function(key, bits, encrypt) { - var _finish = false, _input = null, _output = null, _iv = null; - var mixRound, mashRound; - var i, j, K = []; - key = forge.rc2.expandKey(key, bits); - for (i = 0; i < 64; i++) { - K.push(key.getInt16Le()); - } - if (encrypt) { - mixRound = function(R) { - for (i = 0; i < 4; i++) { - R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); - R[i] = rol(R[i], s[i]); - j++; + if (obj.type === asn1.Type.INTEGER) { + try { + rval += asn1.derToInteger(obj.value); + } catch (ex) { + rval += "0x" + forge.util.bytesToHex(obj.value); } - }; - mashRound = function(R) { - for (i = 0; i < 4; i++) { - R[i] += K[R[(i + 3) % 4] & 63]; + } else if (obj.type === asn1.Type.BITSTRING) { + if (obj.value.length > 1) { + rval += "0x" + forge.util.bytesToHex(obj.value.slice(1)); + } else { + rval += "(none)"; } - }; - } else { - mixRound = function(R) { - for (i = 3; i >= 0; i--) { - R[i] = ror(R[i], s[i]); - R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); - j--; + if (obj.value.length > 0) { + var unused = obj.value.charCodeAt(0); + if (unused == 1) { + rval += " (1 unused bit shown)"; + } else if (unused > 1) { + rval += " (" + unused + " unused bits shown)"; + } } - }; - mashRound = function(R) { - for (i = 3; i >= 0; i--) { - R[i] -= K[R[(i + 3) % 4] & 63]; + } else if (obj.type === asn1.Type.OCTETSTRING) { + if (!_nonLatinRegex.test(obj.value)) { + rval += "(" + obj.value + ") "; } - }; - } - var runPlan = function(plan) { - var R = []; - for (i = 0; i < 4; i++) { - var val2 = _input.getInt16Le(); - if (_iv !== null) { - if (encrypt) { - val2 ^= _iv.getInt16Le(); + rval += "0x" + forge.util.bytesToHex(obj.value); + } else if (obj.type === asn1.Type.UTF8) { + try { + rval += forge.util.decodeUtf8(obj.value); + } catch (e) { + if (e.message === "URI malformed") { + rval += "0x" + forge.util.bytesToHex(obj.value) + " (malformed UTF8)"; } else { - _iv.putInt16Le(val2); + throw e; } } - R.push(val2 & 65535); - } - j = encrypt ? 0 : 63; - for (var ptr = 0; ptr < plan.length; ptr++) { - for (var ctr = 0; ctr < plan[ptr][0]; ctr++) { - plan[ptr][1](R); - } + } else if (obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) { + rval += obj.value; + } else if (_nonLatinRegex.test(obj.value)) { + rval += "0x" + forge.util.bytesToHex(obj.value); + } else if (obj.value.length === 0) { + rval += "[null]"; + } else { + rval += obj.value; } - for (i = 0; i < 4; i++) { - if (_iv !== null) { - if (encrypt) { - _iv.putInt16Le(R[i]); + } + return rval; + }; + } +}); + +// node_modules/node-forge/lib/md.js +var require_md = __commonJS({ + "node_modules/node-forge/lib/md.js"(exports2, module2) { + var forge = require_forge(); + module2.exports = forge.md = forge.md || {}; + forge.md.algorithms = forge.md.algorithms || {}; + } +}); + +// node_modules/node-forge/lib/hmac.js +var require_hmac = __commonJS({ + "node_modules/node-forge/lib/hmac.js"(exports2, module2) { + var forge = require_forge(); + require_md(); + require_util8(); + var hmac = module2.exports = forge.hmac = forge.hmac || {}; + hmac.create = function() { + var _key = null; + var _md = null; + var _ipadding = null; + var _opadding = null; + var ctx = {}; + ctx.start = function(md, key) { + if (md !== null) { + if (typeof md === "string") { + md = md.toLowerCase(); + if (md in forge.md.algorithms) { + _md = forge.md.algorithms[md].create(); } else { - R[i] ^= _iv.getInt16Le(); + throw new Error('Unknown hash algorithm "' + md + '"'); } + } else { + _md = md; } - _output.putInt16Le(R[i]); } - }; - var cipher = null; - cipher = { - /** - * Starts or restarts the encryption or decryption process, whichever - * was previously configured. - * - * To use the cipher in CBC mode, iv may be given either as a string - * of bytes, or as a byte buffer. For ECB mode, give null as iv. - * - * @param iv the initialization vector to use, null for ECB mode. - * @param output the output the buffer to write to, null to create one. - */ - start: function(iv, output) { - if (iv) { - if (typeof iv === "string") { - iv = forge.util.createBuffer(iv); + if (key === null) { + key = _key; + } else { + if (typeof key === "string") { + key = forge.util.createBuffer(key); + } else if (forge.util.isArray(key)) { + var tmp = key; + key = forge.util.createBuffer(); + for (var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); } } - _finish = false; - _input = forge.util.createBuffer(); - _output = output || new forge.util.createBuffer(); - _iv = iv; - cipher.output = _output; - }, - /** - * Updates the next block. - * - * @param input the buffer to read from. - */ - update: function(input) { - if (!_finish) { - _input.putBuffer(input); - } - while (_input.length() >= 8) { - runPlan([ - [5, mixRound], - [1, mashRound], - [6, mixRound], - [1, mashRound], - [5, mixRound] - ]); - } - }, - /** - * Finishes encrypting or decrypting. - * - * @param pad a padding function to use, null for PKCS#7 padding, - * signature(blockSize, buffer, decrypt). - * - * @return true if successful, false on error. - */ - finish: function(pad) { - var rval = true; - if (encrypt) { - if (pad) { - rval = pad(8, _input, !encrypt); - } else { - var padding = _input.length() === 8 ? 8 : 8 - _input.length(); - _input.fillWithByte(padding, padding); - } + var keylen = key.length(); + if (keylen > _md.blockLength) { + _md.start(); + _md.update(key.bytes()); + key = _md.digest(); } - if (rval) { - _finish = true; - cipher.update(); + _ipadding = forge.util.createBuffer(); + _opadding = forge.util.createBuffer(); + keylen = key.length(); + for (var i = 0; i < keylen; ++i) { + var tmp = key.at(i); + _ipadding.putByte(54 ^ tmp); + _opadding.putByte(92 ^ tmp); } - if (!encrypt) { - rval = _input.length() === 0; - if (rval) { - if (pad) { - rval = pad(8, _output, !encrypt); - } else { - var len = _output.length(); - var count = _output.at(len - 1); - if (count > len) { - rval = false; - } else { - _output.truncate(count); - } - } + if (keylen < _md.blockLength) { + var tmp = _md.blockLength - keylen; + for (var i = 0; i < tmp; ++i) { + _ipadding.putByte(54); + _opadding.putByte(92); } } - return rval; + _key = key; + _ipadding = _ipadding.bytes(); + _opadding = _opadding.bytes(); } + _md.start(); + _md.update(_ipadding); }; - return cipher; - }; - forge.rc2.startEncrypting = function(key, iv, output) { - var cipher = forge.rc2.createEncryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; - }; - forge.rc2.createEncryptionCipher = function(key, bits) { - return createCipher(key, bits, true); - }; - forge.rc2.startDecrypting = function(key, iv, output) { - var cipher = forge.rc2.createDecryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; - }; - forge.rc2.createDecryptionCipher = function(key, bits) { - return createCipher(key, bits, false); + ctx.update = function(bytes) { + _md.update(bytes); + }; + ctx.getMac = function() { + var inner = _md.digest().bytes(); + _md.start(); + _md.update(_opadding); + _md.update(inner); + return _md.digest(); + }; + ctx.digest = ctx.getMac; + return ctx; }; } }); -// node_modules/node-forge/lib/jsbn.js -var require_jsbn = __commonJS({ - "node_modules/node-forge/lib/jsbn.js"(exports2, module2) { +// node_modules/node-forge/lib/md5.js +var require_md5 = __commonJS({ + "node_modules/node-forge/lib/md5.js"(exports2, module2) { var forge = require_forge(); - module2.exports = forge.jsbn = forge.jsbn || {}; - var dbits; - var canary = 244837814094590; - var j_lm = (canary & 16777215) == 15715070; - function BigInteger(a, b, c) { - this.data = []; - if (a != null) - if ("number" == typeof a) this.fromNumber(a, b, c); - else if (b == null && "string" != typeof a) this.fromString(a, 256); - else this.fromString(a, b); - } - forge.jsbn.BigInteger = BigInteger; - function nbi() { - return new BigInteger(null); - } - function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this.data[i++] + w.data[j] + c; - c = Math.floor(v / 67108864); - w.data[j++] = v & 67108863; + require_md(); + require_util8(); + var md5 = module2.exports = forge.md5 = forge.md5 || {}; + forge.md.md5 = forge.md.algorithms.md5 = md5; + md5.create = function() { + if (!_initialized) { + _init(); } - return c; - } - function am2(i, x, w, j, c, n) { - var xl = x & 32767, xh = x >> 15; - while (--n >= 0) { - var l = this.data[i] & 32767; - var h = this.data[i++] >> 15; - var m = xh * l + h * xl; - l = xl * l + ((m & 32767) << 15) + w.data[j] + (c & 1073741823); - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); - w.data[j++] = l & 1073741823; + var _state = null; + var _input = forge.util.createBuffer(); + var _w = new Array(16); + var md = { + algorithm: "md5", + blockLength: 64, + digestLength: 16, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + md.start = function() { + md.messageLength = 0; + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 1732584193, + h1: 4023233417, + h2: 2562383102, + h3: 271733878 + }; + return md; + }; + md.start(); + md.update = function(msg, encoding) { + if (encoding === "utf8") { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md.messageLength += len; + len = [len / 4294967296 >>> 0, len >>> 0]; + for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = len[1] / 4294967296 >>> 0; + } + _input.putBytes(msg); + _update(_state, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md; + }; + md.digest = function() { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; + var overflow = remaining & md.blockLength - 1; + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + var bits, carry = 0; + for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { + bits = md.fullMessageLength[i] * 8 + carry; + carry = bits / 4294967296 >>> 0; + finalBlock.putInt32Le(bits >>> 0); + } + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32Le(s2.h0); + rval.putInt32Le(s2.h1); + rval.putInt32Le(s2.h2); + rval.putInt32Le(s2.h3); + return rval; + }; + return md; + }; + var _padding = null; + var _g = null; + var _r = null; + var _k = null; + var _initialized = false; + function _init() { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 64); + _g = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 1, + 6, + 11, + 0, + 5, + 10, + 15, + 4, + 9, + 14, + 3, + 8, + 13, + 2, + 7, + 12, + 5, + 8, + 11, + 14, + 1, + 4, + 7, + 10, + 13, + 0, + 3, + 6, + 9, + 12, + 15, + 2, + 0, + 7, + 14, + 5, + 12, + 3, + 10, + 1, + 8, + 15, + 6, + 13, + 4, + 11, + 2, + 9 + ]; + _r = [ + 7, + 12, + 17, + 22, + 7, + 12, + 17, + 22, + 7, + 12, + 17, + 22, + 7, + 12, + 17, + 22, + 5, + 9, + 14, + 20, + 5, + 9, + 14, + 20, + 5, + 9, + 14, + 20, + 5, + 9, + 14, + 20, + 4, + 11, + 16, + 23, + 4, + 11, + 16, + 23, + 4, + 11, + 16, + 23, + 4, + 11, + 16, + 23, + 6, + 10, + 15, + 21, + 6, + 10, + 15, + 21, + 6, + 10, + 15, + 21, + 6, + 10, + 15, + 21 + ]; + _k = new Array(64); + for (var i = 0; i < 64; ++i) { + _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); } - return c; + _initialized = true; } - function am3(i, x, w, j, c, n) { - var xl = x & 16383, xh = x >> 14; - while (--n >= 0) { - var l = this.data[i] & 16383; - var h = this.data[i++] >> 14; - var m = xh * l + h * xl; - l = xl * l + ((m & 16383) << 14) + w.data[j] + c; - c = (l >> 28) + (m >> 14) + xh * h; - w.data[j++] = l & 268435455; + function _update(s, w, bytes) { + var t, a, b, c, d, f, r, i; + var len = bytes.length(); + while (len >= 64) { + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + for (i = 0; i < 16; ++i) { + w[i] = bytes.getInt32Le(); + f = d ^ b & (c ^ d); + t = a + f + _k[i] + w[i]; + r = _r[i]; + a = d; + d = c; + c = b; + b += t << r | t >>> 32 - r; + } + for (; i < 32; ++i) { + f = c ^ d & (b ^ c); + t = a + f + _k[i] + w[_g[i]]; + r = _r[i]; + a = d; + d = c; + c = b; + b += t << r | t >>> 32 - r; + } + for (; i < 48; ++i) { + f = b ^ c ^ d; + t = a + f + _k[i] + w[_g[i]]; + r = _r[i]; + a = d; + d = c; + c = b; + b += t << r | t >>> 32 - r; + } + for (; i < 64; ++i) { + f = c ^ (b | ~d); + t = a + f + _k[i] + w[_g[i]]; + r = _r[i]; + a = d; + d = c; + c = b; + b += t << r | t >>> 32 - r; + } + s.h0 = s.h0 + a | 0; + s.h1 = s.h1 + b | 0; + s.h2 = s.h2 + c | 0; + s.h3 = s.h3 + d | 0; + len -= 64; } - return c; - } - if (typeof navigator === "undefined") { - BigInteger.prototype.am = am3; - dbits = 28; - } else if (j_lm && navigator.appName == "Microsoft Internet Explorer") { - BigInteger.prototype.am = am2; - dbits = 30; - } else if (j_lm && navigator.appName != "Netscape") { - BigInteger.prototype.am = am1; - dbits = 26; - } else { - BigInteger.prototype.am = am3; - dbits = 28; - } - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = (1 << dbits) - 1; - BigInteger.prototype.DV = 1 << dbits; - var BI_FP = 52; - BigInteger.prototype.FV = Math.pow(2, BI_FP); - BigInteger.prototype.F1 = BI_FP - dbits; - BigInteger.prototype.F2 = 2 * dbits - BI_FP; - var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; - var BI_RC = new Array(); - var rr; - var vv; - rr = "0".charCodeAt(0); - for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; - rr = "a".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - rr = "A".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - function int2char(n) { - return BI_RM.charAt(n); - } - function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; - return c == null ? -1 : c; - } - function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r.data[i] = this.data[i]; - r.t = this.t; - r.s = this.s; - } - function bnpFromInt(x) { - this.t = 1; - this.s = x < 0 ? -1 : 0; - if (x > 0) this.data[0] = x; - else if (x < -1) this.data[0] = x + this.DV; - else this.t = 0; - } - function nbv(i) { - var r = nbi(); - r.fromInt(i); - return r; } - function bnpFromString(s, b) { - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 256) k = 8; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else { - this.fromRadix(s, b); - return; + } +}); + +// node_modules/node-forge/lib/pem.js +var require_pem = __commonJS({ + "node_modules/node-forge/lib/pem.js"(exports2, module2) { + var forge = require_forge(); + require_util8(); + var pem = module2.exports = forge.pem = forge.pem || {}; + pem.encode = function(msg, options) { + options = options || {}; + var rval = "-----BEGIN " + msg.type + "-----\r\n"; + var header; + if (msg.procType) { + header = { + name: "Proc-Type", + values: [String(msg.procType.version), msg.procType.type] + }; + rval += foldHeader(header); } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while (--i >= 0) { - var x = k == 8 ? s[i] & 255 : intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-") mi = true; - continue; + if (msg.contentDomain) { + header = { name: "Content-Domain", values: [msg.contentDomain] }; + rval += foldHeader(header); + } + if (msg.dekInfo) { + header = { name: "DEK-Info", values: [msg.dekInfo.algorithm] }; + if (msg.dekInfo.parameters) { + header.values.push(msg.dekInfo.parameters); } - mi = false; - if (sh == 0) - this.data[this.t++] = x; - else if (sh + k > this.DB) { - this.data[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; - this.data[this.t++] = x >> this.DB - sh; - } else - this.data[this.t - 1] |= x << sh; - sh += k; - if (sh >= this.DB) sh -= this.DB; + rval += foldHeader(header); } - if (k == 8 && (s[0] & 128) != 0) { - this.s = -1; - if (sh > 0) this.data[this.t - 1] |= (1 << this.DB - sh) - 1 << sh; + if (msg.headers) { + for (var i = 0; i < msg.headers.length; ++i) { + rval += foldHeader(msg.headers[i]); + } } - this.clamp(); - if (mi) BigInteger.ZERO.subTo(this, this); - } - function bnpClamp() { - var c = this.s & this.DM; - while (this.t > 0 && this.data[this.t - 1] == c) --this.t; - } - function bnToString(b) { - if (this.s < 0) return "-" + this.negate().toString(b); - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else return this.toRadix(b); - var km = (1 << k) - 1, d, m = false, r = "", i = this.t; - var p = this.DB - i * this.DB % k; - if (i-- > 0) { - if (p < this.DB && (d = this.data[i] >> p) > 0) { - m = true; - r = int2char(d); + if (msg.procType) { + rval += "\r\n"; + } + rval += forge.util.encode64(msg.body, options.maxline || 64) + "\r\n"; + rval += "-----END " + msg.type + "-----\r\n"; + return rval; + }; + pem.decode = function(str2) { + var rval = []; + var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; + var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; + var rCRLF = /\r?\n/; + var match; + while (true) { + match = rMessage.exec(str2); + if (!match) { + break; } - while (i >= 0) { - if (p < k) { - d = (this.data[i] & (1 << p) - 1) << k - p; - d |= this.data[--i] >> (p += this.DB - k); - } else { - d = this.data[i] >> (p -= k) & km; - if (p <= 0) { - p += this.DB; - --i; - } - } - if (d > 0) m = true; - if (m) r += int2char(d); + var type2 = match[1]; + if (type2 === "NEW CERTIFICATE REQUEST") { + type2 = "CERTIFICATE REQUEST"; + } + var msg = { + type: type2, + procType: null, + contentDomain: null, + dekInfo: null, + headers: [], + body: forge.util.decode64(match[3]) + }; + rval.push(msg); + if (!match[2]) { + continue; + } + var lines = match[2].split(rCRLF); + var li = 0; + while (match && li < lines.length) { + var line = lines[li].replace(/\s+$/, ""); + for (var nl = li + 1; nl < lines.length; ++nl) { + var next = lines[nl]; + if (!/\s/.test(next[0])) { + break; + } + line += next; + li = nl; + } + match = line.match(rHeader); + if (match) { + var header = { name: match[1], values: [] }; + var values = match[2].split(","); + for (var vi = 0; vi < values.length; ++vi) { + header.values.push(ltrim(values[vi])); + } + if (!msg.procType) { + if (header.name !== "Proc-Type") { + throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".'); + } else if (header.values.length !== 2) { + throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.'); + } + msg.procType = { version: values[0], type: values[1] }; + } else if (!msg.contentDomain && header.name === "Content-Domain") { + msg.contentDomain = values[0] || ""; + } else if (!msg.dekInfo && header.name === "DEK-Info") { + if (header.values.length === 0) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.'); + } + msg.dekInfo = { algorithm: values[0], parameters: values[1] || null }; + } else { + msg.headers.push(header); + } + } + ++li; + } + if (msg.procType === "ENCRYPTED" && !msg.dekInfo) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".'); } } - return m ? r : "0"; - } - function bnNegate() { - var r = nbi(); - BigInteger.ZERO.subTo(this, r); - return r; - } - function bnAbs() { - return this.s < 0 ? this.negate() : this; - } - function bnCompareTo(a) { - var r = this.s - a.s; - if (r != 0) return r; - var i = this.t; - r = i - a.t; - if (r != 0) return this.s < 0 ? -r : r; - while (--i >= 0) if ((r = this.data[i] - a.data[i]) != 0) return r; - return 0; - } - function nbits(x) { - var r = 1, t; - if ((t = x >>> 16) != 0) { - x = t; - r += 16; - } - if ((t = x >> 8) != 0) { - x = t; - r += 8; - } - if ((t = x >> 4) != 0) { - x = t; - r += 4; + if (rval.length === 0) { + throw new Error("Invalid PEM formatted message."); } - if ((t = x >> 2) != 0) { - x = t; - r += 2; + return rval; + }; + function foldHeader(header) { + var rval = header.name + ": "; + var values = []; + var insertSpace = function(match, $1) { + return " " + $1; + }; + for (var i = 0; i < header.values.length; ++i) { + values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); } - if ((t = x >> 1) != 0) { - x = t; - r += 1; + rval += values.join(",") + "\r\n"; + var length = 0; + var candidate = -1; + for (var i = 0; i < rval.length; ++i, ++length) { + if (length > 65 && candidate !== -1) { + var insert = rval[candidate]; + if (insert === ",") { + ++candidate; + rval = rval.substr(0, candidate) + "\r\n " + rval.substr(candidate); + } else { + rval = rval.substr(0, candidate) + "\r\n" + insert + rval.substr(candidate + 1); + } + length = i - candidate - 1; + candidate = -1; + ++i; + } else if (rval[i] === " " || rval[i] === " " || rval[i] === ",") { + candidate = i; + } } - return r; - } - function bnBitLength() { - if (this.t <= 0) return 0; - return this.DB * (this.t - 1) + nbits(this.data[this.t - 1] ^ this.s & this.DM); - } - function bnpDLShiftTo(n, r) { - var i; - for (i = this.t - 1; i >= 0; --i) r.data[i + n] = this.data[i]; - for (i = n - 1; i >= 0; --i) r.data[i] = 0; - r.t = this.t + n; - r.s = this.s; - } - function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r.data[i - n] = this.data[i]; - r.t = Math.max(this.t - n, 0); - r.s = this.s; + return rval; } - function bnpLShiftTo(n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; - for (i = this.t - 1; i >= 0; --i) { - r.data[i + ds + 1] = this.data[i] >> cbs | c; - c = (this.data[i] & bm) << bs; - } - for (i = ds - 1; i >= 0; --i) r.data[i] = 0; - r.data[ds] = c; - r.t = this.t + ds + 1; - r.s = this.s; - r.clamp(); + function ltrim(str2) { + return str2.replace(/^\s+/, ""); } - function bnpRShiftTo(n, r) { - r.s = this.s; - var ds = Math.floor(n / this.DB); - if (ds >= this.t) { - r.t = 0; + } +}); + +// node_modules/node-forge/lib/des.js +var require_des = __commonJS({ + "node_modules/node-forge/lib/des.js"(exports2, module2) { + var forge = require_forge(); + require_cipher(); + require_cipherModes(); + require_util8(); + module2.exports = forge.des = forge.des || {}; + forge.des.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: false, + mode: mode || (iv === null ? "ECB" : "CBC") + }); + cipher.start(iv); + return cipher; + }; + forge.des.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key, + output: null, + decrypt: false, + mode + }); + }; + forge.des.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key, + output, + decrypt: true, + mode: mode || (iv === null ? "ECB" : "CBC") + }); + cipher.start(iv); + return cipher; + }; + forge.des.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key, + output: null, + decrypt: true, + mode + }); + }; + forge.des.Algorithm = function(name, mode) { + var self2 = this; + self2.name = name; + self2.mode = new mode({ + blockSize: 8, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self2._keys, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self2._keys, inBlock, outBlock, true); + } + } + }); + self2._init = false; + }; + forge.des.Algorithm.prototype.initialize = function(options) { + if (this._init) { return; } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; - r.data[0] = this.data[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { - r.data[i - ds - 1] |= (this.data[i] & bm) << cbs; - r.data[i - ds] = this.data[i] >> bs; - } - if (bs > 0) r.data[this.t - ds - 1] |= (this.s & bm) << cbs; - r.t = this.t - ds; - r.clamp(); - } - function bnpSubTo(a, r) { - var i = 0, c = 0, m = Math.min(a.t, this.t); - while (i < m) { - c += this.data[i] - a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c -= a.s; - while (i < this.t) { - c += this.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c -= a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; + var key = forge.util.createBuffer(options.key); + if (this.name.indexOf("3DES") === 0) { + if (key.length() !== 24) { + throw new Error("Invalid Triple-DES key size: " + key.length() * 8); } - c -= a.s; } - r.s = c < 0 ? -1 : 0; - if (c < -1) r.data[i++] = this.DV + c; - else if (c > 0) r.data[i++] = c; - r.t = i; - r.clamp(); - } - function bnpMultiplyTo(a, r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i + y.t; - while (--i >= 0) r.data[i] = 0; - for (i = 0; i < y.t; ++i) r.data[i + x.t] = x.am(0, y.data[i], r, i, 0, x.t); - r.s = 0; - r.clamp(); - if (this.s != a.s) BigInteger.ZERO.subTo(r, r); + this._keys = _createKeys(key); + this._init = true; + }; + registerAlgorithm("DES-ECB", forge.cipher.modes.ecb); + registerAlgorithm("DES-CBC", forge.cipher.modes.cbc); + registerAlgorithm("DES-CFB", forge.cipher.modes.cfb); + registerAlgorithm("DES-OFB", forge.cipher.modes.ofb); + registerAlgorithm("DES-CTR", forge.cipher.modes.ctr); + registerAlgorithm("3DES-ECB", forge.cipher.modes.ecb); + registerAlgorithm("3DES-CBC", forge.cipher.modes.cbc); + registerAlgorithm("3DES-CFB", forge.cipher.modes.cfb); + registerAlgorithm("3DES-OFB", forge.cipher.modes.ofb); + registerAlgorithm("3DES-CTR", forge.cipher.modes.ctr); + function registerAlgorithm(name, mode) { + var factory = function() { + return new forge.des.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); } - function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2 * x.t; - while (--i >= 0) r.data[i] = 0; - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x.data[i], r, 2 * i, 0, 1); - if ((r.data[i + x.t] += x.am(i + 1, 2 * x.data[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r.data[i + x.t] -= x.DV; - r.data[i + x.t + 1] = 1; + var spfunction1 = [16843776, 0, 65536, 16843780, 16842756, 66564, 4, 65536, 1024, 16843776, 16843780, 1024, 16778244, 16842756, 16777216, 4, 1028, 16778240, 16778240, 66560, 66560, 16842752, 16842752, 16778244, 65540, 16777220, 16777220, 65540, 0, 1028, 66564, 16777216, 65536, 16843780, 4, 16842752, 16843776, 16777216, 16777216, 1024, 16842756, 65536, 66560, 16777220, 1024, 4, 16778244, 66564, 16843780, 65540, 16842752, 16778244, 16777220, 1028, 66564, 16843776, 1028, 16778240, 16778240, 0, 65540, 66560, 0, 16842756]; + var spfunction2 = [-2146402272, -2147450880, 32768, 1081376, 1048576, 32, -2146435040, -2147450848, -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 1048576, 32, -2146435040, 1081344, 1048608, -2147450848, 0, -2147483648, 32768, 1081376, -2146435072, 1048608, -2147483616, 0, 1081344, 32800, -2146402304, -2146435072, 32800, 0, 1081376, -2146435040, 1048576, -2147450848, -2146435072, -2146402304, 32768, -2146435072, -2147450880, 32, -2146402272, 1081376, 32, 32768, -2147483648, 32800, -2146402304, 1048576, -2147483616, 1048608, -2147450848, -2147483616, 1048608, 1081344, 0, -2147450880, 32800, -2147483648, -2146435040, -2146402272, 1081344]; + var spfunction3 = [520, 134349312, 0, 134348808, 134218240, 0, 131592, 134218240, 131080, 134217736, 134217736, 131072, 134349320, 131080, 134348800, 520, 134217728, 8, 134349312, 512, 131584, 134348800, 134348808, 131592, 134218248, 131584, 131072, 134218248, 8, 134349320, 512, 134217728, 134349312, 134217728, 131080, 520, 131072, 134349312, 134218240, 0, 512, 131080, 134349320, 134218240, 134217736, 512, 0, 134348808, 134218248, 131072, 134217728, 134349320, 8, 131592, 131584, 134217736, 134348800, 134218248, 520, 134348800, 131592, 8, 134348808, 131584]; + var spfunction4 = [8396801, 8321, 8321, 128, 8396928, 8388737, 8388609, 8193, 0, 8396800, 8396800, 8396929, 129, 0, 8388736, 8388609, 1, 8192, 8388608, 8396801, 128, 8388608, 8193, 8320, 8388737, 1, 8320, 8388736, 8192, 8396928, 8396929, 129, 8388736, 8388609, 8396800, 8396929, 129, 0, 0, 8396800, 8320, 8388736, 8388737, 1, 8396801, 8321, 8321, 128, 8396929, 129, 1, 8192, 8388609, 8193, 8396928, 8388737, 8193, 8320, 8388608, 8396801, 128, 8388608, 8192, 8396928]; + var spfunction5 = [256, 34078976, 34078720, 1107296512, 524288, 256, 1073741824, 34078720, 1074266368, 524288, 33554688, 1074266368, 1107296512, 1107820544, 524544, 1073741824, 33554432, 1074266112, 1074266112, 0, 1073742080, 1107820800, 1107820800, 33554688, 1107820544, 1073742080, 0, 1107296256, 34078976, 33554432, 1107296256, 524544, 524288, 1107296512, 256, 33554432, 1073741824, 34078720, 1107296512, 1074266368, 33554688, 1073741824, 1107820544, 34078976, 1074266368, 256, 33554432, 1107820544, 1107820800, 524544, 1107296256, 1107820800, 34078720, 0, 1074266112, 1107296256, 524544, 33554688, 1073742080, 524288, 0, 1074266112, 34078976, 1073742080]; + var spfunction6 = [536870928, 541065216, 16384, 541081616, 541065216, 16, 541081616, 4194304, 536887296, 4210704, 4194304, 536870928, 4194320, 536887296, 536870912, 16400, 0, 4194320, 536887312, 16384, 4210688, 536887312, 16, 541065232, 541065232, 0, 4210704, 541081600, 16400, 4210688, 541081600, 536870912, 536887296, 16, 541065232, 4210688, 541081616, 4194304, 16400, 536870928, 4194304, 536887296, 536870912, 16400, 536870928, 541081616, 4210688, 541065216, 4210704, 541081600, 0, 541065232, 16, 16384, 541065216, 4210704, 16384, 4194320, 536887312, 0, 541081600, 536870912, 4194320, 536887312]; + var spfunction7 = [2097152, 69206018, 67110914, 0, 2048, 67110914, 2099202, 69208064, 69208066, 2097152, 0, 67108866, 2, 67108864, 69206018, 2050, 67110912, 2099202, 2097154, 67110912, 67108866, 69206016, 69208064, 2097154, 69206016, 2048, 2050, 69208066, 2099200, 2, 67108864, 2099200, 67108864, 2099200, 2097152, 67110914, 67110914, 69206018, 69206018, 2, 2097154, 67108864, 67110912, 2097152, 69208064, 2050, 2099202, 69208064, 2050, 67108866, 69208066, 69206016, 2099200, 0, 2, 69208066, 0, 2099202, 69206016, 2048, 67108866, 67110912, 2048, 2097154]; + var spfunction8 = [268439616, 4096, 262144, 268701760, 268435456, 268439616, 64, 268435456, 262208, 268697600, 268701760, 266240, 268701696, 266304, 4096, 64, 268697600, 268435520, 268439552, 4160, 266240, 262208, 268697664, 268701696, 4160, 0, 0, 268697664, 268435520, 268439552, 266304, 262144, 266304, 262144, 268701696, 4096, 64, 268697664, 4096, 266304, 268439552, 64, 268435520, 268697600, 268697664, 268435456, 262144, 268439616, 0, 268701760, 262208, 268435520, 268697600, 268439552, 268439616, 0, 268701760, 266240, 266240, 4160, 4160, 262208, 268435456, 268701696]; + function _createKeys(key) { + var pc2bytes0 = [0, 4, 536870912, 536870916, 65536, 65540, 536936448, 536936452, 512, 516, 536871424, 536871428, 66048, 66052, 536936960, 536936964], pc2bytes1 = [0, 1, 1048576, 1048577, 67108864, 67108865, 68157440, 68157441, 256, 257, 1048832, 1048833, 67109120, 67109121, 68157696, 68157697], pc2bytes2 = [0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272, 0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272], pc2bytes3 = [0, 2097152, 134217728, 136314880, 8192, 2105344, 134225920, 136323072, 131072, 2228224, 134348800, 136445952, 139264, 2236416, 134356992, 136454144], pc2bytes4 = [0, 262144, 16, 262160, 0, 262144, 16, 262160, 4096, 266240, 4112, 266256, 4096, 266240, 4112, 266256], pc2bytes5 = [0, 1024, 32, 1056, 0, 1024, 32, 1056, 33554432, 33555456, 33554464, 33555488, 33554432, 33555456, 33554464, 33555488], pc2bytes6 = [0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746, 0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746], pc2bytes7 = [0, 65536, 2048, 67584, 536870912, 536936448, 536872960, 536938496, 131072, 196608, 133120, 198656, 537001984, 537067520, 537004032, 537069568], pc2bytes8 = [0, 262144, 0, 262144, 2, 262146, 2, 262146, 33554432, 33816576, 33554432, 33816576, 33554434, 33816578, 33554434, 33816578], pc2bytes9 = [0, 268435456, 8, 268435464, 0, 268435456, 8, 268435464, 1024, 268436480, 1032, 268436488, 1024, 268436480, 1032, 268436488], pc2bytes10 = [0, 32, 0, 32, 1048576, 1048608, 1048576, 1048608, 8192, 8224, 8192, 8224, 1056768, 1056800, 1056768, 1056800], pc2bytes11 = [0, 16777216, 512, 16777728, 2097152, 18874368, 2097664, 18874880, 67108864, 83886080, 67109376, 83886592, 69206016, 85983232, 69206528, 85983744], pc2bytes12 = [0, 4096, 134217728, 134221824, 524288, 528384, 134742016, 134746112, 16, 4112, 134217744, 134221840, 524304, 528400, 134742032, 134746128], pc2bytes13 = [0, 4, 256, 260, 0, 4, 256, 260, 1, 5, 257, 261, 1, 5, 257, 261]; + var iterations = key.length() > 8 ? 3 : 1; + var keys = []; + var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + var n = 0, tmp; + for (var j = 0; j < iterations; j++) { + var left = key.getInt32(); + var right = key.getInt32(); + tmp = (left >>> 4 ^ right) & 252645135; + right ^= tmp; + left ^= tmp << 4; + tmp = (right >>> -16 ^ left) & 65535; + left ^= tmp; + right ^= tmp << -16; + tmp = (left >>> 2 ^ right) & 858993459; + right ^= tmp; + left ^= tmp << 2; + tmp = (right >>> -16 ^ left) & 65535; + left ^= tmp; + right ^= tmp << -16; + tmp = (left >>> 1 ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + tmp = (right >>> 8 ^ left) & 16711935; + left ^= tmp; + right ^= tmp << 8; + tmp = (left >>> 1 ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + tmp = left << 8 | right >>> 20 & 240; + left = right << 24 | right << 8 & 16711680 | right >>> 8 & 65280 | right >>> 24 & 240; + right = tmp; + for (var i = 0; i < shifts.length; ++i) { + if (shifts[i]) { + left = left << 2 | left >>> 26; + right = right << 2 | right >>> 26; + } else { + left = left << 1 | left >>> 27; + right = right << 1 | right >>> 27; + } + left &= -15; + right &= -15; + var lefttmp = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 15] | pc2bytes2[left >>> 20 & 15] | pc2bytes3[left >>> 16 & 15] | pc2bytes4[left >>> 12 & 15] | pc2bytes5[left >>> 8 & 15] | pc2bytes6[left >>> 4 & 15]; + var righttmp = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 15] | pc2bytes9[right >>> 20 & 15] | pc2bytes10[right >>> 16 & 15] | pc2bytes11[right >>> 12 & 15] | pc2bytes12[right >>> 8 & 15] | pc2bytes13[right >>> 4 & 15]; + tmp = (righttmp >>> 16 ^ lefttmp) & 65535; + keys[n++] = lefttmp ^ tmp; + keys[n++] = righttmp ^ tmp << 16; } } - if (r.t > 0) r.data[r.t - 1] += x.am(i, x.data[i], r, 2 * i, 0, 1); - r.s = 0; - r.clamp(); + return keys; } - function bnpDivRemTo(m, q, r) { - var pm = m.abs(); - if (pm.t <= 0) return; - var pt = this.abs(); - if (pt.t < pm.t) { - if (q != null) q.fromInt(0); - if (r != null) this.copyTo(r); - return; - } - if (r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB - nbits(pm.data[pm.t - 1]); - if (nsh > 0) { - pm.lShiftTo(nsh, y); - pt.lShiftTo(nsh, r); + function _updateBlock(keys, input, output, decrypt) { + var iterations = keys.length === 32 ? 3 : 9; + var looping; + if (iterations === 3) { + looping = decrypt ? [30, -2, -2] : [0, 32, 2]; } else { - pm.copyTo(y); - pt.copyTo(r); - } - var ys = y.t; - var y0 = y.data[ys - 1]; - if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + (ys > 1 ? y.data[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; - var i = r.t, j = i - ys, t = q == null ? nbi() : q; - y.dlShiftTo(j, t); - if (r.compareTo(t) >= 0) { - r.data[r.t++] = 1; - r.subTo(t, r); + looping = decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2]; } - BigInteger.ONE.dlShiftTo(ys, t); - t.subTo(y, y); - while (y.t < ys) y.data[y.t++] = 0; - while (--j >= 0) { - var qd = r.data[--i] == y0 ? this.DM : Math.floor(r.data[i] * d1 + (r.data[i - 1] + e) * d2); - if ((r.data[i] += y.am(0, qd, r, j, 0, ys)) < qd) { - y.dlShiftTo(j, t); - r.subTo(t, r); - while (r.data[i] < --qd) r.subTo(t, r); + var tmp; + var left = input[0]; + var right = input[1]; + tmp = (left >>> 4 ^ right) & 252645135; + right ^= tmp; + left ^= tmp << 4; + tmp = (left >>> 16 ^ right) & 65535; + right ^= tmp; + left ^= tmp << 16; + tmp = (right >>> 2 ^ left) & 858993459; + left ^= tmp; + right ^= tmp << 2; + tmp = (right >>> 8 ^ left) & 16711935; + left ^= tmp; + right ^= tmp << 8; + tmp = (left >>> 1 ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + left = left << 1 | left >>> 31; + right = right << 1 | right >>> 31; + for (var j = 0; j < iterations; j += 3) { + var endloop = looping[j + 1]; + var loopinc = looping[j + 2]; + for (var i = looping[j]; i != endloop; i += loopinc) { + var right1 = right ^ keys[i]; + var right2 = (right >>> 4 | right << 28) ^ keys[i + 1]; + tmp = left; + left = right; + right = tmp ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right2 >>> 24 & 63] | spfunction3[right2 >>> 16 & 63] | spfunction5[right2 >>> 8 & 63] | spfunction7[right2 & 63]); } + tmp = left; + left = right; + right = tmp; } - if (q != null) { - r.drShiftTo(ys, q); - if (ts != ms) BigInteger.ZERO.subTo(q, q); - } - r.t = ys; - r.clamp(); - if (nsh > 0) r.rShiftTo(nsh, r); - if (ts < 0) BigInteger.ZERO.subTo(r, r); - } - function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a, null, r); - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); - return r; + left = left >>> 1 | left << 31; + right = right >>> 1 | right << 31; + tmp = (left >>> 1 ^ right) & 1431655765; + right ^= tmp; + left ^= tmp << 1; + tmp = (right >>> 8 ^ left) & 16711935; + left ^= tmp; + right ^= tmp << 8; + tmp = (right >>> 2 ^ left) & 858993459; + left ^= tmp; + right ^= tmp << 2; + tmp = (left >>> 16 ^ right) & 65535; + right ^= tmp; + left ^= tmp << 16; + tmp = (left >>> 4 ^ right) & 252645135; + right ^= tmp; + left ^= tmp << 4; + output[0] = left; + output[1] = right; } - function Classic(m) { - this.m = m; + function _createCipher(options) { + options = options || {}; + var mode = (options.mode || "CBC").toUpperCase(); + var algorithm = "DES-" + mode; + var cipher; + if (options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + var start = cipher.start; + cipher.start = function(iv, options2) { + var output = null; + if (options2 instanceof forge.util.ByteBuffer) { + output = options2; + options2 = {}; + } + options2 = options2 || {}; + options2.output = output; + options2.iv = iv; + start.call(cipher, options2); + }; + return cipher; } - function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; + } +}); + +// node_modules/node-forge/lib/pbkdf2.js +var require_pbkdf2 = __commonJS({ + "node_modules/node-forge/lib/pbkdf2.js"(exports2, module2) { + var forge = require_forge(); + require_hmac(); + require_md(); + require_util8(); + var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; + var crypto; + if (forge.util.isNodejs && !forge.options.usePureJavaScript) { + crypto = require("crypto"); } - function cRevert(x) { - return x; - } - function cReduce(x) { - x.divRemTo(this.m, null, x); - } - function cMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - function cSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; - function bnpInvDigit() { - if (this.t < 1) return 0; - var x = this.data[0]; - if ((x & 1) == 0) return 0; - var y = x & 3; - y = y * (2 - (x & 15) * y) & 15; - y = y * (2 - (x & 255) * y) & 255; - y = y * (2 - ((x & 65535) * y & 65535)) & 65535; - y = y * (2 - x * y % this.DV) % this.DV; - return y > 0 ? this.DV - y : -y; - } - function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp & 32767; - this.mph = this.mp >> 15; - this.um = (1 << m.DB - 15) - 1; - this.mt2 = 2 * m.t; - } - function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t, r); - r.divRemTo(this.m, null, r); - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); - return r; - } - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - function montReduce(x) { - while (x.t <= this.mt2) - x.data[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { - var j = x.data[i] & 32767; - var u0 = j * this.mpl + ((j * this.mph + (x.data[i] >> 15) * this.mpl & this.um) << 15) & x.DM; - j = i + this.m.t; - x.data[j] += this.m.am(0, u0, x, i, 0, this.m.t); - while (x.data[j] >= x.DV) { - x.data[j] -= x.DV; - x.data[++j]++; - } - } - x.clamp(); - x.drShiftTo(this.m.t, x); - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - function montSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - function montMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; - function bnpIsEven() { - return (this.t > 0 ? this.data[0] & 1 : this.s) == 0; - } - function bnpExp(e, z) { - if (e > 4294967295 || e < 1) return BigInteger.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1; - g.copyTo(r); - while (--i >= 0) { - z.sqrTo(r, r2); - if ((e & 1 << i) > 0) z.mulTo(r2, g, r); - else { - var t = r; - r = r2; - r2 = t; - } - } - return z.revert(r); - } - function bnModPowInt(e, m) { - var z; - if (e < 256 || m.isEven()) z = new Classic(m); - else z = new Montgomery(m); - return this.exp(e, z); - } - BigInteger.prototype.copyTo = bnpCopyTo; - BigInteger.prototype.fromInt = bnpFromInt; - BigInteger.prototype.fromString = bnpFromString; - BigInteger.prototype.clamp = bnpClamp; - BigInteger.prototype.dlShiftTo = bnpDLShiftTo; - BigInteger.prototype.drShiftTo = bnpDRShiftTo; - BigInteger.prototype.lShiftTo = bnpLShiftTo; - BigInteger.prototype.rShiftTo = bnpRShiftTo; - BigInteger.prototype.subTo = bnpSubTo; - BigInteger.prototype.multiplyTo = bnpMultiplyTo; - BigInteger.prototype.squareTo = bnpSquareTo; - BigInteger.prototype.divRemTo = bnpDivRemTo; - BigInteger.prototype.invDigit = bnpInvDigit; - BigInteger.prototype.isEven = bnpIsEven; - BigInteger.prototype.exp = bnpExp; - BigInteger.prototype.toString = bnToString; - BigInteger.prototype.negate = bnNegate; - BigInteger.prototype.abs = bnAbs; - BigInteger.prototype.compareTo = bnCompareTo; - BigInteger.prototype.bitLength = bnBitLength; - BigInteger.prototype.mod = bnMod; - BigInteger.prototype.modPowInt = bnModPowInt; - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); - function bnClone() { - var r = nbi(); - this.copyTo(r); - return r; - } - function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this.data[0] - this.DV; - else if (this.t == 0) return -1; - } else if (this.t == 1) return this.data[0]; - else if (this.t == 0) return 0; - return (this.data[1] & (1 << 32 - this.DB) - 1) << this.DB | this.data[0]; - } - function bnByteValue() { - return this.t == 0 ? this.s : this.data[0] << 24 >> 24; - } - function bnShortValue() { - return this.t == 0 ? this.s : this.data[0] << 16 >> 16; - } - function bnpChunkSize(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)); - } - function bnSigNum() { - if (this.s < 0) return -1; - else if (this.t <= 0 || this.t == 1 && this.data[0] <= 0) return 0; - else return 1; - } - function bnpToRadix(b) { - if (b == null) b = 10; - if (this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), y = nbi(), z = nbi(), r = ""; - this.divRemTo(d, y, z); - while (y.signum() > 0) { - r = (a + z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d, y, z); + module2.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(p, s, c, dkLen, md, callback) { + if (typeof md === "function") { + callback = md; + md = null; } - return z.intValue().toString(b) + r; - } - function bnpFromRadix(s, b) { - this.fromInt(0); - if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), mi = false, j = 0, w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b * w + x; - if (++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w, 0); - j = 0; - w = 0; + if (forge.util.isNodejs && !forge.options.usePureJavaScript && crypto.pbkdf2 && (md === null || typeof md !== "object") && (crypto.pbkdf2Sync.length > 4 || (!md || md === "sha1"))) { + if (typeof md !== "string") { + md = "sha1"; } - } - if (j > 0) { - this.dMultiply(Math.pow(b, j)); - this.dAddOffset(w, 0); - } - if (mi) BigInteger.ZERO.subTo(this, this); - } - function bnpFromNumber(a, b, c) { - if ("number" == typeof b) { - if (a < 2) this.fromInt(1); - else { - this.fromNumber(a, c); - if (!this.testBit(a - 1)) - this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); - if (this.isEven()) this.dAddOffset(1, 0); - while (!this.isProbablePrime(b)) { - this.dAddOffset(2, 0); - if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + p = Buffer.from(p, "binary"); + s = Buffer.from(s, "binary"); + if (!callback) { + if (crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2Sync(p, s, c, dkLen).toString("binary"); } + return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString("binary"); } - } else { - var x = new Array(), t = a & 7; - x.length = (a >> 3) + 1; - b.nextBytes(x); - if (t > 0) x[0] &= (1 << t) - 1; - else x[0] = 0; - this.fromString(x, 256); - } - } - function bnToByteArray() { - var i = this.t, r = new Array(); - r[0] = this.s; - var p = this.DB - i * this.DB % 8, d, k = 0; - if (i-- > 0) { - if (p < this.DB && (d = this.data[i] >> p) != (this.s & this.DM) >> p) - r[k++] = d | this.s << this.DB - p; - while (i >= 0) { - if (p < 8) { - d = (this.data[i] & (1 << p) - 1) << 8 - p; - d |= this.data[--i] >> (p += this.DB - 8); - } else { - d = this.data[i] >> (p -= 8) & 255; - if (p <= 0) { - p += this.DB; - --i; + if (crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2(p, s, c, dkLen, function(err2, key) { + if (err2) { + return callback(err2); } - } - if ((d & 128) != 0) d |= -256; - if (k == 0 && (this.s & 128) != (d & 128)) ++k; - if (k > 0 || d != this.s) r[k++] = d; + callback(null, key.toString("binary")); + }); } + return crypto.pbkdf2(p, s, c, dkLen, md, function(err2, key) { + if (err2) { + return callback(err2); + } + callback(null, key.toString("binary")); + }); } - return r; - } - function bnEquals(a) { - return this.compareTo(a) == 0; - } - function bnMin(a) { - return this.compareTo(a) < 0 ? this : a; - } - function bnMax(a) { - return this.compareTo(a) > 0 ? this : a; - } - function bnpBitwiseTo(a, op, r) { - var i, f, m = Math.min(a.t, this.t); - for (i = 0; i < m; ++i) r.data[i] = op(this.data[i], a.data[i]); - if (a.t < this.t) { - f = a.s & this.DM; - for (i = m; i < this.t; ++i) r.data[i] = op(this.data[i], f); - r.t = this.t; - } else { - f = this.s & this.DM; - for (i = m; i < a.t; ++i) r.data[i] = op(f, a.data[i]); - r.t = a.t; + if (typeof md === "undefined" || md === null) { + md = "sha1"; } - r.s = op(this.s, a.s); - r.clamp(); - } - function op_and(x, y) { - return x & y; - } - function bnAnd(a) { - var r = nbi(); - this.bitwiseTo(a, op_and, r); - return r; - } - function op_or(x, y) { - return x | y; - } - function bnOr(a) { - var r = nbi(); - this.bitwiseTo(a, op_or, r); - return r; - } - function op_xor(x, y) { - return x ^ y; - } - function bnXor(a) { - var r = nbi(); - this.bitwiseTo(a, op_xor, r); - return r; - } - function op_andnot(x, y) { - return x & ~y; - } - function bnAndNot(a) { - var r = nbi(); - this.bitwiseTo(a, op_andnot, r); - return r; - } - function bnNot() { - var r = nbi(); - for (var i = 0; i < this.t; ++i) r.data[i] = this.DM & ~this.data[i]; - r.t = this.t; - r.s = ~this.s; - return r; - } - function bnShiftLeft(n) { - var r = nbi(); - if (n < 0) this.rShiftTo(-n, r); - else this.lShiftTo(n, r); - return r; - } - function bnShiftRight(n) { - var r = nbi(); - if (n < 0) this.lShiftTo(-n, r); - else this.rShiftTo(n, r); - return r; - } - function lbit(x) { - if (x == 0) return -1; - var r = 0; - if ((x & 65535) == 0) { - x >>= 16; - r += 16; + if (typeof md === "string") { + if (!(md in forge.md.algorithms)) { + throw new Error("Unknown hash algorithm: " + md); + } + md = forge.md[md].create(); } - if ((x & 255) == 0) { - x >>= 8; - r += 8; + var hLen = md.digestLength; + if (dkLen > 4294967295 * hLen) { + var err = new Error("Derived key is too long."); + if (callback) { + return callback(err); + } + throw err; } - if ((x & 15) == 0) { - x >>= 4; - r += 4; + var len = Math.ceil(dkLen / hLen); + var r = dkLen - (len - 1) * hLen; + var prf = forge.hmac.create(); + prf.start(md, p); + var dk = ""; + var xor, u_c, u_c1; + if (!callback) { + for (var i = 1; i <= len; ++i) { + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + for (var j = 2; j <= c; ++j) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + } + dk += i < len ? xor : xor.substr(0, r); + } + return dk; } - if ((x & 3) == 0) { - x >>= 2; - r += 2; + var i = 1, j; + function outer() { + if (i > len) { + return callback(null, dk); + } + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + j = 2; + inner(); } - if ((x & 1) == 0) ++r; - return r; - } - function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this.data[i] != 0) return i * this.DB + lbit(this.data[i]); - if (this.s < 0) return this.t * this.DB; - return -1; - } - function cbit(x) { - var r = 0; - while (x != 0) { - x &= x - 1; - ++r; + function inner() { + if (j <= c) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + ++j; + return forge.util.setImmediate(inner); + } + dk += i < len ? xor : xor.substr(0, r); + ++i; + outer(); } - return r; - } - function bnBitCount() { - var r = 0, x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) r += cbit(this.data[i] ^ x); - return r; - } - function bnTestBit(n) { - var j = Math.floor(n / this.DB); - if (j >= this.t) return this.s != 0; - return (this.data[j] & 1 << n % this.DB) != 0; - } - function bnpChangeBit(n, op) { - var r = BigInteger.ONE.shiftLeft(n); - this.bitwiseTo(r, op, r); - return r; - } - function bnSetBit(n) { - return this.changeBit(n, op_or); - } - function bnClearBit(n) { - return this.changeBit(n, op_andnot); - } - function bnFlipBit(n) { - return this.changeBit(n, op_xor); - } - function bnpAddTo(a, r) { - var i = 0, c = 0, m = Math.min(a.t, this.t); - while (i < m) { - c += this.data[i] + a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; + outer(); + }; + } +}); + +// node_modules/node-forge/lib/sha256.js +var require_sha256 = __commonJS({ + "node_modules/node-forge/lib/sha256.js"(exports2, module2) { + var forge = require_forge(); + require_md(); + require_util8(); + var sha256 = module2.exports = forge.sha256 = forge.sha256 || {}; + forge.md.sha256 = forge.md.algorithms.sha256 = sha256; + sha256.create = function() { + if (!_initialized) { + _init(); } - if (a.t < this.t) { - c += a.s; - while (i < this.t) { - c += this.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c += a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = c < 0 ? -1 : 0; - if (c > 0) r.data[i++] = c; - else if (c < -1) r.data[i++] = this.DV + c; - r.t = i; - r.clamp(); - } - function bnAdd(a) { - var r = nbi(); - this.addTo(a, r); - return r; - } - function bnSubtract(a) { - var r = nbi(); - this.subTo(a, r); - return r; - } - function bnMultiply(a) { - var r = nbi(); - this.multiplyTo(a, r); - return r; - } - function bnDivide(a) { - var r = nbi(); - this.divRemTo(a, r, null); - return r; - } - function bnRemainder(a) { - var r = nbi(); - this.divRemTo(a, null, r); - return r; - } - function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a, q, r); - return new Array(q, r); - } - function bnpDMultiply(n) { - this.data[this.t] = this.am(0, n - 1, this, 0, 0, this.t); - ++this.t; - this.clamp(); - } - function bnpDAddOffset(n, w) { - if (n == 0) return; - while (this.t <= w) this.data[this.t++] = 0; - this.data[w] += n; - while (this.data[w] >= this.DV) { - this.data[w] -= this.DV; - if (++w >= this.t) this.data[this.t++] = 0; - ++this.data[w]; - } - } - function NullExp() { - } - function nNop(x) { - return x; - } - function nMulTo(x, y, r) { - x.multiplyTo(y, r); - } - function nSqrTo(x, r) { - x.squareTo(r); - } - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; - function bnPow(e) { - return this.exp(e, new NullExp()); - } - function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n); - r.s = 0; - r.t = i; - while (i > 0) r.data[--i] = 0; - var j; - for (j = r.t - this.t; i < j; ++i) r.data[i + this.t] = this.am(0, a.data[i], r, i, 0, this.t); - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a.data[i], r, i, 0, n - i); - r.clamp(); - } - function bnpMultiplyUpperTo(a, n, r) { - --n; - var i = r.t = this.t + a.t - n; - r.s = 0; - while (--i >= 0) r.data[i] = 0; - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r.data[this.t + i - n] = this.am(n - i, a.data[i], r, 0, 0, this.t + i - n); - r.clamp(); - r.drShiftTo(1, r); - } - function Barrett(m) { - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); - this.mu = this.r2.divide(m); - this.m = m; - } - function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); - else if (x.compareTo(this.m) < 0) return x; - else { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - } - function barrettRevert(x) { - return x; - } - function barrettReduce(x) { - x.drShiftTo(this.m.t - 1, this.r2); - if (x.t > this.m.t + 1) { - x.t = this.m.t + 1; - x.clamp(); - } - this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); - this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); - while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); - x.subTo(this.r2, x); - while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - function barrettSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - function barrettMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; - function bnModPow(e, m) { - var i = e.bitLength(), k, r = nbv(1), z; - if (i <= 0) return r; - else if (i < 18) k = 1; - else if (i < 48) k = 3; - else if (i < 144) k = 4; - else if (i < 768) k = 5; - else k = 6; - if (i < 8) - z = new Classic(m); - else if (m.isEven()) - z = new Barrett(m); - else - z = new Montgomery(m); - var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; - g[1] = z.convert(this); - if (k > 1) { - var g2 = nbi(); - z.sqrTo(g[1], g2); - while (n <= km) { - g[n] = nbi(); - z.mulTo(g2, g[n - 2], g[n]); - n += 2; - } - } - var j = e.t - 1, w, is1 = true, r2 = nbi(), t; - i = nbits(e.data[j]) - 1; - while (j >= 0) { - if (i >= k1) w = e.data[j] >> i - k1 & km; - else { - w = (e.data[j] & (1 << i + 1) - 1) << k1 - i; - if (j > 0) w |= e.data[j - 1] >> this.DB + i - k1; - } - n = k; - while ((w & 1) == 0) { - w >>= 1; - --n; - } - if ((i -= n) < 0) { - i += this.DB; - --j; - } - if (is1) { - g[w].copyTo(r); - is1 = false; - } else { - while (n > 1) { - z.sqrTo(r, r2); - z.sqrTo(r2, r); - n -= 2; - } - if (n > 0) z.sqrTo(r, r2); - else { - t = r; - r = r2; - r2 = t; - } - z.mulTo(r2, g[w], r); - } - while (j >= 0 && (e.data[j] & 1 << i) == 0) { - z.sqrTo(r, r2); - t = r; - r = r2; - r2 = t; - if (--i < 0) { - i = this.DB - 1; - --j; - } - } - } - return z.revert(r); - } - function bnGCD(a) { - var x = this.s < 0 ? this.negate() : this.clone(); - var y = a.s < 0 ? a.negate() : a.clone(); - if (x.compareTo(y) < 0) { - var t = x; - x = y; - y = t; - } - var i = x.getLowestSetBit(), g = y.getLowestSetBit(); - if (g < 0) return x; - if (i < g) g = i; - if (g > 0) { - x.rShiftTo(g, x); - y.rShiftTo(g, y); - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); - if (x.compareTo(y) >= 0) { - x.subTo(y, x); - x.rShiftTo(1, x); - } else { - y.subTo(x, y); - y.rShiftTo(1, y); - } - } - if (g > 0) y.lShiftTo(g, y); - return y; - } - function bnpModInt(n) { - if (n <= 0) return 0; - var d = this.DV % n, r = this.s < 0 ? n - 1 : 0; - if (this.t > 0) - if (d == 0) r = this.data[0] % n; - else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this.data[i]) % n; - return r; - } - function bnModInverse(m) { - var ac = m.isEven(); - if (this.isEven() && ac || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), v = this.clone(); - var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u); - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a); - b.subTo(m, b); - } - a.rShiftTo(1, a); - } else if (!b.isEven()) b.subTo(m, b); - b.rShiftTo(1, b); - } - while (v.isEven()) { - v.rShiftTo(1, v); - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c); - d.subTo(m, d); - } - c.rShiftTo(1, c); - } else if (!d.isEven()) d.subTo(m, d); - d.rShiftTo(1, d); - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u); - if (ac) a.subTo(c, a); - b.subTo(d, b); - } else { - v.subTo(u, v); - if (ac) c.subTo(a, c); - d.subTo(b, d); - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - if (d.compareTo(m) >= 0) return d.subtract(m); - if (d.signum() < 0) d.addTo(m, d); - else return d; - if (d.signum() < 0) return d.add(m); - else return d; - } - var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509]; - var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; - function bnIsProbablePrime(t) { - var i, x = this.abs(); - if (x.t == 1 && x.data[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x.data[0] == lowprimes[i]) return true; - return false; - } - if (x.isEven()) return false; - i = 1; - while (i < lowprimes.length) { - var m = lowprimes[i], j = i + 1; - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while (i < j) if (m % lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); - } - function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if (k <= 0) return false; - var r = n1.shiftRight(k); - var prng = bnGetPrng(); - var a; - for (var i = 0; i < t; ++i) { - do { - a = new BigInteger(this.bitLength(), prng); - } while (a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); - var y = a.modPow(r, this); - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this); - if (y.compareTo(BigInteger.ONE) == 0) return false; - } - if (y.compareTo(n1) != 0) return false; - } - } - return true; - } - function bnGetPrng() { - return { - // x is an array to fill with bytes - nextBytes: function(x) { - for (var i = 0; i < x.length; ++i) { - x[i] = Math.floor(Math.random() * 256); - } - } - }; - } - BigInteger.prototype.chunkSize = bnpChunkSize; - BigInteger.prototype.toRadix = bnpToRadix; - BigInteger.prototype.fromRadix = bnpFromRadix; - BigInteger.prototype.fromNumber = bnpFromNumber; - BigInteger.prototype.bitwiseTo = bnpBitwiseTo; - BigInteger.prototype.changeBit = bnpChangeBit; - BigInteger.prototype.addTo = bnpAddTo; - BigInteger.prototype.dMultiply = bnpDMultiply; - BigInteger.prototype.dAddOffset = bnpDAddOffset; - BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; - BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; - BigInteger.prototype.modInt = bnpModInt; - BigInteger.prototype.millerRabin = bnpMillerRabin; - BigInteger.prototype.clone = bnClone; - BigInteger.prototype.intValue = bnIntValue; - BigInteger.prototype.byteValue = bnByteValue; - BigInteger.prototype.shortValue = bnShortValue; - BigInteger.prototype.signum = bnSigNum; - BigInteger.prototype.toByteArray = bnToByteArray; - BigInteger.prototype.equals = bnEquals; - BigInteger.prototype.min = bnMin; - BigInteger.prototype.max = bnMax; - BigInteger.prototype.and = bnAnd; - BigInteger.prototype.or = bnOr; - BigInteger.prototype.xor = bnXor; - BigInteger.prototype.andNot = bnAndNot; - BigInteger.prototype.not = bnNot; - BigInteger.prototype.shiftLeft = bnShiftLeft; - BigInteger.prototype.shiftRight = bnShiftRight; - BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; - BigInteger.prototype.bitCount = bnBitCount; - BigInteger.prototype.testBit = bnTestBit; - BigInteger.prototype.setBit = bnSetBit; - BigInteger.prototype.clearBit = bnClearBit; - BigInteger.prototype.flipBit = bnFlipBit; - BigInteger.prototype.add = bnAdd; - BigInteger.prototype.subtract = bnSubtract; - BigInteger.prototype.multiply = bnMultiply; - BigInteger.prototype.divide = bnDivide; - BigInteger.prototype.remainder = bnRemainder; - BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; - BigInteger.prototype.modPow = bnModPow; - BigInteger.prototype.modInverse = bnModInverse; - BigInteger.prototype.pow = bnPow; - BigInteger.prototype.gcd = bnGCD; - BigInteger.prototype.isProbablePrime = bnIsProbablePrime; - } -}); - -// node_modules/node-forge/lib/sha1.js -var require_sha1 = __commonJS({ - "node_modules/node-forge/lib/sha1.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util8(); - var sha1 = module2.exports = forge.sha1 = forge.sha1 || {}; - forge.md.sha1 = forge.md.algorithms.sha1 = sha1; - sha1.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge.util.createBuffer(); - var _w = new Array(80); - var md = { - algorithm: "sha1", - blockLength: 64, - digestLength: 20, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); + var _state = null; + var _input = forge.util.createBuffer(); + var _w = new Array(64); + var md = { + algorithm: "sha256", + blockLength: 64, + digestLength: 32, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + md.start = function() { + md.messageLength = 0; + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); } _input = forge.util.createBuffer(); _state = { - h0: 1732584193, - h1: 4023233417, - h2: 2562383102, - h3: 271733878, - h4: 3285377520 + h0: 1779033703, + h1: 3144134277, + h2: 1013904242, + h3: 2773480762, + h4: 1359893119, + h5: 2600822924, + h6: 528734635, + h7: 1541459225 }; return md; }; @@ -29206,7 +27689,10 @@ var require_sha1 = __commonJS({ h1: _state.h1, h2: _state.h2, h3: _state.h3, - h4: _state.h4 + h4: _state.h4, + h5: _state.h5, + h6: _state.h6, + h7: _state.h7 }; _update(s2, _w, finalBlock); var rval = forge.util.createBuffer(); @@ -29215,9256 +27701,11471 @@ var require_sha1 = __commonJS({ rval.putInt32(s2.h2); rval.putInt32(s2.h3); rval.putInt32(s2.h4); + rval.putInt32(s2.h5); + rval.putInt32(s2.h6); + rval.putInt32(s2.h7); return rval; }; return md; }; var _padding = null; var _initialized = false; + var _k = null; function _init() { _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0), 64); + _k = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]; _initialized = true; } function _update(s, w, bytes) { - var t, a, b, c, d, e, f, i; + var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; var len = bytes.length(); while (len >= 64) { - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; for (i = 0; i < 16; ++i) { - t = bytes.getInt32(); - w[i] = t; - f = d ^ b & (c ^ d); - t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 20; ++i) { - t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; - t = t << 1 | t >>> 31; - w[i] = t; - f = d ^ b & (c ^ d); - t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 32; ++i) { - t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; - t = t << 1 | t >>> 31; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 40; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; + w[i] = bytes.getInt32(); } - for (; i < 60; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b & c | d & (b ^ c); - t = (a << 5 | a >>> 27) + f + e + 2400959708 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; + for (; i < 64; ++i) { + t1 = w[i - 2]; + t1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; + t2 = w[i - 15]; + t2 = (t2 >>> 7 | t2 << 25) ^ (t2 >>> 18 | t2 << 14) ^ t2 >>> 3; + w[i] = t1 + w[i - 7] + t2 + w[i - 16] | 0; } - for (; i < 80; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 3395469782 + t; - e = d; + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + f = s.h5; + g = s.h6; + h = s.h7; + for (i = 0; i < 64; ++i) { + s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); + ch = g ^ e & (f ^ g); + s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); + maj = a & b | c & (a ^ b); + t1 = h + s1 + ch + _k[i] + w[i]; + t2 = s0 + maj; + h = g; + g = f; + f = e; + e = d + t1 >>> 0; d = c; - c = (b << 30 | b >>> 2) >>> 0; + c = b; b = a; - a = t; + a = t1 + t2 >>> 0; } s.h0 = s.h0 + a | 0; s.h1 = s.h1 + b | 0; s.h2 = s.h2 + c | 0; s.h3 = s.h3 + d | 0; s.h4 = s.h4 + e | 0; + s.h5 = s.h5 + f | 0; + s.h6 = s.h6 + g | 0; + s.h7 = s.h7 + h | 0; len -= 64; } } } }); -// node_modules/node-forge/lib/pkcs1.js -var require_pkcs1 = __commonJS({ - "node_modules/node-forge/lib/pkcs1.js"(exports2, module2) { +// node_modules/node-forge/lib/prng.js +var require_prng = __commonJS({ + "node_modules/node-forge/lib/prng.js"(exports2, module2) { var forge = require_forge(); require_util8(); - require_random(); - require_sha1(); - var pkcs1 = module2.exports = forge.pkcs1 = forge.pkcs1 || {}; - pkcs1.encode_rsa_oaep = function(key, message, options) { - var label; - var seed; - var md; - var mgf1Md; - if (typeof options === "string") { - label = options; - seed = arguments[3] || void 0; - md = arguments[4] || void 0; - } else if (options) { - label = options.label || void 0; - seed = options.seed || void 0; - md = options.md || void 0; - if (options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - if (!md) { - md = forge.md.sha1.create(); - } else { - md.start(); - } - if (!mgf1Md) { - mgf1Md = md; - } - var keyLength = Math.ceil(key.n.bitLength() / 8); - var maxLength = keyLength - 2 * md.digestLength - 2; - if (message.length > maxLength) { - var error4 = new Error("RSAES-OAEP input message length is too long."); - error4.length = message.length; - error4.maxLength = maxLength; - throw error4; - } - if (!label) { - label = ""; - } - md.update(label, "raw"); - var lHash = md.digest(); - var PS = ""; - var PS_length = maxLength - message.length; - for (var i = 0; i < PS_length; i++) { - PS += "\0"; - } - var DB = lHash.getBytes() + PS + "" + message; - if (!seed) { - seed = forge.random.getBytes(md.digestLength); - } else if (seed.length !== md.digestLength) { - var error4 = new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length."); - error4.seedLength = seed.length; - error4.digestLength = md.digestLength; - throw error4; - } - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); - return "\0" + maskedSeed + maskedDB; - }; - pkcs1.decode_rsa_oaep = function(key, em, options) { - var label; - var md; - var mgf1Md; - if (typeof options === "string") { - label = options; - md = arguments[3] || void 0; - } else if (options) { - label = options.label || void 0; - md = options.md || void 0; - if (options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - var keyLength = Math.ceil(key.n.bitLength() / 8); - if (em.length !== keyLength) { - var error4 = new Error("RSAES-OAEP encoded message length is invalid."); - error4.length = em.length; - error4.expectedLength = keyLength; - throw error4; - } - if (md === void 0) { - md = forge.md.sha1.create(); - } else { - md.start(); - } - if (!mgf1Md) { - mgf1Md = md; - } - if (keyLength < 2 * md.digestLength + 2) { - throw new Error("RSAES-OAEP key is too short for the hash function."); - } - if (!label) { - label = ""; - } - md.update(label, "raw"); - var lHash = md.digest().getBytes(); - var y = em.charAt(0); - var maskedSeed = em.substring(1, md.digestLength + 1); - var maskedDB = em.substring(1 + md.digestLength); - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); - var lHashPrime = db.substring(0, md.digestLength); - var error4 = y !== "\0"; - for (var i = 0; i < md.digestLength; ++i) { - error4 |= lHash.charAt(i) !== lHashPrime.charAt(i); - } - var in_ps = 1; - var index = md.digestLength; - for (var j = md.digestLength; j < db.length; j++) { - var code = db.charCodeAt(j); - var is_0 = code & 1 ^ 1; - var error_mask = in_ps ? 65534 : 0; - error4 |= code & error_mask; - in_ps = in_ps & is_0; - index += in_ps; - } - if (error4 || db.charCodeAt(index) !== 1) { - throw new Error("Invalid RSAES-OAEP padding."); - } - return db.substring(index + 1); - }; - function rsa_mgf1(seed, maskLength, hash) { - if (!hash) { - hash = forge.md.sha1.create(); - } - var t = ""; - var count = Math.ceil(maskLength / hash.digestLength); - for (var i = 0; i < count; ++i) { - var c = String.fromCharCode( - i >> 24 & 255, - i >> 16 & 255, - i >> 8 & 255, - i & 255 - ); - hash.start(); - hash.update(seed + c); - t += hash.digest().getBytes(); - } - return t.substring(0, maskLength); + var _crypto = null; + if (forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions["node-webkit"]) { + _crypto = require("crypto"); } - } -}); - -// node_modules/node-forge/lib/prime.js -var require_prime = __commonJS({ - "node_modules/node-forge/lib/prime.js"(exports2, module2) { - var forge = require_forge(); - require_util8(); - require_jsbn(); - require_random(); - (function() { - if (forge.prime) { - module2.exports = forge.prime; - return; - } - var prime = module2.exports = forge.prime = forge.prime || {}; - var BigInteger = forge.jsbn.BigInteger; - var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; - var THIRTY = new BigInteger(null); - THIRTY.fromInt(30); - var op_or = function(x, y) { - return x | y; + var prng = module2.exports = forge.prng = forge.prng || {}; + prng.create = function(plugin) { + var ctx = { + plugin, + key: null, + seed: null, + time: null, + // number of reseeds so far + reseeds: 0, + // amount of data generated so far + generated: 0, + // no initial key bytes + keyBytes: "" }; - prime.generateProbablePrime = function(bits, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; + var md = plugin.md; + var pools = new Array(32); + for (var i = 0; i < 32; ++i) { + pools[i] = md.create(); + } + ctx.pools = pools; + ctx.pool = 0; + ctx.generate = function(count, callback) { + if (!callback) { + return ctx.generateSync(count); } - options = options || {}; - var algorithm = options.algorithm || "PRIMEINC"; - if (typeof algorithm === "string") { - algorithm = { name: algorithm }; + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + var b = forge.util.createBuffer(); + ctx.key = null; + generate(); + function generate(err) { + if (err) { + return callback(err); + } + if (b.length() >= count) { + return callback(null, b.getBytes(count)); + } + if (ctx.generated > 1048575) { + ctx.key = null; + } + if (ctx.key === null) { + return forge.util.nextTick(function() { + _reseed(generate); + }); + } + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + forge.util.setImmediate(generate); } - algorithm.options = algorithm.options || {}; - var prng = options.prng || forge.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for (var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } + }; + ctx.generateSync = function(count) { + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + ctx.key = null; + var b = forge.util.createBuffer(); + while (b.length() < count) { + if (ctx.generated > 1048575) { + ctx.key = null; } - }; - if (algorithm.name === "PRIMEINC") { - return primeincFindPrime(bits, rng, algorithm.options, callback); + if (ctx.key === null) { + _reseedSync(); + } + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); } - throw new Error("Invalid prime generation algorithm: " + algorithm.name); + return b.getBytes(count); }; - function primeincFindPrime(bits, rng, options, callback) { - if ("workers" in options) { - return primeincFindPrimeWithWorkers(bits, rng, options, callback); + function _reseed(callback) { + if (ctx.pools[0].messageLength >= 32) { + _seed(); + return callback(); } - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + var needed = 32 - ctx.pools[0].messageLength << 5; + ctx.seedFile(needed, function(err, bytes) { + if (err) { + return callback(err); + } + ctx.collect(bytes); + _seed(); + callback(); + }); } - function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { - var num = generateRandom(bits, rng); - var deltaIdx = 0; - var mrTests = getMillerRabinTests(num.bitLength()); - if ("millerRabinTests" in options) { - mrTests = options.millerRabinTests; - } - var maxBlockTime = 10; - if ("maxBlockTime" in options) { - maxBlockTime = options.maxBlockTime; + function _reseedSync() { + if (ctx.pools[0].messageLength >= 32) { + return _seed(); } - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + var needed = 32 - ctx.pools[0].messageLength << 5; + ctx.collect(ctx.seedFileSync(needed)); + _seed(); } - function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { - var start = +/* @__PURE__ */ new Date(); - do { - if (num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - if (num.isProbablePrime(mrTests)) { - return callback(null, num); + function _seed() { + ctx.reseeds = ctx.reseeds === 4294967295 ? 0 : ctx.reseeds + 1; + var md2 = ctx.plugin.md.create(); + md2.update(ctx.keyBytes); + var _2powK = 1; + for (var k = 0; k < 32; ++k) { + if (ctx.reseeds % _2powK === 0) { + md2.update(ctx.pools[k].digest().getBytes()); + ctx.pools[k].start(); } - num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } while (maxBlockTime < 0 || +/* @__PURE__ */ new Date() - start < maxBlockTime); - forge.util.setImmediate(function() { - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); - }); - } - function primeincFindPrimeWithWorkers(bits, rng, options, callback) { - if (typeof Worker === "undefined") { - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + _2powK = _2powK << 1; } - var num = generateRandom(bits, rng); - var numWorkers = options.workers; - var workLoad = options.workLoad || 100; - var range = workLoad * 30 / 8; - var workerScript = options.workerScript || "forge/prime.worker.js"; - if (numWorkers === -1) { - return forge.util.estimateCores(function(err, cores) { - if (err) { - cores = 2; - } - numWorkers = cores - 1; - generate(); - }); + ctx.keyBytes = md2.digest().getBytes(); + md2.start(); + md2.update(ctx.keyBytes); + var seedBytes = md2.digest().getBytes(); + ctx.key = ctx.plugin.formatKey(ctx.keyBytes); + ctx.seed = ctx.plugin.formatSeed(seedBytes); + ctx.generated = 0; + } + function defaultSeedFile(needed) { + var getRandomValues = null; + var globalScope = forge.util.globalScope; + var _crypto2 = globalScope.crypto || globalScope.msCrypto; + if (_crypto2 && _crypto2.getRandomValues) { + getRandomValues = function(arr) { + return _crypto2.getRandomValues(arr); + }; } - generate(); - function generate() { - numWorkers = Math.max(1, numWorkers); - var workers = []; - for (var i = 0; i < numWorkers; ++i) { - workers[i] = new Worker(workerScript); - } - var running = numWorkers; - for (var i = 0; i < numWorkers; ++i) { - workers[i].addEventListener("message", workerMessage); - } - var found = false; - function workerMessage(e) { - if (found) { - return; - } - --running; - var data = e.data; - if (data.found) { - for (var i2 = 0; i2 < workers.length; ++i2) { - workers[i2].terminate(); + var b = forge.util.createBuffer(); + if (getRandomValues) { + while (b.length() < needed) { + var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); + var entropy = new Uint32Array(Math.floor(count)); + try { + getRandomValues(entropy); + for (var i2 = 0; i2 < entropy.length; ++i2) { + b.putInt32(entropy[i2]); + } + } catch (e) { + if (!(typeof QuotaExceededError !== "undefined" && e instanceof QuotaExceededError)) { + throw e; } - found = true; - return callback(null, new BigInteger(data.prime, 16)); } - if (num.bitLength() > bits) { - num = generateRandom(bits, rng); + } + } + if (b.length() < needed) { + var hi, lo, next; + var seed = Math.floor(Math.random() * 65536); + while (b.length() < needed) { + lo = 16807 * (seed & 65535); + hi = 16807 * (seed >> 16); + lo += (hi & 32767) << 16; + lo += hi >> 15; + lo = (lo & 2147483647) + (lo >> 31); + seed = lo & 4294967295; + for (var i2 = 0; i2 < 3; ++i2) { + next = seed >>> (i2 << 3); + next ^= Math.floor(Math.random() * 256); + b.putByte(next & 255); } - var hex = num.toString(16); - e.target.postMessage({ - hex, - workLoad - }); - num.dAddOffset(range, 0); } } + return b.getBytes(needed); } - function generateRandom(bits, rng) { - var num = new BigInteger(bits, rng); - var bits1 = bits - 1; - if (!num.testBit(bits1)) { - num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); - } - num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); - return num; + if (_crypto) { + ctx.seedFile = function(needed, callback) { + _crypto.randomBytes(needed, function(err, bytes) { + if (err) { + return callback(err); + } + callback(null, bytes.toString()); + }); + }; + ctx.seedFileSync = function(needed) { + return _crypto.randomBytes(needed).toString(); + }; + } else { + ctx.seedFile = function(needed, callback) { + try { + callback(null, defaultSeedFile(needed)); + } catch (e) { + callback(e); + } + }; + ctx.seedFileSync = defaultSeedFile; } - function getMillerRabinTests(bits) { - if (bits <= 100) return 27; - if (bits <= 150) return 18; - if (bits <= 200) return 15; - if (bits <= 250) return 12; - if (bits <= 300) return 9; - if (bits <= 350) return 8; - if (bits <= 400) return 7; - if (bits <= 500) return 6; - if (bits <= 600) return 5; - if (bits <= 800) return 4; - if (bits <= 1250) return 3; - return 2; + ctx.collect = function(bytes) { + var count = bytes.length; + for (var i2 = 0; i2 < count; ++i2) { + ctx.pools[ctx.pool].update(bytes.substr(i2, 1)); + ctx.pool = ctx.pool === 31 ? 0 : ctx.pool + 1; + } + }; + ctx.collectInt = function(i2, n) { + var bytes = ""; + for (var x = 0; x < n; x += 8) { + bytes += String.fromCharCode(i2 >> x & 255); + } + ctx.collect(bytes); + }; + ctx.registerWorker = function(worker) { + if (worker === self) { + ctx.seedFile = function(needed, callback) { + function listener2(e) { + var data = e.data; + if (data.forge && data.forge.prng) { + self.removeEventListener("message", listener2); + callback(data.forge.prng.err, data.forge.prng.bytes); + } + } + self.addEventListener("message", listener2); + self.postMessage({ forge: { prng: { needed } } }); + }; + } else { + var listener = function(e) { + var data = e.data; + if (data.forge && data.forge.prng) { + ctx.seedFile(data.forge.prng.needed, function(err, bytes) { + worker.postMessage({ forge: { prng: { err, bytes } } }); + }); + } + }; + worker.addEventListener("message", listener); + } + }; + return ctx; + }; + } +}); + +// node_modules/node-forge/lib/random.js +var require_random = __commonJS({ + "node_modules/node-forge/lib/random.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_sha256(); + require_prng(); + require_util8(); + (function() { + if (forge.random && forge.random.getBytes) { + module2.exports = forge.random; + return; } + (function(jQuery2) { + var prng_aes = {}; + var _prng_aes_output = new Array(4); + var _prng_aes_buffer = forge.util.createBuffer(); + prng_aes.formatKey = function(key2) { + var tmp = forge.util.createBuffer(key2); + key2 = new Array(4); + key2[0] = tmp.getInt32(); + key2[1] = tmp.getInt32(); + key2[2] = tmp.getInt32(); + key2[3] = tmp.getInt32(); + return forge.aes._expandKey(key2, false); + }; + prng_aes.formatSeed = function(seed) { + var tmp = forge.util.createBuffer(seed); + seed = new Array(4); + seed[0] = tmp.getInt32(); + seed[1] = tmp.getInt32(); + seed[2] = tmp.getInt32(); + seed[3] = tmp.getInt32(); + return seed; + }; + prng_aes.cipher = function(key2, seed) { + forge.aes._updateBlock(key2, seed, _prng_aes_output, false); + _prng_aes_buffer.putInt32(_prng_aes_output[0]); + _prng_aes_buffer.putInt32(_prng_aes_output[1]); + _prng_aes_buffer.putInt32(_prng_aes_output[2]); + _prng_aes_buffer.putInt32(_prng_aes_output[3]); + return _prng_aes_buffer.getBytes(); + }; + prng_aes.increment = function(seed) { + ++seed[3]; + return seed; + }; + prng_aes.md = forge.md.sha256; + function spawnPrng() { + var ctx = forge.prng.create(prng_aes); + ctx.getBytes = function(count, callback) { + return ctx.generate(count, callback); + }; + ctx.getBytesSync = function(count) { + return ctx.generate(count); + }; + return ctx; + } + var _ctx = spawnPrng(); + var getRandomValues = null; + var globalScope = forge.util.globalScope; + var _crypto = globalScope.crypto || globalScope.msCrypto; + if (_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; + } + if (forge.options.usePureJavaScript || !forge.util.isNodejs && !getRandomValues) { + if (typeof window === "undefined" || window.document === void 0) { + } + _ctx.collectInt(+/* @__PURE__ */ new Date(), 32); + if (typeof navigator !== "undefined") { + var _navBytes = ""; + for (var key in navigator) { + try { + if (typeof navigator[key] == "string") { + _navBytes += navigator[key]; + } + } catch (e) { + } + } + _ctx.collect(_navBytes); + _navBytes = null; + } + if (jQuery2) { + jQuery2().mousemove(function(e) { + _ctx.collectInt(e.clientX, 16); + _ctx.collectInt(e.clientY, 16); + }); + jQuery2().keypress(function(e) { + _ctx.collectInt(e.charCode, 8); + }); + } + } + if (!forge.random) { + forge.random = _ctx; + } else { + for (var key in _ctx) { + forge.random[key] = _ctx[key]; + } + } + forge.random.createInstance = spawnPrng; + module2.exports = forge.random; + })(typeof jQuery !== "undefined" ? jQuery : null); })(); } }); -// node_modules/node-forge/lib/rsa.js -var require_rsa = __commonJS({ - "node_modules/node-forge/lib/rsa.js"(exports2, module2) { +// node_modules/node-forge/lib/rc2.js +var require_rc2 = __commonJS({ + "node_modules/node-forge/lib/rc2.js"(exports2, module2) { var forge = require_forge(); - require_asn1(); - require_jsbn(); - require_oids(); - require_pkcs1(); - require_prime(); - require_random(); require_util8(); - if (typeof BigInteger === "undefined") { - BigInteger = forge.jsbn.BigInteger; - } - var BigInteger; - var _crypto = forge.util.isNodejs ? require("crypto") : null; - var asn1 = forge.asn1; - var util = forge.util; - forge.pki = forge.pki || {}; - module2.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; - var pki2 = forge.pki; - var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; - var privateKeyValidator = { - // PrivateKeyInfo - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "PrivateKeyInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // privateKeyAlgorithm - name: "PrivateKeyInfo.privateKeyAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "privateKeyOid" - }] - }, { - // PrivateKey - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "privateKey" - }] + var piTable = [ + 217, + 120, + 249, + 196, + 25, + 221, + 181, + 237, + 40, + 233, + 253, + 121, + 74, + 160, + 216, + 157, + 198, + 126, + 55, + 131, + 43, + 118, + 83, + 142, + 98, + 76, + 100, + 136, + 68, + 139, + 251, + 162, + 23, + 154, + 89, + 245, + 135, + 179, + 79, + 19, + 97, + 69, + 109, + 141, + 9, + 129, + 125, + 50, + 189, + 143, + 64, + 235, + 134, + 183, + 123, + 11, + 240, + 149, + 33, + 34, + 92, + 107, + 78, + 130, + 84, + 214, + 101, + 147, + 206, + 96, + 178, + 28, + 115, + 86, + 192, + 20, + 167, + 140, + 241, + 220, + 18, + 117, + 202, + 31, + 59, + 190, + 228, + 209, + 66, + 61, + 212, + 48, + 163, + 60, + 182, + 38, + 111, + 191, + 14, + 218, + 70, + 105, + 7, + 87, + 39, + 242, + 29, + 155, + 188, + 148, + 67, + 3, + 248, + 17, + 199, + 246, + 144, + 239, + 62, + 231, + 6, + 195, + 213, + 47, + 200, + 102, + 30, + 215, + 8, + 232, + 234, + 222, + 128, + 82, + 238, + 247, + 132, + 170, + 114, + 172, + 53, + 77, + 106, + 42, + 150, + 26, + 210, + 113, + 90, + 21, + 73, + 116, + 75, + 159, + 208, + 94, + 4, + 24, + 164, + 236, + 194, + 224, + 65, + 110, + 15, + 81, + 203, + 204, + 36, + 145, + 175, + 80, + 161, + 244, + 112, + 57, + 153, + 124, + 58, + 133, + 35, + 184, + 180, + 122, + 252, + 2, + 54, + 91, + 37, + 85, + 151, + 49, + 45, + 93, + 250, + 152, + 227, + 138, + 146, + 174, + 5, + 223, + 41, + 16, + 103, + 108, + 186, + 201, + 211, + 0, + 230, + 207, + 225, + 158, + 168, + 44, + 99, + 22, + 1, + 63, + 88, + 226, + 137, + 169, + 13, + 56, + 52, + 27, + 171, + 51, + 255, + 176, + 187, + 72, + 12, + 95, + 185, + 177, + 205, + 46, + 197, + 243, + 219, + 71, + 229, + 165, + 156, + 119, + 10, + 166, + 32, + 104, + 254, + 127, + 193, + 173 + ]; + var s = [1, 2, 3, 5]; + var rol = function(word, bits) { + return word << bits & 65535 | (word & 65535) >> 16 - bits; }; - var rsaPrivateKeyValidator = { - // RSAPrivateKey - name: "RSAPrivateKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "RSAPrivateKey.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // modulus (n) - name: "RSAPrivateKey.modulus", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyModulus" - }, { - // publicExponent (e) - name: "RSAPrivateKey.publicExponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPublicExponent" - }, { - // privateExponent (d) - name: "RSAPrivateKey.privateExponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrivateExponent" - }, { - // prime1 (p) - name: "RSAPrivateKey.prime1", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrime1" - }, { - // prime2 (q) - name: "RSAPrivateKey.prime2", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrime2" - }, { - // exponent1 (d mod (p-1)) - name: "RSAPrivateKey.exponent1", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyExponent1" - }, { - // exponent2 (d mod (q-1)) - name: "RSAPrivateKey.exponent2", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyExponent2" - }, { - // coefficient ((inverse of q) mod p) - name: "RSAPrivateKey.coefficient", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyCoefficient" - }] - }; - var rsaPublicKeyValidator = { - // RSAPublicKey - name: "RSAPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // modulus (n) - name: "RSAPublicKey.modulus", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "publicKeyModulus" - }, { - // publicExponent (e) - name: "RSAPublicKey.exponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "publicKeyExponent" - }] - }; - var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { - name: "SubjectPublicKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "subjectPublicKeyInfo", - value: [{ - name: "SubjectPublicKeyInfo.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "publicKeyOid" - }] - }, { - // subjectPublicKey - name: "SubjectPublicKeyInfo.subjectPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: "SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: "rsaPublicKey" - }] - }] - }; - var digestInfoValidator = { - name: "DigestInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "DigestInfo.DigestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "DigestInfo.DigestAlgorithm.algorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "algorithmIdentifier" - }, { - // NULL paramters - name: "DigestInfo.DigestAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.NULL, - // captured only to check existence for md2 and md5 - capture: "parameters", - optional: true, - constructed: false - }] - }, { - // digest - name: "DigestInfo.digest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "digest" - }] - }; - var emsaPkcs1v15encode = function(md) { - var oid; - if (md.algorithm in pki2.oids) { - oid = pki2.oids[md.algorithm]; - } else { - var error4 = new Error("Unknown message digest algorithm."); - error4.algorithm = md.algorithm; - throw error4; - } - var oidBytes = asn1.oidToDer(oid).getBytes(); - var digestInfo = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var digestAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - oidBytes - )); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.NULL, - false, - "" - )); - var digest = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - md.digest().getBytes() - ); - digestInfo.value.push(digestAlgorithm); - digestInfo.value.push(digest); - return asn1.toDer(digestInfo).getBytes(); - }; - var _modPow = function(x, key, pub) { - if (pub) { - return x.modPow(key.e, key.n); - } - if (!key.p || !key.q) { - return x.modPow(key.d, key.n); - } - if (!key.dP) { - key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); - } - if (!key.dQ) { - key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); - } - if (!key.qInv) { - key.qInv = key.q.modInverse(key.p); - } - var r; - do { - r = new BigInteger( - forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), - 16 - ); - } while (r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); - x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); - var xp = x.mod(key.p).modPow(key.dP, key.p); - var xq = x.mod(key.q).modPow(key.dQ, key.q); - while (xp.compareTo(xq) < 0) { - xp = xp.add(key.p); - } - var y = xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq); - y = y.multiply(r.modInverse(key.n)).mod(key.n); - return y; - }; - pki2.rsa.encrypt = function(m, key, bt) { - var pub = bt; - var eb; - var k = Math.ceil(key.n.bitLength() / 8); - if (bt !== false && bt !== true) { - pub = bt === 2; - eb = _encodePkcs1_v1_5(m, key, bt); - } else { - eb = forge.util.createBuffer(); - eb.putBytes(m); - } - var x = new BigInteger(eb.toHex(), 16); - var y = _modPow(x, key, pub); - var yhex = y.toString(16); - var ed = forge.util.createBuffer(); - var zeros = k - Math.ceil(yhex.length / 2); - while (zeros > 0) { - ed.putByte(0); - --zeros; - } - ed.putBytes(forge.util.hexToBytes(yhex)); - return ed.getBytes(); + var ror = function(word, bits) { + return (word & 65535) >> bits | word << 16 - bits & 65535; }; - pki2.rsa.decrypt = function(ed, key, pub, ml) { - var k = Math.ceil(key.n.bitLength() / 8); - if (ed.length !== k) { - var error4 = new Error("Encrypted message length is invalid."); - error4.length = ed.length; - error4.expected = k; - throw error4; - } - var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); - if (y.compareTo(key.n) >= 0) { - throw new Error("Encrypted message is invalid."); + module2.exports = forge.rc2 = forge.rc2 || {}; + forge.rc2.expandKey = function(key, effKeyBits) { + if (typeof key === "string") { + key = forge.util.createBuffer(key); } - var x = _modPow(y, key, pub); - var xhex = x.toString(16); - var eb = forge.util.createBuffer(); - var zeros = k - Math.ceil(xhex.length / 2); - while (zeros > 0) { - eb.putByte(0); - --zeros; + effKeyBits = effKeyBits || 128; + var L = key; + var T = key.length(); + var T1 = effKeyBits; + var T8 = Math.ceil(T1 / 8); + var TM = 255 >> (T1 & 7); + var i; + for (i = T; i < 128; i++) { + L.putByte(piTable[L.at(i - 1) + L.at(i - T) & 255]); } - eb.putBytes(forge.util.hexToBytes(xhex)); - if (ml !== false) { - return _decodePkcs1_v1_5(eb.getBytes(), key, pub); + L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); + for (i = 127 - T8; i >= 0; i--) { + L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); } - return eb.getBytes(); + return L; }; - pki2.rsa.createKeyPairGenerationState = function(bits, e, options) { - if (typeof bits === "string") { - bits = parseInt(bits, 10); + var createCipher = function(key, bits, encrypt) { + var _finish = false, _input = null, _output = null, _iv = null; + var mixRound, mashRound; + var i, j, K = []; + key = forge.rc2.expandKey(key, bits); + for (i = 0; i < 64; i++) { + K.push(key.getInt16Le()); } - bits = bits || 2048; - options = options || {}; - var prng = options.prng || forge.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for (var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); + if (encrypt) { + mixRound = function(R) { + for (i = 0; i < 4; i++) { + R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); + R[i] = rol(R[i], s[i]); + j++; + } + }; + mashRound = function(R) { + for (i = 0; i < 4; i++) { + R[i] += K[R[(i + 3) % 4] & 63]; } - } - }; - var algorithm = options.algorithm || "PRIMEINC"; - var rval; - if (algorithm === "PRIMEINC") { - rval = { - algorithm, - state: 0, - bits, - rng, - eInt: e || 65537, - e: new BigInteger(null), - p: null, - q: null, - qBits: bits >> 1, - pBits: bits - (bits >> 1), - pqState: 0, - num: null, - keys: null }; - rval.e.fromInt(rval.eInt); } else { - throw new Error("Invalid key generation algorithm: " + algorithm); - } - return rval; - }; - pki2.rsa.stepKeyPairGenerationState = function(state, n) { - if (!("algorithm" in state)) { - state.algorithm = "PRIMEINC"; + mixRound = function(R) { + for (i = 3; i >= 0; i--) { + R[i] = ror(R[i], s[i]); + R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); + j--; + } + }; + mashRound = function(R) { + for (i = 3; i >= 0; i--) { + R[i] -= K[R[(i + 3) % 4] & 63]; + } + }; } - var THIRTY = new BigInteger(null); - THIRTY.fromInt(30); - var deltaIdx = 0; - var op_or = function(x, y) { - return x | y; - }; - var t1 = +/* @__PURE__ */ new Date(); - var t2; - var total = 0; - while (state.keys === null && (n <= 0 || total < n)) { - if (state.state === 0) { - var bits = state.p === null ? state.pBits : state.qBits; - var bits1 = bits - 1; - if (state.pqState === 0) { - state.num = new BigInteger(bits, state.rng); - if (!state.num.testBit(bits1)) { - state.num.bitwiseTo( - BigInteger.ONE.shiftLeft(bits1), - op_or, - state.num - ); - } - state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); - deltaIdx = 0; - ++state.pqState; - } else if (state.pqState === 1) { - if (state.num.bitLength() > bits) { - state.pqState = 0; - } else if (state.num.isProbablePrime( - _getMillerRabinTests(state.num.bitLength()) - )) { - ++state.pqState; - } else { - state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } - } else if (state.pqState === 2) { - state.pqState = state.num.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) === 0 ? 3 : 0; - } else if (state.pqState === 3) { - state.pqState = 0; - if (state.p === null) { - state.p = state.num; + var runPlan = function(plan) { + var R = []; + for (i = 0; i < 4; i++) { + var val2 = _input.getInt16Le(); + if (_iv !== null) { + if (encrypt) { + val2 ^= _iv.getInt16Le(); } else { - state.q = state.num; - } - if (state.p !== null && state.q !== null) { - ++state.state; + _iv.putInt16Le(val2); } - state.num = null; - } - } else if (state.state === 1) { - if (state.p.compareTo(state.q) < 0) { - state.num = state.p; - state.p = state.q; - state.q = state.num; - } - ++state.state; - } else if (state.state === 2) { - state.p1 = state.p.subtract(BigInteger.ONE); - state.q1 = state.q.subtract(BigInteger.ONE); - state.phi = state.p1.multiply(state.q1); - ++state.state; - } else if (state.state === 3) { - if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { - ++state.state; - } else { - state.p = null; - state.q = null; - state.state = 0; - } - } else if (state.state === 4) { - state.n = state.p.multiply(state.q); - if (state.n.bitLength() === state.bits) { - ++state.state; - } else { - state.q = null; - state.state = 0; } - } else if (state.state === 5) { - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki2.rsa.setPrivateKey( - state.n, - state.e, - d, - state.p, - state.q, - d.mod(state.p1), - d.mod(state.q1), - state.q.modInverse(state.p) - ), - publicKey: pki2.rsa.setPublicKey(state.n, state.e) - }; - } - t2 = +/* @__PURE__ */ new Date(); - total += t2 - t1; - t1 = t2; - } - return state.keys !== null; - }; - pki2.rsa.generateKeyPair = function(bits, e, options, callback) { - if (arguments.length === 1) { - if (typeof bits === "object") { - options = bits; - bits = void 0; - } else if (typeof bits === "function") { - callback = bits; - bits = void 0; + R.push(val2 & 65535); } - } else if (arguments.length === 2) { - if (typeof bits === "number") { - if (typeof e === "function") { - callback = e; - e = void 0; - } else if (typeof e !== "number") { - options = e; - e = void 0; + j = encrypt ? 0 : 63; + for (var ptr = 0; ptr < plan.length; ptr++) { + for (var ctr = 0; ctr < plan[ptr][0]; ctr++) { + plan[ptr][1](R); } - } else { - options = bits; - callback = e; - bits = void 0; - e = void 0; } - } else if (arguments.length === 3) { - if (typeof e === "number") { - if (typeof options === "function") { - callback = options; - options = void 0; + for (i = 0; i < 4; i++) { + if (_iv !== null) { + if (encrypt) { + _iv.putInt16Le(R[i]); + } else { + R[i] ^= _iv.getInt16Le(); + } } - } else { - callback = options; - options = e; - e = void 0; + _output.putInt16Le(R[i]); } - } - options = options || {}; - if (bits === void 0) { - bits = options.bits || 2048; - } - if (e === void 0) { - e = options.e || 65537; - } - if (!forge.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e === 65537 || e === 3)) { - if (callback) { - if (_detectNodeCrypto("generateKeyPair")) { - return _crypto.generateKeyPair("rsa", { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: "spki", - format: "pem" - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem" - } - }, function(err, pub, priv) { - if (err) { - return callback(err); - } - callback(null, { - privateKey: pki2.privateKeyFromPem(priv), - publicKey: pki2.publicKeyFromPem(pub) - }); - }); - } - if (_detectSubtleCrypto("generateKey") && _detectSubtleCrypto("exportKey")) { - return util.globalScope.crypto.subtle.generateKey({ - name: "RSASSA-PKCS1-v1_5", - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: { name: "SHA-256" } - }, true, ["sign", "verify"]).then(function(pair) { - return util.globalScope.crypto.subtle.exportKey( - "pkcs8", - pair.privateKey - ); - }).then(void 0, function(err) { - callback(err); - }).then(function(pkcs8) { - if (pkcs8) { - var privateKey = pki2.privateKeyFromAsn1( - asn1.fromDer(forge.util.createBuffer(pkcs8)) - ); - callback(null, { - privateKey, - publicKey: pki2.setRsaPublicKey(privateKey.n, privateKey.e) - }); - } - }); + }; + var cipher = null; + cipher = { + /** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * To use the cipher in CBC mode, iv may be given either as a string + * of bytes, or as a byte buffer. For ECB mode, give null as iv. + * + * @param iv the initialization vector to use, null for ECB mode. + * @param output the output the buffer to write to, null to create one. + */ + start: function(iv, output) { + if (iv) { + if (typeof iv === "string") { + iv = forge.util.createBuffer(iv); + } } - if (_detectSubtleMsCrypto("generateKey") && _detectSubtleMsCrypto("exportKey")) { - var genOp = util.globalScope.msCrypto.subtle.generateKey({ - name: "RSASSA-PKCS1-v1_5", - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: { name: "SHA-256" } - }, true, ["sign", "verify"]); - genOp.oncomplete = function(e2) { - var pair = e2.target.result; - var exportOp = util.globalScope.msCrypto.subtle.exportKey( - "pkcs8", - pair.privateKey - ); - exportOp.oncomplete = function(e3) { - var pkcs8 = e3.target.result; - var privateKey = pki2.privateKeyFromAsn1( - asn1.fromDer(forge.util.createBuffer(pkcs8)) - ); - callback(null, { - privateKey, - publicKey: pki2.setRsaPublicKey(privateKey.n, privateKey.e) - }); - }; - exportOp.onerror = function(err) { - callback(err); - }; - }; - genOp.onerror = function(err) { - callback(err); - }; - return; + _finish = false; + _input = forge.util.createBuffer(); + _output = output || new forge.util.createBuffer(); + _iv = iv; + cipher.output = _output; + }, + /** + * Updates the next block. + * + * @param input the buffer to read from. + */ + update: function(input) { + if (!_finish) { + _input.putBuffer(input); } - } else { - if (_detectNodeCrypto("generateKeyPairSync")) { - var keypair = _crypto.generateKeyPairSync("rsa", { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: "spki", - format: "pem" - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem" - } - }); - return { - privateKey: pki2.privateKeyFromPem(keypair.privateKey), - publicKey: pki2.publicKeyFromPem(keypair.publicKey) - }; + while (_input.length() >= 8) { + runPlan([ + [5, mixRound], + [1, mashRound], + [6, mixRound], + [1, mashRound], + [5, mixRound] + ]); } - } - } - var state = pki2.rsa.createKeyPairGenerationState(bits, e, options); - if (!callback) { - pki2.rsa.stepKeyPairGenerationState(state, 0); - return state.keys; - } - _generateKeyPair(state, options, callback); - }; - pki2.setRsaPublicKey = pki2.rsa.setPublicKey = function(n, e) { - var key = { - n, - e - }; - key.encrypt = function(data, scheme, schemeOptions) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSAES-PKCS1-V1_5"; - } - if (scheme === "RSAES-PKCS1-V1_5") { - scheme = { - encode: function(m, key2, pub) { - return _encodePkcs1_v1_5(m, key2, 2).getBytes(); - } - }; - } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { - scheme = { - encode: function(m, key2) { - return forge.pkcs1.encode_rsa_oaep(key2, m, schemeOptions); + }, + /** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use, null for PKCS#7 padding, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ + finish: function(pad) { + var rval = true; + if (encrypt) { + if (pad) { + rval = pad(8, _input, !encrypt); + } else { + var padding = _input.length() === 8 ? 8 : 8 - _input.length(); + _input.fillWithByte(padding, padding); } - }; - } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { - scheme = { encode: function(e3) { - return e3; - } }; - } else if (typeof scheme === "string") { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - var e2 = scheme.encode(data, key, true); - return pki2.rsa.encrypt(e2, key, true); - }; - key.verify = function(digest, signature, scheme, options) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSASSA-PKCS1-V1_5"; - } - if (options === void 0) { - options = { - _parseAllDigestBytes: true - }; - } - if (!("_parseAllDigestBytes" in options)) { - options._parseAllDigestBytes = true; - } - if (scheme === "RSASSA-PKCS1-V1_5") { - scheme = { - verify: function(digest2, d2) { - d2 = _decodePkcs1_v1_5(d2, key, true); - var obj = asn1.fromDer(d2, { - parseAllBytes: options._parseAllDigestBytes - }); - var capture = {}; - var errors = []; - if (!asn1.validate(obj, digestInfoValidator, capture, errors)) { - var error4 = new Error( - "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value." - ); - error4.errors = errors; - throw error4; - } - var oid = asn1.derToOid(capture.algorithmIdentifier); - if (!(oid === forge.oids.md2 || oid === forge.oids.md5 || oid === forge.oids.sha1 || oid === forge.oids.sha224 || oid === forge.oids.sha256 || oid === forge.oids.sha384 || oid === forge.oids.sha512 || oid === forge.oids["sha512-224"] || oid === forge.oids["sha512-256"])) { - var error4 = new Error( - "Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier." - ); - error4.oid = oid; - throw error4; - } - if (oid === forge.oids.md2 || oid === forge.oids.md5) { - if (!("parameters" in capture)) { - throw new Error( - "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters." - ); + } + if (rval) { + _finish = true; + cipher.update(); + } + if (!encrypt) { + rval = _input.length() === 0; + if (rval) { + if (pad) { + rval = pad(8, _output, !encrypt); + } else { + var len = _output.length(); + var count = _output.at(len - 1); + if (count > len) { + rval = false; + } else { + _output.truncate(count); } } - return digest2 === capture.digest; } - }; - } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { - scheme = { - verify: function(digest2, d2) { - d2 = _decodePkcs1_v1_5(d2, key, true); - return digest2 === d2; - } - }; + } + return rval; } - var d = pki2.rsa.decrypt(signature, key, true, false); - return scheme.verify(digest, d, key.n.bitLength()); }; - return key; + return cipher; }; - pki2.setRsaPrivateKey = pki2.rsa.setPrivateKey = function(n, e, d, p, q, dP, dQ, qInv) { - var key = { - n, - e, - d, - p, - q, - dP, - dQ, - qInv - }; - key.decrypt = function(data, scheme, schemeOptions) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSAES-PKCS1-V1_5"; - } - var d2 = pki2.rsa.decrypt(data, key, false, false); - if (scheme === "RSAES-PKCS1-V1_5") { - scheme = { decode: _decodePkcs1_v1_5 }; - } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { - scheme = { - decode: function(d3, key2) { - return forge.pkcs1.decode_rsa_oaep(key2, d3, schemeOptions); - } - }; - } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { - scheme = { decode: function(d3) { - return d3; - } }; - } else { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - return scheme.decode(d2, key, false); - }; - key.sign = function(md, scheme) { - var bt = false; - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } - if (scheme === void 0 || scheme === "RSASSA-PKCS1-V1_5") { - scheme = { encode: emsaPkcs1v15encode }; - bt = 1; - } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { - scheme = { encode: function() { - return md; - } }; - bt = 1; - } - var d2 = scheme.encode(md, key.n.bitLength()); - return pki2.rsa.encrypt(d2, key, bt); - }; - return key; + forge.rc2.startEncrypting = function(key, iv, output) { + var cipher = forge.rc2.createEncryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; }; - pki2.wrapRsaPrivateKey = function(rsaKey) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(0).getBytes() - ), - // privateKeyAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.rsaEncryption).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // PrivateKey - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(rsaKey).getBytes() - ) - ]); + forge.rc2.createEncryptionCipher = function(key, bits) { + return createCipher(key, bits, true); }; - pki2.privateKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (asn1.validate(obj, privateKeyValidator, capture, errors)) { - obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); - } - capture = {}; - errors = []; - if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { - var error4 = new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey."); - error4.errors = errors; - throw error4; - } - var n, e, d, p, q, dP, dQ, qInv; - n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); - e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); - d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); - p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); - q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); - dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); - dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); - qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); - return pki2.setRsaPrivateKey( - new BigInteger(n, 16), - new BigInteger(e, 16), - new BigInteger(d, 16), - new BigInteger(p, 16), - new BigInteger(q, 16), - new BigInteger(dP, 16), - new BigInteger(dQ, 16), - new BigInteger(qInv, 16) - ); + forge.rc2.startDecrypting = function(key, iv, output) { + var cipher = forge.rc2.createDecryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; }; - pki2.privateKeyToAsn1 = pki2.privateKeyToRSAPrivateKey = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0 = only 2 primes, 1 multiple primes) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(0).getBytes() - ), - // modulus (n) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.n) - ), - // publicExponent (e) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.e) - ), - // privateExponent (d) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.d) - ), - // privateKeyPrime1 (p) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.p) - ), - // privateKeyPrime2 (q) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.q) - ), - // privateKeyExponent1 (dP) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.dP) - ), - // privateKeyExponent2 (dQ) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.dQ) - ), - // coefficient (qInv) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.qInv) - ) - ]); + forge.rc2.createDecryptionCipher = function(key, bits) { + return createCipher(key, bits, false); }; - pki2.publicKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (asn1.validate(obj, publicKeyValidator, capture, errors)) { - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki2.oids.rsaEncryption) { - var error4 = new Error("Cannot read public key. Unknown OID."); - error4.oid = oid; - throw error4; - } - obj = capture.rsaPublicKey; - } - errors = []; - if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { - var error4 = new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey."); - error4.errors = errors; - throw error4; + } +}); + +// node_modules/node-forge/lib/jsbn.js +var require_jsbn = __commonJS({ + "node_modules/node-forge/lib/jsbn.js"(exports2, module2) { + var forge = require_forge(); + module2.exports = forge.jsbn = forge.jsbn || {}; + var dbits; + var canary = 244837814094590; + var j_lm = (canary & 16777215) == 15715070; + function BigInteger(a, b, c) { + this.data = []; + if (a != null) + if ("number" == typeof a) this.fromNumber(a, b, c); + else if (b == null && "string" != typeof a) this.fromString(a, 256); + else this.fromString(a, b); + } + forge.jsbn.BigInteger = BigInteger; + function nbi() { + return new BigInteger(null); + } + function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this.data[i++] + w.data[j] + c; + c = Math.floor(v / 67108864); + w.data[j++] = v & 67108863; } - var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); - var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); - return pki2.setRsaPublicKey( - new BigInteger(n, 16), - new BigInteger(e, 16) - ); - }; - pki2.publicKeyToAsn1 = pki2.publicKeyToSubjectPublicKeyInfo = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.rsaEncryption).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // subjectPublicKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ - pki2.publicKeyToRSAPublicKey(key) - ]) - ]); - }; - pki2.publicKeyToRSAPublicKey = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // modulus (n) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.n) - ), - // publicExponent (e) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.e) - ) - ]); - }; - function _encodePkcs1_v1_5(m, key, bt) { - var eb = forge.util.createBuffer(); - var k = Math.ceil(key.n.bitLength() / 8); - if (m.length > k - 11) { - var error4 = new Error("Message is too long for PKCS#1 v1.5 padding."); - error4.length = m.length; - error4.max = k - 11; - throw error4; + return c; + } + function am2(i, x, w, j, c, n) { + var xl = x & 32767, xh = x >> 15; + while (--n >= 0) { + var l = this.data[i] & 32767; + var h = this.data[i++] >> 15; + var m = xh * l + h * xl; + l = xl * l + ((m & 32767) << 15) + w.data[j] + (c & 1073741823); + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); + w.data[j++] = l & 1073741823; } - eb.putByte(0); - eb.putByte(bt); - var padNum = k - 3 - m.length; - var padByte; - if (bt === 0 || bt === 1) { - padByte = bt === 0 ? 0 : 255; - for (var i = 0; i < padNum; ++i) { - eb.putByte(padByte); - } - } else { - while (padNum > 0) { - var numZeros = 0; - var padBytes = forge.random.getBytes(padNum); - for (var i = 0; i < padNum; ++i) { - padByte = padBytes.charCodeAt(i); - if (padByte === 0) { - ++numZeros; - } else { - eb.putByte(padByte); - } - } - padNum = numZeros; - } + return c; + } + function am3(i, x, w, j, c, n) { + var xl = x & 16383, xh = x >> 14; + while (--n >= 0) { + var l = this.data[i] & 16383; + var h = this.data[i++] >> 14; + var m = xh * l + h * xl; + l = xl * l + ((m & 16383) << 14) + w.data[j] + c; + c = (l >> 28) + (m >> 14) + xh * h; + w.data[j++] = l & 268435455; } - eb.putByte(0); - eb.putBytes(m); - return eb; + return c; } - function _decodePkcs1_v1_5(em, key, pub, ml) { - var k = Math.ceil(key.n.bitLength() / 8); - var eb = forge.util.createBuffer(em); - var first = eb.getByte(); - var bt = eb.getByte(); - if (first !== 0 || pub && bt !== 0 && bt !== 1 || !pub && bt != 2 || pub && bt === 0 && typeof ml === "undefined") { - throw new Error("Encryption block is invalid."); + if (typeof navigator === "undefined") { + BigInteger.prototype.am = am3; + dbits = 28; + } else if (j_lm && navigator.appName == "Microsoft Internet Explorer") { + BigInteger.prototype.am = am2; + dbits = 30; + } else if (j_lm && navigator.appName != "Netscape") { + BigInteger.prototype.am = am1; + dbits = 26; + } else { + BigInteger.prototype.am = am3; + dbits = 28; + } + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = (1 << dbits) - 1; + BigInteger.prototype.DV = 1 << dbits; + var BI_FP = 52; + BigInteger.prototype.FV = Math.pow(2, BI_FP); + BigInteger.prototype.F1 = BI_FP - dbits; + BigInteger.prototype.F2 = 2 * dbits - BI_FP; + var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; + var BI_RC = new Array(); + var rr; + var vv; + rr = "0".charCodeAt(0); + for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; + rr = "a".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + rr = "A".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + function int2char(n) { + return BI_RM.charAt(n); + } + function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return c == null ? -1 : c; + } + function bnpCopyTo(r) { + for (var i = this.t - 1; i >= 0; --i) r.data[i] = this.data[i]; + r.t = this.t; + r.s = this.s; + } + function bnpFromInt(x) { + this.t = 1; + this.s = x < 0 ? -1 : 0; + if (x > 0) this.data[0] = x; + else if (x < -1) this.data[0] = x + this.DV; + else this.t = 0; + } + function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; + } + function bnpFromString(s, b) { + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 256) k = 8; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else { + this.fromRadix(s, b); + return; } - var padNum = 0; - if (bt === 0) { - padNum = k - 3 - ml; - for (var i = 0; i < padNum; ++i) { - if (eb.getByte() !== 0) { - throw new Error("Encryption block is invalid."); - } - } - } else if (bt === 1) { - padNum = 0; - while (eb.length() > 1) { - if (eb.getByte() !== 255) { - --eb.read; - break; - } - ++padNum; - } - } else if (bt === 2) { - padNum = 0; - while (eb.length() > 1) { - if (eb.getByte() === 0) { - --eb.read; - break; - } - ++padNum; + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while (--i >= 0) { + var x = k == 8 ? s[i] & 255 : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-") mi = true; + continue; } + mi = false; + if (sh == 0) + this.data[this.t++] = x; + else if (sh + k > this.DB) { + this.data[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; + this.data[this.t++] = x >> this.DB - sh; + } else + this.data[this.t - 1] |= x << sh; + sh += k; + if (sh >= this.DB) sh -= this.DB; } - var zero = eb.getByte(); - if (zero !== 0 || padNum !== k - 3 - eb.length()) { - throw new Error("Encryption block is invalid."); + if (k == 8 && (s[0] & 128) != 0) { + this.s = -1; + if (sh > 0) this.data[this.t - 1] |= (1 << this.DB - sh) - 1 << sh; } - return eb.getBytes(); + this.clamp(); + if (mi) BigInteger.ZERO.subTo(this, this); } - function _generateKeyPair(state, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - var opts = { - algorithm: { - name: options.algorithm || "PRIMEINC", - options: { - workers: options.workers || 2, - workLoad: options.workLoad || 100, - workerScript: options.workerScript + function bnpClamp() { + var c = this.s & this.DM; + while (this.t > 0 && this.data[this.t - 1] == c) --this.t; + } + function bnToString(b) { + if (this.s < 0) return "-" + this.negate().toString(b); + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else return this.toRadix(b); + var km = (1 << k) - 1, d, m = false, r = "", i = this.t; + var p = this.DB - i * this.DB % k; + if (i-- > 0) { + if (p < this.DB && (d = this.data[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this.data[i] & (1 << p) - 1) << k - p; + d |= this.data[--i] >> (p += this.DB - k); + } else { + d = this.data[i] >> (p -= k) & km; + if (p <= 0) { + p += this.DB; + --i; + } } + if (d > 0) m = true; + if (m) r += int2char(d); } - }; - if ("prng" in options) { - opts.prng = options.prng; } - generate(); - function generate() { - getPrime(state.pBits, function(err, num) { - if (err) { - return callback(err); - } - state.p = num; - if (state.q !== null) { - return finish(err, state.q); - } - getPrime(state.qBits, finish); - }); + return m ? r : "0"; + } + function bnNegate() { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + } + function bnAbs() { + return this.s < 0 ? this.negate() : this; + } + function bnCompareTo(a) { + var r = this.s - a.s; + if (r != 0) return r; + var i = this.t; + r = i - a.t; + if (r != 0) return this.s < 0 ? -r : r; + while (--i >= 0) if ((r = this.data[i] - a.data[i]) != 0) return r; + return 0; + } + function nbits(x) { + var r = 1, t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; } - function getPrime(bits, callback2) { - forge.prime.generateProbablePrime(bits, opts, callback2); + if ((t = x >> 8) != 0) { + x = t; + r += 8; } - function finish(err, num) { - if (err) { - return callback(err); - } - state.q = num; - if (state.p.compareTo(state.q) < 0) { - var tmp = state.p; - state.p = state.q; - state.q = tmp; - } - if (state.p.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { - state.p = null; - generate(); - return; - } - if (state.q.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { - state.q = null; - getPrime(state.qBits, finish); - return; - } - state.p1 = state.p.subtract(BigInteger.ONE); - state.q1 = state.q.subtract(BigInteger.ONE); - state.phi = state.p1.multiply(state.q1); - if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { - state.p = state.q = null; - generate(); - return; - } - state.n = state.p.multiply(state.q); - if (state.n.bitLength() !== state.bits) { - state.q = null; - getPrime(state.qBits, finish); - return; - } - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki2.rsa.setPrivateKey( - state.n, - state.e, - d, - state.p, - state.q, - d.mod(state.p1), - d.mod(state.q1), - state.q.modInverse(state.p) - ), - publicKey: pki2.rsa.setPublicKey(state.n, state.e) - }; - callback(null, state.keys); + if ((t = x >> 4) != 0) { + x = t; + r += 4; } - } - function _bnToBytes(b) { - var hex = b.toString(16); - if (hex[0] >= "8") { - hex = "00" + hex; + if ((t = x >> 2) != 0) { + x = t; + r += 2; } - var bytes = forge.util.hexToBytes(hex); - if (bytes.length > 1 && // leading 0x00 for positive integer - (bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer - bytes.charCodeAt(0) === 255 && (bytes.charCodeAt(1) & 128) === 128)) { - return bytes.substr(1); + if ((t = x >> 1) != 0) { + x = t; + r += 1; } - return bytes; + return r; } - function _getMillerRabinTests(bits) { - if (bits <= 100) return 27; - if (bits <= 150) return 18; - if (bits <= 200) return 15; - if (bits <= 250) return 12; - if (bits <= 300) return 9; - if (bits <= 350) return 8; - if (bits <= 400) return 7; - if (bits <= 500) return 6; - if (bits <= 600) return 5; - if (bits <= 800) return 4; - if (bits <= 1250) return 3; - return 2; + function bnBitLength() { + if (this.t <= 0) return 0; + return this.DB * (this.t - 1) + nbits(this.data[this.t - 1] ^ this.s & this.DM); } - function _detectNodeCrypto(fn) { - return forge.util.isNodejs && typeof _crypto[fn] === "function"; + function bnpDLShiftTo(n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) r.data[i + n] = this.data[i]; + for (i = n - 1; i >= 0; --i) r.data[i] = 0; + r.t = this.t + n; + r.s = this.s; } - function _detectSubtleCrypto(fn) { - return typeof util.globalScope !== "undefined" && typeof util.globalScope.crypto === "object" && typeof util.globalScope.crypto.subtle === "object" && typeof util.globalScope.crypto.subtle[fn] === "function"; + function bnpDRShiftTo(n, r) { + for (var i = n; i < this.t; ++i) r.data[i - n] = this.data[i]; + r.t = Math.max(this.t - n, 0); + r.s = this.s; } - function _detectSubtleMsCrypto(fn) { - return typeof util.globalScope !== "undefined" && typeof util.globalScope.msCrypto === "object" && typeof util.globalScope.msCrypto.subtle === "object" && typeof util.globalScope.msCrypto.subtle[fn] === "function"; + function bnpLShiftTo(n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; + for (i = this.t - 1; i >= 0; --i) { + r.data[i + ds + 1] = this.data[i] >> cbs | c; + c = (this.data[i] & bm) << bs; + } + for (i = ds - 1; i >= 0; --i) r.data[i] = 0; + r.data[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); } - function _intToUint8Array(x) { - var bytes = forge.util.hexToBytes(x.toString(16)); - var buffer = new Uint8Array(bytes.length); - for (var i = 0; i < bytes.length; ++i) { - buffer[i] = bytes.charCodeAt(i); + function bnpRShiftTo(n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; } - return buffer; + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r.data[0] = this.data[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r.data[i - ds - 1] |= (this.data[i] & bm) << cbs; + r.data[i - ds] = this.data[i] >> bs; + } + if (bs > 0) r.data[this.t - ds - 1] |= (this.s & bm) << cbs; + r.t = this.t - ds; + r.clamp(); } - } -}); - -// node_modules/node-forge/lib/pbe.js -var require_pbe = __commonJS({ - "node_modules/node-forge/lib/pbe.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_md(); - require_oids(); - require_pbkdf2(); - require_pem(); - require_random(); - require_rc2(); - require_rsa(); - require_util8(); - if (typeof BigInteger === "undefined") { - BigInteger = forge.jsbn.BigInteger; + function bnpSubTo(a, r) { + var i = 0, c = 0, m = Math.min(a.t, this.t); + while (i < m) { + c += this.data[i] - a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c -= a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = c < 0 ? -1 : 0; + if (c < -1) r.data[i++] = this.DV + c; + else if (c > 0) r.data[i++] = c; + r.t = i; + r.clamp(); } - var BigInteger; - var asn1 = forge.asn1; - var pki2 = forge.pki = forge.pki || {}; - module2.exports = pki2.pbe = forge.pbe = forge.pbe || {}; - var oids = pki2.oids; - var encryptedPrivateKeyValidator = { - name: "EncryptedPrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedPrivateKeyInfo.encryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encryptionOid" - }, { - name: "AlgorithmIdentifier.parameters", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "encryptionParams" - }] - }, { - // encryptedData - name: "EncryptedPrivateKeyInfo.encryptedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encryptedData" - }] - }; - var PBES2AlgorithmsValidator = { - name: "PBES2Algorithms", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.keyDerivationFunc", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.keyDerivationFunc.oid", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "kdfOid" - }, { - name: "PBES2Algorithms.params", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.params.salt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "kdfSalt" - }, { - name: "PBES2Algorithms.params.iterationCount", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "kdfIterationCount" - }, { - name: "PBES2Algorithms.params.keyLength", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: "keyLength" - }, { - // prf - name: "PBES2Algorithms.params.prf", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "PBES2Algorithms.params.prf.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "prfOid" - }] - }] - }] - }, { - name: "PBES2Algorithms.encryptionScheme", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.encryptionScheme.oid", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encOid" - }, { - name: "PBES2Algorithms.encryptionScheme.iv", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encIv" - }] - }] - }; - var pkcs12PbeParamsValidator = { - name: "pkcs-12PbeParams", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "pkcs-12PbeParams.salt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "salt" - }, { - name: "pkcs-12PbeParams.iterations", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "iterations" - }] - }; - pki2.encryptPrivateKeyInfo = function(obj, password, options) { - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || "aes128"; - options.prfAlgorithm = options.prfAlgorithm || "sha1"; - var salt = forge.random.getBytesSync(options.saltSize); - var count = options.count; - var countBytes = asn1.integerToDer(count); - var dkLen; - var encryptionAlgorithm; - var encryptedData; - if (options.algorithm.indexOf("aes") === 0 || options.algorithm === "des") { - var ivLen, encOid, cipherFn; - switch (options.algorithm) { - case "aes128": - dkLen = 16; - ivLen = 16; - encOid = oids["aes128-CBC"]; - cipherFn = forge.aes.createEncryptionCipher; - break; - case "aes192": - dkLen = 24; - ivLen = 16; - encOid = oids["aes192-CBC"]; - cipherFn = forge.aes.createEncryptionCipher; - break; - case "aes256": - dkLen = 32; - ivLen = 16; - encOid = oids["aes256-CBC"]; - cipherFn = forge.aes.createEncryptionCipher; - break; - case "des": - dkLen = 8; - ivLen = 8; - encOid = oids["desCBC"]; - cipherFn = forge.des.createEncryptionCipher; - break; - default: - var error4 = new Error("Cannot encrypt private key. Unknown encryption algorithm."); - error4.algorithm = options.algorithm; - throw error4; + function bnpMultiplyTo(a, r) { + var x = this.abs(), y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) r.data[i] = 0; + for (i = 0; i < y.t; ++i) r.data[i + x.t] = x.am(0, y.data[i], r, i, 0, x.t); + r.s = 0; + r.clamp(); + if (this.s != a.s) BigInteger.ZERO.subTo(r, r); + } + function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2 * x.t; + while (--i >= 0) r.data[i] = 0; + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x.data[i], r, 2 * i, 0, 1); + if ((r.data[i + x.t] += x.am(i + 1, 2 * x.data[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r.data[i + x.t] -= x.DV; + r.data[i + x.t + 1] = 1; } - var prfAlgorithm = "hmacWith" + options.prfAlgorithm.toUpperCase(); - var md = prfAlgorithmToMessageDigest(prfAlgorithm); - var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = forge.random.getBytesSync(ivLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pkcs5PBES2"]).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // keyDerivationFunc - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes() - ), - // PBKDF2-params - params - ]), - // encryptionScheme - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(encOid).getBytes() - ), - // iv - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - iv - ) - ]) - ]) - ] - ); - } else if (options.algorithm === "3des") { - dkLen = 24; - var saltBytes = new forge.util.ByteBuffer(salt); - var dk = pki2.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); - var iv = pki2.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); - var cipher = forge.des.createEncryptionCipher(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes() - ), - // pkcs-12PbeParams - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), - // iteration count - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - countBytes.getBytes() - ) - ]) - ] - ); - } else { - var error4 = new Error("Cannot encrypt private key. Unknown encryption algorithm."); - error4.algorithm = options.algorithm; - throw error4; - } - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // encryptionAlgorithm - encryptionAlgorithm, - // encryptedData - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - encryptedData - ) - ]); - return rval; - }; - pki2.decryptPrivateKeyInfo = function(obj, password) { - var rval = null; - var capture = {}; - var errors = []; - if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { - var error4 = new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error4.errors = errors; - throw error4; - } - var oid = asn1.derToOid(capture.encryptionOid); - var cipher = pki2.pbe.getCipher(oid, capture.encryptionParams, password); - var encrypted = forge.util.createBuffer(capture.encryptedData); - cipher.update(encrypted); - if (cipher.finish()) { - rval = asn1.fromDer(cipher.output); - } - return rval; - }; - pki2.encryptedPrivateKeyToPem = function(epki, maxline) { - var msg = { - type: "ENCRYPTED PRIVATE KEY", - body: asn1.toDer(epki).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - pki2.encryptedPrivateKeyFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "ENCRYPTED PRIVATE KEY") { - var error4 = new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".'); - error4.headerType = msg.type; - throw error4; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted."); - } - return asn1.fromDer(msg.body); - }; - pki2.encryptRsaPrivateKey = function(rsaKey, password, options) { - options = options || {}; - if (!options.legacy) { - var rval = pki2.wrapRsaPrivateKey(pki2.privateKeyToAsn1(rsaKey)); - rval = pki2.encryptPrivateKeyInfo(rval, password, options); - return pki2.encryptedPrivateKeyToPem(rval); - } - var algorithm; - var iv; - var dkLen; - var cipherFn; - switch (options.algorithm) { - case "aes128": - algorithm = "AES-128-CBC"; - dkLen = 16; - iv = forge.random.getBytesSync(16); - cipherFn = forge.aes.createEncryptionCipher; - break; - case "aes192": - algorithm = "AES-192-CBC"; - dkLen = 24; - iv = forge.random.getBytesSync(16); - cipherFn = forge.aes.createEncryptionCipher; - break; - case "aes256": - algorithm = "AES-256-CBC"; - dkLen = 32; - iv = forge.random.getBytesSync(16); - cipherFn = forge.aes.createEncryptionCipher; - break; - case "3des": - algorithm = "DES-EDE3-CBC"; - dkLen = 24; - iv = forge.random.getBytesSync(8); - cipherFn = forge.des.createEncryptionCipher; - break; - case "des": - algorithm = "DES-CBC"; - dkLen = 8; - iv = forge.random.getBytesSync(8); - cipherFn = forge.des.createEncryptionCipher; - break; - default: - var error4 = new Error('Could not encrypt RSA private key; unsupported encryption algorithm "' + options.algorithm + '".'); - error4.algorithm = options.algorithm; - throw error4; - } - var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(pki2.privateKeyToAsn1(rsaKey))); - cipher.finish(); - var msg = { - type: "RSA PRIVATE KEY", - procType: { - version: "4", - type: "ENCRYPTED" - }, - dekInfo: { - algorithm, - parameters: forge.util.bytesToHex(iv).toUpperCase() - }, - body: cipher.output.getBytes() - }; - return forge.pem.encode(msg); - }; - pki2.decryptRsaPrivateKey = function(pem, password) { - var rval = null; - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "ENCRYPTED PRIVATE KEY" && msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { - var error4 = new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); - error4.headerType = error4; - throw error4; } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - var dkLen; - var cipherFn; - switch (msg.dekInfo.algorithm) { - case "DES-CBC": - dkLen = 8; - cipherFn = forge.des.createDecryptionCipher; - break; - case "DES-EDE3-CBC": - dkLen = 24; - cipherFn = forge.des.createDecryptionCipher; - break; - case "AES-128-CBC": - dkLen = 16; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "AES-192-CBC": - dkLen = 24; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "AES-256-CBC": - dkLen = 32; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "RC2-40-CBC": - dkLen = 5; - cipherFn = function(key) { - return forge.rc2.createDecryptionCipher(key, 40); - }; - break; - case "RC2-64-CBC": - dkLen = 8; - cipherFn = function(key) { - return forge.rc2.createDecryptionCipher(key, 64); - }; - break; - case "RC2-128-CBC": - dkLen = 16; - cipherFn = function(key) { - return forge.rc2.createDecryptionCipher(key, 128); - }; - break; - default: - var error4 = new Error('Could not decrypt private key; unsupported encryption algorithm "' + msg.dekInfo.algorithm + '".'); - error4.algorithm = msg.dekInfo.algorithm; - throw error4; - } - var iv = forge.util.hexToBytes(msg.dekInfo.parameters); - var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(forge.util.createBuffer(msg.body)); - if (cipher.finish()) { - rval = cipher.output.getBytes(); - } else { - return rval; - } - } else { - rval = msg.body; + if (r.t > 0) r.data[r.t - 1] += x.am(i, x.data[i], r, 2 * i, 0, 1); + r.s = 0; + r.clamp(); + } + function bnpDivRemTo(m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) return; + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) q.fromInt(0); + if (r != null) this.copyTo(r); + return; } - if (msg.type === "ENCRYPTED PRIVATE KEY") { - rval = pki2.decryptPrivateKeyInfo(asn1.fromDer(rval), password); + if (r == null) r = nbi(); + var y = nbi(), ts = this.s, ms = m.s; + var nsh = this.DB - nbits(pm.data[pm.t - 1]); + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); } else { - rval = asn1.fromDer(rval); + pm.copyTo(y); + pt.copyTo(r); } - if (rval !== null) { - rval = pki2.privateKeyFromAsn1(rval); + var ys = y.t; + var y0 = y.data[ys - 1]; + if (y0 == 0) return; + var yt = y0 * (1 << this.F1) + (ys > 1 ? y.data[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; + var i = r.t, j = i - ys, t = q == null ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r.data[r.t++] = 1; + r.subTo(t, r); } - return rval; - }; - pki2.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { - var j, l; - if (typeof md === "undefined" || md === null) { - if (!("sha1" in forge.md)) { - throw new Error('"sha1" hash algorithm unavailable.'); + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); + while (y.t < ys) y.data[y.t++] = 0; + while (--j >= 0) { + var qd = r.data[--i] == y0 ? this.DM : Math.floor(r.data[i] * d1 + (r.data[i - 1] + e) * d2); + if ((r.data[i] += y.am(0, qd, r, j, 0, ys)) < qd) { + y.dlShiftTo(j, t); + r.subTo(t, r); + while (r.data[i] < --qd) r.subTo(t, r); } - md = forge.md.sha1.create(); } - var u = md.digestLength; - var v = md.blockLength; - var result = new forge.util.ByteBuffer(); - var passBuf = new forge.util.ByteBuffer(); - if (password !== null && password !== void 0) { - for (l = 0; l < password.length; l++) { - passBuf.putInt16(password.charCodeAt(l)); + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) BigInteger.ZERO.subTo(q, q); + } + r.t = ys; + r.clamp(); + if (nsh > 0) r.rShiftTo(nsh, r); + if (ts < 0) BigInteger.ZERO.subTo(r, r); + } + function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; + } + function Classic(m) { + this.m = m; + } + function cConvert(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; + } + function cRevert(x) { + return x; + } + function cReduce(x) { + x.divRemTo(this.m, null, x); + } + function cMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + function cSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + Classic.prototype.convert = cConvert; + Classic.prototype.revert = cRevert; + Classic.prototype.reduce = cReduce; + Classic.prototype.mulTo = cMulTo; + Classic.prototype.sqrTo = cSqrTo; + function bnpInvDigit() { + if (this.t < 1) return 0; + var x = this.data[0]; + if ((x & 1) == 0) return 0; + var y = x & 3; + y = y * (2 - (x & 15) * y) & 15; + y = y * (2 - (x & 255) * y) & 255; + y = y * (2 - ((x & 65535) * y & 65535)) & 65535; + y = y * (2 - x * y % this.DV) % this.DV; + return y > 0 ? this.DV - y : -y; + } + function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 32767; + this.mph = this.mp >> 15; + this.um = (1 << m.DB - 15) - 1; + this.mt2 = 2 * m.t; + } + function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; + } + function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + function montReduce(x) { + while (x.t <= this.mt2) + x.data[x.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + var j = x.data[i] & 32767; + var u0 = j * this.mpl + ((j * this.mph + (x.data[i] >> 15) * this.mpl & this.um) << 15) & x.DM; + j = i + this.m.t; + x.data[j] += this.m.am(0, u0, x, i, 0, this.m.t); + while (x.data[j] >= x.DV) { + x.data[j] -= x.DV; + x.data[++j]++; } - passBuf.putInt16(0); } - var p = passBuf.length(); - var s = salt.length(); - var D = new forge.util.ByteBuffer(); - D.fillWithByte(id, v); - var Slen = v * Math.ceil(s / v); - var S = new forge.util.ByteBuffer(); - for (l = 0; l < Slen; l++) { - S.putByte(salt.at(l % s)); + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + function montSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + function montMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + Montgomery.prototype.convert = montConvert; + Montgomery.prototype.revert = montRevert; + Montgomery.prototype.reduce = montReduce; + Montgomery.prototype.mulTo = montMulTo; + Montgomery.prototype.sqrTo = montSqrTo; + function bnpIsEven() { + return (this.t > 0 ? this.data[0] & 1 : this.s) == 0; + } + function bnpExp(e, z) { + if (e > 4294967295 || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & 1 << i) > 0) z.mulTo(r2, g, r); + else { + var t = r; + r = r2; + r2 = t; + } } - var Plen = v * Math.ceil(p / v); - var P = new forge.util.ByteBuffer(); - for (l = 0; l < Plen; l++) { - P.putByte(passBuf.at(l % p)); + return z.revert(r); + } + function bnModPowInt(e, m) { + var z; + if (e < 256 || m.isEven()) z = new Classic(m); + else z = new Montgomery(m); + return this.exp(e, z); + } + BigInteger.prototype.copyTo = bnpCopyTo; + BigInteger.prototype.fromInt = bnpFromInt; + BigInteger.prototype.fromString = bnpFromString; + BigInteger.prototype.clamp = bnpClamp; + BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + BigInteger.prototype.drShiftTo = bnpDRShiftTo; + BigInteger.prototype.lShiftTo = bnpLShiftTo; + BigInteger.prototype.rShiftTo = bnpRShiftTo; + BigInteger.prototype.subTo = bnpSubTo; + BigInteger.prototype.multiplyTo = bnpMultiplyTo; + BigInteger.prototype.squareTo = bnpSquareTo; + BigInteger.prototype.divRemTo = bnpDivRemTo; + BigInteger.prototype.invDigit = bnpInvDigit; + BigInteger.prototype.isEven = bnpIsEven; + BigInteger.prototype.exp = bnpExp; + BigInteger.prototype.toString = bnToString; + BigInteger.prototype.negate = bnNegate; + BigInteger.prototype.abs = bnAbs; + BigInteger.prototype.compareTo = bnCompareTo; + BigInteger.prototype.bitLength = bnBitLength; + BigInteger.prototype.mod = bnMod; + BigInteger.prototype.modPowInt = bnModPowInt; + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); + function bnClone() { + var r = nbi(); + this.copyTo(r); + return r; + } + function bnIntValue() { + if (this.s < 0) { + if (this.t == 1) return this.data[0] - this.DV; + else if (this.t == 0) return -1; + } else if (this.t == 1) return this.data[0]; + else if (this.t == 0) return 0; + return (this.data[1] & (1 << 32 - this.DB) - 1) << this.DB | this.data[0]; + } + function bnByteValue() { + return this.t == 0 ? this.s : this.data[0] << 24 >> 24; + } + function bnShortValue() { + return this.t == 0 ? this.s : this.data[0] << 16 >> 16; + } + function bnpChunkSize(r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)); + } + function bnSigNum() { + if (this.s < 0) return -1; + else if (this.t <= 0 || this.t == 1 && this.data[0] <= 0) return 0; + else return 1; + } + function bnpToRadix(b) { + if (b == null) b = 10; + if (this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a), y = nbi(), z = nbi(), r = ""; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); } - var I = S; - I.putBuffer(P); - var c = Math.ceil(n / u); - for (var i = 1; i <= c; i++) { - var buf = new forge.util.ByteBuffer(); - buf.putBytes(D.bytes()); - buf.putBytes(I.bytes()); - for (var round = 0; round < iter; round++) { - md.start(); - md.update(buf.getBytes()); - buf = md.digest(); - } - var B = new forge.util.ByteBuffer(); - for (l = 0; l < v; l++) { - B.putByte(buf.at(l % u)); + return z.intValue().toString(b) + r; + } + function bnpFromRadix(s, b) { + this.fromInt(0); + if (b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b, cs), mi = false, j = 0, w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; } - var k = Math.ceil(s / v) + Math.ceil(p / v); - var Inew = new forge.util.ByteBuffer(); - for (j = 0; j < k; j++) { - var chunk = new forge.util.ByteBuffer(I.getBytes(v)); - var x = 511; - for (l = B.length() - 1; l >= 0; l--) { - x = x >> 8; - x += B.at(l) + chunk.at(l); - chunk.setAt(l, x & 255); - } - Inew.putBuffer(chunk); + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; } - I = Inew; - result.putBuffer(buf); - } - result.truncate(result.length() - n); - return result; - }; - pki2.pbe.getCipher = function(oid, params, password) { - switch (oid) { - case pki2.oids["pkcs5PBES2"]: - return pki2.pbe.getCipherForPBES2(oid, params, password); - case pki2.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: - case pki2.oids["pbewithSHAAnd40BitRC2-CBC"]: - return pki2.pbe.getCipherForPKCS12PBE(oid, params, password); - default: - var error4 = new Error("Cannot read encrypted PBE data block. Unsupported OID."); - error4.oid = oid; - error4.supportedOids = [ - "pkcs5PBES2", - "pbeWithSHAAnd3-KeyTripleDES-CBC", - "pbewithSHAAnd40BitRC2-CBC" - ]; - throw error4; - } - }; - pki2.pbe.getCipherForPBES2 = function(oid, params, password) { - var capture = {}; - var errors = []; - if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { - var error4 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error4.errors = errors; - throw error4; - } - oid = asn1.derToOid(capture.kdfOid); - if (oid !== pki2.oids["pkcs5PBKDF2"]) { - var error4 = new Error("Cannot read encrypted private key. Unsupported key derivation function OID."); - error4.oid = oid; - error4.supportedOids = ["pkcs5PBKDF2"]; - throw error4; - } - oid = asn1.derToOid(capture.encOid); - if (oid !== pki2.oids["aes128-CBC"] && oid !== pki2.oids["aes192-CBC"] && oid !== pki2.oids["aes256-CBC"] && oid !== pki2.oids["des-EDE3-CBC"] && oid !== pki2.oids["desCBC"]) { - var error4 = new Error("Cannot read encrypted private key. Unsupported encryption scheme OID."); - error4.oid = oid; - error4.supportedOids = [ - "aes128-CBC", - "aes192-CBC", - "aes256-CBC", - "des-EDE3-CBC", - "desCBC" - ]; - throw error4; - } - var salt = capture.kdfSalt; - var count = forge.util.createBuffer(capture.kdfIterationCount); - count = count.getInt(count.length() << 3); - var dkLen; - var cipherFn; - switch (pki2.oids[oid]) { - case "aes128-CBC": - dkLen = 16; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "aes192-CBC": - dkLen = 24; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "aes256-CBC": - dkLen = 32; - cipherFn = forge.aes.createDecryptionCipher; - break; - case "des-EDE3-CBC": - dkLen = 24; - cipherFn = forge.des.createDecryptionCipher; - break; - case "desCBC": - dkLen = 8; - cipherFn = forge.des.createDecryptionCipher; - break; - } - var md = prfOidToMessageDigest(capture.prfOid); - var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = capture.encIv; - var cipher = cipherFn(dk); - cipher.start(iv); - return cipher; - }; - pki2.pbe.getCipherForPKCS12PBE = function(oid, params, password) { - var capture = {}; - var errors = []; - if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { - var error4 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error4.errors = errors; - throw error4; } - var salt = forge.util.createBuffer(capture.salt); - var count = forge.util.createBuffer(capture.iterations); - count = count.getInt(count.length() << 3); - var dkLen, dIvLen, cipherFn; - switch (oid) { - case pki2.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: - dkLen = 24; - dIvLen = 8; - cipherFn = forge.des.startDecrypting; - break; - case pki2.oids["pbewithSHAAnd40BitRC2-CBC"]: - dkLen = 5; - dIvLen = 8; - cipherFn = function(key2, iv2) { - var cipher = forge.rc2.createDecryptionCipher(key2, 40); - cipher.start(iv2, null); - return cipher; - }; - break; - default: - var error4 = new Error("Cannot read PKCS #12 PBE data block. Unsupported OID."); - error4.oid = oid; - throw error4; + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); } - var md = prfOidToMessageDigest(capture.prfOid); - var key = pki2.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); - md.start(); - var iv = pki2.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); - return cipherFn(key, iv); - }; - pki2.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { - if (typeof md === "undefined" || md === null) { - if (!("md5" in forge.md)) { - throw new Error('"md5" hash algorithm unavailable.'); + if (mi) BigInteger.ZERO.subTo(this, this); + } + function bnpFromNumber(a, b, c) { + if ("number" == typeof b) { + if (a < 2) this.fromInt(1); + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + if (this.isEven()) this.dAddOffset(1, 0); + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } } - md = forge.md.md5.create(); - } - if (salt === null) { - salt = ""; - } - var digests = [hash(md, password + salt)]; - for (var length = 16, i = 1; length < dkLen; ++i, length += 16) { - digests.push(hash(md, digests[i - 1] + password + salt)); + } else { + var x = new Array(), t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) x[0] &= (1 << t) - 1; + else x[0] = 0; + this.fromString(x, 256); } - return digests.join("").substr(0, dkLen); - }; - function hash(md, bytes) { - return md.start().update(bytes).digest().getBytes(); } - function prfOidToMessageDigest(prfOid) { - var prfAlgorithm; - if (!prfOid) { - prfAlgorithm = "hmacWithSHA1"; - } else { - prfAlgorithm = pki2.oids[asn1.derToOid(prfOid)]; - if (!prfAlgorithm) { - var error4 = new Error("Unsupported PRF OID."); - error4.oid = prfOid; - error4.supported = [ - "hmacWithSHA1", - "hmacWithSHA224", - "hmacWithSHA256", - "hmacWithSHA384", - "hmacWithSHA512" - ]; - throw error4; + function bnToByteArray() { + var i = this.t, r = new Array(); + r[0] = this.s; + var p = this.DB - i * this.DB % 8, d, k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this.data[i] >> p) != (this.s & this.DM) >> p) + r[k++] = d | this.s << this.DB - p; + while (i >= 0) { + if (p < 8) { + d = (this.data[i] & (1 << p) - 1) << 8 - p; + d |= this.data[--i] >> (p += this.DB - 8); + } else { + d = this.data[i] >> (p -= 8) & 255; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 128) != 0) d |= -256; + if (k == 0 && (this.s & 128) != (d & 128)) ++k; + if (k > 0 || d != this.s) r[k++] = d; } } - return prfAlgorithmToMessageDigest(prfAlgorithm); + return r; } - function prfAlgorithmToMessageDigest(prfAlgorithm) { - var factory = forge.md; - switch (prfAlgorithm) { - case "hmacWithSHA224": - factory = forge.md.sha512; - case "hmacWithSHA1": - case "hmacWithSHA256": - case "hmacWithSHA384": - case "hmacWithSHA512": - prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); - break; - default: - var error4 = new Error("Unsupported PRF algorithm."); - error4.algorithm = prfAlgorithm; - error4.supported = [ - "hmacWithSHA1", - "hmacWithSHA224", - "hmacWithSHA256", - "hmacWithSHA384", - "hmacWithSHA512" - ]; - throw error4; - } - if (!factory || !(prfAlgorithm in factory)) { - throw new Error("Unknown hash algorithm: " + prfAlgorithm); + function bnEquals(a) { + return this.compareTo(a) == 0; + } + function bnMin(a) { + return this.compareTo(a) < 0 ? this : a; + } + function bnMax(a) { + return this.compareTo(a) > 0 ? this : a; + } + function bnpBitwiseTo(a, op, r) { + var i, f, m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) r.data[i] = op(this.data[i], a.data[i]); + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) r.data[i] = op(this.data[i], f); + r.t = this.t; + } else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) r.data[i] = op(f, a.data[i]); + r.t = a.t; } - return factory[prfAlgorithm].create(); + r.s = op(this.s, a.s); + r.clamp(); } - function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { - var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - salt - ), - // iteration count - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - countBytes.getBytes() - ) - ]); - if (prfAlgorithm !== "hmacWithSHA1") { - params.value.push( - // key length - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge.util.hexToBytes(dkLen.toString(16)) - ), - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids[prfAlgorithm]).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ); - } - return params; + function op_and(x, y) { + return x & y; } - } -}); - -// node_modules/node-forge/lib/pkcs7asn1.js -var require_pkcs7asn1 = __commonJS({ - "node_modules/node-forge/lib/pkcs7asn1.js"(exports2, module2) { - var forge = require_forge(); - require_asn1(); - require_util8(); - var asn1 = forge.asn1; - var p7v = module2.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; - forge.pkcs7 = forge.pkcs7 || {}; - forge.pkcs7.asn1 = p7v; - var contentInfoValidator = { - name: "ContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "ContentInfo.ContentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "ContentInfo.content", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - captureAsn1: "content" - }] - }; - p7v.contentInfoValidator = contentInfoValidator; - var encryptedContentInfoValidator = { - name: "EncryptedContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedContentInfo.contentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "EncryptedContentInfo.contentEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedContentInfo.contentEncryptionAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encAlgorithm" - }, { - name: "EncryptedContentInfo.contentEncryptionAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: "encParameter" - }] - }, { - name: "EncryptedContentInfo.encryptedContent", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - /* The PKCS#7 structure output by OpenSSL somewhat differs from what - * other implementations do generate. - * - * OpenSSL generates a structure like this: - * SEQUENCE { - * ... - * [0] - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * - * Whereas other implementations (and this PKCS#7 module) generate: - * SEQUENCE { - * ... - * [0] { - * OCTET STRING - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * } - * - * In order to support both, we just capture the context specific - * field here. The OCTET STRING bit is removed below. - */ - capture: "encryptedContent", - captureAsn1: "encryptedContentAsn1" - }] - }; - p7v.envelopedDataValidator = { - name: "EnvelopedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EnvelopedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, { - name: "EnvelopedData.RecipientInfos", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: "recipientInfos" - }].concat(encryptedContentInfoValidator) - }; - p7v.encryptedDataValidator = { - name: "EncryptedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }].concat(encryptedContentInfoValidator) - }; - var signerValidator = { - name: "SignerInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false - }, { - name: "SignerInfo.issuerAndSerialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.issuerAndSerialNumber.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "issuer" - }, { - name: "SignerInfo.issuerAndSerialNumber.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "serial" - }] - }, { - name: "SignerInfo.digestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.digestAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "digestAlgorithm" - }, { - name: "SignerInfo.digestAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: "digestParameter", - optional: true - }] - }, { - name: "SignerInfo.authenticatedAttributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: "authenticatedAttributes" - }, { - name: "SignerInfo.digestEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - capture: "signatureAlgorithm" - }, { - name: "SignerInfo.encryptedDigest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "signature" - }, { - name: "SignerInfo.unauthenticatedAttributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - capture: "unauthenticatedAttributes" - }] - }; - p7v.signedDataValidator = { - name: "SignedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [ - { - name: "SignedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, - { - name: "SignedData.DigestAlgorithms", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: "digestAlgorithms" - }, - contentInfoValidator, - { - name: "SignedData.Certificates", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - optional: true, - captureAsn1: "certificates" - }, - { - name: "SignedData.CertificateRevocationLists", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - optional: true, - captureAsn1: "crls" - }, - { - name: "SignedData.SignerInfos", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - capture: "signerInfos", - optional: true, - value: [signerValidator] - } - ] - }; - p7v.recipientInfoValidator = { - name: "RecipientInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, { - name: "RecipientInfo.issuerAndSerial", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.issuerAndSerial.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "issuer" - }, { - name: "RecipientInfo.issuerAndSerial.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "serial" - }] - }, { - name: "RecipientInfo.keyEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.keyEncryptionAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encAlgorithm" - }, { - name: "RecipientInfo.keyEncryptionAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: "encParameter", - optional: true - }] - }, { - name: "RecipientInfo.encryptedKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encKey" - }] - }; - } -}); - -// node_modules/node-forge/lib/mgf1.js -var require_mgf1 = __commonJS({ - "node_modules/node-forge/lib/mgf1.js"(exports2, module2) { - var forge = require_forge(); - require_util8(); - forge.mgf = forge.mgf || {}; - var mgf1 = module2.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; - mgf1.create = function(md) { - var mgf = { - /** - * Generate mask of specified length. - * - * @param {String} seed The seed for mask generation. - * @param maskLen Number of bytes to generate. - * @return {String} The generated mask. - */ - generate: function(seed, maskLen) { - var t = new forge.util.ByteBuffer(); - var len = Math.ceil(maskLen / md.digestLength); - for (var i = 0; i < len; i++) { - var c = new forge.util.ByteBuffer(); - c.putInt32(i); - md.start(); - md.update(seed + c.getBytes()); - t.putBuffer(md.digest()); - } - t.truncate(t.length() - maskLen); - return t.getBytes(); - } - }; - return mgf; - }; - } -}); - -// node_modules/node-forge/lib/mgf.js -var require_mgf = __commonJS({ - "node_modules/node-forge/lib/mgf.js"(exports2, module2) { - var forge = require_forge(); - require_mgf1(); - module2.exports = forge.mgf = forge.mgf || {}; - forge.mgf.mgf1 = forge.mgf1; - } -}); - -// node_modules/node-forge/lib/pss.js -var require_pss = __commonJS({ - "node_modules/node-forge/lib/pss.js"(exports2, module2) { - var forge = require_forge(); - require_random(); - require_util8(); - var pss = module2.exports = forge.pss = forge.pss || {}; - pss.create = function(options) { - if (arguments.length === 3) { - options = { - md: arguments[0], - mgf: arguments[1], - saltLength: arguments[2] - }; + function bnAnd(a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + } + function op_or(x, y) { + return x | y; + } + function bnOr(a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + } + function op_xor(x, y) { + return x ^ y; + } + function bnXor(a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + } + function op_andnot(x, y) { + return x & ~y; + } + function bnAndNot(a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + } + function bnNot() { + var r = nbi(); + for (var i = 0; i < this.t; ++i) r.data[i] = this.DM & ~this.data[i]; + r.t = this.t; + r.s = ~this.s; + return r; + } + function bnShiftLeft(n) { + var r = nbi(); + if (n < 0) this.rShiftTo(-n, r); + else this.lShiftTo(n, r); + return r; + } + function bnShiftRight(n) { + var r = nbi(); + if (n < 0) this.lShiftTo(-n, r); + else this.rShiftTo(n, r); + return r; + } + function lbit(x) { + if (x == 0) return -1; + var r = 0; + if ((x & 65535) == 0) { + x >>= 16; + r += 16; } - var hash = options.md; - var mgf = options.mgf; - var hLen = hash.digestLength; - var salt_ = options.salt || null; - if (typeof salt_ === "string") { - salt_ = forge.util.createBuffer(salt_); + if ((x & 255) == 0) { + x >>= 8; + r += 8; } - var sLen; - if ("saltLength" in options) { - sLen = options.saltLength; - } else if (salt_ !== null) { - sLen = salt_.length(); - } else { - throw new Error("Salt length not specified or specific salt not given."); + if ((x & 15) == 0) { + x >>= 4; + r += 4; } - if (salt_ !== null && salt_.length() !== sLen) { - throw new Error("Given salt length does not match length of given salt."); + if ((x & 3) == 0) { + x >>= 2; + r += 2; } - var prng = options.prng || forge.random; - var pssobj = {}; - pssobj.encode = function(md, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - var mHash = md.digest().getBytes(); - if (emLen < hLen + sLen + 2) { - throw new Error("Message is too long to encrypt."); - } - var salt; - if (salt_ === null) { - salt = prng.getBytesSync(sLen); - } else { - salt = salt_.bytes(); - } - var m_ = new forge.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - hash.start(); - hash.update(m_.getBytes()); - var h = hash.digest().getBytes(); - var ps = new forge.util.ByteBuffer(); - ps.fillWithByte(0, emLen - sLen - hLen - 2); - ps.putByte(1); - ps.putBytes(salt); - var db = ps.getBytes(); - var maskLen = emLen - hLen - 1; - var dbMask = mgf.generate(h, maskLen); - var maskedDB = ""; - for (i = 0; i < maskLen; i++) { - maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } - var mask = 65280 >> 8 * emLen - emBits & 255; - maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1); - return maskedDB + h + String.fromCharCode(188); - }; - pssobj.verify = function(mHash, em, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - em = em.substr(-emLen); - if (emLen < hLen + sLen + 2) { - throw new Error("Inconsistent parameters to PSS signature verification."); + if ((x & 1) == 0) ++r; + return r; + } + function bnGetLowestSetBit() { + for (var i = 0; i < this.t; ++i) + if (this.data[i] != 0) return i * this.DB + lbit(this.data[i]); + if (this.s < 0) return this.t * this.DB; + return -1; + } + function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; + } + function bnBitCount() { + var r = 0, x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) r += cbit(this.data[i] ^ x); + return r; + } + function bnTestBit(n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) return this.s != 0; + return (this.data[j] & 1 << n % this.DB) != 0; + } + function bnpChangeBit(n, op) { + var r = BigInteger.ONE.shiftLeft(n); + this.bitwiseTo(r, op, r); + return r; + } + function bnSetBit(n) { + return this.changeBit(n, op_or); + } + function bnClearBit(n) { + return this.changeBit(n, op_andnot); + } + function bnFlipBit(n) { + return this.changeBit(n, op_xor); + } + function bnpAddTo(a, r) { + var i = 0, c = 0, m = Math.min(a.t, this.t); + while (i < m) { + c += this.data[i] + a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; } - if (em.charCodeAt(emLen - 1) !== 188) { - throw new Error("Encoded message does not end in 0xBC."); + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c += a.data[i]; + r.data[i++] = c & this.DM; + c >>= this.DB; } - var maskLen = emLen - hLen - 1; - var maskedDB = em.substr(0, maskLen); - var h = em.substr(maskLen, hLen); - var mask = 65280 >> 8 * emLen - emBits & 255; - if ((maskedDB.charCodeAt(0) & mask) !== 0) { - throw new Error("Bits beyond keysize not zero as expected."); + c += a.s; + } + r.s = c < 0 ? -1 : 0; + if (c > 0) r.data[i++] = c; + else if (c < -1) r.data[i++] = this.DV + c; + r.t = i; + r.clamp(); + } + function bnAdd(a) { + var r = nbi(); + this.addTo(a, r); + return r; + } + function bnSubtract(a) { + var r = nbi(); + this.subTo(a, r); + return r; + } + function bnMultiply(a) { + var r = nbi(); + this.multiplyTo(a, r); + return r; + } + function bnDivide(a) { + var r = nbi(); + this.divRemTo(a, r, null); + return r; + } + function bnRemainder(a) { + var r = nbi(); + this.divRemTo(a, null, r); + return r; + } + function bnDivideAndRemainder(a) { + var q = nbi(), r = nbi(); + this.divRemTo(a, q, r); + return new Array(q, r); + } + function bnpDMultiply(n) { + this.data[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + } + function bnpDAddOffset(n, w) { + if (n == 0) return; + while (this.t <= w) this.data[this.t++] = 0; + this.data[w] += n; + while (this.data[w] >= this.DV) { + this.data[w] -= this.DV; + if (++w >= this.t) this.data[this.t++] = 0; + ++this.data[w]; + } + } + function NullExp() { + } + function nNop(x) { + return x; + } + function nMulTo(x, y, r) { + x.multiplyTo(y, r); + } + function nSqrTo(x, r) { + x.squareTo(r); + } + NullExp.prototype.convert = nNop; + NullExp.prototype.revert = nNop; + NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.sqrTo = nSqrTo; + function bnPow(e) { + return this.exp(e, new NullExp()); + } + function bnpMultiplyLowerTo(a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; + r.t = i; + while (i > 0) r.data[--i] = 0; + var j; + for (j = r.t - this.t; i < j; ++i) r.data[i + this.t] = this.am(0, a.data[i], r, i, 0, this.t); + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a.data[i], r, i, 0, n - i); + r.clamp(); + } + function bnpMultiplyUpperTo(a, n, r) { + --n; + var i = r.t = this.t + a.t - n; + r.s = 0; + while (--i >= 0) r.data[i] = 0; + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r.data[this.t + i - n] = this.am(n - i, a.data[i], r, 0, 0, this.t + i - n); + r.clamp(); + r.drShiftTo(1, r); + } + function Barrett(m) { + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + this.m = m; + } + function barrettConvert(x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); + else if (x.compareTo(this.m) < 0) return x; + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + } + function barrettRevert(x) { + return x; + } + function barrettReduce(x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + function barrettSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + function barrettMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + Barrett.prototype.convert = barrettConvert; + Barrett.prototype.revert = barrettRevert; + Barrett.prototype.reduce = barrettReduce; + Barrett.prototype.mulTo = barrettMulTo; + Barrett.prototype.sqrTo = barrettSqrTo; + function bnModPow(e, m) { + var i = e.bitLength(), k, r = nbv(1), z; + if (i <= 0) return r; + else if (i < 18) k = 1; + else if (i < 48) k = 3; + else if (i < 144) k = 4; + else if (i < 768) k = 5; + else k = 6; + if (i < 8) + z = new Classic(m); + else if (m.isEven()) + z = new Barrett(m); + else + z = new Montgomery(m); + var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; + g[1] = z.convert(this); + if (k > 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; } - var dbMask = mgf.generate(h, maskLen); - var db = ""; - for (i = 0; i < maskLen; i++) { - db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + var j = e.t - 1, w, is1 = true, r2 = nbi(), t; + i = nbits(e.data[j]) - 1; + while (j >= 0) { + if (i >= k1) w = e.data[j] >> i - k1 & km; + else { + w = (e.data[j] & (1 << i + 1) - 1) << k1 - i; + if (j > 0) w |= e.data[j - 1] >> this.DB + i - k1; } - db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); - var checkLen = emLen - hLen - sLen - 2; - for (i = 0; i < checkLen; i++) { - if (db.charCodeAt(i) !== 0) { - throw new Error("Leftmost octets not zero as expected"); + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { + g[w].copyTo(r); + is1 = false; + } else { + while (n > 1) { + z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) z.sqrTo(r, r2); + else { + t = r; + r = r2; + r2 = t; } + z.mulTo(r2, g[w], r); } - if (db.charCodeAt(checkLen) !== 1) { - throw new Error("Inconsistent PSS signature, 0x01 marker not found"); + while (j >= 0 && (e.data[j] & 1 << i) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); + } + function bnGCD(a) { + var x = this.s < 0 ? this.negate() : this.clone(); + var y = a.s < 0 ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(), g = y.getLowestSetBit(); + if (g < 0) return x; + if (i < g) g = i; + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) y.lShiftTo(g, y); + return y; + } + function bnpModInt(n) { + if (n <= 0) return 0; + var d = this.DV % n, r = this.s < 0 ? n - 1 : 0; + if (this.t > 0) + if (d == 0) r = this.data[0] % n; + else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this.data[i]) % n; + return r; + } + function bnModInverse(m) { + var ac = m.isEven(); + if (this.isEven() && ac || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), v = this.clone(); + var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } else if (!b.isEven()) b.subTo(m, b); + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } else if (!d.isEven()) d.subTo(m, d); + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) a.subTo(c, a); + b.subTo(d, b); + } else { + v.subTo(u, v); + if (ac) c.subTo(a, c); + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if (d.compareTo(m) >= 0) return d.subtract(m); + if (d.signum() < 0) d.addTo(m, d); + else return d; + if (d.signum() < 0) return d.add(m); + else return d; + } + var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509]; + var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + function bnIsProbablePrime(t) { + var i, x = this.abs(); + if (x.t == 1 && x.data[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x.data[0] == lowprimes[i]) return true; + return false; + } + if (x.isEven()) return false; + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i], j = i + 1; + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while (i < j) if (m % lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); + } + function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) return false; + var r = n1.shiftRight(k); + var prng = bnGetPrng(); + var a; + for (var i = 0; i < t; ++i) { + do { + a = new BigInteger(this.bitLength(), prng); + } while (a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) return false; + } + if (y.compareTo(n1) != 0) return false; + } + } + return true; + } + function bnGetPrng() { + return { + // x is an array to fill with bytes + nextBytes: function(x) { + for (var i = 0; i < x.length; ++i) { + x[i] = Math.floor(Math.random() * 256); + } } - var salt = db.substr(-sLen); - var m_ = new forge.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - hash.start(); - hash.update(m_.getBytes()); - var h_ = hash.digest().getBytes(); - return h === h_; }; - return pssobj; - }; + } + BigInteger.prototype.chunkSize = bnpChunkSize; + BigInteger.prototype.toRadix = bnpToRadix; + BigInteger.prototype.fromRadix = bnpFromRadix; + BigInteger.prototype.fromNumber = bnpFromNumber; + BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + BigInteger.prototype.changeBit = bnpChangeBit; + BigInteger.prototype.addTo = bnpAddTo; + BigInteger.prototype.dMultiply = bnpDMultiply; + BigInteger.prototype.dAddOffset = bnpDAddOffset; + BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + BigInteger.prototype.modInt = bnpModInt; + BigInteger.prototype.millerRabin = bnpMillerRabin; + BigInteger.prototype.clone = bnClone; + BigInteger.prototype.intValue = bnIntValue; + BigInteger.prototype.byteValue = bnByteValue; + BigInteger.prototype.shortValue = bnShortValue; + BigInteger.prototype.signum = bnSigNum; + BigInteger.prototype.toByteArray = bnToByteArray; + BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.min = bnMin; + BigInteger.prototype.max = bnMax; + BigInteger.prototype.and = bnAnd; + BigInteger.prototype.or = bnOr; + BigInteger.prototype.xor = bnXor; + BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.not = bnNot; + BigInteger.prototype.shiftLeft = bnShiftLeft; + BigInteger.prototype.shiftRight = bnShiftRight; + BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + BigInteger.prototype.bitCount = bnBitCount; + BigInteger.prototype.testBit = bnTestBit; + BigInteger.prototype.setBit = bnSetBit; + BigInteger.prototype.clearBit = bnClearBit; + BigInteger.prototype.flipBit = bnFlipBit; + BigInteger.prototype.add = bnAdd; + BigInteger.prototype.subtract = bnSubtract; + BigInteger.prototype.multiply = bnMultiply; + BigInteger.prototype.divide = bnDivide; + BigInteger.prototype.remainder = bnRemainder; + BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; + BigInteger.prototype.modPow = bnModPow; + BigInteger.prototype.modInverse = bnModInverse; + BigInteger.prototype.pow = bnPow; + BigInteger.prototype.gcd = bnGCD; + BigInteger.prototype.isProbablePrime = bnIsProbablePrime; } }); -// node_modules/node-forge/lib/x509.js -var require_x509 = __commonJS({ - "node_modules/node-forge/lib/x509.js"(exports2, module2) { +// node_modules/node-forge/lib/sha1.js +var require_sha1 = __commonJS({ + "node_modules/node-forge/lib/sha1.js"(exports2, module2) { var forge = require_forge(); - require_aes(); - require_asn1(); - require_des(); require_md(); - require_mgf(); - require_oids(); - require_pem(); - require_pss(); - require_rsa(); require_util8(); - var asn1 = forge.asn1; - var pki2 = module2.exports = forge.pki = forge.pki || {}; - var oids = pki2.oids; - var _shortNames = {}; - _shortNames["CN"] = oids["commonName"]; - _shortNames["commonName"] = "CN"; - _shortNames["C"] = oids["countryName"]; - _shortNames["countryName"] = "C"; - _shortNames["L"] = oids["localityName"]; - _shortNames["localityName"] = "L"; - _shortNames["ST"] = oids["stateOrProvinceName"]; - _shortNames["stateOrProvinceName"] = "ST"; - _shortNames["O"] = oids["organizationName"]; - _shortNames["organizationName"] = "O"; - _shortNames["OU"] = oids["organizationalUnitName"]; - _shortNames["organizationalUnitName"] = "OU"; - _shortNames["E"] = oids["emailAddress"]; - _shortNames["emailAddress"] = "E"; - var publicKeyValidator = forge.pki.rsa.publicKeyValidator; - var x509CertificateValidator = { - name: "Certificate", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Certificate.TBSCertificate", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "tbsCertificate", - value: [ - { - name: "Certificate.TBSCertificate.version", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.version.integer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certVersion" - }] - }, - { - name: "Certificate.TBSCertificate.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certSerialNumber" - }, - { - name: "Certificate.TBSCertificate.signature", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Certificate.TBSCertificate.signature.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certinfoSignatureOid" - }, { - name: "Certificate.TBSCertificate.signature.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "certinfoSignatureParams" - }] - }, - { - name: "Certificate.TBSCertificate.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certIssuer" - }, - { - name: "Certificate.TBSCertificate.validity", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - // Note: UTC and generalized times may both appear so the capture - // names are based on their detected order, the names used below - // are only for the common case, which validity time really means - // "notBefore" and which means "notAfter" will be determined by order - value: [{ - // notBefore (Time) (UTC time case) - name: "Certificate.TBSCertificate.validity.notBefore (utc)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: "certValidity1UTCTime" - }, { - // notBefore (Time) (generalized time case) - name: "Certificate.TBSCertificate.validity.notBefore (generalized)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: "certValidity2GeneralizedTime" - }, { - // notAfter (Time) (only UTC time is supported) - name: "Certificate.TBSCertificate.validity.notAfter (utc)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: "certValidity3UTCTime" - }, { - // notAfter (Time) (only UTC time is supported) - name: "Certificate.TBSCertificate.validity.notAfter (generalized)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: "certValidity4GeneralizedTime" - }] - }, - { - // Name (subject) (RDNSequence) - name: "Certificate.TBSCertificate.subject", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certSubject" - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - // issuerUniqueID (optional) - name: "Certificate.TBSCertificate.issuerUniqueID", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.issuerUniqueID.id", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: "certIssuerUniqueId" - }] - }, - { - // subjectUniqueID (optional) - name: "Certificate.TBSCertificate.subjectUniqueID", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.subjectUniqueID.id", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: "certSubjectUniqueId" - }] - }, - { - // Extensions (optional) - name: "Certificate.TBSCertificate.extensions", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - constructed: true, - captureAsn1: "certExtensions", - optional: true - } - ] - }, { - // AlgorithmIdentifier (signature algorithm) - name: "Certificate.signatureAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: "Certificate.signatureAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certSignatureOid" - }, { - name: "Certificate.TBSCertificate.signature.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "certSignatureParams" - }] - }, { - // SignatureValue - name: "Certificate.signatureValue", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: "certSignature" - }] - }; - var rsassaPssParameterValidator = { - name: "rsapss", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "rsapss.hashAlgorithm", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - value: [{ - name: "rsapss.hashAlgorithm.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "hashOid" - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }, { - name: "rsapss.maskGenAlgorithm", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "maskGenOid" - }, { - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "maskGenHashOid" - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }] - }, { - name: "rsapss.saltLength", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - optional: true, - value: [{ - name: "rsapss.saltLength.saltLength", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: "saltLength" - }] - }, { - name: "rsapss.trailerField", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - optional: true, - value: [{ - name: "rsapss.trailer.trailer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: "trailer" - }] - }] - }; - var certificationRequestInfoValidator = { - name: "CertificationRequestInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certificationRequestInfo", - value: [ - { - name: "CertificationRequestInfo.integer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certificationRequestInfoVersion" - }, - { - // Name (subject) (RDNSequence) - name: "CertificationRequestInfo.subject", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certificationRequestInfoSubject" - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - name: "CertificationRequestInfo.attributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: "certificationRequestInfoAttributes", - value: [{ - name: "CertificationRequestInfo.attributes", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "CertificationRequestInfo.attributes.type", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false - }, { - name: "CertificationRequestInfo.attributes.value", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true - }] - }] + var sha1 = module2.exports = forge.sha1 = forge.sha1 || {}; + forge.md.sha1 = forge.md.algorithms.sha1 = sha1; + sha1.create = function() { + if (!_initialized) { + _init(); + } + var _state = null; + var _input = forge.util.createBuffer(); + var _w = new Array(80); + var md = { + algorithm: "sha1", + blockLength: 64, + digestLength: 20, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + md.start = function() { + md.messageLength = 0; + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); } - ] - }; - var certificationRequestValidator = { - name: "CertificationRequest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "csr", - value: [ - certificationRequestInfoValidator, - { - // AlgorithmIdentifier (signature algorithm) - name: "CertificationRequest.signatureAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: "CertificationRequest.signatureAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "csrSignatureOid" - }, { - name: "CertificationRequest.signatureAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "csrSignatureParams" - }] - }, - { - // signature - name: "CertificationRequest.signature", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: "csrSignature" + _input = forge.util.createBuffer(); + _state = { + h0: 1732584193, + h1: 4023233417, + h2: 2562383102, + h3: 271733878, + h4: 3285377520 + }; + return md; + }; + md.start(); + md.update = function(msg, encoding) { + if (encoding === "utf8") { + msg = forge.util.encodeUtf8(msg); } - ] - }; - pki2.RDNAttributesAsArray = function(rdn, md) { - var rval = []; - var set2, attr, obj; - for (var si = 0; si < rdn.value.length; ++si) { - set2 = rdn.value[si]; - for (var i = 0; i < set2.value.length; ++i) { - obj = {}; - attr = set2.value[i]; - obj.type = asn1.derToOid(attr.value[0].value); - obj.value = attr.value[1].value; - obj.valueTagClass = attr.value[1].type; - if (obj.type in oids) { - obj.name = oids[obj.type]; - if (obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - if (md) { - md.update(obj.type); - md.update(obj.value); - } - rval.push(obj); + var len = msg.length; + md.messageLength += len; + len = [len / 4294967296 >>> 0, len >>> 0]; + for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = len[1] / 4294967296 >>> 0; } - } - return rval; - }; - pki2.CRIAttributesAsArray = function(attributes) { - var rval = []; - for (var si = 0; si < attributes.length; ++si) { - var seq2 = attributes[si]; - var type2 = asn1.derToOid(seq2.value[0].value); - var values = seq2.value[1].value; - for (var vi = 0; vi < values.length; ++vi) { - var obj = {}; - obj.type = type2; - obj.value = values[vi].value; - obj.valueTagClass = values[vi].type; - if (obj.type in oids) { - obj.name = oids[obj.type]; - if (obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - if (obj.type === oids.extensionRequest) { - obj.extensions = []; - for (var ei = 0; ei < obj.value.length; ++ei) { - obj.extensions.push(pki2.certificateExtensionFromAsn1(obj.value[ei])); - } - } - rval.push(obj); + _input.putBytes(msg); + _update(_state, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); } - } - return rval; - }; - function _getAttribute(obj, options) { - if (typeof options === "string") { - options = { shortName: options }; - } - var rval = null; - var attr; - for (var i = 0; rval === null && i < obj.attributes.length; ++i) { - attr = obj.attributes[i]; - if (options.type && options.type === attr.type) { - rval = attr; - } else if (options.name && options.name === attr.name) { - rval = attr; - } else if (options.shortName && options.shortName === attr.shortName) { - rval = attr; + return md; + }; + md.digest = function() { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; + var overflow = remaining & md.blockLength - 1; + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = next / 4294967296 >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; } - } - return rval; - } - var _readSignatureParameters = function(oid, obj, fillDefaults) { - var params = {}; - if (oid !== oids["RSASSA-PSS"]) { - return params; - } - if (fillDefaults) { - params = { - hash: { - algorithmOid: oids["sha1"] - }, - mgf: { - algorithmOid: oids["mgf1"], - hash: { - algorithmOid: oids["sha1"] - } - }, - saltLength: 20 + finalBlock.putInt32(bits); + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4 }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + return rval; + }; + return md; + }; + var _padding = null; + var _initialized = false; + function _init() { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 64); + _initialized = true; + } + function _update(s, w, bytes) { + var t, a, b, c, d, e, f, i; + var len = bytes.length(); + while (len >= 64) { + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + for (i = 0; i < 16; ++i) { + t = bytes.getInt32(); + w[i] = t; + f = d ^ b & (c ^ d); + t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 20; ++i) { + t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + t = t << 1 | t >>> 31; + w[i] = t; + f = d ^ b & (c ^ d); + t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 32; ++i) { + t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + t = t << 1 | t >>> 31; + w[i] = t; + f = b ^ c ^ d; + t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 40; ++i) { + t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; + t = t << 2 | t >>> 30; + w[i] = t; + f = b ^ c ^ d; + t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 60; ++i) { + t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; + t = t << 2 | t >>> 30; + w[i] = t; + f = b & c | d & (b ^ c); + t = (a << 5 | a >>> 27) + f + e + 2400959708 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + for (; i < 80; ++i) { + t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; + t = t << 2 | t >>> 30; + w[i] = t; + f = b ^ c ^ d; + t = (a << 5 | a >>> 27) + f + e + 3395469782 + t; + e = d; + d = c; + c = (b << 30 | b >>> 2) >>> 0; + b = a; + a = t; + } + s.h0 = s.h0 + a | 0; + s.h1 = s.h1 + b | 0; + s.h2 = s.h2 + c | 0; + s.h3 = s.h3 + d | 0; + s.h4 = s.h4 + e | 0; + len -= 64; } - var capture = {}; - var errors = []; - if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { - var error4 = new Error("Cannot read RSASSA-PSS parameter block."); - error4.errors = errors; - throw error4; - } - if (capture.hashOid !== void 0) { - params.hash = params.hash || {}; - params.hash.algorithmOid = asn1.derToOid(capture.hashOid); + } + } +}); + +// node_modules/node-forge/lib/pkcs1.js +var require_pkcs1 = __commonJS({ + "node_modules/node-forge/lib/pkcs1.js"(exports2, module2) { + var forge = require_forge(); + require_util8(); + require_random(); + require_sha1(); + var pkcs1 = module2.exports = forge.pkcs1 = forge.pkcs1 || {}; + pkcs1.encode_rsa_oaep = function(key, message, options) { + var label; + var seed; + var md; + var mgf1Md; + if (typeof options === "string") { + label = options; + seed = arguments[3] || void 0; + md = arguments[4] || void 0; + } else if (options) { + label = options.label || void 0; + seed = options.seed || void 0; + md = options.md || void 0; + if (options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } } - if (capture.maskGenOid !== void 0) { - params.mgf = params.mgf || {}; - params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); - params.mgf.hash = params.mgf.hash || {}; - params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); + if (!md) { + md = forge.md.sha1.create(); + } else { + md.start(); } - if (capture.saltLength !== void 0) { - params.saltLength = capture.saltLength.charCodeAt(0); + if (!mgf1Md) { + mgf1Md = md; } - return params; - }; - var _createSignatureDigest = function(options) { - switch (oids[options.signatureOid]) { - case "sha1WithRSAEncryption": - // deprecated alias - case "sha1WithRSASignature": - return forge.md.sha1.create(); - case "md5WithRSAEncryption": - return forge.md.md5.create(); - case "sha256WithRSAEncryption": - return forge.md.sha256.create(); - case "sha384WithRSAEncryption": - return forge.md.sha384.create(); - case "sha512WithRSAEncryption": - return forge.md.sha512.create(); - case "RSASSA-PSS": - return forge.md.sha256.create(); - default: - var error4 = new Error( - "Could not compute " + options.type + " digest. Unknown signature OID." - ); - error4.signatureOid = options.signatureOid; - throw error4; + var keyLength = Math.ceil(key.n.bitLength() / 8); + var maxLength = keyLength - 2 * md.digestLength - 2; + if (message.length > maxLength) { + var error4 = new Error("RSAES-OAEP input message length is too long."); + error4.length = message.length; + error4.maxLength = maxLength; + throw error4; } - }; - var _verifySignature = function(options) { - var cert = options.certificate; - var scheme; - switch (cert.signatureOid) { - case oids.sha1WithRSAEncryption: - // deprecated alias - case oids.sha1WithRSASignature: - break; - case oids["RSASSA-PSS"]: - var hash, mgf; - hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; - if (hash === void 0 || forge.md[hash] === void 0) { - var error4 = new Error("Unsupported MGF hash function."); - error4.oid = cert.signatureParameters.mgf.hash.algorithmOid; - error4.name = hash; - throw error4; - } - mgf = oids[cert.signatureParameters.mgf.algorithmOid]; - if (mgf === void 0 || forge.mgf[mgf] === void 0) { - var error4 = new Error("Unsupported MGF function."); - error4.oid = cert.signatureParameters.mgf.algorithmOid; - error4.name = mgf; - throw error4; - } - mgf = forge.mgf[mgf].create(forge.md[hash].create()); - hash = oids[cert.signatureParameters.hash.algorithmOid]; - if (hash === void 0 || forge.md[hash] === void 0) { - var error4 = new Error("Unsupported RSASSA-PSS hash function."); - error4.oid = cert.signatureParameters.hash.algorithmOid; - error4.name = hash; - throw error4; - } - scheme = forge.pss.create( - forge.md[hash].create(), - mgf, - cert.signatureParameters.saltLength - ); - break; + if (!label) { + label = ""; } - return cert.publicKey.verify( - options.md.digest().getBytes(), - options.signature, - scheme - ); - }; - pki2.certificateFromPem = function(pem, computeHash, strict) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { - var error4 = new Error( - 'Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".' - ); - error4.headerType = msg.type; - throw error4; + md.update(label, "raw"); + var lHash = md.digest(); + var PS = ""; + var PS_length = maxLength - message.length; + for (var i = 0; i < PS_length; i++) { + PS += "\0"; } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error( - "Could not convert certificate from PEM; PEM is encrypted." - ); + var DB = lHash.getBytes() + PS + "" + message; + if (!seed) { + seed = forge.random.getBytes(md.digestLength); + } else if (seed.length !== md.digestLength) { + var error4 = new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length."); + error4.seedLength = seed.length; + error4.digestLength = md.digestLength; + throw error4; } - var obj = asn1.fromDer(msg.body, strict); - return pki2.certificateFromAsn1(obj, computeHash); - }; - pki2.certificateToPem = function(cert, maxline) { - var msg = { - type: "CERTIFICATE", - body: asn1.toDer(pki2.certificateToAsn1(cert)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); + return "\0" + maskedSeed + maskedDB; }; - pki2.publicKeyFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "PUBLIC KEY" && msg.type !== "RSA PUBLIC KEY") { - var error4 = new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); - error4.headerType = msg.type; + pkcs1.decode_rsa_oaep = function(key, em, options) { + var label; + var md; + var mgf1Md; + if (typeof options === "string") { + label = options; + md = arguments[3] || void 0; + } else if (options) { + label = options.label || void 0; + md = options.md || void 0; + if (options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + var keyLength = Math.ceil(key.n.bitLength() / 8); + if (em.length !== keyLength) { + var error4 = new Error("RSAES-OAEP encoded message length is invalid."); + error4.length = em.length; + error4.expectedLength = keyLength; throw error4; } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert public key from PEM; PEM is encrypted."); + if (md === void 0) { + md = forge.md.sha1.create(); + } else { + md.start(); } - var obj = asn1.fromDer(msg.body); - return pki2.publicKeyFromAsn1(obj); - }; - pki2.publicKeyToPem = function(key, maxline) { - var msg = { - type: "PUBLIC KEY", - body: asn1.toDer(pki2.publicKeyToAsn1(key)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - pki2.publicKeyToRSAPublicKeyPem = function(key, maxline) { - var msg = { - type: "RSA PUBLIC KEY", - body: asn1.toDer(pki2.publicKeyToRSAPublicKey(key)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); - }; - pki2.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge.md.sha1.create(); - var type2 = options.type || "RSAPublicKey"; - var bytes; - switch (type2) { - case "RSAPublicKey": - bytes = asn1.toDer(pki2.publicKeyToRSAPublicKey(key)).getBytes(); - break; - case "SubjectPublicKeyInfo": - bytes = asn1.toDer(pki2.publicKeyToAsn1(key)).getBytes(); - break; - default: - throw new Error('Unknown fingerprint type "' + options.type + '".'); + if (!mgf1Md) { + mgf1Md = md; } - md.start(); - md.update(bytes); - var digest = md.digest(); - if (options.encoding === "hex") { - var hex = digest.toHex(); - if (options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if (options.encoding === "binary") { - return digest.getBytes(); - } else if (options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); + if (keyLength < 2 * md.digestLength + 2) { + throw new Error("RSAES-OAEP key is too short for the hash function."); } - return digest; - }; - pki2.certificationRequestFromPem = function(pem, computeHash, strict) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "CERTIFICATE REQUEST") { - var error4 = new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".'); - error4.headerType = msg.type; - throw error4; + if (!label) { + label = ""; } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert certification request from PEM; PEM is encrypted."); + md.update(label, "raw"); + var lHash = md.digest().getBytes(); + var y = em.charAt(0); + var maskedSeed = em.substring(1, md.digestLength + 1); + var maskedDB = em.substring(1 + md.digestLength); + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); + var lHashPrime = db.substring(0, md.digestLength); + var error4 = y !== "\0"; + for (var i = 0; i < md.digestLength; ++i) { + error4 |= lHash.charAt(i) !== lHashPrime.charAt(i); } - var obj = asn1.fromDer(msg.body, strict); - return pki2.certificationRequestFromAsn1(obj, computeHash); - }; - pki2.certificationRequestToPem = function(csr, maxline) { - var msg = { - type: "CERTIFICATE REQUEST", - body: asn1.toDer(pki2.certificationRequestToAsn1(csr)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); + var in_ps = 1; + var index = md.digestLength; + for (var j = md.digestLength; j < db.length; j++) { + var code = db.charCodeAt(j); + var is_0 = code & 1 ^ 1; + var error_mask = in_ps ? 65534 : 0; + error4 |= code & error_mask; + in_ps = in_ps & is_0; + index += in_ps; + } + if (error4 || db.charCodeAt(index) !== 1) { + throw new Error("Invalid RSAES-OAEP padding."); + } + return db.substring(index + 1); }; - pki2.createCertificate = function() { - var cert = {}; - cert.version = 2; - cert.serialNumber = "00"; - cert.signatureOid = null; - cert.signature = null; - cert.siginfo = {}; - cert.siginfo.algorithmOid = null; - cert.validity = {}; - cert.validity.notBefore = /* @__PURE__ */ new Date(); - cert.validity.notAfter = /* @__PURE__ */ new Date(); - cert.issuer = {}; - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = []; - cert.issuer.hash = null; - cert.subject = {}; - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); + function rsa_mgf1(seed, maskLength, hash) { + if (!hash) { + hash = forge.md.sha1.create(); + } + var t = ""; + var count = Math.ceil(maskLength / hash.digestLength); + for (var i = 0; i < count; ++i) { + var c = String.fromCharCode( + i >> 24 & 255, + i >> 16 & 255, + i >> 8 & 255, + i & 255 + ); + hash.start(); + hash.update(seed + c); + t += hash.digest().getBytes(); + } + return t.substring(0, maskLength); + } + } +}); + +// node_modules/node-forge/lib/prime.js +var require_prime = __commonJS({ + "node_modules/node-forge/lib/prime.js"(exports2, module2) { + var forge = require_forge(); + require_util8(); + require_jsbn(); + require_random(); + (function() { + if (forge.prime) { + module2.exports = forge.prime; + return; + } + var prime = module2.exports = forge.prime = forge.prime || {}; + var BigInteger = forge.jsbn.BigInteger; + var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + var THIRTY = new BigInteger(null); + THIRTY.fromInt(30); + var op_or = function(x, y) { + return x | y; }; - cert.subject.attributes = []; - cert.subject.hash = null; - cert.extensions = []; - cert.publicKey = null; - cert.md = null; - cert.setSubject = function(attrs, uniqueId) { - _fillMissingFields(attrs); - cert.subject.attributes = attrs; - delete cert.subject.uniqueId; - if (uniqueId) { - cert.subject.uniqueId = uniqueId; + prime.generateProbablePrime = function(bits, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; } - cert.subject.hash = null; - }; - cert.setIssuer = function(attrs, uniqueId) { - _fillMissingFields(attrs); - cert.issuer.attributes = attrs; - delete cert.issuer.uniqueId; - if (uniqueId) { - cert.issuer.uniqueId = uniqueId; + options = options || {}; + var algorithm = options.algorithm || "PRIMEINC"; + if (typeof algorithm === "string") { + algorithm = { name: algorithm }; } - cert.issuer.hash = null; - }; - cert.setExtensions = function(exts) { - for (var i = 0; i < exts.length; ++i) { - _fillMissingExtensionFields(exts[i], { cert }); + algorithm.options = algorithm.options || {}; + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for (var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + if (algorithm.name === "PRIMEINC") { + return primeincFindPrime(bits, rng, algorithm.options, callback); } - cert.extensions = exts; + throw new Error("Invalid prime generation algorithm: " + algorithm.name); }; - cert.getExtension = function(options) { - if (typeof options === "string") { - options = { name: options }; - } - var rval = null; - var ext; - for (var i = 0; rval === null && i < cert.extensions.length; ++i) { - ext = cert.extensions[i]; - if (options.id && ext.id === options.id) { - rval = ext; - } else if (options.name && ext.name === options.name) { - rval = ext; - } + function primeincFindPrime(bits, rng, options, callback) { + if ("workers" in options) { + return primeincFindPrimeWithWorkers(bits, rng, options, callback); } - return rval; - }; - cert.sign = function(key, md) { - cert.md = md || forge.md.sha1.create(); - var algorithmOid = oids[cert.md.algorithm + "WithRSAEncryption"]; - if (!algorithmOid) { - var error4 = new Error("Could not compute certificate digest. Unknown message digest algorithm OID."); - error4.algorithm = cert.md.algorithm; - throw error4; + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + } + function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { + var num = generateRandom(bits, rng); + var deltaIdx = 0; + var mrTests = getMillerRabinTests(num.bitLength()); + if ("millerRabinTests" in options) { + mrTests = options.millerRabinTests; } - cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; - cert.tbsCertificate = pki2.getTBSCertificate(cert); - var bytes = asn1.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); - cert.signature = key.sign(cert.md); - }; - cert.verify = function(child) { - var rval = false; - if (!cert.issued(child)) { - var issuer = child.issuer; - var subject = cert.subject; - var error4 = new Error( - "The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject." - ); - error4.expectedIssuer = subject.attributes; - error4.actualIssuer = issuer.attributes; - throw error4; + var maxBlockTime = 10; + if ("maxBlockTime" in options) { + maxBlockTime = options.maxBlockTime; } - var md = child.md; - if (md === null) { - md = _createSignatureDigest({ - signatureOid: child.signatureOid, - type: "certificate" - }); - var tbsCertificate = child.tbsCertificate || pki2.getTBSCertificate(child); - var bytes = asn1.toDer(tbsCertificate); - md.update(bytes.getBytes()); + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + } + function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { + var start = +/* @__PURE__ */ new Date(); + do { + if (num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + if (num.isProbablePrime(mrTests)) { + return callback(null, num); + } + num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } while (maxBlockTime < 0 || +/* @__PURE__ */ new Date() - start < maxBlockTime); + forge.util.setImmediate(function() { + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + }); + } + function primeincFindPrimeWithWorkers(bits, rng, options, callback) { + if (typeof Worker === "undefined") { + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); } - if (md !== null) { - rval = _verifySignature({ - certificate: cert, - md, - signature: child.signature + var num = generateRandom(bits, rng); + var numWorkers = options.workers; + var workLoad = options.workLoad || 100; + var range = workLoad * 30 / 8; + var workerScript = options.workerScript || "forge/prime.worker.js"; + if (numWorkers === -1) { + return forge.util.estimateCores(function(err, cores) { + if (err) { + cores = 2; + } + numWorkers = cores - 1; + generate(); }); } - return rval; - }; - cert.isIssuer = function(parent) { - var rval = false; - var i = cert.issuer; - var s = parent.subject; - if (i.hash && s.hash) { - rval = i.hash === s.hash; - } else if (i.attributes.length === s.attributes.length) { - rval = true; - var iattr, sattr; - for (var n = 0; rval && n < i.attributes.length; ++n) { - iattr = i.attributes[n]; - sattr = s.attributes[n]; - if (iattr.type !== sattr.type || iattr.value !== sattr.value) { - rval = false; + generate(); + function generate() { + numWorkers = Math.max(1, numWorkers); + var workers = []; + for (var i = 0; i < numWorkers; ++i) { + workers[i] = new Worker(workerScript); + } + var running = numWorkers; + for (var i = 0; i < numWorkers; ++i) { + workers[i].addEventListener("message", workerMessage); + } + var found = false; + function workerMessage(e) { + if (found) { + return; + } + --running; + var data = e.data; + if (data.found) { + for (var i2 = 0; i2 < workers.length; ++i2) { + workers[i2].terminate(); + } + found = true; + return callback(null, new BigInteger(data.prime, 16)); + } + if (num.bitLength() > bits) { + num = generateRandom(bits, rng); } + var hex = num.toString(16); + e.target.postMessage({ + hex, + workLoad + }); + num.dAddOffset(range, 0); } } - return rval; - }; - cert.issued = function(child) { - return child.isIssuer(cert); - }; - cert.generateSubjectKeyIdentifier = function() { - return pki2.getPublicKeyFingerprint(cert.publicKey, { type: "RSAPublicKey" }); - }; - cert.verifySubjectKeyIdentifier = function() { - var oid = oids["subjectKeyIdentifier"]; - for (var i = 0; i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if (ext.id === oid) { - var ski = cert.generateSubjectKeyIdentifier().getBytes(); - return forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski; - } + } + function generateRandom(bits, rng) { + var num = new BigInteger(bits, rng); + var bits1 = bits - 1; + if (!num.testBit(bits1)) { + num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); } - return false; - }; - return cert; + num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); + return num; + } + function getMillerRabinTests(bits) { + if (bits <= 100) return 27; + if (bits <= 150) return 18; + if (bits <= 200) return 15; + if (bits <= 250) return 12; + if (bits <= 300) return 9; + if (bits <= 350) return 8; + if (bits <= 400) return 7; + if (bits <= 500) return 6; + if (bits <= 600) return 5; + if (bits <= 800) return 4; + if (bits <= 1250) return 3; + return 2; + } + })(); + } +}); + +// node_modules/node-forge/lib/rsa.js +var require_rsa = __commonJS({ + "node_modules/node-forge/lib/rsa.js"(exports2, module2) { + var forge = require_forge(); + require_asn1(); + require_jsbn(); + require_oids(); + require_pkcs1(); + require_prime(); + require_random(); + require_util8(); + if (typeof BigInteger === "undefined") { + BigInteger = forge.jsbn.BigInteger; + } + var BigInteger; + var _crypto = forge.util.isNodejs ? require("crypto") : null; + var asn1 = forge.asn1; + var util = forge.util; + forge.pki = forge.pki || {}; + module2.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; + var pki2 = forge.pki; + var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + var privateKeyValidator = { + // PrivateKeyInfo + name: "PrivateKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: "PrivateKeyInfo.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyVersion" + }, { + // privateKeyAlgorithm + name: "PrivateKeyInfo.privateKeyAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "privateKeyOid" + }] + }, { + // PrivateKey + name: "PrivateKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "privateKey" + }] }; - pki2.certificateFromAsn1 = function(obj, computeHash) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) { - var error4 = new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate."); - error4.errors = errors; + var rsaPrivateKeyValidator = { + // RSAPrivateKey + name: "RSAPrivateKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: "RSAPrivateKey.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyVersion" + }, { + // modulus (n) + name: "RSAPrivateKey.modulus", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyModulus" + }, { + // publicExponent (e) + name: "RSAPrivateKey.publicExponent", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyPublicExponent" + }, { + // privateExponent (d) + name: "RSAPrivateKey.privateExponent", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyPrivateExponent" + }, { + // prime1 (p) + name: "RSAPrivateKey.prime1", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyPrime1" + }, { + // prime2 (q) + name: "RSAPrivateKey.prime2", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyPrime2" + }, { + // exponent1 (d mod (p-1)) + name: "RSAPrivateKey.exponent1", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyExponent1" + }, { + // exponent2 (d mod (q-1)) + name: "RSAPrivateKey.exponent2", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyExponent2" + }, { + // coefficient ((inverse of q) mod p) + name: "RSAPrivateKey.coefficient", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyCoefficient" + }] + }; + var rsaPublicKeyValidator = { + // RSAPublicKey + name: "RSAPublicKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // modulus (n) + name: "RSAPublicKey.modulus", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "publicKeyModulus" + }, { + // publicExponent (e) + name: "RSAPublicKey.exponent", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "publicKeyExponent" + }] + }; + var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { + name: "SubjectPublicKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "subjectPublicKeyInfo", + value: [{ + name: "SubjectPublicKeyInfo.AlgorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "publicKeyOid" + }] + }, { + // subjectPublicKey + name: "SubjectPublicKeyInfo.subjectPublicKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: "SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: "rsaPublicKey" + }] + }] + }; + var digestInfoValidator = { + name: "DigestInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "DigestInfo.DigestAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "DigestInfo.DigestAlgorithm.algorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "algorithmIdentifier" + }, { + // NULL paramters + name: "DigestInfo.DigestAlgorithm.parameters", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.NULL, + // captured only to check existence for md2 and md5 + capture: "parameters", + optional: true, + constructed: false + }] + }, { + // digest + name: "DigestInfo.digest", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "digest" + }] + }; + var emsaPkcs1v15encode = function(md) { + var oid; + if (md.algorithm in pki2.oids) { + oid = pki2.oids[md.algorithm]; + } else { + var error4 = new Error("Unknown message digest algorithm."); + error4.algorithm = md.algorithm; throw error4; } - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki2.oids.rsaEncryption) { - throw new Error("Cannot read public key. OID is not RSA."); - } - var cert = pki2.createCertificate(); - cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0; - var serial = forge.util.createBuffer(capture.certSerialNumber); - cert.serialNumber = serial.toHex(); - cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid); - cert.signatureParameters = _readSignatureParameters( - cert.signatureOid, - capture.certSignatureParams, - true + var oidBytes = asn1.oidToDer(oid).getBytes(); + var digestInfo = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] ); - cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid); - cert.siginfo.parameters = _readSignatureParameters( - cert.siginfo.algorithmOid, - capture.certinfoSignatureParams, - false + var digestAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] ); - cert.signature = capture.certSignature; - var validity = []; - if (capture.certValidity1UTCTime !== void 0) { - validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); - } - if (capture.certValidity2GeneralizedTime !== void 0) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity2GeneralizedTime - )); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + oidBytes + )); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.NULL, + false, + "" + )); + var digest = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + md.digest().getBytes() + ); + digestInfo.value.push(digestAlgorithm); + digestInfo.value.push(digest); + return asn1.toDer(digestInfo).getBytes(); + }; + var _modPow = function(x, key, pub) { + if (pub) { + return x.modPow(key.e, key.n); } - if (capture.certValidity3UTCTime !== void 0) { - validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); + if (!key.p || !key.q) { + return x.modPow(key.d, key.n); } - if (capture.certValidity4GeneralizedTime !== void 0) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity4GeneralizedTime - )); + if (!key.dP) { + key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); } - if (validity.length > 2) { - throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate."); + if (!key.dQ) { + key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); } - if (validity.length < 2) { - throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime."); + if (!key.qInv) { + key.qInv = key.q.modInverse(key.p); } - cert.validity.notBefore = validity[0]; - cert.validity.notAfter = validity[1]; - cert.tbsCertificate = capture.tbsCertificate; - if (computeHash) { - cert.md = _createSignatureDigest({ - signatureOid: cert.signatureOid, - type: "certificate" - }); - var bytes = asn1.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); + var r; + do { + r = new BigInteger( + forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), + 16 + ); + } while (r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); + x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); + var xp = x.mod(key.p).modPow(key.dP, key.p); + var xq = x.mod(key.q).modPow(key.dQ, key.q); + while (xp.compareTo(xq) < 0) { + xp = xp.add(key.p); } - var imd = forge.md.sha1.create(); - var ibytes = asn1.toDer(capture.certIssuer); - imd.update(ibytes.getBytes()); - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = pki2.RDNAttributesAsArray(capture.certIssuer); - if (capture.certIssuerUniqueId) { - cert.issuer.uniqueId = capture.certIssuerUniqueId; + var y = xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq); + y = y.multiply(r.modInverse(key.n)).mod(key.n); + return y; + }; + pki2.rsa.encrypt = function(m, key, bt) { + var pub = bt; + var eb; + var k = Math.ceil(key.n.bitLength() / 8); + if (bt !== false && bt !== true) { + pub = bt === 2; + eb = _encodePkcs1_v1_5(m, key, bt); + } else { + eb = forge.util.createBuffer(); + eb.putBytes(m); } - cert.issuer.hash = imd.digest().toHex(); - var smd = forge.md.sha1.create(); - var sbytes = asn1.toDer(capture.certSubject); - smd.update(sbytes.getBytes()); - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = pki2.RDNAttributesAsArray(capture.certSubject); - if (capture.certSubjectUniqueId) { - cert.subject.uniqueId = capture.certSubjectUniqueId; + var x = new BigInteger(eb.toHex(), 16); + var y = _modPow(x, key, pub); + var yhex = y.toString(16); + var ed = forge.util.createBuffer(); + var zeros = k - Math.ceil(yhex.length / 2); + while (zeros > 0) { + ed.putByte(0); + --zeros; } - cert.subject.hash = smd.digest().toHex(); - if (capture.certExtensions) { - cert.extensions = pki2.certificateExtensionsFromAsn1(capture.certExtensions); - } else { - cert.extensions = []; + ed.putBytes(forge.util.hexToBytes(yhex)); + return ed.getBytes(); + }; + pki2.rsa.decrypt = function(ed, key, pub, ml) { + var k = Math.ceil(key.n.bitLength() / 8); + if (ed.length !== k) { + var error4 = new Error("Encrypted message length is invalid."); + error4.length = ed.length; + error4.expected = k; + throw error4; } - cert.publicKey = pki2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - return cert; + var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); + if (y.compareTo(key.n) >= 0) { + throw new Error("Encrypted message is invalid."); + } + var x = _modPow(y, key, pub); + var xhex = x.toString(16); + var eb = forge.util.createBuffer(); + var zeros = k - Math.ceil(xhex.length / 2); + while (zeros > 0) { + eb.putByte(0); + --zeros; + } + eb.putBytes(forge.util.hexToBytes(xhex)); + if (ml !== false) { + return _decodePkcs1_v1_5(eb.getBytes(), key, pub); + } + return eb.getBytes(); }; - pki2.certificateExtensionsFromAsn1 = function(exts) { - var rval = []; - for (var i = 0; i < exts.value.length; ++i) { - var extseq = exts.value[i]; - for (var ei = 0; ei < extseq.value.length; ++ei) { - rval.push(pki2.certificateExtensionFromAsn1(extseq.value[ei])); + pki2.rsa.createKeyPairGenerationState = function(bits, e, options) { + if (typeof bits === "string") { + bits = parseInt(bits, 10); + } + bits = bits || 2048; + options = options || {}; + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for (var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } } + }; + var algorithm = options.algorithm || "PRIMEINC"; + var rval; + if (algorithm === "PRIMEINC") { + rval = { + algorithm, + state: 0, + bits, + rng, + eInt: e || 65537, + e: new BigInteger(null), + p: null, + q: null, + qBits: bits >> 1, + pBits: bits - (bits >> 1), + pqState: 0, + num: null, + keys: null + }; + rval.e.fromInt(rval.eInt); + } else { + throw new Error("Invalid key generation algorithm: " + algorithm); } return rval; }; - pki2.certificateExtensionFromAsn1 = function(ext) { - var e = {}; - e.id = asn1.derToOid(ext.value[0].value); - e.critical = false; - if (ext.value[1].type === asn1.Type.BOOLEAN) { - e.critical = ext.value[1].value.charCodeAt(0) !== 0; - e.value = ext.value[2].value; - } else { - e.value = ext.value[1].value; + pki2.rsa.stepKeyPairGenerationState = function(state, n) { + if (!("algorithm" in state)) { + state.algorithm = "PRIMEINC"; } - if (e.id in oids) { - e.name = oids[e.id]; - if (e.name === "keyUsage") { - var ev = asn1.fromDer(e.value); - var b2 = 0; - var b3 = 0; - if (ev.value.length > 1) { - b2 = ev.value.charCodeAt(1); - b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; + var THIRTY = new BigInteger(null); + THIRTY.fromInt(30); + var deltaIdx = 0; + var op_or = function(x, y) { + return x | y; + }; + var t1 = +/* @__PURE__ */ new Date(); + var t2; + var total = 0; + while (state.keys === null && (n <= 0 || total < n)) { + if (state.state === 0) { + var bits = state.p === null ? state.pBits : state.qBits; + var bits1 = bits - 1; + if (state.pqState === 0) { + state.num = new BigInteger(bits, state.rng); + if (!state.num.testBit(bits1)) { + state.num.bitwiseTo( + BigInteger.ONE.shiftLeft(bits1), + op_or, + state.num + ); + } + state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); + deltaIdx = 0; + ++state.pqState; + } else if (state.pqState === 1) { + if (state.num.bitLength() > bits) { + state.pqState = 0; + } else if (state.num.isProbablePrime( + _getMillerRabinTests(state.num.bitLength()) + )) { + ++state.pqState; + } else { + state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } + } else if (state.pqState === 2) { + state.pqState = state.num.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) === 0 ? 3 : 0; + } else if (state.pqState === 3) { + state.pqState = 0; + if (state.p === null) { + state.p = state.num; + } else { + state.q = state.num; + } + if (state.p !== null && state.q !== null) { + ++state.state; + } + state.num = null; } - e.digitalSignature = (b2 & 128) === 128; - e.nonRepudiation = (b2 & 64) === 64; - e.keyEncipherment = (b2 & 32) === 32; - e.dataEncipherment = (b2 & 16) === 16; - e.keyAgreement = (b2 & 8) === 8; - e.keyCertSign = (b2 & 4) === 4; - e.cRLSign = (b2 & 2) === 2; - e.encipherOnly = (b2 & 1) === 1; - e.decipherOnly = (b3 & 128) === 128; - } else if (e.name === "basicConstraints") { - var ev = asn1.fromDer(e.value); - if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { - e.cA = ev.value[0].value.charCodeAt(0) !== 0; + } else if (state.state === 1) { + if (state.p.compareTo(state.q) < 0) { + state.num = state.p; + state.p = state.q; + state.q = state.num; + } + ++state.state; + } else if (state.state === 2) { + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + ++state.state; + } else if (state.state === 3) { + if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { + ++state.state; } else { - e.cA = false; + state.p = null; + state.q = null; + state.state = 0; } - var value = null; - if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { - value = ev.value[0].value; - } else if (ev.value.length > 1) { - value = ev.value[1].value; + } else if (state.state === 4) { + state.n = state.p.multiply(state.q); + if (state.n.bitLength() === state.bits) { + ++state.state; + } else { + state.q = null; + state.state = 0; } - if (value !== null) { - e.pathLenConstraint = asn1.derToInteger(value); + } else if (state.state === 5) { + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki2.rsa.setPrivateKey( + state.n, + state.e, + d, + state.p, + state.q, + d.mod(state.p1), + d.mod(state.q1), + state.q.modInverse(state.p) + ), + publicKey: pki2.rsa.setPublicKey(state.n, state.e) + }; + } + t2 = +/* @__PURE__ */ new Date(); + total += t2 - t1; + t1 = t2; + } + return state.keys !== null; + }; + pki2.rsa.generateKeyPair = function(bits, e, options, callback) { + if (arguments.length === 1) { + if (typeof bits === "object") { + options = bits; + bits = void 0; + } else if (typeof bits === "function") { + callback = bits; + bits = void 0; + } + } else if (arguments.length === 2) { + if (typeof bits === "number") { + if (typeof e === "function") { + callback = e; + e = void 0; + } else if (typeof e !== "number") { + options = e; + e = void 0; } - } else if (e.name === "extKeyUsage") { - var ev = asn1.fromDer(e.value); - for (var vi = 0; vi < ev.value.length; ++vi) { - var oid = asn1.derToOid(ev.value[vi].value); - if (oid in oids) { - e[oids[oid]] = true; - } else { - e[oid] = true; - } + } else { + options = bits; + callback = e; + bits = void 0; + e = void 0; + } + } else if (arguments.length === 3) { + if (typeof e === "number") { + if (typeof options === "function") { + callback = options; + options = void 0; } - } else if (e.name === "nsCertType") { - var ev = asn1.fromDer(e.value); - var b2 = 0; - if (ev.value.length > 1) { - b2 = ev.value.charCodeAt(1); + } else { + callback = options; + options = e; + e = void 0; + } + } + options = options || {}; + if (bits === void 0) { + bits = options.bits || 2048; + } + if (e === void 0) { + e = options.e || 65537; + } + if (!forge.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e === 65537 || e === 3)) { + if (callback) { + if (_detectNodeCrypto("generateKeyPair")) { + return _crypto.generateKeyPair("rsa", { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: "spki", + format: "pem" + }, + privateKeyEncoding: { + type: "pkcs8", + format: "pem" + } + }, function(err, pub, priv) { + if (err) { + return callback(err); + } + callback(null, { + privateKey: pki2.privateKeyFromPem(priv), + publicKey: pki2.publicKeyFromPem(pub) + }); + }); } - e.client = (b2 & 128) === 128; - e.server = (b2 & 64) === 64; - e.email = (b2 & 32) === 32; - e.objsign = (b2 & 16) === 16; - e.reserved = (b2 & 8) === 8; - e.sslCA = (b2 & 4) === 4; - e.emailCA = (b2 & 2) === 2; - e.objCA = (b2 & 1) === 1; - } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { - e.altNames = []; - var gn; - var ev = asn1.fromDer(e.value); - for (var n = 0; n < ev.value.length; ++n) { - gn = ev.value[n]; - var altName = { - type: gn.type, - value: gn.value + if (_detectSubtleCrypto("generateKey") && _detectSubtleCrypto("exportKey")) { + return util.globalScope.crypto.subtle.generateKey({ + name: "RSASSA-PKCS1-v1_5", + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: { name: "SHA-256" } + }, true, ["sign", "verify"]).then(function(pair) { + return util.globalScope.crypto.subtle.exportKey( + "pkcs8", + pair.privateKey + ); + }).then(void 0, function(err) { + callback(err); + }).then(function(pkcs8) { + if (pkcs8) { + var privateKey = pki2.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8)) + ); + callback(null, { + privateKey, + publicKey: pki2.setRsaPublicKey(privateKey.n, privateKey.e) + }); + } + }); + } + if (_detectSubtleMsCrypto("generateKey") && _detectSubtleMsCrypto("exportKey")) { + var genOp = util.globalScope.msCrypto.subtle.generateKey({ + name: "RSASSA-PKCS1-v1_5", + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: { name: "SHA-256" } + }, true, ["sign", "verify"]); + genOp.oncomplete = function(e2) { + var pair = e2.target.result; + var exportOp = util.globalScope.msCrypto.subtle.exportKey( + "pkcs8", + pair.privateKey + ); + exportOp.oncomplete = function(e3) { + var pkcs8 = e3.target.result; + var privateKey = pki2.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8)) + ); + callback(null, { + privateKey, + publicKey: pki2.setRsaPublicKey(privateKey.n, privateKey.e) + }); + }; + exportOp.onerror = function(err) { + callback(err); + }; + }; + genOp.onerror = function(err) { + callback(err); + }; + return; + } + } else { + if (_detectNodeCrypto("generateKeyPairSync")) { + var keypair = _crypto.generateKeyPairSync("rsa", { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: "spki", + format: "pem" + }, + privateKeyEncoding: { + type: "pkcs8", + format: "pem" + } + }); + return { + privateKey: pki2.privateKeyFromPem(keypair.privateKey), + publicKey: pki2.publicKeyFromPem(keypair.publicKey) }; - e.altNames.push(altName); - switch (gn.type) { - // rfc822Name - case 1: - // dNSName - case 2: - // uniformResourceIdentifier (URI) - case 6: - break; - // IPAddress - case 7: - altName.ip = forge.util.bytesToIP(gn.value); - break; - // registeredID - case 8: - altName.oid = asn1.derToOid(gn.value); - break; - default: - } } - } else if (e.name === "subjectKeyIdentifier") { - var ev = asn1.fromDer(e.value); - e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value); } } - return e; - }; - pki2.certificationRequestFromAsn1 = function(obj, computeHash) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) { - var error4 = new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest."); - error4.errors = errors; - throw error4; - } - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki2.oids.rsaEncryption) { - throw new Error("Cannot read public key. OID is not RSA."); - } - var csr = pki2.createCertificationRequest(); - csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; - csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid); - csr.signatureParameters = _readSignatureParameters( - csr.signatureOid, - capture.csrSignatureParams, - true - ); - csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid); - csr.siginfo.parameters = _readSignatureParameters( - csr.siginfo.algorithmOid, - capture.csrSignatureParams, - false - ); - csr.signature = capture.csrSignature; - csr.certificationRequestInfo = capture.certificationRequestInfo; - if (computeHash) { - csr.md = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: "certification request" - }); - var bytes = asn1.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); + var state = pki2.rsa.createKeyPairGenerationState(bits, e, options); + if (!callback) { + pki2.rsa.stepKeyPairGenerationState(state, 0); + return state.keys; } - var smd = forge.md.sha1.create(); - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = pki2.RDNAttributesAsArray( - capture.certificationRequestInfoSubject, - smd - ); - csr.subject.hash = smd.digest().toHex(); - csr.publicKey = pki2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.attributes = pki2.CRIAttributesAsArray( - capture.certificationRequestInfoAttributes || [] - ); - return csr; + _generateKeyPair(state, options, callback); }; - pki2.createCertificationRequest = function() { - var csr = {}; - csr.version = 0; - csr.signatureOid = null; - csr.signature = null; - csr.siginfo = {}; - csr.siginfo.algorithmOid = null; - csr.subject = {}; - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = []; - csr.subject.hash = null; - csr.publicKey = null; - csr.attributes = []; - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.md = null; - csr.setSubject = function(attrs) { - _fillMissingFields(attrs); - csr.subject.attributes = attrs; - csr.subject.hash = null; - }; - csr.setAttributes = function(attrs) { - _fillMissingFields(attrs); - csr.attributes = attrs; - }; - csr.sign = function(key, md) { - csr.md = md || forge.md.sha1.create(); - var algorithmOid = oids[csr.md.algorithm + "WithRSAEncryption"]; - if (!algorithmOid) { - var error4 = new Error("Could not compute certification request digest. Unknown message digest algorithm OID."); - error4.algorithm = csr.md.algorithm; - throw error4; - } - csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; - csr.certificationRequestInfo = pki2.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); - csr.signature = key.sign(csr.md); + pki2.setRsaPublicKey = pki2.rsa.setPublicKey = function(n, e) { + var key = { + n, + e }; - csr.verify = function() { - var rval = false; - var md = csr.md; - if (md === null) { - md = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: "certification request" - }); - var cri = csr.certificationRequestInfo || pki2.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(cri); - md.update(bytes.getBytes()); + key.encrypt = function(data, scheme, schemeOptions) { + if (typeof scheme === "string") { + scheme = scheme.toUpperCase(); + } else if (scheme === void 0) { + scheme = "RSAES-PKCS1-V1_5"; } - if (md !== null) { - rval = _verifySignature({ - certificate: csr, - md, - signature: csr.signature - }); + if (scheme === "RSAES-PKCS1-V1_5") { + scheme = { + encode: function(m, key2, pub) { + return _encodePkcs1_v1_5(m, key2, 2).getBytes(); + } + }; + } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { + scheme = { + encode: function(m, key2) { + return forge.pkcs1.encode_rsa_oaep(key2, m, schemeOptions); + } + }; + } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { + scheme = { encode: function(e3) { + return e3; + } }; + } else if (typeof scheme === "string") { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); } - return rval; + var e2 = scheme.encode(data, key, true); + return pki2.rsa.encrypt(e2, key, true); }; - return csr; - }; - function _dnToAsn1(obj) { - var rval = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var attr, set2; - var attrs = obj.attributes; - for (var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - var value = attr.value; - var valueTagClass = asn1.Type.PRINTABLESTRING; - if ("valueTagClass" in attr) { - valueTagClass = attr.valueTagClass; - if (valueTagClass === asn1.Type.UTF8) { - value = forge.util.encodeUtf8(value); - } - } - set2 = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - // AttributeValue - asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) - ]) - ]); - rval.value.push(set2); - } - return rval; - } - function _fillMissingFields(attrs) { - var attr; - for (var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - if (typeof attr.name === "undefined") { - if (attr.type && attr.type in pki2.oids) { - attr.name = pki2.oids[attr.type]; - } else if (attr.shortName && attr.shortName in _shortNames) { - attr.name = pki2.oids[_shortNames[attr.shortName]]; - } + key.verify = function(digest, signature, scheme, options) { + if (typeof scheme === "string") { + scheme = scheme.toUpperCase(); + } else if (scheme === void 0) { + scheme = "RSASSA-PKCS1-V1_5"; } - if (typeof attr.type === "undefined") { - if (attr.name && attr.name in pki2.oids) { - attr.type = pki2.oids[attr.name]; - } else { - var error4 = new Error("Attribute type not specified."); - error4.attribute = attr; - throw error4; - } + if (options === void 0) { + options = { + _parseAllDigestBytes: true + }; } - if (typeof attr.shortName === "undefined") { - if (attr.name && attr.name in _shortNames) { - attr.shortName = _shortNames[attr.name]; - } + if (!("_parseAllDigestBytes" in options)) { + options._parseAllDigestBytes = true; } - if (attr.type === oids.extensionRequest) { - attr.valueConstructed = true; - attr.valueTagClass = asn1.Type.SEQUENCE; - if (!attr.value && attr.extensions) { - attr.value = []; - for (var ei = 0; ei < attr.extensions.length; ++ei) { - attr.value.push(pki2.certificateExtensionToAsn1( - _fillMissingExtensionFields(attr.extensions[ei]) - )); + if (scheme === "RSASSA-PKCS1-V1_5") { + scheme = { + verify: function(digest2, d2) { + d2 = _decodePkcs1_v1_5(d2, key, true); + var obj = asn1.fromDer(d2, { + parseAllBytes: options._parseAllDigestBytes + }); + var capture = {}; + var errors = []; + if (!asn1.validate(obj, digestInfoValidator, capture, errors)) { + var error4 = new Error( + "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value." + ); + error4.errors = errors; + throw error4; + } + var oid = asn1.derToOid(capture.algorithmIdentifier); + if (!(oid === forge.oids.md2 || oid === forge.oids.md5 || oid === forge.oids.sha1 || oid === forge.oids.sha224 || oid === forge.oids.sha256 || oid === forge.oids.sha384 || oid === forge.oids.sha512 || oid === forge.oids["sha512-224"] || oid === forge.oids["sha512-256"])) { + var error4 = new Error( + "Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier." + ); + error4.oid = oid; + throw error4; + } + if (oid === forge.oids.md2 || oid === forge.oids.md5) { + if (!("parameters" in capture)) { + throw new Error( + "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters." + ); + } + } + return digest2 === capture.digest; } - } - } - if (typeof attr.value === "undefined") { - var error4 = new Error("Attribute value not specified."); - error4.attribute = attr; - throw error4; + }; + } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { + scheme = { + verify: function(digest2, d2) { + d2 = _decodePkcs1_v1_5(d2, key, true); + return digest2 === d2; + } + }; } - } - } - function _fillMissingExtensionFields(e, options) { - options = options || {}; - if (typeof e.name === "undefined") { - if (e.id && e.id in pki2.oids) { - e.name = pki2.oids[e.id]; + var d = pki2.rsa.decrypt(signature, key, true, false); + return scheme.verify(digest, d, key.n.bitLength()); + }; + return key; + }; + pki2.setRsaPrivateKey = pki2.rsa.setPrivateKey = function(n, e, d, p, q, dP, dQ, qInv) { + var key = { + n, + e, + d, + p, + q, + dP, + dQ, + qInv + }; + key.decrypt = function(data, scheme, schemeOptions) { + if (typeof scheme === "string") { + scheme = scheme.toUpperCase(); + } else if (scheme === void 0) { + scheme = "RSAES-PKCS1-V1_5"; } - } - if (typeof e.id === "undefined") { - if (e.name && e.name in pki2.oids) { - e.id = pki2.oids[e.name]; + var d2 = pki2.rsa.decrypt(data, key, false, false); + if (scheme === "RSAES-PKCS1-V1_5") { + scheme = { decode: _decodePkcs1_v1_5 }; + } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { + scheme = { + decode: function(d3, key2) { + return forge.pkcs1.decode_rsa_oaep(key2, d3, schemeOptions); + } + }; + } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { + scheme = { decode: function(d3) { + return d3; + } }; } else { - var error4 = new Error("Extension ID not specified."); - error4.extension = e; - throw error4; - } - } - if (typeof e.value !== "undefined") { - return e; - } - if (e.name === "keyUsage") { - var unused = 0; - var b2 = 0; - var b3 = 0; - if (e.digitalSignature) { - b2 |= 128; - unused = 7; - } - if (e.nonRepudiation) { - b2 |= 64; - unused = 6; - } - if (e.keyEncipherment) { - b2 |= 32; - unused = 5; - } - if (e.dataEncipherment) { - b2 |= 16; - unused = 4; - } - if (e.keyAgreement) { - b2 |= 8; - unused = 3; - } - if (e.keyCertSign) { - b2 |= 4; - unused = 2; - } - if (e.cRLSign) { - b2 |= 2; - unused = 1; - } - if (e.encipherOnly) { - b2 |= 1; - unused = 0; + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); } - if (e.decipherOnly) { - b3 |= 128; - unused = 7; + return scheme.decode(d2, key, false); + }; + key.sign = function(md, scheme) { + var bt = false; + if (typeof scheme === "string") { + scheme = scheme.toUpperCase(); } - var value = String.fromCharCode(unused); - if (b3 !== 0) { - value += String.fromCharCode(b2) + String.fromCharCode(b3); - } else if (b2 !== 0) { - value += String.fromCharCode(b2); + if (scheme === void 0 || scheme === "RSASSA-PKCS1-V1_5") { + scheme = { encode: emsaPkcs1v15encode }; + bt = 1; + } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { + scheme = { encode: function() { + return md; + } }; + bt = 1; } - e.value = asn1.create( + var d2 = scheme.encode(md, key.n.bitLength()); + return pki2.rsa.encrypt(d2, key, bt); + }; + return key; + }; + pki2.wrapRsaPrivateKey = function(rsaKey) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0) + asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, + asn1.Type.INTEGER, false, - value - ); - } else if (e.name === "basicConstraints") { - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - if (e.cA) { - e.value.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BOOLEAN, - false, - String.fromCharCode(255) - )); - } - if ("pathLenConstraint" in e) { - e.value.value.push(asn1.create( + asn1.integerToDer(0).getBytes() + ), + // privateKeyAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, + asn1.Type.OID, false, - asn1.integerToDer(e.pathLenConstraint).getBytes() - )); - } - } else if (e.name === "extKeyUsage") { - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var seq2 = e.value.value; - for (var key in e) { - if (e[key] !== true) { - continue; - } - if (key in oids) { - seq2.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids[key]).getBytes() - )); - } else if (key.indexOf(".") !== -1) { - seq2.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(key).getBytes() - )); - } - } - } else if (e.name === "nsCertType") { - var unused = 0; - var b2 = 0; - if (e.client) { - b2 |= 128; - unused = 7; - } - if (e.server) { - b2 |= 64; - unused = 6; - } - if (e.email) { - b2 |= 32; - unused = 5; - } - if (e.objsign) { - b2 |= 16; - unused = 4; - } - if (e.reserved) { - b2 |= 8; - unused = 3; - } - if (e.sslCA) { - b2 |= 4; - unused = 2; - } - if (e.emailCA) { - b2 |= 2; - unused = 1; - } - if (e.objCA) { - b2 |= 1; - unused = 0; - } - var value = String.fromCharCode(unused); - if (b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1.create( + asn1.oidToDer(pki2.oids.rsaEncryption).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]), + // PrivateKey + asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, + asn1.Type.OCTETSTRING, false, - value - ); - } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var altName; - for (var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - if (altName.type === 7 && altName.ip) { - value = forge.util.bytesFromIP(altName.ip); - if (value === null) { - var error4 = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.' - ); - error4.extension = e; - throw error4; - } - } else if (altName.type === 8) { - if (altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - value = asn1.oidToDer(value); - } - } - e.value.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - altName.type, - false, - value - )); - } - } else if (e.name === "nsComment" && options.cert) { - if (!/^[\x00-\x7F]*$/.test(e.comment) || e.comment.length < 1 || e.comment.length > 128) { - throw new Error('Invalid "nsComment" content.'); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.IA5STRING, + asn1.toDer(rsaKey).getBytes() + ) + ]); + }; + pki2.privateKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + if (asn1.validate(obj, privateKeyValidator, capture, errors)) { + obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); + } + capture = {}; + errors = []; + if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { + var error4 = new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey."); + error4.errors = errors; + throw error4; + } + var n, e, d, p, q, dP, dQ, qInv; + n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); + e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); + d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); + p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); + q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); + dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); + dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); + qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); + return pki2.setRsaPrivateKey( + new BigInteger(n, 16), + new BigInteger(e, 16), + new BigInteger(d, 16), + new BigInteger(p, 16), + new BigInteger(q, 16), + new BigInteger(dP, 16), + new BigInteger(dQ, 16), + new BigInteger(qInv, 16) + ); + }; + pki2.privateKeyToAsn1 = pki2.privateKeyToRSAPrivateKey = function(key) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0 = only 2 primes, 1 multiple primes) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, false, - e.comment - ); - } else if (e.name === "subjectKeyIdentifier" && options.cert) { - var ski = options.cert.generateSubjectKeyIdentifier(); - e.subjectKeyIdentifier = ski.toHex(); - e.value = asn1.create( + asn1.integerToDer(0).getBytes() + ), + // modulus (n) + asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, + asn1.Type.INTEGER, false, - ski.getBytes() - ); - } else if (e.name === "authorityKeyIdentifier" && options.cert) { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq2 = e.value.value; - if (e.keyIdentifier) { - var keyIdentifier = e.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e.keyIdentifier; - seq2.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier) - ); - } - if (e.authorityCertIssuer) { - var authorityCertIssuer = [ - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ - _dnToAsn1(e.authorityCertIssuer === true ? options.cert.issuer : e.authorityCertIssuer) - ]) - ]; - seq2.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer) - ); - } - if (e.serialNumber) { - var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? options.cert.serialNumber : e.serialNumber); - seq2.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber) - ); - } - } else if (e.name === "cRLDistributionPoints") { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq2 = e.value.value; - var subSeq = asn1.create( + _bnToBytes(key.n) + ), + // publicExponent (e) + asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var fullNameGeneralNames = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [] - ); - var altName; - for (var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - if (altName.type === 7 && altName.ip) { - value = forge.util.bytesFromIP(altName.ip); - if (value === null) { - var error4 = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.' - ); - error4.extension = e; - throw error4; - } - } else if (altName.type === 8) { - if (altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - value = asn1.oidToDer(value); - } - } - fullNameGeneralNames.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - altName.type, - false, - value - )); - } - subSeq.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [fullNameGeneralNames] - )); - seq2.push(subSeq); - } - if (typeof e.value === "undefined") { - var error4 = new Error("Extension value not specified."); - error4.extension = e; - throw error4; - } - return e; - } - function _signatureParametersToAsn1(oid, params) { - switch (oid) { - case oids["RSASSA-PSS"]: - var parts = []; - if (params.hash.algorithmOid !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.hash.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ])); - } - if (params.mgf.algorithmOid !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.mgf.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ]) - ])); - } - if (params.saltLength !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(params.saltLength).getBytes() - ) - ])); - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); - default: - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ""); - } - } - function _CRIAttributesToAsn1(csr) { - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); - if (csr.attributes.length === 0) { - return rval; - } - var attrs = csr.attributes; - for (var i = 0; i < attrs.length; ++i) { - var attr = attrs[i]; - var value = attr.value; - var valueTagClass = asn1.Type.UTF8; - if ("valueTagClass" in attr) { - valueTagClass = attr.valueTagClass; - } - if (valueTagClass === asn1.Type.UTF8) { - value = forge.util.encodeUtf8(value); - } - var valueConstructed = false; - if ("valueConstructed" in attr) { - valueConstructed = attr.valueConstructed; - } - var seq2 = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - asn1.create( - asn1.Class.UNIVERSAL, - valueTagClass, - valueConstructed, - value - ) - ]) - ]); - rval.value.push(seq2); - } - return rval; - } - var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); - var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); - function _dateToAsn1(date) { - if (date >= jan_1_1950 && date < jan_1_2050) { - return asn1.create( + asn1.Type.INTEGER, + false, + _bnToBytes(key.e) + ), + // privateExponent (d) + asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.UTCTIME, + asn1.Type.INTEGER, false, - asn1.dateToUtcTime(date) - ); - } else { - return asn1.create( + _bnToBytes(key.d) + ), + // privateKeyPrime1 (p) + asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.GENERALIZEDTIME, + asn1.Type.INTEGER, false, - asn1.dateToGeneralizedTime(date) - ); - } - } - pki2.getTBSCertificate = function(cert) { - var notBefore = _dateToAsn1(cert.validity.notBefore); - var notAfter = _dateToAsn1(cert.validity.notAfter); - var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // integer - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(cert.version).getBytes() - ) - ]), - // serialNumber + _bnToBytes(key.p) + ), + // privateKeyPrime2 (q) asn1.create( asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - forge.util.hexToBytes(cert.serialNumber) + _bnToBytes(key.q) ), - // signature - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(cert.siginfo.algorithmOid).getBytes() - ), - // parameters - _signatureParametersToAsn1( - cert.siginfo.algorithmOid, - cert.siginfo.parameters - ) - ]), - // issuer - _dnToAsn1(cert.issuer), - // validity - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - notBefore, - notAfter - ]), - // subject - _dnToAsn1(cert.subject), - // SubjectPublicKeyInfo - pki2.publicKeyToAsn1(cert.publicKey) - ]); - if (cert.issuer.uniqueId) { - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0) + cert.issuer.uniqueId - ) - ]) - ); - } - if (cert.subject.uniqueId) { - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0) + cert.subject.uniqueId - ) - ]) - ); - } - if (cert.extensions.length > 0) { - tbs.value.push(pki2.certificateExtensionsToAsn1(cert.extensions)); - } - return tbs; - }; - pki2.getCertificationRequestInfo = function(csr) { - var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version + // privateKeyExponent1 (dP) asn1.create( asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(csr.version).getBytes() + _bnToBytes(key.dP) ), - // subject - _dnToAsn1(csr.subject), - // SubjectPublicKeyInfo - pki2.publicKeyToAsn1(csr.publicKey), - // attributes - _CRIAttributesToAsn1(csr) - ]); - return cri; - }; - pki2.distinguishedNameToAsn1 = function(dn) { - return _dnToAsn1(dn); - }; - pki2.certificateToAsn1 = function(cert) { - var tbsCertificate = cert.tbsCertificate || pki2.getTBSCertificate(cert); - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // TBSCertificate - tbsCertificate, - // AlgorithmIdentifier (signature algorithm) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(cert.signatureOid).getBytes() - ), - // parameters - _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) - ]), - // SignatureValue + // privateKeyExponent2 (dQ) asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, + asn1.Type.INTEGER, false, - String.fromCharCode(0) + cert.signature + _bnToBytes(key.dQ) + ), + // coefficient (qInv) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.qInv) ) ]); }; - pki2.certificateExtensionsToAsn1 = function(exts) { - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); - var seq2 = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - rval.value.push(seq2); - for (var i = 0; i < exts.length; ++i) { - seq2.value.push(pki2.certificateExtensionToAsn1(exts[i])); - } - return rval; - }; - pki2.certificateExtensionToAsn1 = function(ext) { - var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(ext.id).getBytes() - )); - if (ext.critical) { - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BOOLEAN, - false, - String.fromCharCode(255) - )); + pki2.publicKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + if (asn1.validate(obj, publicKeyValidator, capture, errors)) { + var oid = asn1.derToOid(capture.publicKeyOid); + if (oid !== pki2.oids.rsaEncryption) { + var error4 = new Error("Cannot read public key. Unknown OID."); + error4.oid = oid; + throw error4; + } + obj = capture.rsaPublicKey; } - var value = ext.value; - if (typeof ext.value !== "string") { - value = asn1.toDer(value).getBytes(); + errors = []; + if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { + var error4 = new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey."); + error4.errors = errors; + throw error4; } - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - value - )); - return extseq; + var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); + var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); + return pki2.setRsaPublicKey( + new BigInteger(n, 16), + new BigInteger(e, 16) + ); }; - pki2.certificationRequestToAsn1 = function(csr) { - var cri = csr.certificationRequestInfo || pki2.getCertificationRequestInfo(csr); + pki2.publicKeyToAsn1 = pki2.publicKeyToSubjectPublicKeyInfo = function(key) { return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // CertificationRequestInfo - cri, - // AlgorithmIdentifier (signature algorithm) + // AlgorithmIdentifier asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(csr.signatureOid).getBytes() + asn1.oidToDer(pki2.oids.rsaEncryption).getBytes() ), - // parameters - _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") ]), - // signature + // subjectPublicKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ + pki2.publicKeyToRSAPublicKey(key) + ]) + ]); + }; + pki2.publicKeyToRSAPublicKey = function(key) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // modulus (n) asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, + asn1.Type.INTEGER, false, - String.fromCharCode(0) + csr.signature + _bnToBytes(key.n) + ), + // publicExponent (e) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + _bnToBytes(key.e) ) ]); }; - pki2.createCaStore = function(certs) { - var caStore = { - // stored certificates - certs: {} - }; - caStore.getIssuer = function(cert2) { - var rval = getBySubject(cert2.issuer); - return rval; - }; - caStore.addCertificate = function(cert2) { - if (typeof cert2 === "string") { - cert2 = forge.pki.certificateFromPem(cert2); + function _encodePkcs1_v1_5(m, key, bt) { + var eb = forge.util.createBuffer(); + var k = Math.ceil(key.n.bitLength() / 8); + if (m.length > k - 11) { + var error4 = new Error("Message is too long for PKCS#1 v1.5 padding."); + error4.length = m.length; + error4.max = k - 11; + throw error4; + } + eb.putByte(0); + eb.putByte(bt); + var padNum = k - 3 - m.length; + var padByte; + if (bt === 0 || bt === 1) { + padByte = bt === 0 ? 0 : 255; + for (var i = 0; i < padNum; ++i) { + eb.putByte(padByte); } - ensureSubjectHasHash(cert2.subject); - if (!caStore.hasCertificate(cert2)) { - if (cert2.subject.hash in caStore.certs) { - var tmp = caStore.certs[cert2.subject.hash]; - if (!forge.util.isArray(tmp)) { - tmp = [tmp]; + } else { + while (padNum > 0) { + var numZeros = 0; + var padBytes = forge.random.getBytes(padNum); + for (var i = 0; i < padNum; ++i) { + padByte = padBytes.charCodeAt(i); + if (padByte === 0) { + ++numZeros; + } else { + eb.putByte(padByte); } - tmp.push(cert2); - caStore.certs[cert2.subject.hash] = tmp; - } else { - caStore.certs[cert2.subject.hash] = cert2; } + padNum = numZeros; } - }; - caStore.hasCertificate = function(cert2) { - if (typeof cert2 === "string") { - cert2 = forge.pki.certificateFromPem(cert2); - } - var match = getBySubject(cert2.subject); - if (!match) { - return false; - } - if (!forge.util.isArray(match)) { - match = [match]; - } - var der1 = asn1.toDer(pki2.certificateToAsn1(cert2)).getBytes(); - for (var i2 = 0; i2 < match.length; ++i2) { - var der2 = asn1.toDer(pki2.certificateToAsn1(match[i2])).getBytes(); - if (der1 === der2) { - return true; + } + eb.putByte(0); + eb.putBytes(m); + return eb; + } + function _decodePkcs1_v1_5(em, key, pub, ml) { + var k = Math.ceil(key.n.bitLength() / 8); + var eb = forge.util.createBuffer(em); + var first = eb.getByte(); + var bt = eb.getByte(); + if (first !== 0 || pub && bt !== 0 && bt !== 1 || !pub && bt != 2 || pub && bt === 0 && typeof ml === "undefined") { + throw new Error("Encryption block is invalid."); + } + var padNum = 0; + if (bt === 0) { + padNum = k - 3 - ml; + for (var i = 0; i < padNum; ++i) { + if (eb.getByte() !== 0) { + throw new Error("Encryption block is invalid."); } } - return false; - }; - caStore.listAllCertificates = function() { - var certList = []; - for (var hash in caStore.certs) { - if (caStore.certs.hasOwnProperty(hash)) { - var value = caStore.certs[hash]; - if (!forge.util.isArray(value)) { - certList.push(value); - } else { - for (var i2 = 0; i2 < value.length; ++i2) { - certList.push(value[i2]); - } - } + } else if (bt === 1) { + padNum = 0; + while (eb.length() > 1) { + if (eb.getByte() !== 255) { + --eb.read; + break; } + ++padNum; } - return certList; - }; - caStore.removeCertificate = function(cert2) { - var result; - if (typeof cert2 === "string") { - cert2 = forge.pki.certificateFromPem(cert2); - } - ensureSubjectHasHash(cert2.subject); - if (!caStore.hasCertificate(cert2)) { - return null; - } - var match = getBySubject(cert2.subject); - if (!forge.util.isArray(match)) { - result = caStore.certs[cert2.subject.hash]; - delete caStore.certs[cert2.subject.hash]; - return result; - } - var der1 = asn1.toDer(pki2.certificateToAsn1(cert2)).getBytes(); - for (var i2 = 0; i2 < match.length; ++i2) { - var der2 = asn1.toDer(pki2.certificateToAsn1(match[i2])).getBytes(); - if (der1 === der2) { - result = match[i2]; - match.splice(i2, 1); + } else if (bt === 2) { + padNum = 0; + while (eb.length() > 1) { + if (eb.getByte() === 0) { + --eb.read; + break; } - } - if (match.length === 0) { - delete caStore.certs[cert2.subject.hash]; - } - return result; - }; - function getBySubject(subject) { - ensureSubjectHasHash(subject); - return caStore.certs[subject.hash] || null; - } - function ensureSubjectHasHash(subject) { - if (!subject.hash) { - var md = forge.md.sha1.create(); - subject.attributes = pki2.RDNAttributesAsArray(_dnToAsn1(subject), md); - subject.hash = md.digest().toHex(); + ++padNum; } } - if (certs) { - for (var i = 0; i < certs.length; ++i) { - var cert = certs[i]; - caStore.addCertificate(cert); - } + var zero = eb.getByte(); + if (zero !== 0 || padNum !== k - 3 - eb.length()) { + throw new Error("Encryption block is invalid."); } - return caStore; - }; - pki2.certificateError = { - bad_certificate: "forge.pki.BadCertificate", - unsupported_certificate: "forge.pki.UnsupportedCertificate", - certificate_revoked: "forge.pki.CertificateRevoked", - certificate_expired: "forge.pki.CertificateExpired", - certificate_unknown: "forge.pki.CertificateUnknown", - unknown_ca: "forge.pki.UnknownCertificateAuthority" - }; - pki2.verifyCertificateChain = function(caStore, chain, options) { + return eb.getBytes(); + } + function _generateKeyPair(state, options, callback) { if (typeof options === "function") { - options = { verify: options }; + callback = options; + options = {}; } options = options || {}; - chain = chain.slice(0); - var certs = chain.slice(0); - var validityCheckDate = options.validityCheckDate; - if (typeof validityCheckDate === "undefined") { - validityCheckDate = /* @__PURE__ */ new Date(); - } - var first = true; - var error4 = null; - var depth = 0; - do { - var cert = chain.shift(); - var parent = null; - var selfSigned = false; - if (validityCheckDate) { - if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) { - error4 = { - message: "Certificate is not valid yet or has expired.", - error: pki2.certificateError.certificate_expired, - notBefore: cert.validity.notBefore, - notAfter: cert.validity.notAfter, - // TODO: we might want to reconsider renaming 'now' to - // 'validityCheckDate' should this API be changed in the future. - now: validityCheckDate - }; + var opts = { + algorithm: { + name: options.algorithm || "PRIMEINC", + options: { + workers: options.workers || 2, + workLoad: options.workLoad || 100, + workerScript: options.workerScript } } - if (error4 === null) { - parent = chain[0] || caStore.getIssuer(cert); - if (parent === null) { - if (cert.isIssuer(cert)) { - selfSigned = true; - parent = cert; - } - } - if (parent) { - var parents = parent; - if (!forge.util.isArray(parents)) { - parents = [parents]; - } - var verified = false; - while (!verified && parents.length > 0) { - parent = parents.shift(); - try { - verified = parent.verify(cert); - } catch (ex) { - } - } - if (!verified) { - error4 = { - message: "Certificate signature is invalid.", - error: pki2.certificateError.bad_certificate - }; - } + }; + if ("prng" in options) { + opts.prng = options.prng; + } + generate(); + function generate() { + getPrime(state.pBits, function(err, num) { + if (err) { + return callback(err); } - if (error4 === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) { - error4 = { - message: "Certificate is not trusted.", - error: pki2.certificateError.unknown_ca - }; + state.p = num; + if (state.q !== null) { + return finish(err, state.q); } + getPrime(state.qBits, finish); + }); + } + function getPrime(bits, callback2) { + forge.prime.generateProbablePrime(bits, opts, callback2); + } + function finish(err, num) { + if (err) { + return callback(err); } - if (error4 === null && parent && !cert.isIssuer(parent)) { - error4 = { - message: "Certificate issuer is invalid.", - error: pki2.certificateError.bad_certificate - }; + state.q = num; + if (state.p.compareTo(state.q) < 0) { + var tmp = state.p; + state.p = state.q; + state.q = tmp; } - if (error4 === null) { - var se = { - keyUsage: true, - basicConstraints: true - }; - for (var i = 0; error4 === null && i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if (ext.critical && !(ext.name in se)) { - error4 = { - message: "Certificate has an unsupported critical extension.", - error: pki2.certificateError.unsupported_certificate - }; - } - } + if (state.p.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + state.p = null; + generate(); + return; } - if (error4 === null && (!first || chain.length === 0 && (!parent || selfSigned))) { - var bcExt = cert.getExtension("basicConstraints"); - var keyUsageExt = cert.getExtension("keyUsage"); - if (keyUsageExt !== null) { - if (!keyUsageExt.keyCertSign || bcExt === null) { - error4 = { - message: "Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.", - error: pki2.certificateError.bad_certificate - }; - } - } - if (error4 === null && bcExt !== null && !bcExt.cA) { - error4 = { - message: "Certificate basicConstraints indicates the certificate is not a CA.", - error: pki2.certificateError.bad_certificate - }; - } - if (error4 === null && keyUsageExt !== null && "pathLenConstraint" in bcExt) { - var pathLen = depth - 1; - if (pathLen > bcExt.pathLenConstraint) { - error4 = { - message: "Certificate basicConstraints pathLenConstraint violated.", - error: pki2.certificateError.bad_certificate - }; - } - } + if (state.q.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + state.q = null; + getPrime(state.qBits, finish); + return; } - var vfd = error4 === null ? true : error4.error; - var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; - if (ret === true) { - error4 = null; - } else { - if (vfd === true) { - error4 = { - message: "The application rejected the certificate.", - error: pki2.certificateError.bad_certificate - }; - } - if (ret || ret === 0) { - if (typeof ret === "object" && !forge.util.isArray(ret)) { - if (ret.message) { - error4.message = ret.message; - } - if (ret.error) { - error4.error = ret.error; - } - } else if (typeof ret === "string") { - error4.error = ret; - } - } - throw error4; + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + if (state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + state.p = state.q = null; + generate(); + return; } - first = false; - ++depth; - } while (chain.length > 0); - return true; - }; + state.n = state.p.multiply(state.q); + if (state.n.bitLength() !== state.bits) { + state.q = null; + getPrime(state.qBits, finish); + return; + } + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki2.rsa.setPrivateKey( + state.n, + state.e, + d, + state.p, + state.q, + d.mod(state.p1), + d.mod(state.q1), + state.q.modInverse(state.p) + ), + publicKey: pki2.rsa.setPublicKey(state.n, state.e) + }; + callback(null, state.keys); + } + } + function _bnToBytes(b) { + var hex = b.toString(16); + if (hex[0] >= "8") { + hex = "00" + hex; + } + var bytes = forge.util.hexToBytes(hex); + if (bytes.length > 1 && // leading 0x00 for positive integer + (bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer + bytes.charCodeAt(0) === 255 && (bytes.charCodeAt(1) & 128) === 128)) { + return bytes.substr(1); + } + return bytes; + } + function _getMillerRabinTests(bits) { + if (bits <= 100) return 27; + if (bits <= 150) return 18; + if (bits <= 200) return 15; + if (bits <= 250) return 12; + if (bits <= 300) return 9; + if (bits <= 350) return 8; + if (bits <= 400) return 7; + if (bits <= 500) return 6; + if (bits <= 600) return 5; + if (bits <= 800) return 4; + if (bits <= 1250) return 3; + return 2; + } + function _detectNodeCrypto(fn) { + return forge.util.isNodejs && typeof _crypto[fn] === "function"; + } + function _detectSubtleCrypto(fn) { + return typeof util.globalScope !== "undefined" && typeof util.globalScope.crypto === "object" && typeof util.globalScope.crypto.subtle === "object" && typeof util.globalScope.crypto.subtle[fn] === "function"; + } + function _detectSubtleMsCrypto(fn) { + return typeof util.globalScope !== "undefined" && typeof util.globalScope.msCrypto === "object" && typeof util.globalScope.msCrypto.subtle === "object" && typeof util.globalScope.msCrypto.subtle[fn] === "function"; + } + function _intToUint8Array(x) { + var bytes = forge.util.hexToBytes(x.toString(16)); + var buffer = new Uint8Array(bytes.length); + for (var i = 0; i < bytes.length; ++i) { + buffer[i] = bytes.charCodeAt(i); + } + return buffer; + } } }); -// node_modules/node-forge/lib/pkcs12.js -var require_pkcs12 = __commonJS({ - "node_modules/node-forge/lib/pkcs12.js"(exports2, module2) { +// node_modules/node-forge/lib/pbe.js +var require_pbe = __commonJS({ + "node_modules/node-forge/lib/pbe.js"(exports2, module2) { var forge = require_forge(); + require_aes(); require_asn1(); - require_hmac(); + require_des(); + require_md(); require_oids(); - require_pkcs7asn1(); - require_pbe(); + require_pbkdf2(); + require_pem(); require_random(); + require_rc2(); require_rsa(); - require_sha1(); require_util8(); - require_x509(); + if (typeof BigInteger === "undefined") { + BigInteger = forge.jsbn.BigInteger; + } + var BigInteger; var asn1 = forge.asn1; - var pki2 = forge.pki; - var p12 = module2.exports = forge.pkcs12 = forge.pkcs12 || {}; - var contentInfoValidator = { - name: "ContentInfo", + var pki2 = forge.pki = forge.pki || {}; + module2.exports = pki2.pbe = forge.pbe = forge.pbe || {}; + var oids = pki2.oids; + var encryptedPrivateKeyValidator = { + name: "EncryptedPrivateKeyInfo", tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, - // a ContentInfo constructed: true, value: [{ - name: "ContentInfo.contentType", + name: "EncryptedPrivateKeyInfo.encryptionAlgorithm", tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "ContentInfo.content", - tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: asn1.Type.SEQUENCE, constructed: true, - captureAsn1: "content" + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "encryptionOid" + }, { + name: "AlgorithmIdentifier.parameters", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "encryptionParams" + }] + }, { + // encryptedData + name: "EncryptedPrivateKeyInfo.encryptedData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "encryptedData" }] }; - var pfxValidator = { - name: "PFX", + var PBES2AlgorithmsValidator = { + name: "PBES2Algorithms", tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, - value: [ - { - name: "PFX.version", + value: [{ + name: "PBES2Algorithms.keyDerivationFunc", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "PBES2Algorithms.keyDerivationFunc.oid", tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, + type: asn1.Type.OID, constructed: false, - capture: "version" - }, - contentInfoValidator, - { - name: "PFX.macData", + capture: "kdfOid" + }, { + name: "PBES2Algorithms.params", tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, - optional: true, - captureAsn1: "mac", value: [{ - name: "PFX.macData.mac", + name: "PBES2Algorithms.params.salt", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "kdfSalt" + }, { + name: "PBES2Algorithms.params.iterationCount", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "kdfIterationCount" + }, { + name: "PBES2Algorithms.params.keyLength", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: "keyLength" + }, { + // prf + name: "PBES2Algorithms.params.prf", tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, - // DigestInfo constructed: true, + optional: true, value: [{ - name: "PFX.macData.mac.digestAlgorithm", + name: "PBES2Algorithms.params.prf.algorithm", tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // DigestAlgorithmIdentifier - constructed: true, - value: [{ - name: "PFX.macData.mac.digestAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "macAlgorithm" - }, { - name: "PFX.macData.mac.digestAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: "macAlgorithmParameters" - }] - }, { - name: "PFX.macData.mac.digest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, + type: asn1.Type.OID, constructed: false, - capture: "macDigest" + capture: "prfOid" }] - }, { - name: "PFX.macData.macSalt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "macSalt" - }, { - name: "PFX.macData.iterations", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: "macIterations" }] - } - ] - }; - var safeBagValidator = { - name: "SafeBag", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SafeBag.bagId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "bagId" - }, { - name: "SafeBag.bagValue", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: "bagValue" + }] }, { - name: "SafeBag.bagAttributes", + name: "PBES2Algorithms.encryptionScheme", tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, + type: asn1.Type.SEQUENCE, constructed: true, - optional: true, - capture: "bagAttributes" + value: [{ + name: "PBES2Algorithms.encryptionScheme.oid", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "encOid" + }, { + name: "PBES2Algorithms.encryptionScheme.iv", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "encIv" + }] }] }; - var attributeValidator = { - name: "Attribute", + var pkcs12PbeParamsValidator = { + name: "pkcs-12PbeParams", tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ - name: "Attribute.attrId", + name: "pkcs-12PbeParams.salt", tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, + type: asn1.Type.OCTETSTRING, constructed: false, - capture: "oid" + capture: "salt" }, { - name: "Attribute.attrValues", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - capture: "values" - }] - }; - var certBagValidator = { - name: "CertBag", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "CertBag.certId", + name: "pkcs-12PbeParams.iterations", tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, + type: asn1.Type.INTEGER, constructed: false, - capture: "certId" - }, { - name: "CertBag.certValue", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - /* So far we only support X.509 certificates (which are wrapped in - an OCTET STRING, hence hard code that here). */ - value: [{ - name: "CertBag.certValue[0]", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.OCTETSTRING, - constructed: false, - capture: "cert" - }] + capture: "iterations" }] }; - function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { - var result = []; - for (var i = 0; i < safeContents.length; i++) { - for (var j = 0; j < safeContents[i].safeBags.length; j++) { - var bag = safeContents[i].safeBags[j]; - if (bagType !== void 0 && bag.type !== bagType) { - continue; - } - if (attrName === null) { - result.push(bag); - continue; - } - if (bag.attributes[attrName] !== void 0 && bag.attributes[attrName].indexOf(attrValue) >= 0) { - result.push(bag); - } - } - } - return result; - } - p12.pkcs12FromAsn1 = function(obj, strict, password) { - if (typeof strict === "string") { - password = strict; - strict = true; - } else if (strict === void 0) { - strict = true; - } - var capture = {}; - var errors = []; - if (!asn1.validate(obj, pfxValidator, capture, errors)) { - var error4 = new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX."); - error4.errors = error4; - throw error4; - } - var pfx = { - version: capture.version.charCodeAt(0), - safeContents: [], - /** - * Gets bags with matching attributes. - * - * @param filter the attributes to filter by: - * [localKeyId] the localKeyId to search for. - * [localKeyIdHex] the localKeyId in hex to search for. - * [friendlyName] the friendly name to search for. - * [bagType] bag type to narrow each attribute search by. - * - * @return a map of attribute type to an array of matching bags or, if no - * attribute was given but a bag type, the map key will be the - * bag type. - */ - getBags: function(filter) { - var rval = {}; - var localKeyId; - if ("localKeyId" in filter) { - localKeyId = filter.localKeyId; - } else if ("localKeyIdHex" in filter) { - localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); - } - if (localKeyId === void 0 && !("friendlyName" in filter) && "bagType" in filter) { - rval[filter.bagType] = _getBagsByAttribute( - pfx.safeContents, - null, - null, - filter.bagType - ); - } - if (localKeyId !== void 0) { - rval.localKeyId = _getBagsByAttribute( - pfx.safeContents, - "localKeyId", - localKeyId, - filter.bagType - ); - } - if ("friendlyName" in filter) { - rval.friendlyName = _getBagsByAttribute( - pfx.safeContents, - "friendlyName", - filter.friendlyName, - filter.bagType - ); - } - return rval; - }, - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching friendlyName attribute. - * - * @param friendlyName the friendly name to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching friendlyName attribute. - */ - getBagsByFriendlyName: function(friendlyName, bagType) { - return _getBagsByAttribute( - pfx.safeContents, - "friendlyName", - friendlyName, - bagType - ); - }, - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching localKeyId attribute. - * - * @param localKeyId the localKeyId to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching localKeyId attribute. - */ - getBagsByLocalKeyId: function(localKeyId, bagType) { - return _getBagsByAttribute( - pfx.safeContents, - "localKeyId", - localKeyId, - bagType - ); - } - }; - if (capture.version.charCodeAt(0) !== 3) { - var error4 = new Error("PKCS#12 PFX of version other than 3 not supported."); - error4.version = capture.version.charCodeAt(0); - throw error4; - } - if (asn1.derToOid(capture.contentType) !== pki2.oids.data) { - var error4 = new Error("Only PKCS#12 PFX in password integrity mode supported."); - error4.oid = asn1.derToOid(capture.contentType); - throw error4; - } - var data = capture.content.value[0]; - if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { - throw new Error("PKCS#12 authSafe content data is not an OCTET STRING."); - } - data = _decodePkcs7Data(data); - if (capture.mac) { - var md = null; - var macKeyBytes = 0; - var macAlgorithm = asn1.derToOid(capture.macAlgorithm); - switch (macAlgorithm) { - case pki2.oids.sha1: - md = forge.md.sha1.create(); - macKeyBytes = 20; - break; - case pki2.oids.sha256: - md = forge.md.sha256.create(); - macKeyBytes = 32; - break; - case pki2.oids.sha384: - md = forge.md.sha384.create(); - macKeyBytes = 48; - break; - case pki2.oids.sha512: - md = forge.md.sha512.create(); - macKeyBytes = 64; + pki2.encryptPrivateKeyInfo = function(obj, password, options) { + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || "aes128"; + options.prfAlgorithm = options.prfAlgorithm || "sha1"; + var salt = forge.random.getBytesSync(options.saltSize); + var count = options.count; + var countBytes = asn1.integerToDer(count); + var dkLen; + var encryptionAlgorithm; + var encryptedData; + if (options.algorithm.indexOf("aes") === 0 || options.algorithm === "des") { + var ivLen, encOid, cipherFn; + switch (options.algorithm) { + case "aes128": + dkLen = 16; + ivLen = 16; + encOid = oids["aes128-CBC"]; + cipherFn = forge.aes.createEncryptionCipher; break; - case pki2.oids.md5: - md = forge.md.md5.create(); - macKeyBytes = 16; + case "aes192": + dkLen = 24; + ivLen = 16; + encOid = oids["aes192-CBC"]; + cipherFn = forge.aes.createEncryptionCipher; break; - } - if (md === null) { - throw new Error("PKCS#12 uses unsupported MAC algorithm: " + macAlgorithm); - } - var macSalt = new forge.util.ByteBuffer(capture.macSalt); - var macIterations = "macIterations" in capture ? parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1; - var macKey = p12.generateKey( - password, - macSalt, - 3, - macIterations, - macKeyBytes, - md - ); - var mac = forge.hmac.create(); - mac.start(md, macKey); - mac.update(data.value); - var macValue = mac.getMac(); - if (macValue.getBytes() !== capture.macDigest) { - throw new Error("PKCS#12 MAC could not be verified. Invalid password?"); - } - } - _decodeAuthenticatedSafe(pfx, data.value, strict, password); - return pfx; - }; - function _decodePkcs7Data(data) { - if (data.composed || data.constructed) { - var value = forge.util.createBuffer(); - for (var i = 0; i < data.value.length; ++i) { - value.putBytes(data.value[i].value); - } - data.composed = data.constructed = false; - data.value = value.getBytes(); - } - return data; - } - function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { - authSafe = asn1.fromDer(authSafe, strict); - if (authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) { - throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo"); - } - for (var i = 0; i < authSafe.value.length; i++) { - var contentInfo = authSafe.value[i]; - var capture = {}; - var errors = []; - if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { - var error4 = new Error("Cannot read ContentInfo."); - error4.errors = errors; - throw error4; - } - var obj = { - encrypted: false - }; - var safeContents = null; - var data = capture.content.value[0]; - switch (asn1.derToOid(capture.contentType)) { - case pki2.oids.data: - if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { - throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING."); - } - safeContents = _decodePkcs7Data(data).value; + case "aes256": + dkLen = 32; + ivLen = 16; + encOid = oids["aes256-CBC"]; + cipherFn = forge.aes.createEncryptionCipher; break; - case pki2.oids.encryptedData: - safeContents = _decryptSafeContents(data, password); - obj.encrypted = true; + case "des": + dkLen = 8; + ivLen = 8; + encOid = oids["desCBC"]; + cipherFn = forge.des.createEncryptionCipher; break; default: - var error4 = new Error("Unsupported PKCS#12 contentType."); - error4.contentType = asn1.derToOid(capture.contentType); + var error4 = new Error("Cannot encrypt private key. Unknown encryption algorithm."); + error4.algorithm = options.algorithm; throw error4; } - obj.safeBags = _decodeSafeContents(safeContents, strict, password); - pfx.safeContents.push(obj); + var prfAlgorithm = "hmacWith" + options.prfAlgorithm.toUpperCase(); + var md = prfAlgorithmToMessageDigest(prfAlgorithm); + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = forge.random.getBytesSync(ivLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oids["pkcs5PBES2"]).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // keyDerivationFunc + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes() + ), + // PBKDF2-params + params + ]), + // encryptionScheme + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(encOid).getBytes() + ), + // iv + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + iv + ) + ]) + ]) + ] + ); + } else if (options.algorithm === "3des") { + dkLen = 24; + var saltBytes = new forge.util.ByteBuffer(salt); + var dk = pki2.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); + var iv = pki2.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); + var cipher = forge.des.createEncryptionCipher(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes() + ), + // pkcs-12PbeParams + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), + // iteration count + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + countBytes.getBytes() + ) + ]) + ] + ); + } else { + var error4 = new Error("Cannot encrypt private key. Unknown encryption algorithm."); + error4.algorithm = options.algorithm; + throw error4; } - } - function _decryptSafeContents(data, password) { + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // encryptionAlgorithm + encryptionAlgorithm, + // encryptedData + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + encryptedData + ) + ]); + return rval; + }; + pki2.decryptPrivateKeyInfo = function(obj, password) { + var rval = null; var capture = {}; var errors = []; - if (!asn1.validate( - data, - forge.pkcs7.asn1.encryptedDataValidator, - capture, - errors - )) { - var error4 = new Error("Cannot read EncryptedContentInfo."); + if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { + var error4 = new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); error4.errors = errors; throw error4; } - var oid = asn1.derToOid(capture.contentType); - if (oid !== pki2.oids.data) { - var error4 = new Error( - "PKCS#12 EncryptedContentInfo ContentType is not Data." - ); - error4.oid = oid; - throw error4; - } - oid = asn1.derToOid(capture.encAlgorithm); - var cipher = pki2.pbe.getCipher(oid, capture.encParameter, password); - var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); - var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); + var oid = asn1.derToOid(capture.encryptionOid); + var cipher = pki2.pbe.getCipher(oid, capture.encryptionParams, password); + var encrypted = forge.util.createBuffer(capture.encryptedData); cipher.update(encrypted); - if (!cipher.finish()) { - throw new Error("Failed to decrypt PKCS#12 SafeContents."); - } - return cipher.output.getBytes(); - } - function _decodeSafeContents(safeContents, strict, password) { - if (!strict && safeContents.length === 0) { - return []; + if (cipher.finish()) { + rval = asn1.fromDer(cipher.output); } - safeContents = asn1.fromDer(safeContents, strict); - if (safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) { - throw new Error( - "PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag." - ); + return rval; + }; + pki2.encryptedPrivateKeyToPem = function(epki, maxline) { + var msg = { + type: "ENCRYPTED PRIVATE KEY", + body: asn1.toDer(epki).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.encryptedPrivateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "ENCRYPTED PRIVATE KEY") { + var error4 = new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".'); + error4.headerType = msg.type; + throw error4; } - var res = []; - for (var i = 0; i < safeContents.value.length; i++) { - var safeBag = safeContents.value[i]; - var capture = {}; - var errors = []; - if (!asn1.validate(safeBag, safeBagValidator, capture, errors)) { - var error4 = new Error("Cannot read SafeBag."); - error4.errors = errors; + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted."); + } + return asn1.fromDer(msg.body); + }; + pki2.encryptRsaPrivateKey = function(rsaKey, password, options) { + options = options || {}; + if (!options.legacy) { + var rval = pki2.wrapRsaPrivateKey(pki2.privateKeyToAsn1(rsaKey)); + rval = pki2.encryptPrivateKeyInfo(rval, password, options); + return pki2.encryptedPrivateKeyToPem(rval); + } + var algorithm; + var iv; + var dkLen; + var cipherFn; + switch (options.algorithm) { + case "aes128": + algorithm = "AES-128-CBC"; + dkLen = 16; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case "aes192": + algorithm = "AES-192-CBC"; + dkLen = 24; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case "aes256": + algorithm = "AES-256-CBC"; + dkLen = 32; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case "3des": + algorithm = "DES-EDE3-CBC"; + dkLen = 24; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + case "des": + algorithm = "DES-CBC"; + dkLen = 8; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error4 = new Error('Could not encrypt RSA private key; unsupported encryption algorithm "' + options.algorithm + '".'); + error4.algorithm = options.algorithm; throw error4; - } - var bag = { - type: asn1.derToOid(capture.bagId), - attributes: _decodeBagAttributes(capture.bagAttributes) - }; - res.push(bag); - var validator, decoder; - var bagAsn1 = capture.bagValue.value[0]; - switch (bag.type) { - case pki2.oids.pkcs8ShroudedKeyBag: - bagAsn1 = pki2.decryptPrivateKeyInfo(bagAsn1, password); - if (bagAsn1 === null) { - throw new Error( - "Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?" - ); - } - /* fall through */ - case pki2.oids.keyBag: - try { - bag.key = pki2.privateKeyFromAsn1(bagAsn1); - } catch (e) { - bag.key = null; - bag.asn1 = bagAsn1; - } - continue; - /* Nothing more to do. */ - case pki2.oids.certBag: - validator = certBagValidator; - decoder = function() { - if (asn1.derToOid(capture.certId) !== pki2.oids.x509Certificate) { - var error5 = new Error( - "Unsupported certificate type, only X.509 supported." - ); - error5.oid = asn1.derToOid(capture.certId); - throw error5; - } - var certAsn1 = asn1.fromDer(capture.cert, strict); - try { - bag.cert = pki2.certificateFromAsn1(certAsn1, true); - } catch (e) { - bag.cert = null; - bag.asn1 = certAsn1; - } + } + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(pki2.privateKeyToAsn1(rsaKey))); + cipher.finish(); + var msg = { + type: "RSA PRIVATE KEY", + procType: { + version: "4", + type: "ENCRYPTED" + }, + dekInfo: { + algorithm, + parameters: forge.util.bytesToHex(iv).toUpperCase() + }, + body: cipher.output.getBytes() + }; + return forge.pem.encode(msg); + }; + pki2.decryptRsaPrivateKey = function(pem, password) { + var rval = null; + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "ENCRYPTED PRIVATE KEY" && msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { + var error4 = new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); + error4.headerType = error4; + throw error4; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + var dkLen; + var cipherFn; + switch (msg.dekInfo.algorithm) { + case "DES-CBC": + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + case "DES-EDE3-CBC": + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case "AES-128-CBC": + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "AES-192-CBC": + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "AES-256-CBC": + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "RC2-40-CBC": + dkLen = 5; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 40); + }; + break; + case "RC2-64-CBC": + dkLen = 8; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 64); + }; + break; + case "RC2-128-CBC": + dkLen = 16; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 128); }; break; default: - var error4 = new Error("Unsupported PKCS#12 SafeBag type."); - error4.oid = bag.type; + var error4 = new Error('Could not decrypt private key; unsupported encryption algorithm "' + msg.dekInfo.algorithm + '".'); + error4.algorithm = msg.dekInfo.algorithm; throw error4; } - if (validator !== void 0 && !asn1.validate(bagAsn1, validator, capture, errors)) { - var error4 = new Error("Cannot read PKCS#12 " + validator.name); - error4.errors = errors; - throw error4; + var iv = forge.util.hexToBytes(msg.dekInfo.parameters); + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(forge.util.createBuffer(msg.body)); + if (cipher.finish()) { + rval = cipher.output.getBytes(); + } else { + return rval; } - decoder(); + } else { + rval = msg.body; } - return res; - } - function _decodeBagAttributes(attributes) { - var decodedAttrs = {}; - if (attributes !== void 0) { - for (var i = 0; i < attributes.length; ++i) { - var capture = {}; - var errors = []; - if (!asn1.validate(attributes[i], attributeValidator, capture, errors)) { - var error4 = new Error("Cannot read PKCS#12 BagAttribute."); - error4.errors = errors; - throw error4; - } - var oid = asn1.derToOid(capture.oid); - if (pki2.oids[oid] === void 0) { - continue; - } - decodedAttrs[pki2.oids[oid]] = []; - for (var j = 0; j < capture.values.length; ++j) { - decodedAttrs[pki2.oids[oid]].push(capture.values[j].value); - } + if (msg.type === "ENCRYPTED PRIVATE KEY") { + rval = pki2.decryptPrivateKeyInfo(asn1.fromDer(rval), password); + } else { + rval = asn1.fromDer(rval); + } + if (rval !== null) { + rval = pki2.privateKeyFromAsn1(rval); + } + return rval; + }; + pki2.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { + var j, l; + if (typeof md === "undefined" || md === null) { + if (!("sha1" in forge.md)) { + throw new Error('"sha1" hash algorithm unavailable.'); } + md = forge.md.sha1.create(); } - return decodedAttrs; - } - p12.toPkcs12Asn1 = function(key, cert, password, options) { - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || options.encAlgorithm || "aes128"; - if (!("useMac" in options)) { - options.useMac = true; + var u = md.digestLength; + var v = md.blockLength; + var result = new forge.util.ByteBuffer(); + var passBuf = new forge.util.ByteBuffer(); + if (password !== null && password !== void 0) { + for (l = 0; l < password.length; l++) { + passBuf.putInt16(password.charCodeAt(l)); + } + passBuf.putInt16(0); } - if (!("localKeyId" in options)) { - options.localKeyId = null; + var p = passBuf.length(); + var s = salt.length(); + var D = new forge.util.ByteBuffer(); + D.fillWithByte(id, v); + var Slen = v * Math.ceil(s / v); + var S = new forge.util.ByteBuffer(); + for (l = 0; l < Slen; l++) { + S.putByte(salt.at(l % s)); } - if (!("generateLocalKeyId" in options)) { - options.generateLocalKeyId = true; + var Plen = v * Math.ceil(p / v); + var P = new forge.util.ByteBuffer(); + for (l = 0; l < Plen; l++) { + P.putByte(passBuf.at(l % p)); } - var localKeyId = options.localKeyId; - var bagAttrs; - if (localKeyId !== null) { - localKeyId = forge.util.hexToBytes(localKeyId); - } else if (options.generateLocalKeyId) { - if (cert) { - var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; - if (typeof pairedCert === "string") { - pairedCert = pki2.certificateFromPem(pairedCert); + var I = S; + I.putBuffer(P); + var c = Math.ceil(n / u); + for (var i = 1; i <= c; i++) { + var buf = new forge.util.ByteBuffer(); + buf.putBytes(D.bytes()); + buf.putBytes(I.bytes()); + for (var round = 0; round < iter; round++) { + md.start(); + md.update(buf.getBytes()); + buf = md.digest(); + } + var B = new forge.util.ByteBuffer(); + for (l = 0; l < v; l++) { + B.putByte(buf.at(l % u)); + } + var k = Math.ceil(s / v) + Math.ceil(p / v); + var Inew = new forge.util.ByteBuffer(); + for (j = 0; j < k; j++) { + var chunk = new forge.util.ByteBuffer(I.getBytes(v)); + var x = 511; + for (l = B.length() - 1; l >= 0; l--) { + x = x >> 8; + x += B.at(l) + chunk.at(l); + chunk.setAt(l, x & 255); } - var sha1 = forge.md.sha1.create(); - sha1.update(asn1.toDer(pki2.certificateToAsn1(pairedCert)).getBytes()); - localKeyId = sha1.digest().getBytes(); - } else { - localKeyId = forge.random.getBytes(20); + Inew.putBuffer(chunk); } + I = Inew; + result.putBuffer(buf); } - var attrs = []; - if (localKeyId !== null) { - attrs.push( - // localKeyID - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.localKeyId).getBytes() - ), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - localKeyId - ) - ]) - ]) - ); + result.truncate(result.length() - n); + return result; + }; + pki2.pbe.getCipher = function(oid, params, password) { + switch (oid) { + case pki2.oids["pkcs5PBES2"]: + return pki2.pbe.getCipherForPBES2(oid, params, password); + case pki2.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: + case pki2.oids["pbewithSHAAnd40BitRC2-CBC"]: + return pki2.pbe.getCipherForPKCS12PBE(oid, params, password); + default: + var error4 = new Error("Cannot read encrypted PBE data block. Unsupported OID."); + error4.oid = oid; + error4.supportedOids = [ + "pkcs5PBES2", + "pbeWithSHAAnd3-KeyTripleDES-CBC", + "pbewithSHAAnd40BitRC2-CBC" + ]; + throw error4; } - if ("friendlyName" in options) { - attrs.push( - // friendlyName - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.friendlyName).getBytes() - ), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BMPSTRING, - false, - options.friendlyName - ) - ]) - ]) - ); + }; + pki2.pbe.getCipherForPBES2 = function(oid, params, password) { + var capture = {}; + var errors = []; + if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { + var error4 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); + error4.errors = errors; + throw error4; } - if (attrs.length > 0) { - bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); + oid = asn1.derToOid(capture.kdfOid); + if (oid !== pki2.oids["pkcs5PBKDF2"]) { + var error4 = new Error("Cannot read encrypted private key. Unsupported key derivation function OID."); + error4.oid = oid; + error4.supportedOids = ["pkcs5PBKDF2"]; + throw error4; } - var contents = []; - var chain = []; - if (cert !== null) { - if (forge.util.isArray(cert)) { - chain = cert; - } else { - chain = [cert]; - } + oid = asn1.derToOid(capture.encOid); + if (oid !== pki2.oids["aes128-CBC"] && oid !== pki2.oids["aes192-CBC"] && oid !== pki2.oids["aes256-CBC"] && oid !== pki2.oids["des-EDE3-CBC"] && oid !== pki2.oids["desCBC"]) { + var error4 = new Error("Cannot read encrypted private key. Unsupported encryption scheme OID."); + error4.oid = oid; + error4.supportedOids = [ + "aes128-CBC", + "aes192-CBC", + "aes256-CBC", + "des-EDE3-CBC", + "desCBC" + ]; + throw error4; } - var certSafeBags = []; - for (var i = 0; i < chain.length; ++i) { - cert = chain[i]; - if (typeof cert === "string") { - cert = pki2.certificateFromPem(cert); - } - var certBagAttrs = i === 0 ? bagAttrs : void 0; - var certAsn1 = pki2.certificateToAsn1(cert); - var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.certBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // CertBag - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // certId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.x509Certificate).getBytes() - ), - // certValue (x509Certificate) - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(certAsn1).getBytes() - ) - ]) - ]) - ]), - // bagAttributes (OPTIONAL) - certBagAttrs - ]); - certSafeBags.push(certSafeBag); + var salt = capture.kdfSalt; + var count = forge.util.createBuffer(capture.kdfIterationCount); + count = count.getInt(count.length() << 3); + var dkLen; + var cipherFn; + switch (pki2.oids[oid]) { + case "aes128-CBC": + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "aes192-CBC": + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "aes256-CBC": + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case "des-EDE3-CBC": + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case "desCBC": + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; } - if (certSafeBags.length > 0) { - var certSafeContents = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - certSafeBags - ); - var certCI = ( - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki2.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(certSafeContents).getBytes() - ) - ]) - ]) - ); - contents.push(certCI); + var md = prfOidToMessageDigest(capture.prfOid); + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = capture.encIv; + var cipher = cipherFn(dk); + cipher.start(iv); + return cipher; + }; + pki2.pbe.getCipherForPKCS12PBE = function(oid, params, password) { + var capture = {}; + var errors = []; + if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { + var error4 = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); + error4.errors = errors; + throw error4; } - var keyBag = null; - if (key !== null) { - var pkAsn1 = pki2.wrapRsaPrivateKey(pki2.privateKeyToAsn1(key)); - if (password === null) { - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.keyBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // PrivateKeyInfo - pkAsn1 - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } else { - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.pkcs8ShroudedKeyBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // EncryptedPrivateKeyInfo - pki2.encryptPrivateKeyInfo(pkAsn1, password, options) - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); + var salt = forge.util.createBuffer(capture.salt); + var count = forge.util.createBuffer(capture.iterations); + count = count.getInt(count.length() << 3); + var dkLen, dIvLen, cipherFn; + switch (oid) { + case pki2.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: + dkLen = 24; + dIvLen = 8; + cipherFn = forge.des.startDecrypting; + break; + case pki2.oids["pbewithSHAAnd40BitRC2-CBC"]: + dkLen = 5; + dIvLen = 8; + cipherFn = function(key2, iv2) { + var cipher = forge.rc2.createDecryptionCipher(key2, 40); + cipher.start(iv2, null); + return cipher; + }; + break; + default: + var error4 = new Error("Cannot read PKCS #12 PBE data block. Unsupported OID."); + error4.oid = oid; + throw error4; + } + var md = prfOidToMessageDigest(capture.prfOid); + var key = pki2.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); + md.start(); + var iv = pki2.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); + return cipherFn(key, iv); + }; + pki2.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { + if (typeof md === "undefined" || md === null) { + if (!("md5" in forge.md)) { + throw new Error('"md5" hash algorithm unavailable.'); } - var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); - var keyCI = ( - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki2.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(keySafeContents).getBytes() - ) - ]) - ]) - ); - contents.push(keyCI); + md = forge.md.md5.create(); } - var safe = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - contents - ); - var macData; - if (options.useMac) { - var sha1 = forge.md.sha1.create(); - var macSalt = new forge.util.ByteBuffer( - forge.random.getBytes(options.saltSize) - ); - var count = options.count; - var key = p12.generateKey(password, macSalt, 3, count, 20); - var mac = forge.hmac.create(); - mac.start(sha1, key); - mac.update(asn1.toDer(safe).getBytes()); - var macValue = mac.getMac(); - macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // mac DigestInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm = SHA-1 - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki2.oids.sha1).getBytes() - ), - // parameters = Null - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // digest - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - macValue.getBytes() - ) - ]), - // macSalt OCTET STRING - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - macSalt.getBytes() - ), - // iterations INTEGER (XXX: Only support count < 65536) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(count).getBytes() - ) - ]); + if (salt === null) { + salt = ""; } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (3) + var digests = [hash(md, password + salt)]; + for (var length = 16, i = 1; length < dkLen; ++i, length += 16) { + digests.push(hash(md, digests[i - 1] + password + salt)); + } + return digests.join("").substr(0, dkLen); + }; + function hash(md, bytes) { + return md.start().update(bytes).digest().getBytes(); + } + function prfOidToMessageDigest(prfOid) { + var prfAlgorithm; + if (!prfOid) { + prfAlgorithm = "hmacWithSHA1"; + } else { + prfAlgorithm = pki2.oids[asn1.derToOid(prfOid)]; + if (!prfAlgorithm) { + var error4 = new Error("Unsupported PRF OID."); + error4.oid = prfOid; + error4.supported = [ + "hmacWithSHA1", + "hmacWithSHA224", + "hmacWithSHA256", + "hmacWithSHA384", + "hmacWithSHA512" + ]; + throw error4; + } + } + return prfAlgorithmToMessageDigest(prfAlgorithm); + } + function prfAlgorithmToMessageDigest(prfAlgorithm) { + var factory = forge.md; + switch (prfAlgorithm) { + case "hmacWithSHA224": + factory = forge.md.sha512; + case "hmacWithSHA1": + case "hmacWithSHA256": + case "hmacWithSHA384": + case "hmacWithSHA512": + prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); + break; + default: + var error4 = new Error("Unsupported PRF algorithm."); + error4.algorithm = prfAlgorithm; + error4.supported = [ + "hmacWithSHA1", + "hmacWithSHA224", + "hmacWithSHA256", + "hmacWithSHA384", + "hmacWithSHA512" + ]; + throw error4; + } + if (!factory || !(prfAlgorithm in factory)) { + throw new Error("Unknown hash algorithm: " + prfAlgorithm); + } + return factory[prfAlgorithm].create(); + } + function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { + var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, + asn1.Type.OCTETSTRING, false, - asn1.integerToDer(3).getBytes() + salt ), - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType + // iteration count + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + countBytes.getBytes() + ) + ]); + if (prfAlgorithm !== "hmacWithSHA1") { + params.value.push( + // key length asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.OID, + asn1.Type.INTEGER, false, - // OID for the content type is 'data' - asn1.oidToDer(pki2.oids.data).getBytes() + forge.util.hexToBytes(dkLen.toString(16)) ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm asn1.create( asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, + asn1.Type.OID, false, - asn1.toDer(safe).getBytes() - ) + asn1.oidToDer(pki2.oids[prfAlgorithm]).getBytes() + ), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") ]) - ]), - macData - ]); - }; - p12.generateKey = forge.pbe.generatePkcs12Key; + ); + } + return params; + } } }); -// node_modules/node-forge/lib/pki.js -var require_pki = __commonJS({ - "node_modules/node-forge/lib/pki.js"(exports2, module2) { +// node_modules/node-forge/lib/pkcs7asn1.js +var require_pkcs7asn1 = __commonJS({ + "node_modules/node-forge/lib/pkcs7asn1.js"(exports2, module2) { var forge = require_forge(); require_asn1(); - require_oids(); - require_pbe(); - require_pem(); - require_pbkdf2(); - require_pkcs12(); - require_pss(); - require_rsa(); require_util8(); - require_x509(); var asn1 = forge.asn1; - var pki2 = module2.exports = forge.pki = forge.pki || {}; - pki2.pemToDer = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert PEM to DER; PEM is encrypted."); - } - return forge.util.createBuffer(msg.body); - }; - pki2.privateKeyFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { - var error4 = new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); - error4.headerType = msg.type; - throw error4; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert private key from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return pki2.privateKeyFromAsn1(obj); - }; - pki2.privateKeyToPem = function(key, maxline) { - var msg = { - type: "RSA PRIVATE KEY", - body: asn1.toDer(pki2.privateKeyToAsn1(key)).getBytes() - }; - return forge.pem.encode(msg, { maxline }); + var p7v = module2.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; + forge.pkcs7 = forge.pkcs7 || {}; + forge.pkcs7.asn1 = p7v; + var contentInfoValidator = { + name: "ContentInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "ContentInfo.ContentType", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "contentType" + }, { + name: "ContentInfo.content", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + captureAsn1: "content" + }] }; - pki2.privateKeyInfoToPem = function(pki3, maxline) { - var msg = { - type: "PRIVATE KEY", - body: asn1.toDer(pki3).getBytes() - }; - return forge.pem.encode(msg, { maxline }); + p7v.contentInfoValidator = contentInfoValidator; + var encryptedContentInfoValidator = { + name: "EncryptedContentInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "EncryptedContentInfo.contentType", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "contentType" + }, { + name: "EncryptedContentInfo.contentEncryptionAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "EncryptedContentInfo.contentEncryptionAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "encAlgorithm" + }, { + name: "EncryptedContentInfo.contentEncryptionAlgorithm.parameter", + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: "encParameter" + }] + }, { + name: "EncryptedContentInfo.encryptedContent", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + /* The PKCS#7 structure output by OpenSSL somewhat differs from what + * other implementations do generate. + * + * OpenSSL generates a structure like this: + * SEQUENCE { + * ... + * [0] + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * + * Whereas other implementations (and this PKCS#7 module) generate: + * SEQUENCE { + * ... + * [0] { + * OCTET STRING + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * } + * + * In order to support both, we just capture the context specific + * field here. The OCTET STRING bit is removed below. + */ + capture: "encryptedContent", + captureAsn1: "encryptedContentAsn1" + }] }; - } -}); - -// node_modules/node-forge/lib/tls.js -var require_tls = __commonJS({ - "node_modules/node-forge/lib/tls.js"(exports2, module2) { - var forge = require_forge(); - require_asn1(); - require_hmac(); - require_md5(); - require_pem(); - require_pki(); - require_random(); - require_sha1(); - require_util8(); - var prf_TLS1 = function(secret, label, seed, length) { - var rval = forge.util.createBuffer(); - var idx = secret.length >> 1; - var slen = idx + (secret.length & 1); - var s1 = secret.substr(0, slen); - var s2 = secret.substr(idx, slen); - var ai = forge.util.createBuffer(); - var hmac = forge.hmac.create(); - seed = label + seed; - var md5itr = Math.ceil(length / 16); - var sha1itr = Math.ceil(length / 20); - hmac.start("MD5", s1); - var md5bytes = forge.util.createBuffer(); - ai.putBytes(seed); - for (var i = 0; i < md5itr; ++i) { - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - md5bytes.putBuffer(hmac.digest()); - } - hmac.start("SHA1", s2); - var sha1bytes = forge.util.createBuffer(); - ai.clear(); - ai.putBytes(seed); - for (var i = 0; i < sha1itr; ++i) { - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - sha1bytes.putBuffer(hmac.digest()); - } - rval.putBytes(forge.util.xorBytes( - md5bytes.getBytes(), - sha1bytes.getBytes(), - length - )); - return rval; + p7v.envelopedDataValidator = { + name: "EnvelopedData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "EnvelopedData.Version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }, { + name: "EnvelopedData.RecipientInfos", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: "recipientInfos" + }].concat(encryptedContentInfoValidator) }; - var hmac_sha1 = function(key2, seqNum, record) { - var hmac = forge.hmac.create(); - hmac.start("SHA1", key2); - var b = forge.util.createBuffer(); - b.putInt32(seqNum[0]); - b.putInt32(seqNum[1]); - b.putByte(record.type); - b.putByte(record.version.major); - b.putByte(record.version.minor); - b.putInt16(record.length); - b.putBytes(record.fragment.bytes()); - hmac.update(b.getBytes()); - return hmac.digest().getBytes(); + p7v.encryptedDataValidator = { + name: "EncryptedData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "EncryptedData.Version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }].concat(encryptedContentInfoValidator) }; - var deflate = function(c, record, s) { - var rval = false; - try { - var bytes = c.deflate(record.fragment.getBytes()); - record.fragment = forge.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch (ex) { - } - return rval; - }; - var inflate = function(c, record, s) { - var rval = false; - try { - var bytes = c.inflate(record.fragment.getBytes()); - record.fragment = forge.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch (ex) { - } - return rval; - }; - var readVector = function(b, lenBytes) { - var len = 0; - switch (lenBytes) { - case 1: - len = b.getByte(); - break; - case 2: - len = b.getInt16(); - break; - case 3: - len = b.getInt24(); - break; - case 4: - len = b.getInt32(); - break; - } - return forge.util.createBuffer(b.getBytes(len)); - }; - var writeVector = function(b, lenBytes, v) { - b.putInt(v.length(), lenBytes << 3); - b.putBuffer(v); - }; - var tls = {}; - tls.Versions = { - TLS_1_0: { major: 3, minor: 1 }, - TLS_1_1: { major: 3, minor: 2 }, - TLS_1_2: { major: 3, minor: 3 } - }; - tls.SupportedVersions = [ - tls.Versions.TLS_1_1, - tls.Versions.TLS_1_0 - ]; - tls.Version = tls.SupportedVersions[0]; - tls.MaxFragment = 16384 - 1024; - tls.ConnectionEnd = { - server: 0, - client: 1 - }; - tls.PRFAlgorithm = { - tls_prf_sha256: 0 - }; - tls.BulkCipherAlgorithm = { - none: null, - rc4: 0, - des3: 1, - aes: 2 - }; - tls.CipherType = { - stream: 0, - block: 1, - aead: 2 - }; - tls.MACAlgorithm = { - none: null, - hmac_md5: 0, - hmac_sha1: 1, - hmac_sha256: 2, - hmac_sha384: 3, - hmac_sha512: 4 - }; - tls.CompressionMethod = { - none: 0, - deflate: 1 - }; - tls.ContentType = { - change_cipher_spec: 20, - alert: 21, - handshake: 22, - application_data: 23, - heartbeat: 24 - }; - tls.HandshakeType = { - hello_request: 0, - client_hello: 1, - server_hello: 2, - certificate: 11, - server_key_exchange: 12, - certificate_request: 13, - server_hello_done: 14, - certificate_verify: 15, - client_key_exchange: 16, - finished: 20 - }; - tls.Alert = {}; - tls.Alert.Level = { - warning: 1, - fatal: 2 + var signerValidator = { + name: "SignerInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "SignerInfo.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false + }, { + name: "SignerInfo.issuerAndSerialNumber", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "SignerInfo.issuerAndSerialNumber.issuer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "issuer" + }, { + name: "SignerInfo.issuerAndSerialNumber.serialNumber", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "serial" + }] + }, { + name: "SignerInfo.digestAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "SignerInfo.digestAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "digestAlgorithm" + }, { + name: "SignerInfo.digestAlgorithm.parameter", + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: "digestParameter", + optional: true + }] + }, { + name: "SignerInfo.authenticatedAttributes", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: "authenticatedAttributes" + }, { + name: "SignerInfo.digestEncryptionAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + capture: "signatureAlgorithm" + }, { + name: "SignerInfo.encryptedDigest", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "signature" + }, { + name: "SignerInfo.unauthenticatedAttributes", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + capture: "unauthenticatedAttributes" + }] }; - tls.Alert.Description = { - close_notify: 0, - unexpected_message: 10, - bad_record_mac: 20, - decryption_failed: 21, - record_overflow: 22, - decompression_failure: 30, - handshake_failure: 40, - bad_certificate: 42, - unsupported_certificate: 43, - certificate_revoked: 44, - certificate_expired: 45, - certificate_unknown: 46, - illegal_parameter: 47, - unknown_ca: 48, - access_denied: 49, - decode_error: 50, - decrypt_error: 51, - export_restriction: 60, - protocol_version: 70, - insufficient_security: 71, - internal_error: 80, - user_canceled: 90, - no_renegotiation: 100 + p7v.signedDataValidator = { + name: "SignedData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: "SignedData.Version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }, + { + name: "SignedData.DigestAlgorithms", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: "digestAlgorithms" + }, + contentInfoValidator, + { + name: "SignedData.Certificates", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + optional: true, + captureAsn1: "certificates" + }, + { + name: "SignedData.CertificateRevocationLists", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + optional: true, + captureAsn1: "crls" + }, + { + name: "SignedData.SignerInfos", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + capture: "signerInfos", + optional: true, + value: [signerValidator] + } + ] }; - tls.HeartbeatMessageType = { - heartbeat_request: 1, - heartbeat_response: 2 + p7v.recipientInfoValidator = { + name: "RecipientInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "RecipientInfo.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }, { + name: "RecipientInfo.issuerAndSerial", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "RecipientInfo.issuerAndSerial.issuer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "issuer" + }, { + name: "RecipientInfo.issuerAndSerial.serialNumber", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "serial" + }] + }, { + name: "RecipientInfo.keyEncryptionAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "RecipientInfo.keyEncryptionAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "encAlgorithm" + }, { + name: "RecipientInfo.keyEncryptionAlgorithm.parameter", + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: "encParameter", + optional: true + }] + }, { + name: "RecipientInfo.encryptedKey", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "encKey" + }] }; - tls.CipherSuites = {}; - tls.getCipherSuite = function(twoBytes) { - var rval = null; - for (var key2 in tls.CipherSuites) { - var cs = tls.CipherSuites[key2]; - if (cs.id[0] === twoBytes.charCodeAt(0) && cs.id[1] === twoBytes.charCodeAt(1)) { - rval = cs; - break; + } +}); + +// node_modules/node-forge/lib/mgf1.js +var require_mgf1 = __commonJS({ + "node_modules/node-forge/lib/mgf1.js"(exports2, module2) { + var forge = require_forge(); + require_util8(); + forge.mgf = forge.mgf || {}; + var mgf1 = module2.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; + mgf1.create = function(md) { + var mgf = { + /** + * Generate mask of specified length. + * + * @param {String} seed The seed for mask generation. + * @param maskLen Number of bytes to generate. + * @return {String} The generated mask. + */ + generate: function(seed, maskLen) { + var t = new forge.util.ByteBuffer(); + var len = Math.ceil(maskLen / md.digestLength); + for (var i = 0; i < len; i++) { + var c = new forge.util.ByteBuffer(); + c.putInt32(i); + md.start(); + md.update(seed + c.getBytes()); + t.putBuffer(md.digest()); + } + t.truncate(t.length() - maskLen); + return t.getBytes(); } - } - return rval; + }; + return mgf; }; - tls.handleUnexpected = function(c, record) { - var ignore = !c.open && c.entity === tls.ConnectionEnd.client; - if (!ignore) { - c.error(c, { - message: "Unexpected message. Received TLS record out of order.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unexpected_message - } - }); + } +}); + +// node_modules/node-forge/lib/mgf.js +var require_mgf = __commonJS({ + "node_modules/node-forge/lib/mgf.js"(exports2, module2) { + var forge = require_forge(); + require_mgf1(); + module2.exports = forge.mgf = forge.mgf || {}; + forge.mgf.mgf1 = forge.mgf1; + } +}); + +// node_modules/node-forge/lib/pss.js +var require_pss = __commonJS({ + "node_modules/node-forge/lib/pss.js"(exports2, module2) { + var forge = require_forge(); + require_random(); + require_util8(); + var pss = module2.exports = forge.pss = forge.pss || {}; + pss.create = function(options) { + if (arguments.length === 3) { + options = { + md: arguments[0], + mgf: arguments[1], + saltLength: arguments[2] + }; } - }; - tls.handleHelloRequest = function(c, record, length) { - if (!c.handshaking && c.handshakes > 0) { - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.no_renegotiation - })); - tls.flush(c); + var hash = options.md; + var mgf = options.mgf; + var hLen = hash.digestLength; + var salt_ = options.salt || null; + if (typeof salt_ === "string") { + salt_ = forge.util.createBuffer(salt_); } - c.process(); - }; - tls.parseHelloMessage = function(c, record, length) { - var msg = null; - var client = c.entity === tls.ConnectionEnd.client; - if (length < 38) { - c.error(c, { - message: client ? "Invalid ServerHello message. Message too short." : "Invalid ClientHello message. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); + var sLen; + if ("saltLength" in options) { + sLen = options.saltLength; + } else if (salt_ !== null) { + sLen = salt_.length(); } else { - var b = record.fragment; - var remaining = b.length(); - msg = { - version: { - major: b.getByte(), - minor: b.getByte() - }, - random: forge.util.createBuffer(b.getBytes(32)), - session_id: readVector(b, 1), - extensions: [] - }; - if (client) { - msg.cipher_suite = b.getBytes(2); - msg.compression_method = b.getByte(); - } else { - msg.cipher_suites = readVector(b, 2); - msg.compression_methods = readVector(b, 1); - } - remaining = length - (remaining - b.length()); - if (remaining > 0) { - var exts = readVector(b, 2); - while (exts.length() > 0) { - msg.extensions.push({ - type: [exts.getByte(), exts.getByte()], - data: readVector(exts, 2) - }); - } - if (!client) { - for (var i = 0; i < msg.extensions.length; ++i) { - var ext = msg.extensions[i]; - if (ext.type[0] === 0 && ext.type[1] === 0) { - var snl = readVector(ext.data, 2); - while (snl.length() > 0) { - var snType = snl.getByte(); - if (snType !== 0) { - break; - } - c.session.extensions.server_name.serverNameList.push( - readVector(snl, 2).getBytes() - ); - } - } - } - } - } - if (c.session.version) { - if (msg.version.major !== c.session.version.major || msg.version.minor !== c.session.version.minor) { - return c.error(c, { - message: "TLS version change is disallowed during renegotiation.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } + throw new Error("Salt length not specified or specific salt not given."); + } + if (salt_ !== null && salt_.length() !== sLen) { + throw new Error("Given salt length does not match length of given salt."); + } + var prng = options.prng || forge.random; + var pssobj = {}; + pssobj.encode = function(md, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + var mHash = md.digest().getBytes(); + if (emLen < hLen + sLen + 2) { + throw new Error("Message is too long to encrypt."); } - if (client) { - c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); + var salt; + if (salt_ === null) { + salt = prng.getBytesSync(sLen); } else { - var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); - while (tmp.length() > 0) { - c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); - if (c.session.cipherSuite !== null) { - break; - } - } + salt = salt_.bytes(); } - if (c.session.cipherSuite === null) { - return c.error(c, { - message: "No cipher suites in common.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - }, - cipherSuite: forge.util.bytesToHex(msg.cipher_suite) - }); - } - if (client) { - c.session.compressionMethod = msg.compression_method; - } else { - c.session.compressionMethod = tls.CompressionMethod.none; + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + hash.start(); + hash.update(m_.getBytes()); + var h = hash.digest().getBytes(); + var ps = new forge.util.ByteBuffer(); + ps.fillWithByte(0, emLen - sLen - hLen - 2); + ps.putByte(1); + ps.putBytes(salt); + var db = ps.getBytes(); + var maskLen = emLen - hLen - 1; + var dbMask = mgf.generate(h, maskLen); + var maskedDB = ""; + for (i = 0; i < maskLen; i++) { + maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); } - } - return msg; - }; - tls.createSecurityParameters = function(c, msg) { - var client = c.entity === tls.ConnectionEnd.client; - var msgRandom = msg.random.bytes(); - var cRandom = client ? c.session.sp.client_random : msgRandom; - var sRandom = client ? msgRandom : tls.createRandom().getBytes(); - c.session.sp = { - entity: c.entity, - prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, - bulk_cipher_algorithm: null, - cipher_type: null, - enc_key_length: null, - block_length: null, - fixed_iv_length: null, - record_iv_length: null, - mac_algorithm: null, - mac_length: null, - mac_key_length: null, - compression_algorithm: c.session.compressionMethod, - pre_master_secret: null, - master_secret: null, - client_random: cRandom, - server_random: sRandom + var mask = 65280 >> 8 * emLen - emBits & 255; + maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1); + return maskedDB + h + String.fromCharCode(188); }; - }; - tls.handleServerHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if (c.fail) { - return; - } - if (msg.version.minor <= c.version.minor) { - c.version.minor = msg.version.minor; - } else { - return c.error(c, { - message: "Incompatible TLS version.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - c.session.version = c.version; - var sessionId = msg.session_id.bytes(); - if (sessionId.length > 0 && sessionId === c.session.id) { - c.expect = SCC; - c.session.resuming = true; - c.session.sp.server_random = msg.random.bytes(); - } else { - c.expect = SCE; - c.session.resuming = false; - tls.createSecurityParameters(c, msg); - } - c.session.id = sessionId; - c.process(); - }; - tls.handleClientHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if (c.fail) { - return; - } - var sessionId = msg.session_id.bytes(); - var session = null; - if (c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - if (session === null) { - sessionId = ""; - } else if (session.version.major !== msg.version.major || session.version.minor > msg.version.minor) { - session = null; - sessionId = ""; + pssobj.verify = function(mHash, em, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + em = em.substr(-emLen); + if (emLen < hLen + sLen + 2) { + throw new Error("Inconsistent parameters to PSS signature verification."); } - } - if (sessionId.length === 0) { - sessionId = forge.random.getBytes(32); - } - c.session.id = sessionId; - c.session.clientHelloVersion = msg.version; - c.session.sp = {}; - if (session) { - c.version = c.session.version = session.version; - c.session.sp = session.sp; - } else { - var version; - for (var i = 1; i < tls.SupportedVersions.length; ++i) { - version = tls.SupportedVersions[i]; - if (version.minor <= msg.version.minor) { - break; - } + if (em.charCodeAt(emLen - 1) !== 188) { + throw new Error("Encoded message does not end in 0xBC."); } - c.version = { major: version.major, minor: version.minor }; - c.session.version = c.version; - } - if (session !== null) { - c.expect = CCC; - c.session.resuming = true; - c.session.sp.client_random = msg.random.bytes(); - } else { - c.expect = c.verifyClient !== false ? CCE : CKE; - c.session.resuming = false; - tls.createSecurityParameters(c, msg); - } - c.open = true; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHello(c) - })); - if (c.session.resuming) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c.state.pending = tls.createConnectionState(c); - c.state.current.write = c.state.pending.write; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); - } else { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - })); - if (!c.fail) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerKeyExchange(c) - })); - if (c.verifyClient !== false) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificateRequest(c) - })); - } - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHelloDone(c) - })); + var maskLen = emLen - hLen - 1; + var maskedDB = em.substr(0, maskLen); + var h = em.substr(maskLen, hLen); + var mask = 65280 >> 8 * emLen - emBits & 255; + if ((maskedDB.charCodeAt(0) & mask) !== 0) { + throw new Error("Bits beyond keysize not zero as expected."); } - } - tls.flush(c); - c.process(); - }; - tls.handleCertificate = function(c, record, length) { - if (length < 3) { - return c.error(c, { - message: "Invalid Certificate message. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - var msg = { - certificate_list: readVector(b, 3) - }; - var cert, asn1; - var certs = []; - try { - while (msg.certificate_list.length() > 0) { - cert = readVector(msg.certificate_list, 3); - asn1 = forge.asn1.fromDer(cert); - cert = forge.pki.certificateFromAsn1(asn1, true); - certs.push(cert); + var dbMask = mgf.generate(h, maskLen); + var db = ""; + for (i = 0; i < maskLen; i++) { + db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); } - } catch (ex) { - return c.error(c, { - message: "Could not parse certificate list.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - } - }); - } - var client = c.entity === tls.ConnectionEnd.client; - if ((client || c.verifyClient === true) && certs.length === 0) { - c.error(c, { - message: client ? "No server certificate provided." : "No client certificate provided.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter + db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); + var checkLen = emLen - hLen - sLen - 2; + for (i = 0; i < checkLen; i++) { + if (db.charCodeAt(i) !== 0) { + throw new Error("Leftmost octets not zero as expected"); } - }); - } else if (certs.length === 0) { - c.expect = client ? SKE : CKE; - } else { - if (client) { - c.session.serverCertificate = certs[0]; - } else { - c.session.clientCertificate = certs[0]; } - if (tls.verifyCertificateChain(c, certs)) { - c.expect = client ? SKE : CKE; + if (db.charCodeAt(checkLen) !== 1) { + throw new Error("Inconsistent PSS signature, 0x01 marker not found"); } - } - c.process(); + var salt = db.substr(-sLen); + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + hash.start(); + hash.update(m_.getBytes()); + var h_ = hash.digest().getBytes(); + return h === h_; + }; + return pssobj; }; - tls.handleServerKeyExchange = function(c, record, length) { - if (length > 0) { - return c.error(c, { - message: "Invalid key parameters. Only RSA is supported.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate + } +}); + +// node_modules/node-forge/lib/x509.js +var require_x509 = __commonJS({ + "node_modules/node-forge/lib/x509.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_asn1(); + require_des(); + require_md(); + require_mgf(); + require_oids(); + require_pem(); + require_pss(); + require_rsa(); + require_util8(); + var asn1 = forge.asn1; + var pki2 = module2.exports = forge.pki = forge.pki || {}; + var oids = pki2.oids; + var _shortNames = {}; + _shortNames["CN"] = oids["commonName"]; + _shortNames["commonName"] = "CN"; + _shortNames["C"] = oids["countryName"]; + _shortNames["countryName"] = "C"; + _shortNames["L"] = oids["localityName"]; + _shortNames["localityName"] = "L"; + _shortNames["ST"] = oids["stateOrProvinceName"]; + _shortNames["stateOrProvinceName"] = "ST"; + _shortNames["O"] = oids["organizationName"]; + _shortNames["organizationName"] = "O"; + _shortNames["OU"] = oids["organizationalUnitName"]; + _shortNames["organizationalUnitName"] = "OU"; + _shortNames["E"] = oids["emailAddress"]; + _shortNames["emailAddress"] = "E"; + var publicKeyValidator = forge.pki.rsa.publicKeyValidator; + var x509CertificateValidator = { + name: "Certificate", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "Certificate.TBSCertificate", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "tbsCertificate", + value: [ + { + name: "Certificate.TBSCertificate.version", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + value: [{ + name: "Certificate.TBSCertificate.version.integer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "certVersion" + }] + }, + { + name: "Certificate.TBSCertificate.serialNumber", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "certSerialNumber" + }, + { + name: "Certificate.TBSCertificate.signature", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "Certificate.TBSCertificate.signature.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "certinfoSignatureOid" + }, { + name: "Certificate.TBSCertificate.signature.parameters", + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: "certinfoSignatureParams" + }] + }, + { + name: "Certificate.TBSCertificate.issuer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "certIssuer" + }, + { + name: "Certificate.TBSCertificate.validity", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + // Note: UTC and generalized times may both appear so the capture + // names are based on their detected order, the names used below + // are only for the common case, which validity time really means + // "notBefore" and which means "notAfter" will be determined by order + value: [{ + // notBefore (Time) (UTC time case) + name: "Certificate.TBSCertificate.validity.notBefore (utc)", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: "certValidity1UTCTime" + }, { + // notBefore (Time) (generalized time case) + name: "Certificate.TBSCertificate.validity.notBefore (generalized)", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: "certValidity2GeneralizedTime" + }, { + // notAfter (Time) (only UTC time is supported) + name: "Certificate.TBSCertificate.validity.notAfter (utc)", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: "certValidity3UTCTime" + }, { + // notAfter (Time) (only UTC time is supported) + name: "Certificate.TBSCertificate.validity.notAfter (generalized)", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: "certValidity4GeneralizedTime" + }] + }, + { + // Name (subject) (RDNSequence) + name: "Certificate.TBSCertificate.subject", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "certSubject" + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + // issuerUniqueID (optional) + name: "Certificate.TBSCertificate.issuerUniqueID", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + value: [{ + name: "Certificate.TBSCertificate.issuerUniqueID.id", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: "certIssuerUniqueId" + }] + }, + { + // subjectUniqueID (optional) + name: "Certificate.TBSCertificate.subjectUniqueID", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + constructed: true, + optional: true, + value: [{ + name: "Certificate.TBSCertificate.subjectUniqueID.id", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: "certSubjectUniqueId" + }] + }, + { + // Extensions (optional) + name: "Certificate.TBSCertificate.extensions", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + constructed: true, + captureAsn1: "certExtensions", + optional: true } - }); - } - c.expect = SCR; - c.process(); + ] + }, { + // AlgorithmIdentifier (signature algorithm) + name: "Certificate.signatureAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: "Certificate.signatureAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "certSignatureOid" + }, { + name: "Certificate.TBSCertificate.signature.parameters", + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: "certSignatureParams" + }] + }, { + // SignatureValue + name: "Certificate.signatureValue", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: "certSignature" + }] }; - tls.handleClientKeyExchange = function(c, record, length) { - if (length < 48) { - return c.error(c, { - message: "Invalid key parameters. Only RSA is supported.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate - } - }); - } - var b = record.fragment; - var msg = { - enc_pre_master_secret: readVector(b, 2).getBytes() - }; - var privateKey = null; - if (c.getPrivateKey) { - try { - privateKey = c.getPrivateKey(c, c.session.serverCertificate); - privateKey = forge.pki.privateKeyFromPem(privateKey); - } catch (ex) { - c.error(c, { - message: "Could not get private key.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); + var rsassaPssParameterValidator = { + name: "rsapss", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "rsapss.hashAlgorithm", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + value: [{ + name: "rsapss.hashAlgorithm.AlgorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: "rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "hashOid" + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }, { + name: "rsapss.maskGenAlgorithm", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + value: [{ + name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "maskGenOid" + }, { + name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "maskGenHashOid" + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }] + }, { + name: "rsapss.saltLength", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + optional: true, + value: [{ + name: "rsapss.saltLength.saltLength", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: "saltLength" + }] + }, { + name: "rsapss.trailerField", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + optional: true, + value: [{ + name: "rsapss.trailer.trailer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: "trailer" + }] + }] + }; + var certificationRequestInfoValidator = { + name: "CertificationRequestInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "certificationRequestInfo", + value: [ + { + name: "CertificationRequestInfo.integer", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "certificationRequestInfoVersion" + }, + { + // Name (subject) (RDNSequence) + name: "CertificationRequestInfo.subject", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "certificationRequestInfoSubject" + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + name: "CertificationRequestInfo.attributes", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: "certificationRequestInfoAttributes", + value: [{ + name: "CertificationRequestInfo.attributes", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "CertificationRequestInfo.attributes.type", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false + }, { + name: "CertificationRequestInfo.attributes.value", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true + }] + }] } - } - if (privateKey === null) { - return c.error(c, { - message: "No private key set.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - try { - var sp = c.session.sp; - sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); - var version = c.session.clientHelloVersion; - if (version.major !== sp.pre_master_secret.charCodeAt(0) || version.minor !== sp.pre_master_secret.charCodeAt(1)) { - throw new Error("TLS version rollback attack detected."); + ] + }; + var certificationRequestValidator = { + name: "CertificationRequest", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "csr", + value: [ + certificationRequestInfoValidator, + { + // AlgorithmIdentifier (signature algorithm) + name: "CertificationRequest.signatureAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: "CertificationRequest.signatureAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "csrSignatureOid" + }, { + name: "CertificationRequest.signatureAlgorithm.parameters", + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: "csrSignatureParams" + }] + }, + { + // signature + name: "CertificationRequest.signature", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: "csrSignature" } - } catch (ex) { - sp.pre_master_secret = forge.random.getBytes(48); - } - c.expect = CCC; - if (c.session.clientCertificate !== null) { - c.expect = CCV; - } - c.process(); + ] }; - tls.handleCertificateRequest = function(c, record, length) { - if (length < 3) { - return c.error(c, { - message: "Invalid CertificateRequest. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter + pki2.RDNAttributesAsArray = function(rdn, md) { + var rval = []; + var set2, attr, obj; + for (var si = 0; si < rdn.value.length; ++si) { + set2 = rdn.value[si]; + for (var i = 0; i < set2.value.length; ++i) { + obj = {}; + attr = set2.value[i]; + obj.type = asn1.derToOid(attr.value[0].value); + obj.value = attr.value[1].value; + obj.valueTagClass = attr.value[1].type; + if (obj.type in oids) { + obj.name = oids[obj.type]; + if (obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } } - }); - } - var b = record.fragment; - var msg = { - certificate_types: readVector(b, 1), - certificate_authorities: readVector(b, 2) - }; - c.session.certificateRequest = msg; - c.expect = SHD; - c.process(); - }; - tls.handleCertificateVerify = function(c, record, length) { - if (length < 2) { - return c.error(c, { - message: "Invalid CertificateVerify. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter + if (md) { + md.update(obj.type); + md.update(obj.value); } - }); - } - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - var msg = { - signature: readVector(b, 2).getBytes() - }; - var verify = forge.util.createBuffer(); - verify.putBuffer(c.session.md5.digest()); - verify.putBuffer(c.session.sha1.digest()); - verify = verify.getBytes(); - try { - var cert = c.session.clientCertificate; - if (!cert.publicKey.verify(verify, msg.signature, "NONE")) { - throw new Error("CertificateVerify signature does not match."); + rval.push(obj); } - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - } catch (ex) { - return c.error(c, { - message: "Bad signature in CertificateVerify.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - } - }); } - c.expect = CCC; - c.process(); + return rval; }; - tls.handleServerHelloDone = function(c, record, length) { - if (length > 0) { - return c.error(c, { - message: "Invalid ServerHelloDone message. Invalid length.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.record_overflow - } - }); - } - if (c.serverCertificate === null) { - var error4 = { - message: "No server certificate provided. Not enough security.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.insufficient_security + pki2.CRIAttributesAsArray = function(attributes) { + var rval = []; + for (var si = 0; si < attributes.length; ++si) { + var seq2 = attributes[si]; + var type2 = asn1.derToOid(seq2.value[0].value); + var values = seq2.value[1].value; + for (var vi = 0; vi < values.length; ++vi) { + var obj = {}; + obj.type = type2; + obj.value = values[vi].value; + obj.valueTagClass = values[vi].type; + if (obj.type in oids) { + obj.name = oids[obj.type]; + if (obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } } - }; - var depth = 0; - var ret = c.verify(c, error4.alert.description, depth, []); - if (ret !== true) { - if (ret || ret === 0) { - if (typeof ret === "object" && !forge.util.isArray(ret)) { - if (ret.message) { - error4.message = ret.message; - } - if (ret.alert) { - error4.alert.description = ret.alert; - } - } else if (typeof ret === "number") { - error4.alert.description = ret; + if (obj.type === oids.extensionRequest) { + obj.extensions = []; + for (var ei = 0; ei < obj.value.length; ++ei) { + obj.extensions.push(pki2.certificateExtensionFromAsn1(obj.value[ei])); } } - return c.error(c, error4); + rval.push(obj); } } - if (c.session.certificateRequest !== null) { - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - }); - tls.queue(c, record); + return rval; + }; + function _getAttribute(obj, options) { + if (typeof options === "string") { + options = { shortName: options }; } - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientKeyExchange(c) - }); - tls.queue(c, record); - c.expect = SER; - var callback = function(c2, signature) { - if (c2.session.certificateRequest !== null && c2.session.clientCertificate !== null) { - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.handshake, - data: tls.createCertificateVerify(c2, signature) - })); + var rval = null; + var attr; + for (var i = 0; rval === null && i < obj.attributes.length; ++i) { + attr = obj.attributes[i]; + if (options.type && options.type === attr.type) { + rval = attr; + } else if (options.name && options.name === attr.name) { + rval = attr; + } else if (options.shortName && options.shortName === attr.shortName) { + rval = attr; } - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c2.state.pending = tls.createConnectionState(c2); - c2.state.current.write = c2.state.pending.write; - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.handshake, - data: tls.createFinished(c2) - })); - c2.expect = SCC; - tls.flush(c2); - c2.process(); - }; - if (c.session.certificateRequest === null || c.session.clientCertificate === null) { - return callback(c, null); } - tls.getClientSignature(c, callback); - }; - tls.handleChangeCipherSpec = function(c, record) { - if (record.fragment.getByte() !== 1) { - return c.error(c, { - message: "Invalid ChangeCipherSpec message received.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); + return rval; + } + var _readSignatureParameters = function(oid, obj, fillDefaults) { + var params = {}; + if (oid !== oids["RSASSA-PSS"]) { + return params; } - var client = c.entity === tls.ConnectionEnd.client; - if (c.session.resuming && client || !c.session.resuming && !client) { - c.state.pending = tls.createConnectionState(c); + if (fillDefaults) { + params = { + hash: { + algorithmOid: oids["sha1"] + }, + mgf: { + algorithmOid: oids["mgf1"], + hash: { + algorithmOid: oids["sha1"] + } + }, + saltLength: 20 + }; } - c.state.current.read = c.state.pending.read; - if (!c.session.resuming && client || c.session.resuming && !client) { - c.state.pending = null; + var capture = {}; + var errors = []; + if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { + var error4 = new Error("Cannot read RSASSA-PSS parameter block."); + error4.errors = errors; + throw error4; } - c.expect = client ? SFI : CFI; - c.process(); - }; - tls.handleFinished = function(c, record, length) { - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - var vd = record.fragment.getBytes(); - b = forge.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - var client = c.entity === tls.ConnectionEnd.client; - var label = client ? "server finished" : "client finished"; - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - if (b.getBytes() !== vd) { - return c.error(c, { - message: "Invalid verify_data in Finished message.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decrypt_error - } - }); + if (capture.hashOid !== void 0) { + params.hash = params.hash || {}; + params.hash.algorithmOid = asn1.derToOid(capture.hashOid); } - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - if (c.session.resuming && client || !c.session.resuming && !client) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c.state.current.write = c.state.pending.write; - c.state.pending = null; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); + if (capture.maskGenOid !== void 0) { + params.mgf = params.mgf || {}; + params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); + params.mgf.hash = params.mgf.hash || {}; + params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); } - c.expect = client ? SAD : CAD; - c.handshaking = false; - ++c.handshakes; - c.peerCertificate = client ? c.session.serverCertificate : c.session.clientCertificate; - tls.flush(c); - c.isConnected = true; - c.connected(c); - c.process(); + if (capture.saltLength !== void 0) { + params.saltLength = capture.saltLength.charCodeAt(0); + } + return params; }; - tls.handleAlert = function(c, record) { - var b = record.fragment; - var alert = { - level: b.getByte(), - description: b.getByte() - }; - var msg; - switch (alert.description) { - case tls.Alert.Description.close_notify: - msg = "Connection closed."; - break; - case tls.Alert.Description.unexpected_message: - msg = "Unexpected message."; - break; - case tls.Alert.Description.bad_record_mac: - msg = "Bad record MAC."; - break; - case tls.Alert.Description.decryption_failed: - msg = "Decryption failed."; - break; - case tls.Alert.Description.record_overflow: - msg = "Record overflow."; - break; - case tls.Alert.Description.decompression_failure: - msg = "Decompression failed."; - break; - case tls.Alert.Description.handshake_failure: - msg = "Handshake failure."; - break; - case tls.Alert.Description.bad_certificate: - msg = "Bad certificate."; - break; - case tls.Alert.Description.unsupported_certificate: - msg = "Unsupported certificate."; - break; - case tls.Alert.Description.certificate_revoked: - msg = "Certificate revoked."; - break; - case tls.Alert.Description.certificate_expired: - msg = "Certificate expired."; - break; - case tls.Alert.Description.certificate_unknown: - msg = "Certificate unknown."; - break; - case tls.Alert.Description.illegal_parameter: - msg = "Illegal parameter."; - break; - case tls.Alert.Description.unknown_ca: - msg = "Unknown certificate authority."; - break; - case tls.Alert.Description.access_denied: - msg = "Access denied."; - break; - case tls.Alert.Description.decode_error: - msg = "Decode error."; - break; - case tls.Alert.Description.decrypt_error: - msg = "Decrypt error."; - break; - case tls.Alert.Description.export_restriction: - msg = "Export restriction."; - break; - case tls.Alert.Description.protocol_version: - msg = "Unsupported protocol version."; - break; - case tls.Alert.Description.insufficient_security: - msg = "Insufficient security."; - break; - case tls.Alert.Description.internal_error: - msg = "Internal error."; - break; - case tls.Alert.Description.user_canceled: - msg = "User canceled."; - break; - case tls.Alert.Description.no_renegotiation: - msg = "Renegotiation not supported."; - break; + var _createSignatureDigest = function(options) { + switch (oids[options.signatureOid]) { + case "sha1WithRSAEncryption": + // deprecated alias + case "sha1WithRSASignature": + return forge.md.sha1.create(); + case "md5WithRSAEncryption": + return forge.md.md5.create(); + case "sha256WithRSAEncryption": + return forge.md.sha256.create(); + case "sha384WithRSAEncryption": + return forge.md.sha384.create(); + case "sha512WithRSAEncryption": + return forge.md.sha512.create(); + case "RSASSA-PSS": + return forge.md.sha256.create(); default: - msg = "Unknown error."; + var error4 = new Error( + "Could not compute " + options.type + " digest. Unknown signature OID." + ); + error4.signatureOid = options.signatureOid; + throw error4; + } + }; + var _verifySignature = function(options) { + var cert = options.certificate; + var scheme; + switch (cert.signatureOid) { + case oids.sha1WithRSAEncryption: + // deprecated alias + case oids.sha1WithRSASignature: + break; + case oids["RSASSA-PSS"]: + var hash, mgf; + hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; + if (hash === void 0 || forge.md[hash] === void 0) { + var error4 = new Error("Unsupported MGF hash function."); + error4.oid = cert.signatureParameters.mgf.hash.algorithmOid; + error4.name = hash; + throw error4; + } + mgf = oids[cert.signatureParameters.mgf.algorithmOid]; + if (mgf === void 0 || forge.mgf[mgf] === void 0) { + var error4 = new Error("Unsupported MGF function."); + error4.oid = cert.signatureParameters.mgf.algorithmOid; + error4.name = mgf; + throw error4; + } + mgf = forge.mgf[mgf].create(forge.md[hash].create()); + hash = oids[cert.signatureParameters.hash.algorithmOid]; + if (hash === void 0 || forge.md[hash] === void 0) { + var error4 = new Error("Unsupported RSASSA-PSS hash function."); + error4.oid = cert.signatureParameters.hash.algorithmOid; + error4.name = hash; + throw error4; + } + scheme = forge.pss.create( + forge.md[hash].create(), + mgf, + cert.signatureParameters.saltLength + ); break; } - if (alert.description === tls.Alert.Description.close_notify) { - return c.close(); + return cert.publicKey.verify( + options.md.digest().getBytes(), + options.signature, + scheme + ); + }; + pki2.certificateFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { + var error4 = new Error( + 'Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".' + ); + error4.headerType = msg.type; + throw error4; } - c.error(c, { - message: msg, - send: false, - // origin is the opposite end - origin: c.entity === tls.ConnectionEnd.client ? "server" : "client", - alert - }); - c.process(); + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error( + "Could not convert certificate from PEM; PEM is encrypted." + ); + } + var obj = asn1.fromDer(msg.body, strict); + return pki2.certificateFromAsn1(obj, computeHash); }; - tls.handleHandshake = function(c, record) { - var b = record.fragment; - var type2 = b.getByte(); - var length = b.getInt24(); - if (length > b.length()) { - c.fragmented = record; - record.fragment = forge.util.createBuffer(); - b.read -= 4; - return c.process(); + pki2.certificateToPem = function(cert, maxline) { + var msg = { + type: "CERTIFICATE", + body: asn1.toDer(pki2.certificateToAsn1(cert)).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.publicKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "PUBLIC KEY" && msg.type !== "RSA PUBLIC KEY") { + var error4 = new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); + error4.headerType = msg.type; + throw error4; } - c.fragmented = null; - b.read -= 4; - var bytes = b.bytes(length + 4); - b.read += 4; - if (type2 in hsTable[c.entity][c.expect]) { - if (c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { - c.handshaking = true; - c.session = { - version: null, - extensions: { - server_name: { - serverNameList: [] - } - }, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - clientCertificate: null, - md5: forge.md.md5.create(), - sha1: forge.md.sha1.create() - }; - } - if (type2 !== tls.HandshakeType.hello_request && type2 !== tls.HandshakeType.certificate_verify && type2 !== tls.HandshakeType.finished) { - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - } - hsTable[c.entity][c.expect][type2](c, record, length); - } else { - tls.handleUnexpected(c, record); + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert public key from PEM; PEM is encrypted."); } + var obj = asn1.fromDer(msg.body); + return pki2.publicKeyFromAsn1(obj); }; - tls.handleApplicationData = function(c, record) { - c.data.putBuffer(record.fragment); - c.dataReady(c); - c.process(); + pki2.publicKeyToPem = function(key, maxline) { + var msg = { + type: "PUBLIC KEY", + body: asn1.toDer(pki2.publicKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, { maxline }); }; - tls.handleHeartbeat = function(c, record) { - var b = record.fragment; - var type2 = b.getByte(); - var length = b.getInt16(); - var payload = b.getBytes(length); - if (type2 === tls.HeartbeatMessageType.heartbeat_request) { - if (c.handshaking || length > payload.length) { - return c.process(); - } - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_response, - payload - ) - })); - tls.flush(c); - } else if (type2 === tls.HeartbeatMessageType.heartbeat_response) { - if (payload !== c.expectedHeartbeatPayload) { - return c.process(); - } - if (c.heartbeatReceived) { - c.heartbeatReceived(c, forge.util.createBuffer(payload)); + pki2.publicKeyToRSAPublicKeyPem = function(key, maxline) { + var msg = { + type: "RSA PUBLIC KEY", + body: asn1.toDer(pki2.publicKeyToRSAPublicKey(key)).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge.md.sha1.create(); + var type2 = options.type || "RSAPublicKey"; + var bytes; + switch (type2) { + case "RSAPublicKey": + bytes = asn1.toDer(pki2.publicKeyToRSAPublicKey(key)).getBytes(); + break; + case "SubjectPublicKeyInfo": + bytes = asn1.toDer(pki2.publicKeyToAsn1(key)).getBytes(); + break; + default: + throw new Error('Unknown fingerprint type "' + options.type + '".'); + } + md.start(); + md.update(bytes); + var digest = md.digest(); + if (options.encoding === "hex") { + var hex = digest.toHex(); + if (options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); } + return hex; + } else if (options.encoding === "binary") { + return digest.getBytes(); + } else if (options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); } - c.process(); + return digest; }; - var SHE = 0; - var SCE = 1; - var SKE = 2; - var SCR = 3; - var SHD = 4; - var SCC = 5; - var SFI = 6; - var SAD = 7; - var SER = 8; - var CHE = 0; - var CCE = 1; - var CKE = 2; - var CCV = 3; - var CCC = 4; - var CFI = 5; - var CAD = 6; - var __ = tls.handleUnexpected; - var R0 = tls.handleChangeCipherSpec; - var R1 = tls.handleAlert; - var R2 = tls.handleHandshake; - var R3 = tls.handleApplicationData; - var R4 = tls.handleHeartbeat; - var ctTable = []; - ctTable[tls.ConnectionEnd.client] = [ - // CC,AL,HS,AD,HB - /*SHE*/ - [__, R1, R2, __, R4], - /*SCE*/ - [__, R1, R2, __, R4], - /*SKE*/ - [__, R1, R2, __, R4], - /*SCR*/ - [__, R1, R2, __, R4], - /*SHD*/ - [__, R1, R2, __, R4], - /*SCC*/ - [R0, R1, __, __, R4], - /*SFI*/ - [__, R1, R2, __, R4], - /*SAD*/ - [__, R1, R2, R3, R4], - /*SER*/ - [__, R1, R2, __, R4] - ]; - ctTable[tls.ConnectionEnd.server] = [ - // CC,AL,HS,AD - /*CHE*/ - [__, R1, R2, __, R4], - /*CCE*/ - [__, R1, R2, __, R4], - /*CKE*/ - [__, R1, R2, __, R4], - /*CCV*/ - [__, R1, R2, __, R4], - /*CCC*/ - [R0, R1, __, __, R4], - /*CFI*/ - [__, R1, R2, __, R4], - /*CAD*/ - [__, R1, R2, R3, R4], - /*CER*/ - [__, R1, R2, __, R4] - ]; - var H0 = tls.handleHelloRequest; - var H1 = tls.handleServerHello; - var H2 = tls.handleCertificate; - var H3 = tls.handleServerKeyExchange; - var H4 = tls.handleCertificateRequest; - var H5 = tls.handleServerHelloDone; - var H6 = tls.handleFinished; - var hsTable = []; - hsTable[tls.ConnectionEnd.client] = [ - // HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI - /*SHE*/ - [__, __, H1, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SCE*/ - [H0, __, __, __, __, __, __, __, __, __, __, H2, H3, H4, H5, __, __, __, __, __, __], - /*SKE*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, H3, H4, H5, __, __, __, __, __, __], - /*SCR*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, H4, H5, __, __, __, __, __, __], - /*SHD*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, H5, __, __, __, __, __, __], - /*SCC*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SFI*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], - /*SAD*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SER*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] - ]; - var H7 = tls.handleClientHello; - var H8 = tls.handleClientKeyExchange; - var H9 = tls.handleCertificateVerify; - hsTable[tls.ConnectionEnd.server] = [ - // 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI - /*CHE*/ - [__, H7, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CCE*/ - [__, __, __, __, __, __, __, __, __, __, __, H2, __, __, __, __, __, __, __, __, __], - /*CKE*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H8, __, __, __, __], - /*CCV*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H9, __, __, __, __, __], - /*CCC*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CFI*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], - /*CAD*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CER*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] - ]; - tls.generateKeys = function(c, sp) { - var prf = prf_TLS1; - var random = sp.client_random + sp.server_random; - if (!c.session.resuming) { - sp.master_secret = prf( - sp.pre_master_secret, - "master secret", - random, - 48 - ).bytes(); - sp.pre_master_secret = null; + pki2.certificationRequestFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "CERTIFICATE REQUEST") { + var error4 = new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".'); + error4.headerType = msg.type; + throw error4; } - random = sp.server_random + sp.client_random; - var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; - var tls10 = c.version.major === tls.Versions.TLS_1_0.major && c.version.minor === tls.Versions.TLS_1_0.minor; - if (tls10) { - length += 2 * sp.fixed_iv_length; + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert certification request from PEM; PEM is encrypted."); } - var km = prf(sp.master_secret, "key expansion", random, length); - var rval = { - client_write_MAC_key: km.getBytes(sp.mac_key_length), - server_write_MAC_key: km.getBytes(sp.mac_key_length), - client_write_key: km.getBytes(sp.enc_key_length), - server_write_key: km.getBytes(sp.enc_key_length) + var obj = asn1.fromDer(msg.body, strict); + return pki2.certificationRequestFromAsn1(obj, computeHash); + }; + pki2.certificationRequestToPem = function(csr, maxline) { + var msg = { + type: "CERTIFICATE REQUEST", + body: asn1.toDer(pki2.certificationRequestToAsn1(csr)).getBytes() }; - if (tls10) { - rval.client_write_IV = km.getBytes(sp.fixed_iv_length); - rval.server_write_IV = km.getBytes(sp.fixed_iv_length); - } - return rval; + return forge.pem.encode(msg, { maxline }); }; - tls.createConnectionState = function(c) { - var client = c.entity === tls.ConnectionEnd.client; - var createMode = function() { - var mode = { - // two 32-bit numbers, first is most significant - sequenceNumber: [0, 0], - macKey: null, - macLength: 0, - macFunction: null, - cipherState: null, - cipherFunction: function(record) { - return true; - }, - compressionState: null, - compressFunction: function(record) { - return true; - }, - updateSequenceNumber: function() { - if (mode.sequenceNumber[1] === 4294967295) { - mode.sequenceNumber[1] = 0; - ++mode.sequenceNumber[0]; - } else { - ++mode.sequenceNumber[1]; - } - } - }; - return mode; + pki2.createCertificate = function() { + var cert = {}; + cert.version = 2; + cert.serialNumber = "00"; + cert.signatureOid = null; + cert.signature = null; + cert.siginfo = {}; + cert.siginfo.algorithmOid = null; + cert.validity = {}; + cert.validity.notBefore = /* @__PURE__ */ new Date(); + cert.validity.notAfter = /* @__PURE__ */ new Date(); + cert.issuer = {}; + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); }; - var state = { - read: createMode(), - write: createMode() + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); }; - state.read.update = function(c2, record) { - if (!state.read.cipherFunction(record, state.read)) { - c2.error(c2, { - message: "Could not decrypt record or bad MAC.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - // doesn't matter if decryption failed or MAC was - // invalid, return the same error so as not to reveal - // which one occurred - description: tls.Alert.Description.bad_record_mac - } - }); - } else if (!state.read.compressFunction(c2, record, state.read)) { - c2.error(c2, { - message: "Could not decompress record.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decompression_failure - } - }); + cert.issuer.attributes = []; + cert.issuer.hash = null; + cert.subject = {}; + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = []; + cert.subject.hash = null; + cert.extensions = []; + cert.publicKey = null; + cert.md = null; + cert.setSubject = function(attrs, uniqueId) { + _fillMissingFields(attrs); + cert.subject.attributes = attrs; + delete cert.subject.uniqueId; + if (uniqueId) { + cert.subject.uniqueId = uniqueId; } - return !c2.fail; + cert.subject.hash = null; }; - state.write.update = function(c2, record) { - if (!state.write.compressFunction(c2, record, state.write)) { - c2.error(c2, { - message: "Could not compress record.", - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } + cert.setIssuer = function(attrs, uniqueId) { + _fillMissingFields(attrs); + cert.issuer.attributes = attrs; + delete cert.issuer.uniqueId; + if (uniqueId) { + cert.issuer.uniqueId = uniqueId; + } + cert.issuer.hash = null; + }; + cert.setExtensions = function(exts) { + for (var i = 0; i < exts.length; ++i) { + _fillMissingExtensionFields(exts[i], { cert }); + } + cert.extensions = exts; + }; + cert.getExtension = function(options) { + if (typeof options === "string") { + options = { name: options }; + } + var rval = null; + var ext; + for (var i = 0; rval === null && i < cert.extensions.length; ++i) { + ext = cert.extensions[i]; + if (options.id && ext.id === options.id) { + rval = ext; + } else if (options.name && ext.name === options.name) { + rval = ext; + } + } + return rval; + }; + cert.sign = function(key, md) { + cert.md = md || forge.md.sha1.create(); + var algorithmOid = oids[cert.md.algorithm + "WithRSAEncryption"]; + if (!algorithmOid) { + var error4 = new Error("Could not compute certificate digest. Unknown message digest algorithm OID."); + error4.algorithm = cert.md.algorithm; + throw error4; + } + cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; + cert.tbsCertificate = pki2.getTBSCertificate(cert); + var bytes = asn1.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + cert.signature = key.sign(cert.md); + }; + cert.verify = function(child) { + var rval = false; + if (!cert.issued(child)) { + var issuer = child.issuer; + var subject = cert.subject; + var error4 = new Error( + "The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject." + ); + error4.expectedIssuer = subject.attributes; + error4.actualIssuer = issuer.attributes; + throw error4; + } + var md = child.md; + if (md === null) { + md = _createSignatureDigest({ + signatureOid: child.signatureOid, + type: "certificate" }); - } else if (!state.write.cipherFunction(record, state.write)) { - c2.error(c2, { - message: "Could not encrypt record.", - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } + var tbsCertificate = child.tbsCertificate || pki2.getTBSCertificate(child); + var bytes = asn1.toDer(tbsCertificate); + md.update(bytes.getBytes()); + } + if (md !== null) { + rval = _verifySignature({ + certificate: cert, + md, + signature: child.signature }); } - return !c2.fail; + return rval; }; - if (c.session) { - var sp = c.session.sp; - c.session.cipherSuite.initSecurityParameters(sp); - sp.keys = tls.generateKeys(c, sp); - state.read.macKey = client ? sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; - state.write.macKey = client ? sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; - c.session.cipherSuite.initConnectionState(state, c, sp); - switch (sp.compression_algorithm) { - case tls.CompressionMethod.none: - break; - case tls.CompressionMethod.deflate: - state.read.compressFunction = inflate; - state.write.compressFunction = deflate; - break; - default: - throw new Error("Unsupported compression algorithm."); + cert.isIssuer = function(parent) { + var rval = false; + var i = cert.issuer; + var s = parent.subject; + if (i.hash && s.hash) { + rval = i.hash === s.hash; + } else if (i.attributes.length === s.attributes.length) { + rval = true; + var iattr, sattr; + for (var n = 0; rval && n < i.attributes.length; ++n) { + iattr = i.attributes[n]; + sattr = s.attributes[n]; + if (iattr.type !== sattr.type || iattr.value !== sattr.value) { + rval = false; + } + } } - } - return state; - }; - tls.createRandom = function() { - var d = /* @__PURE__ */ new Date(); - var utc = +d + d.getTimezoneOffset() * 6e4; - var rval = forge.util.createBuffer(); - rval.putInt32(utc); - rval.putBytes(forge.random.getBytes(28)); - return rval; + return rval; + }; + cert.issued = function(child) { + return child.isIssuer(cert); + }; + cert.generateSubjectKeyIdentifier = function() { + return pki2.getPublicKeyFingerprint(cert.publicKey, { type: "RSAPublicKey" }); + }; + cert.verifySubjectKeyIdentifier = function() { + var oid = oids["subjectKeyIdentifier"]; + for (var i = 0; i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if (ext.id === oid) { + var ski = cert.generateSubjectKeyIdentifier().getBytes(); + return forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski; + } + } + return false; + }; + return cert; }; - tls.createRecord = function(c, options) { - if (!options.data) { - return null; + pki2.certificateFromAsn1 = function(obj, computeHash) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) { + var error4 = new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate."); + error4.errors = errors; + throw error4; } - var record = { - type: options.type, - version: { - major: c.version.major, - minor: c.version.minor - }, - length: options.data.length(), - fragment: options.data + var oid = asn1.derToOid(capture.publicKeyOid); + if (oid !== pki2.oids.rsaEncryption) { + throw new Error("Cannot read public key. OID is not RSA."); + } + var cert = pki2.createCertificate(); + cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0; + var serial = forge.util.createBuffer(capture.certSerialNumber); + cert.serialNumber = serial.toHex(); + cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid); + cert.signatureParameters = _readSignatureParameters( + cert.signatureOid, + capture.certSignatureParams, + true + ); + cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid); + cert.siginfo.parameters = _readSignatureParameters( + cert.siginfo.algorithmOid, + capture.certinfoSignatureParams, + false + ); + cert.signature = capture.certSignature; + var validity = []; + if (capture.certValidity1UTCTime !== void 0) { + validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); + } + if (capture.certValidity2GeneralizedTime !== void 0) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity2GeneralizedTime + )); + } + if (capture.certValidity3UTCTime !== void 0) { + validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); + } + if (capture.certValidity4GeneralizedTime !== void 0) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity4GeneralizedTime + )); + } + if (validity.length > 2) { + throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate."); + } + if (validity.length < 2) { + throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime."); + } + cert.validity.notBefore = validity[0]; + cert.validity.notAfter = validity[1]; + cert.tbsCertificate = capture.tbsCertificate; + if (computeHash) { + cert.md = _createSignatureDigest({ + signatureOid: cert.signatureOid, + type: "certificate" + }); + var bytes = asn1.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + } + var imd = forge.md.sha1.create(); + var ibytes = asn1.toDer(capture.certIssuer); + imd.update(ibytes.getBytes()); + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); }; - return record; - }; - tls.createAlert = function(c, alert) { - var b = forge.util.createBuffer(); - b.putByte(alert.level); - b.putByte(alert.description); - return tls.createRecord(c, { - type: tls.ContentType.alert, - data: b - }); - }; - tls.createClientHello = function(c) { - c.session.clientHelloVersion = { - major: c.version.major, - minor: c.version.minor + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); }; - var cipherSuites = forge.util.createBuffer(); - for (var i = 0; i < c.cipherSuites.length; ++i) { - var cs = c.cipherSuites[i]; - cipherSuites.putByte(cs.id[0]); - cipherSuites.putByte(cs.id[1]); - } - var cSuites = cipherSuites.length(); - var compressionMethods = forge.util.createBuffer(); - compressionMethods.putByte(tls.CompressionMethod.none); - var cMethods = compressionMethods.length(); - var extensions = forge.util.createBuffer(); - if (c.virtualHost) { - var ext = forge.util.createBuffer(); - ext.putByte(0); - ext.putByte(0); - var serverName = forge.util.createBuffer(); - serverName.putByte(0); - writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost)); - var snList = forge.util.createBuffer(); - writeVector(snList, 2, serverName); - writeVector(ext, 2, snList); - extensions.putBuffer(ext); + cert.issuer.attributes = pki2.RDNAttributesAsArray(capture.certIssuer); + if (capture.certIssuerUniqueId) { + cert.issuer.uniqueId = capture.certIssuerUniqueId; } - var extLength = extensions.length(); - if (extLength > 0) { - extLength += 2; + cert.issuer.hash = imd.digest().toHex(); + var smd = forge.md.sha1.create(); + var sbytes = asn1.toDer(capture.certSubject); + smd.update(sbytes.getBytes()); + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = pki2.RDNAttributesAsArray(capture.certSubject); + if (capture.certSubjectUniqueId) { + cert.subject.uniqueId = capture.certSubjectUniqueId; } - var sessionId = c.session.id; - var length = sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + cSuites + // cipher suites vector - 1 + cMethods + // compression methods vector - extLength; - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_hello); - rval.putInt24(length); - rval.putByte(c.version.major); - rval.putByte(c.version.minor); - rval.putBytes(c.session.sp.client_random); - writeVector(rval, 1, forge.util.createBuffer(sessionId)); - writeVector(rval, 2, cipherSuites); - writeVector(rval, 1, compressionMethods); - if (extLength > 0) { - writeVector(rval, 2, extensions); + cert.subject.hash = smd.digest().toHex(); + if (capture.certExtensions) { + cert.extensions = pki2.certificateExtensionsFromAsn1(capture.certExtensions); + } else { + cert.extensions = []; } - return rval; + cert.publicKey = pki2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + return cert; }; - tls.createServerHello = function(c) { - var sessionId = c.session.id; - var length = sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + // chosen cipher suite - 1; - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello); - rval.putInt24(length); - rval.putByte(c.version.major); - rval.putByte(c.version.minor); - rval.putBytes(c.session.sp.server_random); - writeVector(rval, 1, forge.util.createBuffer(sessionId)); - rval.putByte(c.session.cipherSuite.id[0]); - rval.putByte(c.session.cipherSuite.id[1]); - rval.putByte(c.session.compressionMethod); + pki2.certificateExtensionsFromAsn1 = function(exts) { + var rval = []; + for (var i = 0; i < exts.value.length; ++i) { + var extseq = exts.value[i]; + for (var ei = 0; ei < extseq.value.length; ++ei) { + rval.push(pki2.certificateExtensionFromAsn1(extseq.value[ei])); + } + } return rval; }; - tls.createCertificate = function(c) { - var client = c.entity === tls.ConnectionEnd.client; - var cert = null; - if (c.getCertificate) { - var hint; - if (client) { - hint = c.session.certificateRequest; - } else { - hint = c.session.extensions.server_name.serverNameList; - } - cert = c.getCertificate(c, hint); + pki2.certificateExtensionFromAsn1 = function(ext) { + var e = {}; + e.id = asn1.derToOid(ext.value[0].value); + e.critical = false; + if (ext.value[1].type === asn1.Type.BOOLEAN) { + e.critical = ext.value[1].value.charCodeAt(0) !== 0; + e.value = ext.value[2].value; + } else { + e.value = ext.value[1].value; } - var certList = forge.util.createBuffer(); - if (cert !== null) { - try { - if (!forge.util.isArray(cert)) { - cert = [cert]; + if (e.id in oids) { + e.name = oids[e.id]; + if (e.name === "keyUsage") { + var ev = asn1.fromDer(e.value); + var b2 = 0; + var b3 = 0; + if (ev.value.length > 1) { + b2 = ev.value.charCodeAt(1); + b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; } - var asn1 = null; - for (var i = 0; i < cert.length; ++i) { - var msg = forge.pem.decode(cert[i])[0]; - if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { - var error4 = new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); - error4.headerType = msg.type; - throw error4; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert certificate from PEM; PEM is encrypted."); - } - var der = forge.util.createBuffer(msg.body); - if (asn1 === null) { - asn1 = forge.asn1.fromDer(der.bytes(), false); + e.digitalSignature = (b2 & 128) === 128; + e.nonRepudiation = (b2 & 64) === 64; + e.keyEncipherment = (b2 & 32) === 32; + e.dataEncipherment = (b2 & 16) === 16; + e.keyAgreement = (b2 & 8) === 8; + e.keyCertSign = (b2 & 4) === 4; + e.cRLSign = (b2 & 2) === 2; + e.encipherOnly = (b2 & 1) === 1; + e.decipherOnly = (b3 & 128) === 128; + } else if (e.name === "basicConstraints") { + var ev = asn1.fromDer(e.value); + if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { + e.cA = ev.value[0].value.charCodeAt(0) !== 0; + } else { + e.cA = false; + } + var value = null; + if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { + value = ev.value[0].value; + } else if (ev.value.length > 1) { + value = ev.value[1].value; + } + if (value !== null) { + e.pathLenConstraint = asn1.derToInteger(value); + } + } else if (e.name === "extKeyUsage") { + var ev = asn1.fromDer(e.value); + for (var vi = 0; vi < ev.value.length; ++vi) { + var oid = asn1.derToOid(ev.value[vi].value); + if (oid in oids) { + e[oids[oid]] = true; + } else { + e[oid] = true; } - var certBuffer = forge.util.createBuffer(); - writeVector(certBuffer, 3, der); - certList.putBuffer(certBuffer); } - cert = forge.pki.certificateFromAsn1(asn1); - if (client) { - c.session.clientCertificate = cert; - } else { - c.session.serverCertificate = cert; + } else if (e.name === "nsCertType") { + var ev = asn1.fromDer(e.value); + var b2 = 0; + if (ev.value.length > 1) { + b2 = ev.value.charCodeAt(1); } - } catch (ex) { - return c.error(c, { - message: "Could not send certificate list.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate + e.client = (b2 & 128) === 128; + e.server = (b2 & 64) === 64; + e.email = (b2 & 32) === 32; + e.objsign = (b2 & 16) === 16; + e.reserved = (b2 & 8) === 8; + e.sslCA = (b2 & 4) === 4; + e.emailCA = (b2 & 2) === 2; + e.objCA = (b2 & 1) === 1; + } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { + e.altNames = []; + var gn; + var ev = asn1.fromDer(e.value); + for (var n = 0; n < ev.value.length; ++n) { + gn = ev.value[n]; + var altName = { + type: gn.type, + value: gn.value + }; + e.altNames.push(altName); + switch (gn.type) { + // rfc822Name + case 1: + // dNSName + case 2: + // uniformResourceIdentifier (URI) + case 6: + break; + // IPAddress + case 7: + altName.ip = forge.util.bytesToIP(gn.value); + break; + // registeredID + case 8: + altName.oid = asn1.derToOid(gn.value); + break; + default: } - }); + } + } else if (e.name === "subjectKeyIdentifier") { + var ev = asn1.fromDer(e.value); + e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value); } } - var length = 3 + certList.length(); - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate); - rval.putInt24(length); - writeVector(rval, 3, certList); - return rval; - }; - tls.createClientKeyExchange = function(c) { - var b = forge.util.createBuffer(); - b.putByte(c.session.clientHelloVersion.major); - b.putByte(c.session.clientHelloVersion.minor); - b.putBytes(forge.random.getBytes(46)); - var sp = c.session.sp; - sp.pre_master_secret = b.getBytes(); - var key2 = c.session.serverCertificate.publicKey; - b = key2.encrypt(sp.pre_master_secret); - var length = b.length + 2; - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_key_exchange); - rval.putInt24(length); - rval.putInt16(b.length); - rval.putBytes(b); - return rval; + return e; }; - tls.createServerKeyExchange = function(c) { - var length = 0; - var rval = forge.util.createBuffer(); - if (length > 0) { - rval.putByte(tls.HandshakeType.server_key_exchange); - rval.putInt24(length); + pki2.certificationRequestFromAsn1 = function(obj, computeHash) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) { + var error4 = new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest."); + error4.errors = errors; + throw error4; } - return rval; + var oid = asn1.derToOid(capture.publicKeyOid); + if (oid !== pki2.oids.rsaEncryption) { + throw new Error("Cannot read public key. OID is not RSA."); + } + var csr = pki2.createCertificationRequest(); + csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; + csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.signatureParameters = _readSignatureParameters( + csr.signatureOid, + capture.csrSignatureParams, + true + ); + csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.siginfo.parameters = _readSignatureParameters( + csr.siginfo.algorithmOid, + capture.csrSignatureParams, + false + ); + csr.signature = capture.csrSignature; + csr.certificationRequestInfo = capture.certificationRequestInfo; + if (computeHash) { + csr.md = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: "certification request" + }); + var bytes = asn1.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); + } + var smd = forge.md.sha1.create(); + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = pki2.RDNAttributesAsArray( + capture.certificationRequestInfoSubject, + smd + ); + csr.subject.hash = smd.digest().toHex(); + csr.publicKey = pki2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.attributes = pki2.CRIAttributesAsArray( + capture.certificationRequestInfoAttributes || [] + ); + return csr; }; - tls.getClientSignature = function(c, callback) { - var b = forge.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - b = b.getBytes(); - c.getSignature = c.getSignature || function(c2, b2, callback2) { - var privateKey = null; - if (c2.getPrivateKey) { - try { - privateKey = c2.getPrivateKey(c2, c2.session.clientCertificate); - privateKey = forge.pki.privateKeyFromPem(privateKey); - } catch (ex) { - c2.error(c2, { - message: "Could not get private key.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } + pki2.createCertificationRequest = function() { + var csr = {}; + csr.version = 0; + csr.signatureOid = null; + csr.signature = null; + csr.siginfo = {}; + csr.siginfo.algorithmOid = null; + csr.subject = {}; + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = []; + csr.subject.hash = null; + csr.publicKey = null; + csr.attributes = []; + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.md = null; + csr.setSubject = function(attrs) { + _fillMissingFields(attrs); + csr.subject.attributes = attrs; + csr.subject.hash = null; + }; + csr.setAttributes = function(attrs) { + _fillMissingFields(attrs); + csr.attributes = attrs; + }; + csr.sign = function(key, md) { + csr.md = md || forge.md.sha1.create(); + var algorithmOid = oids[csr.md.algorithm + "WithRSAEncryption"]; + if (!algorithmOid) { + var error4 = new Error("Could not compute certification request digest. Unknown message digest algorithm OID."); + error4.algorithm = csr.md.algorithm; + throw error4; } - if (privateKey === null) { - c2.error(c2, { - message: "No private key set.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } + csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; + csr.certificationRequestInfo = pki2.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); + csr.signature = key.sign(csr.md); + }; + csr.verify = function() { + var rval = false; + var md = csr.md; + if (md === null) { + md = _createSignatureDigest({ + signatureOid: csr.signatureOid, + type: "certification request" }); - } else { - b2 = privateKey.sign(b2, null); + var cri = csr.certificationRequestInfo || pki2.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(cri); + md.update(bytes.getBytes()); } - callback2(c2, b2); + if (md !== null) { + rval = _verifySignature({ + certificate: csr, + md, + signature: csr.signature + }); + } + return rval; }; - c.getSignature(c, b, callback); - }; - tls.createCertificateVerify = function(c, signature) { - var length = signature.length + 2; - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_verify); - rval.putInt24(length); - rval.putInt16(signature.length); - rval.putBytes(signature); - return rval; - }; - tls.createCertificateRequest = function(c) { - var certTypes = forge.util.createBuffer(); - certTypes.putByte(1); - var cAs = forge.util.createBuffer(); - for (var key2 in c.caStore.certs) { - var cert = c.caStore.certs[key2]; - var dn = forge.pki.distinguishedNameToAsn1(cert.subject); - var byteBuffer = forge.asn1.toDer(dn); - cAs.putInt16(byteBuffer.length()); - cAs.putBuffer(byteBuffer); - } - var length = 1 + certTypes.length() + 2 + cAs.length(); - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_request); - rval.putInt24(length); - writeVector(rval, 1, certTypes); - writeVector(rval, 2, cAs); - return rval; - }; - tls.createServerHelloDone = function(c) { - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello_done); - rval.putInt24(0); - return rval; - }; - tls.createChangeCipherSpec = function() { - var rval = forge.util.createBuffer(); - rval.putByte(1); - return rval; - }; - tls.createFinished = function(c) { - var b = forge.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - var client = c.entity === tls.ConnectionEnd.client; - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - var label = client ? "client finished" : "server finished"; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - var rval = forge.util.createBuffer(); - rval.putByte(tls.HandshakeType.finished); - rval.putInt24(b.length()); - rval.putBuffer(b); - return rval; - }; - tls.createHeartbeat = function(type2, payload, payloadLength) { - if (typeof payloadLength === "undefined") { - payloadLength = payload.length; - } - var rval = forge.util.createBuffer(); - rval.putByte(type2); - rval.putInt16(payloadLength); - rval.putBytes(payload); - var plaintextLength = rval.length(); - var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); - rval.putBytes(forge.random.getBytes(paddingLength)); - return rval; + return csr; }; - tls.queue = function(c, record) { - if (!record) { - return; - } - if (record.fragment.length() === 0) { - if (record.type === tls.ContentType.handshake || record.type === tls.ContentType.alert || record.type === tls.ContentType.change_cipher_spec) { - return; + function _dnToAsn1(obj) { + var rval = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + var attr, set2; + var attrs = obj.attributes; + for (var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + var value = attr.value; + var valueTagClass = asn1.Type.PRINTABLESTRING; + if ("valueTagClass" in attr) { + valueTagClass = attr.valueTagClass; + if (valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } } + set2 = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(attr.type).getBytes() + ), + // AttributeValue + asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) + ]) + ]); + rval.value.push(set2); } - if (record.type === tls.ContentType.handshake) { - var bytes = record.fragment.bytes(); - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - bytes = null; - } - var records; - if (record.fragment.length() <= tls.MaxFragment) { - records = [record]; - } else { - records = []; - var data = record.fragment.bytes(); - while (data.length > tls.MaxFragment) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge.util.createBuffer(data.slice(0, tls.MaxFragment)) - })); - data = data.slice(tls.MaxFragment); - } - if (data.length > 0) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge.util.createBuffer(data) - })); + return rval; + } + function _fillMissingFields(attrs) { + var attr; + for (var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + if (typeof attr.name === "undefined") { + if (attr.type && attr.type in pki2.oids) { + attr.name = pki2.oids[attr.type]; + } else if (attr.shortName && attr.shortName in _shortNames) { + attr.name = pki2.oids[_shortNames[attr.shortName]]; + } } - } - for (var i = 0; i < records.length && !c.fail; ++i) { - var rec = records[i]; - var s = c.state.current.write; - if (s.update(c, rec)) { - c.records.push(rec); + if (typeof attr.type === "undefined") { + if (attr.name && attr.name in pki2.oids) { + attr.type = pki2.oids[attr.name]; + } else { + var error4 = new Error("Attribute type not specified."); + error4.attribute = attr; + throw error4; + } } - } - }; - tls.flush = function(c) { - for (var i = 0; i < c.records.length; ++i) { - var record = c.records[i]; - c.tlsData.putByte(record.type); - c.tlsData.putByte(record.version.major); - c.tlsData.putByte(record.version.minor); - c.tlsData.putInt16(record.fragment.length()); - c.tlsData.putBuffer(c.records[i].fragment); - } - c.records = []; - return c.tlsDataReady(c); - }; - var _certErrorToAlertDesc = function(error4) { - switch (error4) { - case true: - return true; - case forge.pki.certificateError.bad_certificate: - return tls.Alert.Description.bad_certificate; - case forge.pki.certificateError.unsupported_certificate: - return tls.Alert.Description.unsupported_certificate; - case forge.pki.certificateError.certificate_revoked: - return tls.Alert.Description.certificate_revoked; - case forge.pki.certificateError.certificate_expired: - return tls.Alert.Description.certificate_expired; - case forge.pki.certificateError.certificate_unknown: - return tls.Alert.Description.certificate_unknown; - case forge.pki.certificateError.unknown_ca: - return tls.Alert.Description.unknown_ca; - default: - return tls.Alert.Description.bad_certificate; - } - }; - var _alertDescToCertError = function(desc) { - switch (desc) { - case true: - return true; - case tls.Alert.Description.bad_certificate: - return forge.pki.certificateError.bad_certificate; - case tls.Alert.Description.unsupported_certificate: - return forge.pki.certificateError.unsupported_certificate; - case tls.Alert.Description.certificate_revoked: - return forge.pki.certificateError.certificate_revoked; - case tls.Alert.Description.certificate_expired: - return forge.pki.certificateError.certificate_expired; - case tls.Alert.Description.certificate_unknown: - return forge.pki.certificateError.certificate_unknown; - case tls.Alert.Description.unknown_ca: - return forge.pki.certificateError.unknown_ca; - default: - return forge.pki.certificateError.bad_certificate; - } - }; - tls.verifyCertificateChain = function(c, chain) { - try { - var options = {}; - for (var key2 in c.verifyOptions) { - options[key2] = c.verifyOptions[key2]; + if (typeof attr.shortName === "undefined") { + if (attr.name && attr.name in _shortNames) { + attr.shortName = _shortNames[attr.name]; + } } - options.verify = function(vfd, depth, chain2) { - var desc = _certErrorToAlertDesc(vfd); - var ret = c.verify(c, vfd, depth, chain2); - if (ret !== true) { - if (typeof ret === "object" && !forge.util.isArray(ret)) { - var error4 = new Error("The application rejected the certificate."); - error4.send = true; - error4.alert = { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - }; - if (ret.message) { - error4.message = ret.message; - } - if (ret.alert) { - error4.alert.description = ret.alert; - } - throw error4; - } - if (ret !== vfd) { - ret = _alertDescToCertError(ret); + if (attr.type === oids.extensionRequest) { + attr.valueConstructed = true; + attr.valueTagClass = asn1.Type.SEQUENCE; + if (!attr.value && attr.extensions) { + attr.value = []; + for (var ei = 0; ei < attr.extensions.length; ++ei) { + attr.value.push(pki2.certificateExtensionToAsn1( + _fillMissingExtensionFields(attr.extensions[ei]) + )); } } - return ret; - }; - forge.pki.verifyCertificateChain(c.caStore, chain, options); - } catch (ex) { - var err = ex; - if (typeof err !== "object" || forge.util.isArray(err)) { - err = { - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(ex) - } - }; - } - if (!("send" in err)) { - err.send = true; } - if (!("alert" in err)) { - err.alert = { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(err.error) - }; + if (typeof attr.value === "undefined") { + var error4 = new Error("Attribute value not specified."); + error4.attribute = attr; + throw error4; } - c.error(c, err); } - return !c.fail; - }; - tls.createSessionCache = function(cache, capacity) { - var rval = null; - if (cache && cache.getSession && cache.setSession && cache.order) { - rval = cache; - } else { - rval = {}; - rval.cache = cache || {}; - rval.capacity = Math.max(capacity || 100, 1); - rval.order = []; - for (var key2 in cache) { - if (rval.order.length <= capacity) { - rval.order.push(key2); - } else { - delete cache[key2]; - } + } + function _fillMissingExtensionFields(e, options) { + options = options || {}; + if (typeof e.name === "undefined") { + if (e.id && e.id in pki2.oids) { + e.name = pki2.oids[e.id]; } - rval.getSession = function(sessionId) { - var session = null; - var key3 = null; - if (sessionId) { - key3 = forge.util.bytesToHex(sessionId); - } else if (rval.order.length > 0) { - key3 = rval.order[0]; - } - if (key3 !== null && key3 in rval.cache) { - session = rval.cache[key3]; - delete rval.cache[key3]; - for (var i in rval.order) { - if (rval.order[i] === key3) { - rval.order.splice(i, 1); - break; - } - } - } - return session; - }; - rval.setSession = function(sessionId, session) { - if (rval.order.length === rval.capacity) { - var key3 = rval.order.shift(); - delete rval.cache[key3]; - } - var key3 = forge.util.bytesToHex(sessionId); - rval.order.push(key3); - rval.cache[key3] = session; - }; } - return rval; - }; - tls.createConnection = function(options) { - var caStore = null; - if (options.caStore) { - if (forge.util.isArray(options.caStore)) { - caStore = forge.pki.createCaStore(options.caStore); + if (typeof e.id === "undefined") { + if (e.name && e.name in pki2.oids) { + e.id = pki2.oids[e.name]; } else { - caStore = options.caStore; + var error4 = new Error("Extension ID not specified."); + error4.extension = e; + throw error4; } - } else { - caStore = forge.pki.createCaStore(); } - var cipherSuites = options.cipherSuites || null; - if (cipherSuites === null) { - cipherSuites = []; - for (var key2 in tls.CipherSuites) { - cipherSuites.push(tls.CipherSuites[key2]); - } + if (typeof e.value !== "undefined") { + return e; } - var entity = options.server || false ? tls.ConnectionEnd.server : tls.ConnectionEnd.client; - var sessionCache = options.sessionCache ? tls.createSessionCache(options.sessionCache) : null; - var c = { - version: { major: tls.Version.major, minor: tls.Version.minor }, - entity, - sessionId: options.sessionId, - caStore, - sessionCache, - cipherSuites, - connected: options.connected, - virtualHost: options.virtualHost || null, - verifyClient: options.verifyClient || false, - verify: options.verify || function(cn, vfd, dpth, cts) { - return vfd; - }, - verifyOptions: options.verifyOptions || {}, - getCertificate: options.getCertificate || null, - getPrivateKey: options.getPrivateKey || null, - getSignature: options.getSignature || null, - input: forge.util.createBuffer(), - tlsData: forge.util.createBuffer(), - data: forge.util.createBuffer(), - tlsDataReady: options.tlsDataReady, - dataReady: options.dataReady, - heartbeatReceived: options.heartbeatReceived, - closed: options.closed, - error: function(c2, ex) { - ex.origin = ex.origin || (c2.entity === tls.ConnectionEnd.client ? "client" : "server"); - if (ex.send) { - tls.queue(c2, tls.createAlert(c2, ex.alert)); - tls.flush(c2); - } - var fatal = ex.fatal !== false; - if (fatal) { - c2.fail = true; - } - options.error(c2, ex); - if (fatal) { - c2.close(false); - } - }, - deflate: options.deflate || null, - inflate: options.inflate || null - }; - c.reset = function(clearFail) { - c.version = { major: tls.Version.major, minor: tls.Version.minor }; - c.record = null; - c.session = null; - c.peerCertificate = null; - c.state = { - pending: null, - current: null - }; - c.expect = c.entity === tls.ConnectionEnd.client ? SHE : CHE; - c.fragmented = null; - c.records = []; - c.open = false; - c.handshakes = 0; - c.handshaking = false; - c.isConnected = false; - c.fail = !(clearFail || typeof clearFail === "undefined"); - c.input.clear(); - c.tlsData.clear(); - c.data.clear(); - c.state.current = tls.createConnectionState(c); - }; - c.reset(); - var _update = function(c2, record) { - var aligned = record.type - tls.ContentType.change_cipher_spec; - var handlers = ctTable[c2.entity][c2.expect]; - if (aligned in handlers) { - handlers[aligned](c2, record); - } else { - tls.handleUnexpected(c2, record); + if (e.name === "keyUsage") { + var unused = 0; + var b2 = 0; + var b3 = 0; + if (e.digitalSignature) { + b2 |= 128; + unused = 7; } - }; - var _readRecordHeader = function(c2) { - var rval = 0; - var b = c2.input; - var len = b.length(); - if (len < 5) { - rval = 5 - len; - } else { - c2.record = { - type: b.getByte(), - version: { - major: b.getByte(), - minor: b.getByte() - }, - length: b.getInt16(), - fragment: forge.util.createBuffer(), - ready: false - }; - var compatibleVersion = c2.record.version.major === c2.version.major; - if (compatibleVersion && c2.session && c2.session.version) { - compatibleVersion = c2.record.version.minor === c2.version.minor; + if (e.nonRepudiation) { + b2 |= 64; + unused = 6; + } + if (e.keyEncipherment) { + b2 |= 32; + unused = 5; + } + if (e.dataEncipherment) { + b2 |= 16; + unused = 4; + } + if (e.keyAgreement) { + b2 |= 8; + unused = 3; + } + if (e.keyCertSign) { + b2 |= 4; + unused = 2; + } + if (e.cRLSign) { + b2 |= 2; + unused = 1; + } + if (e.encipherOnly) { + b2 |= 1; + unused = 0; + } + if (e.decipherOnly) { + b3 |= 128; + unused = 7; + } + var value = String.fromCharCode(unused); + if (b3 !== 0) { + value += String.fromCharCode(b2) + String.fromCharCode(b3); + } else if (b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + value + ); + } else if (e.name === "basicConstraints") { + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + if (e.cA) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BOOLEAN, + false, + String.fromCharCode(255) + )); + } + if ("pathLenConstraint" in e) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(e.pathLenConstraint).getBytes() + )); + } + } else if (e.name === "extKeyUsage") { + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + var seq2 = e.value.value; + for (var key in e) { + if (e[key] !== true) { + continue; } - if (!compatibleVersion) { - c2.error(c2, { - message: "Incompatible TLS version.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); + if (key in oids) { + seq2.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oids[key]).getBytes() + )); + } else if (key.indexOf(".") !== -1) { + seq2.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(key).getBytes() + )); } } - return rval; - }; - var _readRecord = function(c2) { - var rval = 0; - var b = c2.input; - var len = b.length(); - if (len < c2.record.length) { - rval = c2.record.length - len; - } else { - c2.record.fragment.putBytes(b.getBytes(c2.record.length)); - b.compact(); - var s = c2.state.current.read; - if (s.update(c2, c2.record)) { - if (c2.fragmented !== null) { - if (c2.fragmented.type === c2.record.type) { - c2.fragmented.fragment.putBuffer(c2.record.fragment); - c2.record = c2.fragmented; - } else { - c2.error(c2, { - message: "Invalid fragmented record.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unexpected_message - } - }); - } - } - c2.record.ready = true; - } + } else if (e.name === "nsCertType") { + var unused = 0; + var b2 = 0; + if (e.client) { + b2 |= 128; + unused = 7; } - return rval; - }; - c.handshake = function(sessionId) { - if (c.entity !== tls.ConnectionEnd.client) { - c.error(c, { - message: "Cannot initiate handshake as a server.", - fatal: false - }); - } else if (c.handshaking) { - c.error(c, { - message: "Handshake already in progress.", - fatal: false - }); - } else { - if (c.fail && !c.open && c.handshakes === 0) { - c.fail = false; - } - c.handshaking = true; - sessionId = sessionId || ""; - var session = null; - if (sessionId.length > 0) { - if (c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - } - if (session === null) { - sessionId = ""; + if (e.server) { + b2 |= 64; + unused = 6; + } + if (e.email) { + b2 |= 32; + unused = 5; + } + if (e.objsign) { + b2 |= 16; + unused = 4; + } + if (e.reserved) { + b2 |= 8; + unused = 3; + } + if (e.sslCA) { + b2 |= 4; + unused = 2; + } + if (e.emailCA) { + b2 |= 2; + unused = 1; + } + if (e.objCA) { + b2 |= 1; + unused = 0; + } + var value = String.fromCharCode(unused); + if (b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + value + ); + } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var altName; + for (var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + if (altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if (value === null) { + var error4 = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.' + ); + error4.extension = e; + throw error4; } - } - if (sessionId.length === 0 && c.sessionCache) { - session = c.sessionCache.getSession(); - if (session !== null) { - sessionId = session.id; + } else if (altName.type === 8) { + if (altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + value = asn1.oidToDer(value); } } - c.session = { - id: sessionId, - version: null, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - certificateRequest: null, - clientCertificate: null, - sp: {}, - md5: forge.md.md5.create(), - sha1: forge.md.sha1.create() - }; - if (session) { - c.version = session.version; - c.session.sp = session.sp; - } - c.session.sp.client_random = tls.createRandom().getBytes(); - c.open = true; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientHello(c) - })); - tls.flush(c); - } - }; - c.process = function(data) { - var rval = 0; - if (data) { - c.input.putBytes(data); + e.value.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + altName.type, + false, + value + )); } - if (!c.fail) { - if (c.record !== null && c.record.ready && c.record.fragment.isEmpty()) { - c.record = null; - } - if (c.record === null) { - rval = _readRecordHeader(c); - } - if (!c.fail && c.record !== null && !c.record.ready) { - rval = _readRecord(c); - } - if (!c.fail && c.record !== null && c.record.ready) { - _update(c, c.record); - } + } else if (e.name === "nsComment" && options.cert) { + if (!/^[\x00-\x7F]*$/.test(e.comment) || e.comment.length < 1 || e.comment.length > 128) { + throw new Error('Invalid "nsComment" content.'); } - return rval; - }; - c.prepare = function(data) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.application_data, - data: forge.util.createBuffer(data) - })); - return tls.flush(c); - }; - c.prepareHeartbeatRequest = function(payload, payloadLength) { - if (payload instanceof forge.util.ByteBuffer) { - payload = payload.bytes(); + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.IA5STRING, + false, + e.comment + ); + } else if (e.name === "subjectKeyIdentifier" && options.cert) { + var ski = options.cert.generateSubjectKeyIdentifier(); + e.subjectKeyIdentifier = ski.toHex(); + e.value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + ski.getBytes() + ); + } else if (e.name === "authorityKeyIdentifier" && options.cert) { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq2 = e.value.value; + if (e.keyIdentifier) { + var keyIdentifier = e.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e.keyIdentifier; + seq2.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier) + ); } - if (typeof payloadLength === "undefined") { - payloadLength = payload.length; + if (e.authorityCertIssuer) { + var authorityCertIssuer = [ + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ + _dnToAsn1(e.authorityCertIssuer === true ? options.cert.issuer : e.authorityCertIssuer) + ]) + ]; + seq2.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer) + ); } - c.expectedHeartbeatPayload = payload; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_request, - payload, - payloadLength - ) - })); - return tls.flush(c); - }; - c.close = function(clearFail) { - if (!c.fail && c.sessionCache && c.session) { - var session = { - id: c.session.id, - version: c.session.version, - sp: c.session.sp - }; - session.sp.keys = null; - c.sessionCache.setSession(session.id, session); + if (e.serialNumber) { + var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? options.cert.serialNumber : e.serialNumber); + seq2.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber) + ); } - if (c.open) { - c.open = false; - c.input.clear(); - if (c.isConnected || c.handshaking) { - c.isConnected = c.handshaking = false; - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.close_notify - })); - tls.flush(c); + } else if (e.name === "cRLDistributionPoints") { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq2 = e.value.value; + var subSeq = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [] + ); + var fullNameGeneralNames = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + 0, + true, + [] + ); + var altName; + for (var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + if (altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if (value === null) { + var error4 = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.' + ); + error4.extension = e; + throw error4; + } + } else if (altName.type === 8) { + if (altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + value = asn1.oidToDer(value); + } } - c.closed(c); + fullNameGeneralNames.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + altName.type, + false, + value + )); } - c.reset(clearFail); - }; - return c; - }; - module2.exports = forge.tls = forge.tls || {}; - for (key in tls) { - if (typeof tls[key] !== "function") { - forge.tls[key] = tls[key]; - } - } - var key; - forge.tls.prf_tls1 = prf_TLS1; - forge.tls.hmac_sha1 = hmac_sha1; - forge.tls.createSessionCache = tls.createSessionCache; - forge.tls.createConnection = tls.createConnection; - } -}); - -// node_modules/node-forge/lib/aesCipherSuites.js -var require_aesCipherSuites = __commonJS({ - "node_modules/node-forge/lib/aesCipherSuites.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_tls(); - var tls = module2.exports = forge.tls; - tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"] = { - id: [0, 47], - name: "TLS_RSA_WITH_AES_128_CBC_SHA", - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 16; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState - }; - tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"] = { - id: [0, 53], - name: "TLS_RSA_WITH_AES_256_CBC_SHA", - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 32; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState - }; - function initConnectionState(state, c, sp) { - var client = c.entity === forge.tls.ConnectionEnd.client; - state.read.cipherState = { - init: false, - cipher: forge.cipher.createDecipher("AES-CBC", client ? sp.keys.server_write_key : sp.keys.client_write_key), - iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV - }; - state.write.cipherState = { - init: false, - cipher: forge.cipher.createCipher("AES-CBC", client ? sp.keys.client_write_key : sp.keys.server_write_key), - iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV - }; - state.read.cipherFunction = decrypt_aes_cbc_sha1; - state.write.cipherFunction = encrypt_aes_cbc_sha1; - state.read.macLength = state.write.macLength = sp.mac_length; - state.read.macFunction = state.write.macFunction = tls.hmac_sha1; - } - function encrypt_aes_cbc_sha1(record, s) { - var rval = false; - var mac = s.macFunction(s.macKey, s.sequenceNumber, record); - record.fragment.putBytes(mac); - s.updateSequenceNumber(); - var iv; - if (record.version.minor === tls.Versions.TLS_1_0.minor) { - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = forge.random.getBytesSync(16); - } - s.cipherState.init = true; - var cipher = s.cipherState.cipher; - cipher.start({ iv }); - if (record.version.minor >= tls.Versions.TLS_1_1.minor) { - cipher.output.putBytes(iv); + subSeq.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + 0, + true, + [fullNameGeneralNames] + )); + seq2.push(subSeq); } - cipher.update(record.fragment); - if (cipher.finish(encrypt_aes_cbc_sha1_padding)) { - record.fragment = cipher.output; - record.length = record.fragment.length(); - rval = true; + if (typeof e.value === "undefined") { + var error4 = new Error("Extension value not specified."); + error4.extension = e; + throw error4; } - return rval; + return e; } - function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { - if (!decrypt) { - var padding = blockSize - input.length() % blockSize; - input.fillWithByte(padding - 1, padding); + function _signatureParametersToAsn1(oid, params) { + switch (oid) { + case oids["RSASSA-PSS"]: + var parts = []; + if (params.hash.algorithmOid !== void 0) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(params.hash.algorithmOid).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]) + ])); + } + if (params.mgf.algorithmOid !== void 0) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(params.mgf.algorithmOid).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]) + ]) + ])); + } + if (params.saltLength !== void 0) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(params.saltLength).getBytes() + ) + ])); + } + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); + default: + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ""); } - return true; } - function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { - var rval = true; - if (decrypt) { - var len = output.length(); - var paddingLength = output.last(); - for (var i = len - 1 - paddingLength; i < len - 1; ++i) { - rval = rval && output.at(i) == paddingLength; + function _CRIAttributesToAsn1(csr) { + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + if (csr.attributes.length === 0) { + return rval; + } + var attrs = csr.attributes; + for (var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + var value = attr.value; + var valueTagClass = asn1.Type.UTF8; + if ("valueTagClass" in attr) { + valueTagClass = attr.valueTagClass; } - if (rval) { - output.truncate(paddingLength + 1); + if (valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + var valueConstructed = false; + if ("valueConstructed" in attr) { + valueConstructed = attr.valueConstructed; } + var seq2 = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(attr.type).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + asn1.create( + asn1.Class.UNIVERSAL, + valueTagClass, + valueConstructed, + value + ) + ]) + ]); + rval.value.push(seq2); } return rval; } - function decrypt_aes_cbc_sha1(record, s) { - var rval = false; - var iv; - if (record.version.minor === tls.Versions.TLS_1_0.minor) { - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = record.fragment.getBytes(16); - } - s.cipherState.init = true; - var cipher = s.cipherState.cipher; - cipher.start({ iv }); - cipher.update(record.fragment); - rval = cipher.finish(decrypt_aes_cbc_sha1_padding); - var macLen = s.macLength; - var mac = forge.random.getBytesSync(macLen); - var len = cipher.output.length(); - if (len >= macLen) { - record.fragment = cipher.output.getBytes(len - macLen); - mac = cipher.output.getBytes(macLen); + var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); + var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); + function _dateToAsn1(date) { + if (date >= jan_1_1950 && date < jan_1_2050) { + return asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.UTCTIME, + false, + asn1.dateToUtcTime(date) + ); } else { - record.fragment = cipher.output.getBytes(); + return asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.GENERALIZEDTIME, + false, + asn1.dateToGeneralizedTime(date) + ); } - record.fragment = forge.util.createBuffer(record.fragment); - record.length = record.fragment.length(); - var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); - s.updateSequenceNumber(); - rval = compareMacs(s.macKey, mac, mac2) && rval; - return rval; - } - function compareMacs(key, mac1, mac2) { - var hmac = forge.hmac.create(); - hmac.start("SHA1", key); - hmac.update(mac1); - mac1 = hmac.digest().getBytes(); - hmac.start(null, null); - hmac.update(mac2); - mac2 = hmac.digest().getBytes(); - return mac1 === mac2; } - } -}); - -// node_modules/node-forge/lib/sha512.js -var require_sha512 = __commonJS({ - "node_modules/node-forge/lib/sha512.js"(exports2, module2) { - var forge = require_forge(); - require_md(); - require_util8(); - var sha512 = module2.exports = forge.sha512 = forge.sha512 || {}; - forge.md.sha512 = forge.md.algorithms.sha512 = sha512; - var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; - sha384.create = function() { - return sha512.create("SHA-384"); - }; - forge.md.sha384 = forge.md.algorithms.sha384 = sha384; - forge.sha512.sha256 = forge.sha512.sha256 || { - create: function() { - return sha512.create("SHA-512/256"); - } - }; - forge.md["sha512/256"] = forge.md.algorithms["sha512/256"] = forge.sha512.sha256; - forge.sha512.sha224 = forge.sha512.sha224 || { - create: function() { - return sha512.create("SHA-512/224"); + pki2.getTBSCertificate = function(cert) { + var notBefore = _dateToAsn1(cert.validity.notBefore); + var notAfter = _dateToAsn1(cert.validity.notAfter); + var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // integer + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(cert.version).getBytes() + ) + ]), + // serialNumber + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + forge.util.hexToBytes(cert.serialNumber) + ), + // signature + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(cert.siginfo.algorithmOid).getBytes() + ), + // parameters + _signatureParametersToAsn1( + cert.siginfo.algorithmOid, + cert.siginfo.parameters + ) + ]), + // issuer + _dnToAsn1(cert.issuer), + // validity + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + notBefore, + notAfter + ]), + // subject + _dnToAsn1(cert.subject), + // SubjectPublicKeyInfo + pki2.publicKeyToAsn1(cert.publicKey) + ]); + if (cert.issuer.uniqueId) { + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0) + cert.issuer.uniqueId + ) + ]) + ); } - }; - forge.md["sha512/224"] = forge.md.algorithms["sha512/224"] = forge.sha512.sha224; - sha512.create = function(algorithm) { - if (!_initialized) { - _init(); + if (cert.subject.uniqueId) { + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0) + cert.subject.uniqueId + ) + ]) + ); } - if (typeof algorithm === "undefined") { - algorithm = "SHA-512"; + if (cert.extensions.length > 0) { + tbs.value.push(pki2.certificateExtensionsToAsn1(cert.extensions)); } - if (!(algorithm in _states)) { - throw new Error("Invalid SHA-512 algorithm: " + algorithm); + return tbs; + }; + pki2.getCertificationRequestInfo = function(csr) { + var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(csr.version).getBytes() + ), + // subject + _dnToAsn1(csr.subject), + // SubjectPublicKeyInfo + pki2.publicKeyToAsn1(csr.publicKey), + // attributes + _CRIAttributesToAsn1(csr) + ]); + return cri; + }; + pki2.distinguishedNameToAsn1 = function(dn) { + return _dnToAsn1(dn); + }; + pki2.certificateToAsn1 = function(cert) { + var tbsCertificate = cert.tbsCertificate || pki2.getTBSCertificate(cert); + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // TBSCertificate + tbsCertificate, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(cert.signatureOid).getBytes() + ), + // parameters + _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) + ]), + // SignatureValue + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + String.fromCharCode(0) + cert.signature + ) + ]); + }; + pki2.certificateExtensionsToAsn1 = function(exts) { + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); + var seq2 = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + rval.value.push(seq2); + for (var i = 0; i < exts.length; ++i) { + seq2.value.push(pki2.certificateExtensionToAsn1(exts[i])); } - var _state = _states[algorithm]; - var _h = null; - var _input = forge.util.createBuffer(); - var _w = new Array(80); - for (var wi = 0; wi < 80; ++wi) { - _w[wi] = new Array(2); + return rval; + }; + pki2.certificateExtensionToAsn1 = function(ext) { + var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(ext.id).getBytes() + )); + if (ext.critical) { + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BOOLEAN, + false, + String.fromCharCode(255) + )); } - var digestLength = 64; - switch (algorithm) { - case "SHA-384": - digestLength = 48; - break; - case "SHA-512/256": - digestLength = 32; - break; - case "SHA-512/224": - digestLength = 28; - break; + var value = ext.value; + if (typeof ext.value !== "string") { + value = asn1.toDer(value).getBytes(); } - var md = { - // SHA-512 => sha512 - algorithm: algorithm.replace("-", "").toLowerCase(), - blockLength: 128, - digestLength, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 16 + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + value + )); + return extseq; + }; + pki2.certificationRequestToAsn1 = function(csr) { + var cri = csr.certificationRequestInfo || pki2.getCertificationRequestInfo(csr); + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // CertificationRequestInfo + cri, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(csr.signatureOid).getBytes() + ), + // parameters + _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) + ]), + // signature + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BITSTRING, + false, + String.fromCharCode(0) + csr.signature + ) + ]); + }; + pki2.createCaStore = function(certs) { + var caStore = { + // stored certificates + certs: {} }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength128 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge.util.createBuffer(); - _h = new Array(_state.length); - for (var i = 0; i < _state.length; ++i) { - _h[i] = _state[i].slice(0); + caStore.getIssuer = function(cert2) { + var rval = getBySubject(cert2.issuer); + return rval; + }; + caStore.addCertificate = function(cert2) { + if (typeof cert2 === "string") { + cert2 = forge.pki.certificateFromPem(cert2); + } + ensureSubjectHasHash(cert2.subject); + if (!caStore.hasCertificate(cert2)) { + if (cert2.subject.hash in caStore.certs) { + var tmp = caStore.certs[cert2.subject.hash]; + if (!forge.util.isArray(tmp)) { + tmp = [tmp]; + } + tmp.push(cert2); + caStore.certs[cert2.subject.hash] = tmp; + } else { + caStore.certs[cert2.subject.hash] = cert2; + } } - return md; }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge.util.encodeUtf8(msg); + caStore.hasCertificate = function(cert2) { + if (typeof cert2 === "string") { + cert2 = forge.pki.certificateFromPem(cert2); } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; + var match = getBySubject(cert2.subject); + if (!match) { + return false; } - _input.putBytes(msg); - _update(_h, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); + if (!forge.util.isArray(match)) { + match = [match]; } - return md; + var der1 = asn1.toDer(pki2.certificateToAsn1(cert2)).getBytes(); + for (var i2 = 0; i2 < match.length; ++i2) { + var der2 = asn1.toDer(pki2.certificateToAsn1(match[i2])).getBytes(); + if (der1 === der2) { + return true; + } + } + return false; }; - md.digest = function() { - var finalBlock = forge.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; + caStore.listAllCertificates = function() { + var certList = []; + for (var hash in caStore.certs) { + if (caStore.certs.hasOwnProperty(hash)) { + var value = caStore.certs[hash]; + if (!forge.util.isArray(value)) { + certList.push(value); + } else { + for (var i2 = 0; i2 < value.length; ++i2) { + certList.push(value[i2]); + } + } + } } - finalBlock.putInt32(bits); - var h = new Array(_h.length); - for (var i = 0; i < _h.length; ++i) { - h[i] = _h[i].slice(0); + return certList; + }; + caStore.removeCertificate = function(cert2) { + var result; + if (typeof cert2 === "string") { + cert2 = forge.pki.certificateFromPem(cert2); } - _update(h, _w, finalBlock); - var rval = forge.util.createBuffer(); - var hlen; - if (algorithm === "SHA-512") { - hlen = h.length; - } else if (algorithm === "SHA-384") { - hlen = h.length - 2; - } else { - hlen = h.length - 4; + ensureSubjectHasHash(cert2.subject); + if (!caStore.hasCertificate(cert2)) { + return null; } - for (var i = 0; i < hlen; ++i) { - rval.putInt32(h[i][0]); - if (i !== hlen - 1 || algorithm !== "SHA-512/224") { - rval.putInt32(h[i][1]); + var match = getBySubject(cert2.subject); + if (!forge.util.isArray(match)) { + result = caStore.certs[cert2.subject.hash]; + delete caStore.certs[cert2.subject.hash]; + return result; + } + var der1 = asn1.toDer(pki2.certificateToAsn1(cert2)).getBytes(); + for (var i2 = 0; i2 < match.length; ++i2) { + var der2 = asn1.toDer(pki2.certificateToAsn1(match[i2])).getBytes(); + if (der1 === der2) { + result = match[i2]; + match.splice(i2, 1); } } - return rval; - }; - return md; - }; - var _padding = null; - var _initialized = false; - var _k = null; - var _states = null; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge.util.fillString(String.fromCharCode(0), 128); - _k = [ - [1116352408, 3609767458], - [1899447441, 602891725], - [3049323471, 3964484399], - [3921009573, 2173295548], - [961987163, 4081628472], - [1508970993, 3053834265], - [2453635748, 2937671579], - [2870763221, 3664609560], - [3624381080, 2734883394], - [310598401, 1164996542], - [607225278, 1323610764], - [1426881987, 3590304994], - [1925078388, 4068182383], - [2162078206, 991336113], - [2614888103, 633803317], - [3248222580, 3479774868], - [3835390401, 2666613458], - [4022224774, 944711139], - [264347078, 2341262773], - [604807628, 2007800933], - [770255983, 1495990901], - [1249150122, 1856431235], - [1555081692, 3175218132], - [1996064986, 2198950837], - [2554220882, 3999719339], - [2821834349, 766784016], - [2952996808, 2566594879], - [3210313671, 3203337956], - [3336571891, 1034457026], - [3584528711, 2466948901], - [113926993, 3758326383], - [338241895, 168717936], - [666307205, 1188179964], - [773529912, 1546045734], - [1294757372, 1522805485], - [1396182291, 2643833823], - [1695183700, 2343527390], - [1986661051, 1014477480], - [2177026350, 1206759142], - [2456956037, 344077627], - [2730485921, 1290863460], - [2820302411, 3158454273], - [3259730800, 3505952657], - [3345764771, 106217008], - [3516065817, 3606008344], - [3600352804, 1432725776], - [4094571909, 1467031594], - [275423344, 851169720], - [430227734, 3100823752], - [506948616, 1363258195], - [659060556, 3750685593], - [883997877, 3785050280], - [958139571, 3318307427], - [1322822218, 3812723403], - [1537002063, 2003034995], - [1747873779, 3602036899], - [1955562222, 1575990012], - [2024104815, 1125592928], - [2227730452, 2716904306], - [2361852424, 442776044], - [2428436474, 593698344], - [2756734187, 3733110249], - [3204031479, 2999351573], - [3329325298, 3815920427], - [3391569614, 3928383900], - [3515267271, 566280711], - [3940187606, 3454069534], - [4118630271, 4000239992], - [116418474, 1914138554], - [174292421, 2731055270], - [289380356, 3203993006], - [460393269, 320620315], - [685471733, 587496836], - [852142971, 1086792851], - [1017036298, 365543100], - [1126000580, 2618297676], - [1288033470, 3409855158], - [1501505948, 4234509866], - [1607167915, 987167468], - [1816402316, 1246189591] - ]; - _states = {}; - _states["SHA-512"] = [ - [1779033703, 4089235720], - [3144134277, 2227873595], - [1013904242, 4271175723], - [2773480762, 1595750129], - [1359893119, 2917565137], - [2600822924, 725511199], - [528734635, 4215389547], - [1541459225, 327033209] - ]; - _states["SHA-384"] = [ - [3418070365, 3238371032], - [1654270250, 914150663], - [2438529370, 812702999], - [355462360, 4144912697], - [1731405415, 4290775857], - [2394180231, 1750603025], - [3675008525, 1694076839], - [1203062813, 3204075428] - ]; - _states["SHA-512/256"] = [ - [573645204, 4230739756], - [2673172387, 3360449730], - [596883563, 1867755857], - [2520282905, 1497426621], - [2519219938, 2827943907], - [3193839141, 1401305490], - [721525244, 746961066], - [246885852, 2177182882] - ]; - _states["SHA-512/224"] = [ - [2352822216, 424955298], - [1944164710, 2312950998], - [502970286, 855612546], - [1738396948, 1479516111], - [258812777, 2077511080], - [2011393907, 79989058], - [1067287976, 1780299464], - [286451373, 2446758561] - ]; - _initialized = true; - } - function _update(s, w, bytes) { - var t1_hi, t1_lo; - var t2_hi, t2_lo; - var s0_hi, s0_lo; - var s1_hi, s1_lo; - var ch_hi, ch_lo; - var maj_hi, maj_lo; - var a_hi, a_lo; - var b_hi, b_lo; - var c_hi, c_lo; - var d_hi, d_lo; - var e_hi, e_lo; - var f_hi, f_lo; - var g_hi, g_lo; - var h_hi, h_lo; - var i, hi, lo, w2, w7, w15, w16; - var len = bytes.length(); - while (len >= 128) { - for (i = 0; i < 16; ++i) { - w[i][0] = bytes.getInt32() >>> 0; - w[i][1] = bytes.getInt32() >>> 0; + if (match.length === 0) { + delete caStore.certs[cert2.subject.hash]; } - for (; i < 80; ++i) { - w2 = w[i - 2]; - hi = w2[0]; - lo = w2[1]; - t1_hi = ((hi >>> 19 | lo << 13) ^ // ROTR 19 - (lo >>> 29 | hi << 3) ^ // ROTR 61/(swap + ROTR 29) - hi >>> 6) >>> 0; - t1_lo = ((hi << 13 | lo >>> 19) ^ // ROTR 19 - (lo << 3 | hi >>> 29) ^ // ROTR 61/(swap + ROTR 29) - (hi << 26 | lo >>> 6)) >>> 0; - w15 = w[i - 15]; - hi = w15[0]; - lo = w15[1]; - t2_hi = ((hi >>> 1 | lo << 31) ^ // ROTR 1 - (hi >>> 8 | lo << 24) ^ // ROTR 8 - hi >>> 7) >>> 0; - t2_lo = ((hi << 31 | lo >>> 1) ^ // ROTR 1 - (hi << 24 | lo >>> 8) ^ // ROTR 8 - (hi << 25 | lo >>> 7)) >>> 0; - w7 = w[i - 7]; - w16 = w[i - 16]; - lo = t1_lo + w7[1] + t2_lo + w16[1]; - w[i][0] = t1_hi + w7[0] + t2_hi + w16[0] + (lo / 4294967296 >>> 0) >>> 0; - w[i][1] = lo >>> 0; + return result; + }; + function getBySubject(subject) { + ensureSubjectHasHash(subject); + return caStore.certs[subject.hash] || null; + } + function ensureSubjectHasHash(subject) { + if (!subject.hash) { + var md = forge.md.sha1.create(); + subject.attributes = pki2.RDNAttributesAsArray(_dnToAsn1(subject), md); + subject.hash = md.digest().toHex(); } - a_hi = s[0][0]; - a_lo = s[0][1]; - b_hi = s[1][0]; - b_lo = s[1][1]; - c_hi = s[2][0]; - c_lo = s[2][1]; - d_hi = s[3][0]; - d_lo = s[3][1]; - e_hi = s[4][0]; - e_lo = s[4][1]; - f_hi = s[5][0]; - f_lo = s[5][1]; - g_hi = s[6][0]; - g_lo = s[6][1]; - h_hi = s[7][0]; - h_lo = s[7][1]; - for (i = 0; i < 80; ++i) { - s1_hi = ((e_hi >>> 14 | e_lo << 18) ^ // ROTR 14 - (e_hi >>> 18 | e_lo << 14) ^ // ROTR 18 - (e_lo >>> 9 | e_hi << 23)) >>> 0; - s1_lo = ((e_hi << 18 | e_lo >>> 14) ^ // ROTR 14 - (e_hi << 14 | e_lo >>> 18) ^ // ROTR 18 - (e_lo << 23 | e_hi >>> 9)) >>> 0; - ch_hi = (g_hi ^ e_hi & (f_hi ^ g_hi)) >>> 0; - ch_lo = (g_lo ^ e_lo & (f_lo ^ g_lo)) >>> 0; - s0_hi = ((a_hi >>> 28 | a_lo << 4) ^ // ROTR 28 - (a_lo >>> 2 | a_hi << 30) ^ // ROTR 34/(swap + ROTR 2) - (a_lo >>> 7 | a_hi << 25)) >>> 0; - s0_lo = ((a_hi << 4 | a_lo >>> 28) ^ // ROTR 28 - (a_lo << 30 | a_hi >>> 2) ^ // ROTR 34/(swap + ROTR 2) - (a_lo << 25 | a_hi >>> 7)) >>> 0; - maj_hi = (a_hi & b_hi | c_hi & (a_hi ^ b_hi)) >>> 0; - maj_lo = (a_lo & b_lo | c_lo & (a_lo ^ b_lo)) >>> 0; - lo = h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]; - t1_hi = h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + (lo / 4294967296 >>> 0) >>> 0; - t1_lo = lo >>> 0; - lo = s0_lo + maj_lo; - t2_hi = s0_hi + maj_hi + (lo / 4294967296 >>> 0) >>> 0; - t2_lo = lo >>> 0; - h_hi = g_hi; - h_lo = g_lo; - g_hi = f_hi; - g_lo = f_lo; - f_hi = e_hi; - f_lo = e_lo; - lo = d_lo + t1_lo; - e_hi = d_hi + t1_hi + (lo / 4294967296 >>> 0) >>> 0; - e_lo = lo >>> 0; - d_hi = c_hi; - d_lo = c_lo; - c_hi = b_hi; - c_lo = b_lo; - b_hi = a_hi; - b_lo = a_lo; - lo = t1_lo + t2_lo; - a_hi = t1_hi + t2_hi + (lo / 4294967296 >>> 0) >>> 0; - a_lo = lo >>> 0; + } + if (certs) { + for (var i = 0; i < certs.length; ++i) { + var cert = certs[i]; + caStore.addCertificate(cert); } - lo = s[0][1] + a_lo; - s[0][0] = s[0][0] + a_hi + (lo / 4294967296 >>> 0) >>> 0; - s[0][1] = lo >>> 0; - lo = s[1][1] + b_lo; - s[1][0] = s[1][0] + b_hi + (lo / 4294967296 >>> 0) >>> 0; - s[1][1] = lo >>> 0; - lo = s[2][1] + c_lo; - s[2][0] = s[2][0] + c_hi + (lo / 4294967296 >>> 0) >>> 0; - s[2][1] = lo >>> 0; - lo = s[3][1] + d_lo; - s[3][0] = s[3][0] + d_hi + (lo / 4294967296 >>> 0) >>> 0; - s[3][1] = lo >>> 0; - lo = s[4][1] + e_lo; - s[4][0] = s[4][0] + e_hi + (lo / 4294967296 >>> 0) >>> 0; - s[4][1] = lo >>> 0; - lo = s[5][1] + f_lo; - s[5][0] = s[5][0] + f_hi + (lo / 4294967296 >>> 0) >>> 0; - s[5][1] = lo >>> 0; - lo = s[6][1] + g_lo; - s[6][0] = s[6][0] + g_hi + (lo / 4294967296 >>> 0) >>> 0; - s[6][1] = lo >>> 0; - lo = s[7][1] + h_lo; - s[7][0] = s[7][0] + h_hi + (lo / 4294967296 >>> 0) >>> 0; - s[7][1] = lo >>> 0; - len -= 128; } - } - } -}); - -// node_modules/node-forge/lib/asn1-validator.js -var require_asn1_validator = __commonJS({ - "node_modules/node-forge/lib/asn1-validator.js"(exports2) { - var forge = require_forge(); - require_asn1(); - var asn1 = forge.asn1; - exports2.privateKeyValidator = { - // PrivateKeyInfo - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "PrivateKeyInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // privateKeyAlgorithm - name: "PrivateKeyInfo.privateKeyAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "privateKeyOid" - }] - }, { - // PrivateKey - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "privateKey" - }] + return caStore; }; - exports2.publicKeyValidator = { - name: "SubjectPublicKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "subjectPublicKeyInfo", - value: [ - { - name: "SubjectPublicKeyInfo.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "publicKeyOid" - }] - }, - // capture group for ed25519PublicKey - { - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - composed: true, - captureBitStringValue: "ed25519PublicKey" - } - // FIXME: this is capture group for rsaPublicKey, use it in this API or - // discard? - /* { - // subjectPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'rsaPublicKey' - }] - } */ - ] + pki2.certificateError = { + bad_certificate: "forge.pki.BadCertificate", + unsupported_certificate: "forge.pki.UnsupportedCertificate", + certificate_revoked: "forge.pki.CertificateRevoked", + certificate_expired: "forge.pki.CertificateExpired", + certificate_unknown: "forge.pki.CertificateUnknown", + unknown_ca: "forge.pki.UnknownCertificateAuthority" }; - } -}); - -// node_modules/node-forge/lib/ed25519.js -var require_ed25519 = __commonJS({ - "node_modules/node-forge/lib/ed25519.js"(exports2, module2) { - var forge = require_forge(); - require_jsbn(); - require_random(); - require_sha512(); - require_util8(); - var asn1Validator = require_asn1_validator(); - var publicKeyValidator = asn1Validator.publicKeyValidator; - var privateKeyValidator = asn1Validator.privateKeyValidator; - if (typeof BigInteger === "undefined") { - BigInteger = forge.jsbn.BigInteger; - } - var BigInteger; - var ByteBuffer = forge.util.ByteBuffer; - var NativeBuffer = typeof Buffer === "undefined" ? Uint8Array : Buffer; - forge.pki = forge.pki || {}; - module2.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; - var ed25519 = forge.ed25519; - ed25519.constants = {}; - ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; - ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; - ed25519.constants.SEED_BYTE_LENGTH = 32; - ed25519.constants.SIGN_BYTE_LENGTH = 64; - ed25519.constants.HASH_BYTE_LENGTH = 64; - ed25519.generateKeyPair = function(options) { + pki2.verifyCertificateChain = function(caStore, chain, options) { + if (typeof options === "function") { + options = { verify: options }; + } options = options || {}; - var seed = options.seed; - if (seed === void 0) { - seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); - } else if (typeof seed === "string") { - if (seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { - throw new TypeError( - '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + " bytes in length." - ); + chain = chain.slice(0); + var certs = chain.slice(0); + var validityCheckDate = options.validityCheckDate; + if (typeof validityCheckDate === "undefined") { + validityCheckDate = /* @__PURE__ */ new Date(); + } + var first = true; + var error4 = null; + var depth = 0; + do { + var cert = chain.shift(); + var parent = null; + var selfSigned = false; + if (validityCheckDate) { + if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) { + error4 = { + message: "Certificate is not valid yet or has expired.", + error: pki2.certificateError.certificate_expired, + notBefore: cert.validity.notBefore, + notAfter: cert.validity.notAfter, + // TODO: we might want to reconsider renaming 'now' to + // 'validityCheckDate' should this API be changed in the future. + now: validityCheckDate + }; + } + } + if (error4 === null) { + parent = chain[0] || caStore.getIssuer(cert); + if (parent === null) { + if (cert.isIssuer(cert)) { + selfSigned = true; + parent = cert; + } + } + if (parent) { + var parents = parent; + if (!forge.util.isArray(parents)) { + parents = [parents]; + } + var verified = false; + while (!verified && parents.length > 0) { + parent = parents.shift(); + try { + verified = parent.verify(cert); + } catch (ex) { + } + } + if (!verified) { + error4 = { + message: "Certificate signature is invalid.", + error: pki2.certificateError.bad_certificate + }; + } + } + if (error4 === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) { + error4 = { + message: "Certificate is not trusted.", + error: pki2.certificateError.unknown_ca + }; + } + } + if (error4 === null && parent && !cert.isIssuer(parent)) { + error4 = { + message: "Certificate issuer is invalid.", + error: pki2.certificateError.bad_certificate + }; + } + if (error4 === null) { + var se = { + keyUsage: true, + basicConstraints: true + }; + for (var i = 0; error4 === null && i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if (ext.critical && !(ext.name in se)) { + error4 = { + message: "Certificate has an unsupported critical extension.", + error: pki2.certificateError.unsupported_certificate + }; + } + } + } + if (error4 === null && (!first || chain.length === 0 && (!parent || selfSigned))) { + var bcExt = cert.getExtension("basicConstraints"); + var keyUsageExt = cert.getExtension("keyUsage"); + if (keyUsageExt !== null) { + if (!keyUsageExt.keyCertSign || bcExt === null) { + error4 = { + message: "Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.", + error: pki2.certificateError.bad_certificate + }; + } + } + if (error4 === null && bcExt !== null && !bcExt.cA) { + error4 = { + message: "Certificate basicConstraints indicates the certificate is not a CA.", + error: pki2.certificateError.bad_certificate + }; + } + if (error4 === null && keyUsageExt !== null && "pathLenConstraint" in bcExt) { + var pathLen = depth - 1; + if (pathLen > bcExt.pathLenConstraint) { + error4 = { + message: "Certificate basicConstraints pathLenConstraint violated.", + error: pki2.certificateError.bad_certificate + }; + } + } + } + var vfd = error4 === null ? true : error4.error; + var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; + if (ret === true) { + error4 = null; + } else { + if (vfd === true) { + error4 = { + message: "The application rejected the certificate.", + error: pki2.certificateError.bad_certificate + }; + } + if (ret || ret === 0) { + if (typeof ret === "object" && !forge.util.isArray(ret)) { + if (ret.message) { + error4.message = ret.message; + } + if (ret.error) { + error4.error = ret.error; + } + } else if (typeof ret === "string") { + error4.error = ret; + } + } + throw error4; + } + first = false; + ++depth; + } while (chain.length > 0); + return true; + }; + } +}); + +// node_modules/node-forge/lib/pkcs12.js +var require_pkcs12 = __commonJS({ + "node_modules/node-forge/lib/pkcs12.js"(exports2, module2) { + var forge = require_forge(); + require_asn1(); + require_hmac(); + require_oids(); + require_pkcs7asn1(); + require_pbe(); + require_random(); + require_rsa(); + require_sha1(); + require_util8(); + require_x509(); + var asn1 = forge.asn1; + var pki2 = forge.pki; + var p12 = module2.exports = forge.pkcs12 = forge.pkcs12 || {}; + var contentInfoValidator = { + name: "ContentInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + // a ContentInfo + constructed: true, + value: [{ + name: "ContentInfo.contentType", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "contentType" + }, { + name: "ContentInfo.content", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: "content" + }] + }; + var pfxValidator = { + name: "PFX", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [ + { + name: "PFX.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "version" + }, + contentInfoValidator, + { + name: "PFX.macData", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: "mac", + value: [{ + name: "PFX.macData.mac", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + // DigestInfo + constructed: true, + value: [{ + name: "PFX.macData.mac.digestAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + // DigestAlgorithmIdentifier + constructed: true, + value: [{ + name: "PFX.macData.mac.digestAlgorithm.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "macAlgorithm" + }, { + name: "PFX.macData.mac.digestAlgorithm.parameters", + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: "macAlgorithmParameters" + }] + }, { + name: "PFX.macData.mac.digest", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "macDigest" + }] + }, { + name: "PFX.macData.macSalt", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "macSalt" + }, { + name: "PFX.macData.iterations", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: "macIterations" + }] + } + ] + }; + var safeBagValidator = { + name: "SafeBag", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "SafeBag.bagId", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "bagId" + }, { + name: "SafeBag.bagValue", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: "bagValue" + }, { + name: "SafeBag.bagAttributes", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + optional: true, + capture: "bagAttributes" + }] + }; + var attributeValidator = { + name: "Attribute", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "Attribute.attrId", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "oid" + }, { + name: "Attribute.attrValues", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + capture: "values" + }] + }; + var certBagValidator = { + name: "CertBag", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "CertBag.certId", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "certId" + }, { + name: "CertBag.certValue", + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + /* So far we only support X.509 certificates (which are wrapped in + an OCTET STRING, hence hard code that here). */ + value: [{ + name: "CertBag.certValue[0]", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.OCTETSTRING, + constructed: false, + capture: "cert" + }] + }] + }; + function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { + var result = []; + for (var i = 0; i < safeContents.length; i++) { + for (var j = 0; j < safeContents[i].safeBags.length; j++) { + var bag = safeContents[i].safeBags[j]; + if (bagType !== void 0 && bag.type !== bagType) { + continue; + } + if (attrName === null) { + result.push(bag); + continue; + } + if (bag.attributes[attrName] !== void 0 && bag.attributes[attrName].indexOf(attrValue) >= 0) { + result.push(bag); + } } - } else if (!(seed instanceof Uint8Array)) { - throw new TypeError( - '"seed" must be a node.js Buffer, Uint8Array, or a binary string.' - ); } - seed = messageToNativeBuffer({ message: seed, encoding: "binary" }); - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - for (var i = 0; i < 32; ++i) { - sk[i] = seed[i]; + return result; + } + p12.pkcs12FromAsn1 = function(obj, strict, password) { + if (typeof strict === "string") { + password = strict; + strict = true; + } else if (strict === void 0) { + strict = true; } - crypto_sign_keypair(pk, sk); - return { publicKey: pk, privateKey: sk }; - }; - ed25519.privateKeyFromAsn1 = function(obj) { var capture = {}; var errors = []; - var valid2 = forge.asn1.validate(obj, privateKeyValidator, capture, errors); - if (!valid2) { - var error4 = new Error("Invalid Key."); - error4.errors = errors; + if (!asn1.validate(obj, pfxValidator, capture, errors)) { + var error4 = new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX."); + error4.errors = error4; throw error4; } - var oid = forge.asn1.derToOid(capture.privateKeyOid); - var ed25519Oid = forge.oids.EdDSA25519; - if (oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); + var pfx = { + version: capture.version.charCodeAt(0), + safeContents: [], + /** + * Gets bags with matching attributes. + * + * @param filter the attributes to filter by: + * [localKeyId] the localKeyId to search for. + * [localKeyIdHex] the localKeyId in hex to search for. + * [friendlyName] the friendly name to search for. + * [bagType] bag type to narrow each attribute search by. + * + * @return a map of attribute type to an array of matching bags or, if no + * attribute was given but a bag type, the map key will be the + * bag type. + */ + getBags: function(filter) { + var rval = {}; + var localKeyId; + if ("localKeyId" in filter) { + localKeyId = filter.localKeyId; + } else if ("localKeyIdHex" in filter) { + localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); + } + if (localKeyId === void 0 && !("friendlyName" in filter) && "bagType" in filter) { + rval[filter.bagType] = _getBagsByAttribute( + pfx.safeContents, + null, + null, + filter.bagType + ); + } + if (localKeyId !== void 0) { + rval.localKeyId = _getBagsByAttribute( + pfx.safeContents, + "localKeyId", + localKeyId, + filter.bagType + ); + } + if ("friendlyName" in filter) { + rval.friendlyName = _getBagsByAttribute( + pfx.safeContents, + "friendlyName", + filter.friendlyName, + filter.bagType + ); + } + return rval; + }, + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching friendlyName attribute. + * + * @param friendlyName the friendly name to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching friendlyName attribute. + */ + getBagsByFriendlyName: function(friendlyName, bagType) { + return _getBagsByAttribute( + pfx.safeContents, + "friendlyName", + friendlyName, + bagType + ); + }, + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching localKeyId attribute. + * + * @param localKeyId the localKeyId to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching localKeyId attribute. + */ + getBagsByLocalKeyId: function(localKeyId, bagType) { + return _getBagsByAttribute( + pfx.safeContents, + "localKeyId", + localKeyId, + bagType + ); + } + }; + if (capture.version.charCodeAt(0) !== 3) { + var error4 = new Error("PKCS#12 PFX of version other than 3 not supported."); + error4.version = capture.version.charCodeAt(0); + throw error4; } - var privateKey = capture.privateKey; - var privateKeyBytes = messageToNativeBuffer({ - message: forge.asn1.fromDer(privateKey).value, - encoding: "binary" - }); - return { privateKeyBytes }; - }; - ed25519.publicKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - var valid2 = forge.asn1.validate(obj, publicKeyValidator, capture, errors); - if (!valid2) { - var error4 = new Error("Invalid Key."); - error4.errors = errors; + if (asn1.derToOid(capture.contentType) !== pki2.oids.data) { + var error4 = new Error("Only PKCS#12 PFX in password integrity mode supported."); + error4.oid = asn1.derToOid(capture.contentType); throw error4; } - var oid = forge.asn1.derToOid(capture.publicKeyOid); - var ed25519Oid = forge.oids.EdDSA25519; - if (oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); + var data = capture.content.value[0]; + if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { + throw new Error("PKCS#12 authSafe content data is not an OCTET STRING."); } - var publicKeyBytes = capture.ed25519PublicKey; - if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new Error("Key length is invalid."); - } - return messageToNativeBuffer({ - message: publicKeyBytes, - encoding: "binary" - }); - }; - ed25519.publicKeyFromPrivateKey = function(options) { - options = options || {}; - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: "binary" - }); - if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH + data = _decodePkcs7Data(data); + if (capture.mac) { + var md = null; + var macKeyBytes = 0; + var macAlgorithm = asn1.derToOid(capture.macAlgorithm); + switch (macAlgorithm) { + case pki2.oids.sha1: + md = forge.md.sha1.create(); + macKeyBytes = 20; + break; + case pki2.oids.sha256: + md = forge.md.sha256.create(); + macKeyBytes = 32; + break; + case pki2.oids.sha384: + md = forge.md.sha384.create(); + macKeyBytes = 48; + break; + case pki2.oids.sha512: + md = forge.md.sha512.create(); + macKeyBytes = 64; + break; + case pki2.oids.md5: + md = forge.md.md5.create(); + macKeyBytes = 16; + break; + } + if (md === null) { + throw new Error("PKCS#12 uses unsupported MAC algorithm: " + macAlgorithm); + } + var macSalt = new forge.util.ByteBuffer(capture.macSalt); + var macIterations = "macIterations" in capture ? parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1; + var macKey = p12.generateKey( + password, + macSalt, + 3, + macIterations, + macKeyBytes, + md ); + var mac = forge.hmac.create(); + mac.start(md, macKey); + mac.update(data.value); + var macValue = mac.getMac(); + if (macValue.getBytes() !== capture.macDigest) { + throw new Error("PKCS#12 MAC could not be verified. Invalid password?"); + } } - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - for (var i = 0; i < pk.length; ++i) { - pk[i] = privateKey[32 + i]; - } - return pk; + _decodeAuthenticatedSafe(pfx, data.value, strict, password); + return pfx; }; - ed25519.sign = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: "binary" - }); - if (privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { - var keyPair = ed25519.generateKeyPair({ seed: privateKey }); - privateKey = keyPair.privateKey; - } else if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + " or " + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH - ); + function _decodePkcs7Data(data) { + if (data.composed || data.constructed) { + var value = forge.util.createBuffer(); + for (var i = 0; i < data.value.length; ++i) { + value.putBytes(data.value[i].value); + } + data.composed = data.constructed = false; + data.value = value.getBytes(); } - var signedMsg = new NativeBuffer( - ed25519.constants.SIGN_BYTE_LENGTH + msg.length - ); - crypto_sign(signedMsg, msg, msg.length, privateKey); - var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); - for (var i = 0; i < sig.length; ++i) { - sig[i] = signedMsg[i]; + return data; + } + function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { + authSafe = asn1.fromDer(authSafe, strict); + if (authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) { + throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo"); } - return sig; - }; - ed25519.verify = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - if (options.signature === void 0) { - throw new TypeError( - '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.' - ); + for (var i = 0; i < authSafe.value.length; i++) { + var contentInfo = authSafe.value[i]; + var capture = {}; + var errors = []; + if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { + var error4 = new Error("Cannot read ContentInfo."); + error4.errors = errors; + throw error4; + } + var obj = { + encrypted: false + }; + var safeContents = null; + var data = capture.content.value[0]; + switch (asn1.derToOid(capture.contentType)) { + case pki2.oids.data: + if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { + throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING."); + } + safeContents = _decodePkcs7Data(data).value; + break; + case pki2.oids.encryptedData: + safeContents = _decryptSafeContents(data, password); + obj.encrypted = true; + break; + default: + var error4 = new Error("Unsupported PKCS#12 contentType."); + error4.contentType = asn1.derToOid(capture.contentType); + throw error4; + } + obj.safeBags = _decodeSafeContents(safeContents, strict, password); + pfx.safeContents.push(obj); } - var sig = messageToNativeBuffer({ - message: options.signature, - encoding: "binary" - }); - if (sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { - throw new TypeError( - '"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH - ); + } + function _decryptSafeContents(data, password) { + var capture = {}; + var errors = []; + if (!asn1.validate( + data, + forge.pkcs7.asn1.encryptedDataValidator, + capture, + errors + )) { + var error4 = new Error("Cannot read EncryptedContentInfo."); + error4.errors = errors; + throw error4; } - var publicKey = messageToNativeBuffer({ - message: options.publicKey, - encoding: "binary" - }); - if (publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH + var oid = asn1.derToOid(capture.contentType); + if (oid !== pki2.oids.data) { + var error4 = new Error( + "PKCS#12 EncryptedContentInfo ContentType is not Data." ); + error4.oid = oid; + throw error4; } - var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var i; - for (i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { - sm[i] = sig[i]; + oid = asn1.derToOid(capture.encAlgorithm); + var cipher = pki2.pbe.getCipher(oid, capture.encParameter, password); + var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); + var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); + cipher.update(encrypted); + if (!cipher.finish()) { + throw new Error("Failed to decrypt PKCS#12 SafeContents."); } - for (i = 0; i < msg.length; ++i) { - sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; + return cipher.output.getBytes(); + } + function _decodeSafeContents(safeContents, strict, password) { + if (!strict && safeContents.length === 0) { + return []; } - return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; - }; - function messageToNativeBuffer(options) { - var message = options.message; - if (message instanceof Uint8Array || message instanceof NativeBuffer) { - return message; + safeContents = asn1.fromDer(safeContents, strict); + if (safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) { + throw new Error( + "PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag." + ); } - var encoding = options.encoding; - if (message === void 0) { - if (options.md) { - message = options.md.digest().getBytes(); - encoding = "binary"; - } else { - throw new TypeError('"options.message" or "options.md" not specified.'); + var res = []; + for (var i = 0; i < safeContents.value.length; i++) { + var safeBag = safeContents.value[i]; + var capture = {}; + var errors = []; + if (!asn1.validate(safeBag, safeBagValidator, capture, errors)) { + var error4 = new Error("Cannot read SafeBag."); + error4.errors = errors; + throw error4; } - } - if (typeof message === "string" && !encoding) { - throw new TypeError('"options.encoding" must be "binary" or "utf8".'); - } - if (typeof message === "string") { - if (typeof Buffer !== "undefined") { - return Buffer.from(message, encoding); + var bag = { + type: asn1.derToOid(capture.bagId), + attributes: _decodeBagAttributes(capture.bagAttributes) + }; + res.push(bag); + var validator, decoder; + var bagAsn1 = capture.bagValue.value[0]; + switch (bag.type) { + case pki2.oids.pkcs8ShroudedKeyBag: + bagAsn1 = pki2.decryptPrivateKeyInfo(bagAsn1, password); + if (bagAsn1 === null) { + throw new Error( + "Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?" + ); + } + /* fall through */ + case pki2.oids.keyBag: + try { + bag.key = pki2.privateKeyFromAsn1(bagAsn1); + } catch (e) { + bag.key = null; + bag.asn1 = bagAsn1; + } + continue; + /* Nothing more to do. */ + case pki2.oids.certBag: + validator = certBagValidator; + decoder = function() { + if (asn1.derToOid(capture.certId) !== pki2.oids.x509Certificate) { + var error5 = new Error( + "Unsupported certificate type, only X.509 supported." + ); + error5.oid = asn1.derToOid(capture.certId); + throw error5; + } + var certAsn1 = asn1.fromDer(capture.cert, strict); + try { + bag.cert = pki2.certificateFromAsn1(certAsn1, true); + } catch (e) { + bag.cert = null; + bag.asn1 = certAsn1; + } + }; + break; + default: + var error4 = new Error("Unsupported PKCS#12 SafeBag type."); + error4.oid = bag.type; + throw error4; } - message = new ByteBuffer(message, encoding); - } else if (!(message instanceof ByteBuffer)) { - throw new TypeError( - '"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.' - ); - } - var buffer = new NativeBuffer(message.length()); - for (var i = 0; i < buffer.length; ++i) { - buffer[i] = message.at(i); - } - return buffer; - } - var gf0 = gf(); - var gf1 = gf([1]); - var D = gf([ - 30883, - 4953, - 19914, - 30187, - 55467, - 16705, - 2637, - 112, - 59544, - 30585, - 16505, - 36039, - 65139, - 11119, - 27886, - 20995 - ]); - var D2 = gf([ - 61785, - 9906, - 39828, - 60374, - 45398, - 33411, - 5274, - 224, - 53552, - 61171, - 33010, - 6542, - 64743, - 22239, - 55772, - 9222 - ]); - var X = gf([ - 54554, - 36645, - 11616, - 51542, - 42930, - 38181, - 51040, - 26924, - 56412, - 64982, - 57905, - 49316, - 21502, - 52590, - 14035, - 8553 - ]); - var Y = gf([ - 26200, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214 - ]); - var L = new Float64Array([ - 237, - 211, - 245, - 92, - 26, - 99, - 18, - 88, - 214, - 156, - 247, - 162, - 222, - 249, - 222, - 20, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 16 - ]); - var I = gf([ - 41136, - 18958, - 6951, - 50414, - 58488, - 44335, - 6150, - 12099, - 55207, - 15867, - 153, - 11085, - 57099, - 20417, - 9344, - 11139 - ]); - function sha512(msg, msgLen) { - var md = forge.md.sha512.create(); - var buffer = new ByteBuffer(msg); - md.update(buffer.getBytes(msgLen), "binary"); - var hash = md.digest().getBytes(); - if (typeof Buffer !== "undefined") { - return Buffer.from(hash, "binary"); - } - var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); - for (var i = 0; i < 64; ++i) { - out[i] = hash.charCodeAt(i); + if (validator !== void 0 && !asn1.validate(bagAsn1, validator, capture, errors)) { + var error4 = new Error("Cannot read PKCS#12 " + validator.name); + error4.errors = errors; + throw error4; + } + decoder(); } - return out; + return res; } - function crypto_sign_keypair(pk, sk) { - var p = [gf(), gf(), gf(), gf()]; - var i; - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - scalarbase(p, d); - pack(pk, p); - for (i = 0; i < 32; ++i) { - sk[i + 32] = pk[i]; + function _decodeBagAttributes(attributes) { + var decodedAttrs = {}; + if (attributes !== void 0) { + for (var i = 0; i < attributes.length; ++i) { + var capture = {}; + var errors = []; + if (!asn1.validate(attributes[i], attributeValidator, capture, errors)) { + var error4 = new Error("Cannot read PKCS#12 BagAttribute."); + error4.errors = errors; + throw error4; + } + var oid = asn1.derToOid(capture.oid); + if (pki2.oids[oid] === void 0) { + continue; + } + decodedAttrs[pki2.oids[oid]] = []; + for (var j = 0; j < capture.values.length; ++j) { + decodedAttrs[pki2.oids[oid]].push(capture.values[j].value); + } + } } - return 0; + return decodedAttrs; } - function crypto_sign(sm, m, n, sk) { - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - var smlen = n + 64; - for (i = 0; i < n; ++i) { - sm[64 + i] = m[i]; - } - for (i = 0; i < 32; ++i) { - sm[32 + i] = d[32 + i]; - } - var r = sha512(sm.subarray(32), n + 32); - reduce(r); - scalarbase(p, r); - pack(sm, p); - for (i = 32; i < 64; ++i) { - sm[i] = sk[i]; - } - var h = sha512(sm, n + 64); - reduce(h); - for (i = 32; i < 64; ++i) { - x[i] = 0; + p12.toPkcs12Asn1 = function(key, cert, password, options) { + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || options.encAlgorithm || "aes128"; + if (!("useMac" in options)) { + options.useMac = true; } - for (i = 0; i < 32; ++i) { - x[i] = r[i]; + if (!("localKeyId" in options)) { + options.localKeyId = null; } - for (i = 0; i < 32; ++i) { - for (j = 0; j < 32; j++) { - x[i + j] += h[i] * d[j]; - } + if (!("generateLocalKeyId" in options)) { + options.generateLocalKeyId = true; } - modL(sm.subarray(32), x); - return smlen; - } - function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new NativeBuffer(32); - var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; - mlen = -1; - if (n < 64) { - return -1; + var localKeyId = options.localKeyId; + var bagAttrs; + if (localKeyId !== null) { + localKeyId = forge.util.hexToBytes(localKeyId); + } else if (options.generateLocalKeyId) { + if (cert) { + var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; + if (typeof pairedCert === "string") { + pairedCert = pki2.certificateFromPem(pairedCert); + } + var sha1 = forge.md.sha1.create(); + sha1.update(asn1.toDer(pki2.certificateToAsn1(pairedCert)).getBytes()); + localKeyId = sha1.digest().getBytes(); + } else { + localKeyId = forge.random.getBytes(20); + } } - if (unpackneg(q, pk)) { - return -1; + var attrs = []; + if (localKeyId !== null) { + attrs.push( + // localKeyID + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.localKeyId).getBytes() + ), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + localKeyId + ) + ]) + ]) + ); } - for (i = 0; i < n; ++i) { - m[i] = sm[i]; + if ("friendlyName" in options) { + attrs.push( + // friendlyName + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.friendlyName).getBytes() + ), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.BMPSTRING, + false, + options.friendlyName + ) + ]) + ]) + ); } - for (i = 0; i < 32; ++i) { - m[i + 32] = pk[i]; + if (attrs.length > 0) { + bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); } - var h = sha512(m, n); - reduce(h); - scalarmult(p, q, h); - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; ++i) { - m[i] = 0; + var contents = []; + var chain = []; + if (cert !== null) { + if (forge.util.isArray(cert)) { + chain = cert; + } else { + chain = [cert]; } - return -1; } - for (i = 0; i < n; ++i) { - m[i] = sm[i + 64]; - } - mlen = n; - return mlen; - } - function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = x[j] + 128 >> 8; - x[j] -= carry * 256; + var certSafeBags = []; + for (var i = 0; i < chain.length; ++i) { + cert = chain[i]; + if (typeof cert === "string") { + cert = pki2.certificateFromPem(cert); } - x[j] += carry; - x[i] = 0; + var certBagAttrs = i === 0 ? bagAttrs : void 0; + var certAsn1 = pki2.certificateToAsn1(cert); + var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.certBag).getBytes() + ), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // CertBag + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // certId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.x509Certificate).getBytes() + ), + // certValue (x509Certificate) + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + asn1.toDer(certAsn1).getBytes() + ) + ]) + ]) + ]), + // bagAttributes (OPTIONAL) + certBagAttrs + ]); + certSafeBags.push(certSafeBag); } - carry = 0; - for (j = 0; j < 32; ++j) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; + if (certSafeBags.length > 0) { + var certSafeContents = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + certSafeBags + ); + var certCI = ( + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + // OID for the content type is 'data' + asn1.oidToDer(pki2.oids.data).getBytes() + ), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + asn1.toDer(certSafeContents).getBytes() + ) + ]) + ]) + ); + contents.push(certCI); } - for (j = 0; j < 32; ++j) { - x[j] -= carry * L[j]; + var keyBag = null; + if (key !== null) { + var pkAsn1 = pki2.wrapRsaPrivateKey(pki2.privateKeyToAsn1(key)); + if (password === null) { + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.keyBag).getBytes() + ), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // PrivateKeyInfo + pkAsn1 + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } else { + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.pkcs8ShroudedKeyBag).getBytes() + ), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // EncryptedPrivateKeyInfo + pki2.encryptPrivateKeyInfo(pkAsn1, password, options) + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } + var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); + var keyCI = ( + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + // OID for the content type is 'data' + asn1.oidToDer(pki2.oids.data).getBytes() + ), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + asn1.toDer(keySafeContents).getBytes() + ) + ]) + ]) + ); + contents.push(keyCI); } - for (i = 0; i < 32; ++i) { - x[i + 1] += x[i] >> 8; - r[i] = x[i] & 255; + var safe = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + contents + ); + var macData; + if (options.useMac) { + var sha1 = forge.md.sha1.create(); + var macSalt = new forge.util.ByteBuffer( + forge.random.getBytes(options.saltSize) + ); + var count = options.count; + var key = p12.generateKey(password, macSalt, 3, count, 20); + var mac = forge.hmac.create(); + mac.start(sha1, key); + mac.update(asn1.toDer(safe).getBytes()); + var macValue = mac.getMac(); + macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // mac DigestInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm = SHA-1 + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(pki2.oids.sha1).getBytes() + ), + // parameters = Null + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]), + // digest + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + macValue.getBytes() + ) + ]), + // macSalt OCTET STRING + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + macSalt.getBytes() + ), + // iterations INTEGER (XXX: Only support count < 65536) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(count).getBytes() + ) + ]); } - } - function reduce(r) { - var x = new Float64Array(64); - for (var i = 0; i < 64; ++i) { - x[i] = r[i]; - r[i] = 0; + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (3) + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(3).getBytes() + ), + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + // OID for the content type is 'data' + asn1.oidToDer(pki2.oids.data).getBytes() + ), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + asn1.toDer(safe).getBytes() + ) + ]) + ]), + macData + ]); + }; + p12.generateKey = forge.pbe.generatePkcs12Key; + } +}); + +// node_modules/node-forge/lib/pki.js +var require_pki = __commonJS({ + "node_modules/node-forge/lib/pki.js"(exports2, module2) { + var forge = require_forge(); + require_asn1(); + require_oids(); + require_pbe(); + require_pem(); + require_pbkdf2(); + require_pkcs12(); + require_pss(); + require_rsa(); + require_util8(); + require_x509(); + var asn1 = forge.asn1; + var pki2 = module2.exports = forge.pki = forge.pki || {}; + pki2.pemToDer = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert PEM to DER; PEM is encrypted."); } - modL(r, x); - } - function add(p, q) { - var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); - } - function cswap(p, q, b) { - for (var i = 0; i < 4; ++i) { - sel25519(p[i], q[i], b); + return forge.util.createBuffer(msg.body); + }; + pki2.privateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { + var error4 = new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); + error4.headerType = msg.type; + throw error4; } - } - function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; - } - function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; ++i) { - t[i] = n[i]; + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert private key from PEM; PEM is encrypted."); } - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; ++j) { - m[0] = t[0] - 65517; - for (i = 1; i < 15; ++i) { - m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1); - m[i - 1] &= 65535; - } - m[15] = t[15] - 32767 - (m[14] >> 16 & 1); - b = m[15] >> 16 & 1; - m[14] &= 65535; - sel25519(t, m, 1 - b); + var obj = asn1.fromDer(msg.body); + return pki2.privateKeyFromAsn1(obj); + }; + pki2.privateKeyToPem = function(key, maxline) { + var msg = { + type: "RSA PRIVATE KEY", + body: asn1.toDer(pki2.privateKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + pki2.privateKeyInfoToPem = function(pki3, maxline) { + var msg = { + type: "PRIVATE KEY", + body: asn1.toDer(pki3).getBytes() + }; + return forge.pem.encode(msg, { maxline }); + }; + } +}); + +// node_modules/node-forge/lib/tls.js +var require_tls = __commonJS({ + "node_modules/node-forge/lib/tls.js"(exports2, module2) { + var forge = require_forge(); + require_asn1(); + require_hmac(); + require_md5(); + require_pem(); + require_pki(); + require_random(); + require_sha1(); + require_util8(); + var prf_TLS1 = function(secret, label, seed, length) { + var rval = forge.util.createBuffer(); + var idx = secret.length >> 1; + var slen = idx + (secret.length & 1); + var s1 = secret.substr(0, slen); + var s2 = secret.substr(idx, slen); + var ai = forge.util.createBuffer(); + var hmac = forge.hmac.create(); + seed = label + seed; + var md5itr = Math.ceil(length / 16); + var sha1itr = Math.ceil(length / 20); + hmac.start("MD5", s1); + var md5bytes = forge.util.createBuffer(); + ai.putBytes(seed); + for (var i = 0; i < md5itr; ++i) { + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + md5bytes.putBuffer(hmac.digest()); } - for (i = 0; i < 16; i++) { - o[2 * i] = t[i] & 255; - o[2 * i + 1] = t[i] >> 8; + hmac.start("SHA1", s2); + var sha1bytes = forge.util.createBuffer(); + ai.clear(); + ai.putBytes(seed); + for (var i = 0; i < sha1itr; ++i) { + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + sha1bytes.putBuffer(hmac.digest()); } - } - function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) { - M(r[0], r[0], I); - } - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) { - return -1; - } - if (par25519(r[0]) === p[31] >> 7) { - Z(r[0], gf0, r[0]); + rval.putBytes(forge.util.xorBytes( + md5bytes.getBytes(), + sha1bytes.getBytes(), + length + )); + return rval; + }; + var hmac_sha1 = function(key2, seqNum, record) { + var hmac = forge.hmac.create(); + hmac.start("SHA1", key2); + var b = forge.util.createBuffer(); + b.putInt32(seqNum[0]); + b.putInt32(seqNum[1]); + b.putByte(record.type); + b.putByte(record.version.major); + b.putByte(record.version.minor); + b.putInt16(record.length); + b.putBytes(record.fragment.bytes()); + hmac.update(b.getBytes()); + return hmac.digest().getBytes(); + }; + var deflate = function(c, record, s) { + var rval = false; + try { + var bytes = c.deflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch (ex) { } - M(r[3], r[0], r[1]); - return 0; - } - function unpack25519(o, n) { - var i; - for (i = 0; i < 16; ++i) { - o[i] = n[2 * i] + (n[2 * i + 1] << 8); + return rval; + }; + var inflate = function(c, record, s) { + var rval = false; + try { + var bytes = c.inflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch (ex) { } - o[15] &= 32767; - } - function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; ++a) { - c[a] = i[a]; + return rval; + }; + var readVector = function(b, lenBytes) { + var len = 0; + switch (lenBytes) { + case 1: + len = b.getByte(); + break; + case 2: + len = b.getInt16(); + break; + case 3: + len = b.getInt24(); + break; + case 4: + len = b.getInt32(); + break; } - for (a = 250; a >= 0; --a) { - S(c, c); - if (a !== 1) { - M(c, c, i); + return forge.util.createBuffer(b.getBytes(len)); + }; + var writeVector = function(b, lenBytes, v) { + b.putInt(v.length(), lenBytes << 3); + b.putBuffer(v); + }; + var tls = {}; + tls.Versions = { + TLS_1_0: { major: 3, minor: 1 }, + TLS_1_1: { major: 3, minor: 2 }, + TLS_1_2: { major: 3, minor: 3 } + }; + tls.SupportedVersions = [ + tls.Versions.TLS_1_1, + tls.Versions.TLS_1_0 + ]; + tls.Version = tls.SupportedVersions[0]; + tls.MaxFragment = 16384 - 1024; + tls.ConnectionEnd = { + server: 0, + client: 1 + }; + tls.PRFAlgorithm = { + tls_prf_sha256: 0 + }; + tls.BulkCipherAlgorithm = { + none: null, + rc4: 0, + des3: 1, + aes: 2 + }; + tls.CipherType = { + stream: 0, + block: 1, + aead: 2 + }; + tls.MACAlgorithm = { + none: null, + hmac_md5: 0, + hmac_sha1: 1, + hmac_sha256: 2, + hmac_sha384: 3, + hmac_sha512: 4 + }; + tls.CompressionMethod = { + none: 0, + deflate: 1 + }; + tls.ContentType = { + change_cipher_spec: 20, + alert: 21, + handshake: 22, + application_data: 23, + heartbeat: 24 + }; + tls.HandshakeType = { + hello_request: 0, + client_hello: 1, + server_hello: 2, + certificate: 11, + server_key_exchange: 12, + certificate_request: 13, + server_hello_done: 14, + certificate_verify: 15, + client_key_exchange: 16, + finished: 20 + }; + tls.Alert = {}; + tls.Alert.Level = { + warning: 1, + fatal: 2 + }; + tls.Alert.Description = { + close_notify: 0, + unexpected_message: 10, + bad_record_mac: 20, + decryption_failed: 21, + record_overflow: 22, + decompression_failure: 30, + handshake_failure: 40, + bad_certificate: 42, + unsupported_certificate: 43, + certificate_revoked: 44, + certificate_expired: 45, + certificate_unknown: 46, + illegal_parameter: 47, + unknown_ca: 48, + access_denied: 49, + decode_error: 50, + decrypt_error: 51, + export_restriction: 60, + protocol_version: 70, + insufficient_security: 71, + internal_error: 80, + user_canceled: 90, + no_renegotiation: 100 + }; + tls.HeartbeatMessageType = { + heartbeat_request: 1, + heartbeat_response: 2 + }; + tls.CipherSuites = {}; + tls.getCipherSuite = function(twoBytes) { + var rval = null; + for (var key2 in tls.CipherSuites) { + var cs = tls.CipherSuites[key2]; + if (cs.id[0] === twoBytes.charCodeAt(0) && cs.id[1] === twoBytes.charCodeAt(1)) { + rval = cs; + break; } } - for (a = 0; a < 16; ++a) { - o[a] = c[a]; + return rval; + }; + tls.handleUnexpected = function(c, record) { + var ignore = !c.open && c.entity === tls.ConnectionEnd.client; + if (!ignore) { + c.error(c, { + message: "Unexpected message. Received TLS record out of order.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unexpected_message + } + }); } - } - function neq25519(a, b) { - var c = new NativeBuffer(32); - var d = new NativeBuffer(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); - } - function crypto_verify_32(x, xi, y, yi) { - return vn(x, xi, y, yi, 32); - } - function vn(x, xi, y, yi, n) { - var i, d = 0; - for (i = 0; i < n; ++i) { - d |= x[xi + i] ^ y[yi + i]; + }; + tls.handleHelloRequest = function(c, record, length) { + if (!c.handshaking && c.handshakes > 0) { + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.no_renegotiation + })); + tls.flush(c); } - return (1 & d - 1 >>> 8) - 1; - } - function par25519(a) { - var d = new NativeBuffer(32); - pack25519(d, a); - return d[0] & 1; - } - function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = s[i / 8 | 0] >> (i & 7) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); + c.process(); + }; + tls.parseHelloMessage = function(c, record, length) { + var msg = null; + var client = c.entity === tls.ConnectionEnd.client; + if (length < 38) { + c.error(c, { + message: client ? "Invalid ServerHello message. Message too short." : "Invalid ClientHello message. Message too short.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else { + var b = record.fragment; + var remaining = b.length(); + msg = { + version: { + major: b.getByte(), + minor: b.getByte() + }, + random: forge.util.createBuffer(b.getBytes(32)), + session_id: readVector(b, 1), + extensions: [] + }; + if (client) { + msg.cipher_suite = b.getBytes(2); + msg.compression_method = b.getByte(); + } else { + msg.cipher_suites = readVector(b, 2); + msg.compression_methods = readVector(b, 1); + } + remaining = length - (remaining - b.length()); + if (remaining > 0) { + var exts = readVector(b, 2); + while (exts.length() > 0) { + msg.extensions.push({ + type: [exts.getByte(), exts.getByte()], + data: readVector(exts, 2) + }); + } + if (!client) { + for (var i = 0; i < msg.extensions.length; ++i) { + var ext = msg.extensions[i]; + if (ext.type[0] === 0 && ext.type[1] === 0) { + var snl = readVector(ext.data, 2); + while (snl.length() > 0) { + var snType = snl.getByte(); + if (snType !== 0) { + break; + } + c.session.extensions.server_name.serverNameList.push( + readVector(snl, 2).getBytes() + ); + } + } + } + } + } + if (c.session.version) { + if (msg.version.major !== c.session.version.major || msg.version.minor !== c.session.version.minor) { + return c.error(c, { + message: "TLS version change is disallowed during renegotiation.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + if (client) { + c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); + } else { + var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); + while (tmp.length() > 0) { + c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); + if (c.session.cipherSuite !== null) { + break; + } + } + } + if (c.session.cipherSuite === null) { + return c.error(c, { + message: "No cipher suites in common.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + }, + cipherSuite: forge.util.bytesToHex(msg.cipher_suite) + }); + } + if (client) { + c.session.compressionMethod = msg.compression_method; + } else { + c.session.compressionMethod = tls.CompressionMethod.none; + } } - } - function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); - } - function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) { - r[i] = a[i] | 0; + return msg; + }; + tls.createSecurityParameters = function(c, msg) { + var client = c.entity === tls.ConnectionEnd.client; + var msgRandom = msg.random.bytes(); + var cRandom = client ? c.session.sp.client_random : msgRandom; + var sRandom = client ? msgRandom : tls.createRandom().getBytes(); + c.session.sp = { + entity: c.entity, + prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, + bulk_cipher_algorithm: null, + cipher_type: null, + enc_key_length: null, + block_length: null, + fixed_iv_length: null, + record_iv_length: null, + mac_algorithm: null, + mac_length: null, + mac_key_length: null, + compression_algorithm: c.session.compressionMethod, + pre_master_secret: null, + master_secret: null, + client_random: cRandom, + server_random: sRandom + }; + }; + tls.handleServerHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if (c.fail) { + return; } - } - function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; ++a) { - c[a] = i[a]; + if (msg.version.minor <= c.version.minor) { + c.version.minor = msg.version.minor; + } else { + return c.error(c, { + message: "Incompatible TLS version.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); } - for (a = 253; a >= 0; --a) { - S(c, c); - if (a !== 2 && a !== 4) { - M(c, c, i); - } + c.session.version = c.version; + var sessionId = msg.session_id.bytes(); + if (sessionId.length > 0 && sessionId === c.session.id) { + c.expect = SCC; + c.session.resuming = true; + c.session.sp.server_random = msg.random.bytes(); + } else { + c.expect = SCE; + c.session.resuming = false; + tls.createSecurityParameters(c, msg); } - for (a = 0; a < 16; ++a) { - o[a] = c[a]; + c.session.id = sessionId; + c.process(); + }; + tls.handleClientHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if (c.fail) { + return; } - } - function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; ++i) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; + var sessionId = msg.session_id.bytes(); + var session = null; + if (c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + if (session === null) { + sessionId = ""; + } else if (session.version.major !== msg.version.major || session.version.minor > msg.version.minor) { + session = null; + sessionId = ""; + } } - o[0] += c - 1 + 37 * (c - 1); - } - function sel25519(p, q, b) { - var t, c = ~(b - 1); - for (var i = 0; i < 16; ++i) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; + if (sessionId.length === 0) { + sessionId = forge.random.getBytes(32); } - } - function gf(init) { - var i, r = new Float64Array(16); - if (init) { - for (i = 0; i < init.length; ++i) { - r[i] = init[i]; + c.session.id = sessionId; + c.session.clientHelloVersion = msg.version; + c.session.sp = {}; + if (session) { + c.version = c.session.version = session.version; + c.session.sp = session.sp; + } else { + var version; + for (var i = 1; i < tls.SupportedVersions.length; ++i) { + version = tls.SupportedVersions[i]; + if (version.minor <= msg.version.minor) { + break; + } } + c.version = { major: version.major, minor: version.minor }; + c.session.version = c.version; } - return r; - } - function A(o, a, b) { - for (var i = 0; i < 16; ++i) { - o[i] = a[i] + b[i]; - } - } - function Z(o, a, b) { - for (var i = 0; i < 16; ++i) { - o[i] = a[i] - b[i]; + if (session !== null) { + c.expect = CCC; + c.session.resuming = true; + c.session.sp.client_random = msg.random.bytes(); + } else { + c.expect = c.verifyClient !== false ? CCE : CKE; + c.session.resuming = false; + tls.createSecurityParameters(c, msg); } - } - function S(o, a) { + c.open = true; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHello(c) + })); + if (c.session.resuming) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + c.state.pending = tls.createConnectionState(c); + c.state.current.write = c.state.pending.write; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + } else { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + })); + if (!c.fail) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerKeyExchange(c) + })); + if (c.verifyClient !== false) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificateRequest(c) + })); + } + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHelloDone(c) + })); + } + } + tls.flush(c); + c.process(); + }; + tls.handleCertificate = function(c, record, length) { + if (length < 3) { + return c.error(c, { + message: "Invalid Certificate message. Message too short.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var b = record.fragment; + var msg = { + certificate_list: readVector(b, 3) + }; + var cert, asn1; + var certs = []; + try { + while (msg.certificate_list.length() > 0) { + cert = readVector(msg.certificate_list, 3); + asn1 = forge.asn1.fromDer(cert); + cert = forge.pki.certificateFromAsn1(asn1, true); + certs.push(cert); + } + } catch (ex) { + return c.error(c, { + message: "Could not parse certificate list.", + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + var client = c.entity === tls.ConnectionEnd.client; + if ((client || c.verifyClient === true) && certs.length === 0) { + c.error(c, { + message: client ? "No server certificate provided." : "No client certificate provided.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else if (certs.length === 0) { + c.expect = client ? SKE : CKE; + } else { + if (client) { + c.session.serverCertificate = certs[0]; + } else { + c.session.clientCertificate = certs[0]; + } + if (tls.verifyCertificateChain(c, certs)) { + c.expect = client ? SKE : CKE; + } + } + c.process(); + }; + tls.handleServerKeyExchange = function(c, record, length) { + if (length > 0) { + return c.error(c, { + message: "Invalid key parameters. Only RSA is supported.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + c.expect = SCR; + c.process(); + }; + tls.handleClientKeyExchange = function(c, record, length) { + if (length < 48) { + return c.error(c, { + message: "Invalid key parameters. Only RSA is supported.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + var b = record.fragment; + var msg = { + enc_pre_master_secret: readVector(b, 2).getBytes() + }; + var privateKey = null; + if (c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.serverCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch (ex) { + c.error(c, { + message: "Could not get private key.", + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + if (privateKey === null) { + return c.error(c, { + message: "No private key set.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + try { + var sp = c.session.sp; + sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); + var version = c.session.clientHelloVersion; + if (version.major !== sp.pre_master_secret.charCodeAt(0) || version.minor !== sp.pre_master_secret.charCodeAt(1)) { + throw new Error("TLS version rollback attack detected."); + } + } catch (ex) { + sp.pre_master_secret = forge.random.getBytes(48); + } + c.expect = CCC; + if (c.session.clientCertificate !== null) { + c.expect = CCV; + } + c.process(); + }; + tls.handleCertificateRequest = function(c, record, length) { + if (length < 3) { + return c.error(c, { + message: "Invalid CertificateRequest. Message too short.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var b = record.fragment; + var msg = { + certificate_types: readVector(b, 1), + certificate_authorities: readVector(b, 2) + }; + c.session.certificateRequest = msg; + c.expect = SHD; + c.process(); + }; + tls.handleCertificateVerify = function(c, record, length) { + if (length < 2) { + return c.error(c, { + message: "Invalid CertificateVerify. Message too short.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + var msg = { + signature: readVector(b, 2).getBytes() + }; + var verify = forge.util.createBuffer(); + verify.putBuffer(c.session.md5.digest()); + verify.putBuffer(c.session.sha1.digest()); + verify = verify.getBytes(); + try { + var cert = c.session.clientCertificate; + if (!cert.publicKey.verify(verify, msg.signature, "NONE")) { + throw new Error("CertificateVerify signature does not match."); + } + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + } catch (ex) { + return c.error(c, { + message: "Bad signature in CertificateVerify.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + } + }); + } + c.expect = CCC; + c.process(); + }; + tls.handleServerHelloDone = function(c, record, length) { + if (length > 0) { + return c.error(c, { + message: "Invalid ServerHelloDone message. Invalid length.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.record_overflow + } + }); + } + if (c.serverCertificate === null) { + var error4 = { + message: "No server certificate provided. Not enough security.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.insufficient_security + } + }; + var depth = 0; + var ret = c.verify(c, error4.alert.description, depth, []); + if (ret !== true) { + if (ret || ret === 0) { + if (typeof ret === "object" && !forge.util.isArray(ret)) { + if (ret.message) { + error4.message = ret.message; + } + if (ret.alert) { + error4.alert.description = ret.alert; + } + } else if (typeof ret === "number") { + error4.alert.description = ret; + } + } + return c.error(c, error4); + } + } + if (c.session.certificateRequest !== null) { + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + }); + tls.queue(c, record); + } + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientKeyExchange(c) + }); + tls.queue(c, record); + c.expect = SER; + var callback = function(c2, signature) { + if (c2.session.certificateRequest !== null && c2.session.clientCertificate !== null) { + tls.queue(c2, tls.createRecord(c2, { + type: tls.ContentType.handshake, + data: tls.createCertificateVerify(c2, signature) + })); + } + tls.queue(c2, tls.createRecord(c2, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + c2.state.pending = tls.createConnectionState(c2); + c2.state.current.write = c2.state.pending.write; + tls.queue(c2, tls.createRecord(c2, { + type: tls.ContentType.handshake, + data: tls.createFinished(c2) + })); + c2.expect = SCC; + tls.flush(c2); + c2.process(); + }; + if (c.session.certificateRequest === null || c.session.clientCertificate === null) { + return callback(c, null); + } + tls.getClientSignature(c, callback); + }; + tls.handleChangeCipherSpec = function(c, record) { + if (record.fragment.getByte() !== 1) { + return c.error(c, { + message: "Invalid ChangeCipherSpec message received.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + var client = c.entity === tls.ConnectionEnd.client; + if (c.session.resuming && client || !c.session.resuming && !client) { + c.state.pending = tls.createConnectionState(c); + } + c.state.current.read = c.state.pending.read; + if (!c.session.resuming && client || c.session.resuming && !client) { + c.state.pending = null; + } + c.expect = client ? SFI : CFI; + c.process(); + }; + tls.handleFinished = function(c, record, length) { + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + var vd = record.fragment.getBytes(); + b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + var client = c.entity === tls.ConnectionEnd.client; + var label = client ? "server finished" : "client finished"; + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + if (b.getBytes() !== vd) { + return c.error(c, { + message: "Invalid verify_data in Finished message.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decrypt_error + } + }); + } + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + if (c.session.resuming && client || !c.session.resuming && !client) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + c.state.current.write = c.state.pending.write; + c.state.pending = null; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + } + c.expect = client ? SAD : CAD; + c.handshaking = false; + ++c.handshakes; + c.peerCertificate = client ? c.session.serverCertificate : c.session.clientCertificate; + tls.flush(c); + c.isConnected = true; + c.connected(c); + c.process(); + }; + tls.handleAlert = function(c, record) { + var b = record.fragment; + var alert = { + level: b.getByte(), + description: b.getByte() + }; + var msg; + switch (alert.description) { + case tls.Alert.Description.close_notify: + msg = "Connection closed."; + break; + case tls.Alert.Description.unexpected_message: + msg = "Unexpected message."; + break; + case tls.Alert.Description.bad_record_mac: + msg = "Bad record MAC."; + break; + case tls.Alert.Description.decryption_failed: + msg = "Decryption failed."; + break; + case tls.Alert.Description.record_overflow: + msg = "Record overflow."; + break; + case tls.Alert.Description.decompression_failure: + msg = "Decompression failed."; + break; + case tls.Alert.Description.handshake_failure: + msg = "Handshake failure."; + break; + case tls.Alert.Description.bad_certificate: + msg = "Bad certificate."; + break; + case tls.Alert.Description.unsupported_certificate: + msg = "Unsupported certificate."; + break; + case tls.Alert.Description.certificate_revoked: + msg = "Certificate revoked."; + break; + case tls.Alert.Description.certificate_expired: + msg = "Certificate expired."; + break; + case tls.Alert.Description.certificate_unknown: + msg = "Certificate unknown."; + break; + case tls.Alert.Description.illegal_parameter: + msg = "Illegal parameter."; + break; + case tls.Alert.Description.unknown_ca: + msg = "Unknown certificate authority."; + break; + case tls.Alert.Description.access_denied: + msg = "Access denied."; + break; + case tls.Alert.Description.decode_error: + msg = "Decode error."; + break; + case tls.Alert.Description.decrypt_error: + msg = "Decrypt error."; + break; + case tls.Alert.Description.export_restriction: + msg = "Export restriction."; + break; + case tls.Alert.Description.protocol_version: + msg = "Unsupported protocol version."; + break; + case tls.Alert.Description.insufficient_security: + msg = "Insufficient security."; + break; + case tls.Alert.Description.internal_error: + msg = "Internal error."; + break; + case tls.Alert.Description.user_canceled: + msg = "User canceled."; + break; + case tls.Alert.Description.no_renegotiation: + msg = "Renegotiation not supported."; + break; + default: + msg = "Unknown error."; + break; + } + if (alert.description === tls.Alert.Description.close_notify) { + return c.close(); + } + c.error(c, { + message: msg, + send: false, + // origin is the opposite end + origin: c.entity === tls.ConnectionEnd.client ? "server" : "client", + alert + }); + c.process(); + }; + tls.handleHandshake = function(c, record) { + var b = record.fragment; + var type2 = b.getByte(); + var length = b.getInt24(); + if (length > b.length()) { + c.fragmented = record; + record.fragment = forge.util.createBuffer(); + b.read -= 4; + return c.process(); + } + c.fragmented = null; + b.read -= 4; + var bytes = b.bytes(length + 4); + b.read += 4; + if (type2 in hsTable[c.entity][c.expect]) { + if (c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { + c.handshaking = true; + c.session = { + version: null, + extensions: { + server_name: { + serverNameList: [] + } + }, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + clientCertificate: null, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + } + if (type2 !== tls.HandshakeType.hello_request && type2 !== tls.HandshakeType.certificate_verify && type2 !== tls.HandshakeType.finished) { + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + } + hsTable[c.entity][c.expect][type2](c, record, length); + } else { + tls.handleUnexpected(c, record); + } + }; + tls.handleApplicationData = function(c, record) { + c.data.putBuffer(record.fragment); + c.dataReady(c); + c.process(); + }; + tls.handleHeartbeat = function(c, record) { + var b = record.fragment; + var type2 = b.getByte(); + var length = b.getInt16(); + var payload = b.getBytes(length); + if (type2 === tls.HeartbeatMessageType.heartbeat_request) { + if (c.handshaking || length > payload.length) { + return c.process(); + } + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_response, + payload + ) + })); + tls.flush(c); + } else if (type2 === tls.HeartbeatMessageType.heartbeat_response) { + if (payload !== c.expectedHeartbeatPayload) { + return c.process(); + } + if (c.heartbeatReceived) { + c.heartbeatReceived(c, forge.util.createBuffer(payload)); + } + } + c.process(); + }; + var SHE = 0; + var SCE = 1; + var SKE = 2; + var SCR = 3; + var SHD = 4; + var SCC = 5; + var SFI = 6; + var SAD = 7; + var SER = 8; + var CHE = 0; + var CCE = 1; + var CKE = 2; + var CCV = 3; + var CCC = 4; + var CFI = 5; + var CAD = 6; + var __ = tls.handleUnexpected; + var R0 = tls.handleChangeCipherSpec; + var R1 = tls.handleAlert; + var R2 = tls.handleHandshake; + var R3 = tls.handleApplicationData; + var R4 = tls.handleHeartbeat; + var ctTable = []; + ctTable[tls.ConnectionEnd.client] = [ + // CC,AL,HS,AD,HB + /*SHE*/ + [__, R1, R2, __, R4], + /*SCE*/ + [__, R1, R2, __, R4], + /*SKE*/ + [__, R1, R2, __, R4], + /*SCR*/ + [__, R1, R2, __, R4], + /*SHD*/ + [__, R1, R2, __, R4], + /*SCC*/ + [R0, R1, __, __, R4], + /*SFI*/ + [__, R1, R2, __, R4], + /*SAD*/ + [__, R1, R2, R3, R4], + /*SER*/ + [__, R1, R2, __, R4] + ]; + ctTable[tls.ConnectionEnd.server] = [ + // CC,AL,HS,AD + /*CHE*/ + [__, R1, R2, __, R4], + /*CCE*/ + [__, R1, R2, __, R4], + /*CKE*/ + [__, R1, R2, __, R4], + /*CCV*/ + [__, R1, R2, __, R4], + /*CCC*/ + [R0, R1, __, __, R4], + /*CFI*/ + [__, R1, R2, __, R4], + /*CAD*/ + [__, R1, R2, R3, R4], + /*CER*/ + [__, R1, R2, __, R4] + ]; + var H0 = tls.handleHelloRequest; + var H1 = tls.handleServerHello; + var H2 = tls.handleCertificate; + var H3 = tls.handleServerKeyExchange; + var H4 = tls.handleCertificateRequest; + var H5 = tls.handleServerHelloDone; + var H6 = tls.handleFinished; + var hsTable = []; + hsTable[tls.ConnectionEnd.client] = [ + // HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI + /*SHE*/ + [__, __, H1, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*SCE*/ + [H0, __, __, __, __, __, __, __, __, __, __, H2, H3, H4, H5, __, __, __, __, __, __], + /*SKE*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, H3, H4, H5, __, __, __, __, __, __], + /*SCR*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, H4, H5, __, __, __, __, __, __], + /*SHD*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, H5, __, __, __, __, __, __], + /*SCC*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*SFI*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], + /*SAD*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*SER*/ + [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] + ]; + var H7 = tls.handleClientHello; + var H8 = tls.handleClientKeyExchange; + var H9 = tls.handleCertificateVerify; + hsTable[tls.ConnectionEnd.server] = [ + // 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI + /*CHE*/ + [__, H7, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*CCE*/ + [__, __, __, __, __, __, __, __, __, __, __, H2, __, __, __, __, __, __, __, __, __], + /*CKE*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H8, __, __, __, __], + /*CCV*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H9, __, __, __, __, __], + /*CCC*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*CFI*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], + /*CAD*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], + /*CER*/ + [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] + ]; + tls.generateKeys = function(c, sp) { + var prf = prf_TLS1; + var random = sp.client_random + sp.server_random; + if (!c.session.resuming) { + sp.master_secret = prf( + sp.pre_master_secret, + "master secret", + random, + 48 + ).bytes(); + sp.pre_master_secret = null; + } + random = sp.server_random + sp.client_random; + var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; + var tls10 = c.version.major === tls.Versions.TLS_1_0.major && c.version.minor === tls.Versions.TLS_1_0.minor; + if (tls10) { + length += 2 * sp.fixed_iv_length; + } + var km = prf(sp.master_secret, "key expansion", random, length); + var rval = { + client_write_MAC_key: km.getBytes(sp.mac_key_length), + server_write_MAC_key: km.getBytes(sp.mac_key_length), + client_write_key: km.getBytes(sp.enc_key_length), + server_write_key: km.getBytes(sp.enc_key_length) + }; + if (tls10) { + rval.client_write_IV = km.getBytes(sp.fixed_iv_length); + rval.server_write_IV = km.getBytes(sp.fixed_iv_length); + } + return rval; + }; + tls.createConnectionState = function(c) { + var client = c.entity === tls.ConnectionEnd.client; + var createMode = function() { + var mode = { + // two 32-bit numbers, first is most significant + sequenceNumber: [0, 0], + macKey: null, + macLength: 0, + macFunction: null, + cipherState: null, + cipherFunction: function(record) { + return true; + }, + compressionState: null, + compressFunction: function(record) { + return true; + }, + updateSequenceNumber: function() { + if (mode.sequenceNumber[1] === 4294967295) { + mode.sequenceNumber[1] = 0; + ++mode.sequenceNumber[0]; + } else { + ++mode.sequenceNumber[1]; + } + } + }; + return mode; + }; + var state = { + read: createMode(), + write: createMode() + }; + state.read.update = function(c2, record) { + if (!state.read.cipherFunction(record, state.read)) { + c2.error(c2, { + message: "Could not decrypt record or bad MAC.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + // doesn't matter if decryption failed or MAC was + // invalid, return the same error so as not to reveal + // which one occurred + description: tls.Alert.Description.bad_record_mac + } + }); + } else if (!state.read.compressFunction(c2, record, state.read)) { + c2.error(c2, { + message: "Could not decompress record.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decompression_failure + } + }); + } + return !c2.fail; + }; + state.write.update = function(c2, record) { + if (!state.write.compressFunction(c2, record, state.write)) { + c2.error(c2, { + message: "Could not compress record.", + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else if (!state.write.cipherFunction(record, state.write)) { + c2.error(c2, { + message: "Could not encrypt record.", + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + return !c2.fail; + }; + if (c.session) { + var sp = c.session.sp; + c.session.cipherSuite.initSecurityParameters(sp); + sp.keys = tls.generateKeys(c, sp); + state.read.macKey = client ? sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; + state.write.macKey = client ? sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; + c.session.cipherSuite.initConnectionState(state, c, sp); + switch (sp.compression_algorithm) { + case tls.CompressionMethod.none: + break; + case tls.CompressionMethod.deflate: + state.read.compressFunction = inflate; + state.write.compressFunction = deflate; + break; + default: + throw new Error("Unsupported compression algorithm."); + } + } + return state; + }; + tls.createRandom = function() { + var d = /* @__PURE__ */ new Date(); + var utc = +d + d.getTimezoneOffset() * 6e4; + var rval = forge.util.createBuffer(); + rval.putInt32(utc); + rval.putBytes(forge.random.getBytes(28)); + return rval; + }; + tls.createRecord = function(c, options) { + if (!options.data) { + return null; + } + var record = { + type: options.type, + version: { + major: c.version.major, + minor: c.version.minor + }, + length: options.data.length(), + fragment: options.data + }; + return record; + }; + tls.createAlert = function(c, alert) { + var b = forge.util.createBuffer(); + b.putByte(alert.level); + b.putByte(alert.description); + return tls.createRecord(c, { + type: tls.ContentType.alert, + data: b + }); + }; + tls.createClientHello = function(c) { + c.session.clientHelloVersion = { + major: c.version.major, + minor: c.version.minor + }; + var cipherSuites = forge.util.createBuffer(); + for (var i = 0; i < c.cipherSuites.length; ++i) { + var cs = c.cipherSuites[i]; + cipherSuites.putByte(cs.id[0]); + cipherSuites.putByte(cs.id[1]); + } + var cSuites = cipherSuites.length(); + var compressionMethods = forge.util.createBuffer(); + compressionMethods.putByte(tls.CompressionMethod.none); + var cMethods = compressionMethods.length(); + var extensions = forge.util.createBuffer(); + if (c.virtualHost) { + var ext = forge.util.createBuffer(); + ext.putByte(0); + ext.putByte(0); + var serverName = forge.util.createBuffer(); + serverName.putByte(0); + writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost)); + var snList = forge.util.createBuffer(); + writeVector(snList, 2, serverName); + writeVector(ext, 2, snList); + extensions.putBuffer(ext); + } + var extLength = extensions.length(); + if (extLength > 0) { + extLength += 2; + } + var sessionId = c.session.id; + var length = sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + cSuites + // cipher suites vector + 1 + cMethods + // compression methods vector + extLength; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_hello); + rval.putInt24(length); + rval.putByte(c.version.major); + rval.putByte(c.version.minor); + rval.putBytes(c.session.sp.client_random); + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + writeVector(rval, 2, cipherSuites); + writeVector(rval, 1, compressionMethods); + if (extLength > 0) { + writeVector(rval, 2, extensions); + } + return rval; + }; + tls.createServerHello = function(c) { + var sessionId = c.session.id; + var length = sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + // chosen cipher suite + 1; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello); + rval.putInt24(length); + rval.putByte(c.version.major); + rval.putByte(c.version.minor); + rval.putBytes(c.session.sp.server_random); + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + rval.putByte(c.session.cipherSuite.id[0]); + rval.putByte(c.session.cipherSuite.id[1]); + rval.putByte(c.session.compressionMethod); + return rval; + }; + tls.createCertificate = function(c) { + var client = c.entity === tls.ConnectionEnd.client; + var cert = null; + if (c.getCertificate) { + var hint; + if (client) { + hint = c.session.certificateRequest; + } else { + hint = c.session.extensions.server_name.serverNameList; + } + cert = c.getCertificate(c, hint); + } + var certList = forge.util.createBuffer(); + if (cert !== null) { + try { + if (!forge.util.isArray(cert)) { + cert = [cert]; + } + var asn1 = null; + for (var i = 0; i < cert.length; ++i) { + var msg = forge.pem.decode(cert[i])[0]; + if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { + var error4 = new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); + error4.headerType = msg.type; + throw error4; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert certificate from PEM; PEM is encrypted."); + } + var der = forge.util.createBuffer(msg.body); + if (asn1 === null) { + asn1 = forge.asn1.fromDer(der.bytes(), false); + } + var certBuffer = forge.util.createBuffer(); + writeVector(certBuffer, 3, der); + certList.putBuffer(certBuffer); + } + cert = forge.pki.certificateFromAsn1(asn1); + if (client) { + c.session.clientCertificate = cert; + } else { + c.session.serverCertificate = cert; + } + } catch (ex) { + return c.error(c, { + message: "Could not send certificate list.", + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + } + var length = 3 + certList.length(); + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate); + rval.putInt24(length); + writeVector(rval, 3, certList); + return rval; + }; + tls.createClientKeyExchange = function(c) { + var b = forge.util.createBuffer(); + b.putByte(c.session.clientHelloVersion.major); + b.putByte(c.session.clientHelloVersion.minor); + b.putBytes(forge.random.getBytes(46)); + var sp = c.session.sp; + sp.pre_master_secret = b.getBytes(); + var key2 = c.session.serverCertificate.publicKey; + b = key2.encrypt(sp.pre_master_secret); + var length = b.length + 2; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_key_exchange); + rval.putInt24(length); + rval.putInt16(b.length); + rval.putBytes(b); + return rval; + }; + tls.createServerKeyExchange = function(c) { + var length = 0; + var rval = forge.util.createBuffer(); + if (length > 0) { + rval.putByte(tls.HandshakeType.server_key_exchange); + rval.putInt24(length); + } + return rval; + }; + tls.getClientSignature = function(c, callback) { + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + b = b.getBytes(); + c.getSignature = c.getSignature || function(c2, b2, callback2) { + var privateKey = null; + if (c2.getPrivateKey) { + try { + privateKey = c2.getPrivateKey(c2, c2.session.clientCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch (ex) { + c2.error(c2, { + message: "Could not get private key.", + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + if (privateKey === null) { + c2.error(c2, { + message: "No private key set.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else { + b2 = privateKey.sign(b2, null); + } + callback2(c2, b2); + }; + c.getSignature(c, b, callback); + }; + tls.createCertificateVerify = function(c, signature) { + var length = signature.length + 2; + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_verify); + rval.putInt24(length); + rval.putInt16(signature.length); + rval.putBytes(signature); + return rval; + }; + tls.createCertificateRequest = function(c) { + var certTypes = forge.util.createBuffer(); + certTypes.putByte(1); + var cAs = forge.util.createBuffer(); + for (var key2 in c.caStore.certs) { + var cert = c.caStore.certs[key2]; + var dn = forge.pki.distinguishedNameToAsn1(cert.subject); + var byteBuffer = forge.asn1.toDer(dn); + cAs.putInt16(byteBuffer.length()); + cAs.putBuffer(byteBuffer); + } + var length = 1 + certTypes.length() + 2 + cAs.length(); + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_request); + rval.putInt24(length); + writeVector(rval, 1, certTypes); + writeVector(rval, 2, cAs); + return rval; + }; + tls.createServerHelloDone = function(c) { + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello_done); + rval.putInt24(0); + return rval; + }; + tls.createChangeCipherSpec = function() { + var rval = forge.util.createBuffer(); + rval.putByte(1); + return rval; + }; + tls.createFinished = function(c) { + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + var client = c.entity === tls.ConnectionEnd.client; + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + var label = client ? "client finished" : "server finished"; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.finished); + rval.putInt24(b.length()); + rval.putBuffer(b); + return rval; + }; + tls.createHeartbeat = function(type2, payload, payloadLength) { + if (typeof payloadLength === "undefined") { + payloadLength = payload.length; + } + var rval = forge.util.createBuffer(); + rval.putByte(type2); + rval.putInt16(payloadLength); + rval.putBytes(payload); + var plaintextLength = rval.length(); + var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); + rval.putBytes(forge.random.getBytes(paddingLength)); + return rval; + }; + tls.queue = function(c, record) { + if (!record) { + return; + } + if (record.fragment.length() === 0) { + if (record.type === tls.ContentType.handshake || record.type === tls.ContentType.alert || record.type === tls.ContentType.change_cipher_spec) { + return; + } + } + if (record.type === tls.ContentType.handshake) { + var bytes = record.fragment.bytes(); + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + bytes = null; + } + var records; + if (record.fragment.length() <= tls.MaxFragment) { + records = [record]; + } else { + records = []; + var data = record.fragment.bytes(); + while (data.length > tls.MaxFragment) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data.slice(0, tls.MaxFragment)) + })); + data = data.slice(tls.MaxFragment); + } + if (data.length > 0) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data) + })); + } + } + for (var i = 0; i < records.length && !c.fail; ++i) { + var rec = records[i]; + var s = c.state.current.write; + if (s.update(c, rec)) { + c.records.push(rec); + } + } + }; + tls.flush = function(c) { + for (var i = 0; i < c.records.length; ++i) { + var record = c.records[i]; + c.tlsData.putByte(record.type); + c.tlsData.putByte(record.version.major); + c.tlsData.putByte(record.version.minor); + c.tlsData.putInt16(record.fragment.length()); + c.tlsData.putBuffer(c.records[i].fragment); + } + c.records = []; + return c.tlsDataReady(c); + }; + var _certErrorToAlertDesc = function(error4) { + switch (error4) { + case true: + return true; + case forge.pki.certificateError.bad_certificate: + return tls.Alert.Description.bad_certificate; + case forge.pki.certificateError.unsupported_certificate: + return tls.Alert.Description.unsupported_certificate; + case forge.pki.certificateError.certificate_revoked: + return tls.Alert.Description.certificate_revoked; + case forge.pki.certificateError.certificate_expired: + return tls.Alert.Description.certificate_expired; + case forge.pki.certificateError.certificate_unknown: + return tls.Alert.Description.certificate_unknown; + case forge.pki.certificateError.unknown_ca: + return tls.Alert.Description.unknown_ca; + default: + return tls.Alert.Description.bad_certificate; + } + }; + var _alertDescToCertError = function(desc) { + switch (desc) { + case true: + return true; + case tls.Alert.Description.bad_certificate: + return forge.pki.certificateError.bad_certificate; + case tls.Alert.Description.unsupported_certificate: + return forge.pki.certificateError.unsupported_certificate; + case tls.Alert.Description.certificate_revoked: + return forge.pki.certificateError.certificate_revoked; + case tls.Alert.Description.certificate_expired: + return forge.pki.certificateError.certificate_expired; + case tls.Alert.Description.certificate_unknown: + return forge.pki.certificateError.certificate_unknown; + case tls.Alert.Description.unknown_ca: + return forge.pki.certificateError.unknown_ca; + default: + return forge.pki.certificateError.bad_certificate; + } + }; + tls.verifyCertificateChain = function(c, chain) { + try { + var options = {}; + for (var key2 in c.verifyOptions) { + options[key2] = c.verifyOptions[key2]; + } + options.verify = function(vfd, depth, chain2) { + var desc = _certErrorToAlertDesc(vfd); + var ret = c.verify(c, vfd, depth, chain2); + if (ret !== true) { + if (typeof ret === "object" && !forge.util.isArray(ret)) { + var error4 = new Error("The application rejected the certificate."); + error4.send = true; + error4.alert = { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + }; + if (ret.message) { + error4.message = ret.message; + } + if (ret.alert) { + error4.alert.description = ret.alert; + } + throw error4; + } + if (ret !== vfd) { + ret = _alertDescToCertError(ret); + } + } + return ret; + }; + forge.pki.verifyCertificateChain(c.caStore, chain, options); + } catch (ex) { + var err = ex; + if (typeof err !== "object" || forge.util.isArray(err)) { + err = { + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(ex) + } + }; + } + if (!("send" in err)) { + err.send = true; + } + if (!("alert" in err)) { + err.alert = { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(err.error) + }; + } + c.error(c, err); + } + return !c.fail; + }; + tls.createSessionCache = function(cache, capacity) { + var rval = null; + if (cache && cache.getSession && cache.setSession && cache.order) { + rval = cache; + } else { + rval = {}; + rval.cache = cache || {}; + rval.capacity = Math.max(capacity || 100, 1); + rval.order = []; + for (var key2 in cache) { + if (rval.order.length <= capacity) { + rval.order.push(key2); + } else { + delete cache[key2]; + } + } + rval.getSession = function(sessionId) { + var session = null; + var key3 = null; + if (sessionId) { + key3 = forge.util.bytesToHex(sessionId); + } else if (rval.order.length > 0) { + key3 = rval.order[0]; + } + if (key3 !== null && key3 in rval.cache) { + session = rval.cache[key3]; + delete rval.cache[key3]; + for (var i in rval.order) { + if (rval.order[i] === key3) { + rval.order.splice(i, 1); + break; + } + } + } + return session; + }; + rval.setSession = function(sessionId, session) { + if (rval.order.length === rval.capacity) { + var key3 = rval.order.shift(); + delete rval.cache[key3]; + } + var key3 = forge.util.bytesToHex(sessionId); + rval.order.push(key3); + rval.cache[key3] = session; + }; + } + return rval; + }; + tls.createConnection = function(options) { + var caStore = null; + if (options.caStore) { + if (forge.util.isArray(options.caStore)) { + caStore = forge.pki.createCaStore(options.caStore); + } else { + caStore = options.caStore; + } + } else { + caStore = forge.pki.createCaStore(); + } + var cipherSuites = options.cipherSuites || null; + if (cipherSuites === null) { + cipherSuites = []; + for (var key2 in tls.CipherSuites) { + cipherSuites.push(tls.CipherSuites[key2]); + } + } + var entity = options.server || false ? tls.ConnectionEnd.server : tls.ConnectionEnd.client; + var sessionCache = options.sessionCache ? tls.createSessionCache(options.sessionCache) : null; + var c = { + version: { major: tls.Version.major, minor: tls.Version.minor }, + entity, + sessionId: options.sessionId, + caStore, + sessionCache, + cipherSuites, + connected: options.connected, + virtualHost: options.virtualHost || null, + verifyClient: options.verifyClient || false, + verify: options.verify || function(cn, vfd, dpth, cts) { + return vfd; + }, + verifyOptions: options.verifyOptions || {}, + getCertificate: options.getCertificate || null, + getPrivateKey: options.getPrivateKey || null, + getSignature: options.getSignature || null, + input: forge.util.createBuffer(), + tlsData: forge.util.createBuffer(), + data: forge.util.createBuffer(), + tlsDataReady: options.tlsDataReady, + dataReady: options.dataReady, + heartbeatReceived: options.heartbeatReceived, + closed: options.closed, + error: function(c2, ex) { + ex.origin = ex.origin || (c2.entity === tls.ConnectionEnd.client ? "client" : "server"); + if (ex.send) { + tls.queue(c2, tls.createAlert(c2, ex.alert)); + tls.flush(c2); + } + var fatal = ex.fatal !== false; + if (fatal) { + c2.fail = true; + } + options.error(c2, ex); + if (fatal) { + c2.close(false); + } + }, + deflate: options.deflate || null, + inflate: options.inflate || null + }; + c.reset = function(clearFail) { + c.version = { major: tls.Version.major, minor: tls.Version.minor }; + c.record = null; + c.session = null; + c.peerCertificate = null; + c.state = { + pending: null, + current: null + }; + c.expect = c.entity === tls.ConnectionEnd.client ? SHE : CHE; + c.fragmented = null; + c.records = []; + c.open = false; + c.handshakes = 0; + c.handshaking = false; + c.isConnected = false; + c.fail = !(clearFail || typeof clearFail === "undefined"); + c.input.clear(); + c.tlsData.clear(); + c.data.clear(); + c.state.current = tls.createConnectionState(c); + }; + c.reset(); + var _update = function(c2, record) { + var aligned = record.type - tls.ContentType.change_cipher_spec; + var handlers = ctTable[c2.entity][c2.expect]; + if (aligned in handlers) { + handlers[aligned](c2, record); + } else { + tls.handleUnexpected(c2, record); + } + }; + var _readRecordHeader = function(c2) { + var rval = 0; + var b = c2.input; + var len = b.length(); + if (len < 5) { + rval = 5 - len; + } else { + c2.record = { + type: b.getByte(), + version: { + major: b.getByte(), + minor: b.getByte() + }, + length: b.getInt16(), + fragment: forge.util.createBuffer(), + ready: false + }; + var compatibleVersion = c2.record.version.major === c2.version.major; + if (compatibleVersion && c2.session && c2.session.version) { + compatibleVersion = c2.record.version.minor === c2.version.minor; + } + if (!compatibleVersion) { + c2.error(c2, { + message: "Incompatible TLS version.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + return rval; + }; + var _readRecord = function(c2) { + var rval = 0; + var b = c2.input; + var len = b.length(); + if (len < c2.record.length) { + rval = c2.record.length - len; + } else { + c2.record.fragment.putBytes(b.getBytes(c2.record.length)); + b.compact(); + var s = c2.state.current.read; + if (s.update(c2, c2.record)) { + if (c2.fragmented !== null) { + if (c2.fragmented.type === c2.record.type) { + c2.fragmented.fragment.putBuffer(c2.record.fragment); + c2.record = c2.fragmented; + } else { + c2.error(c2, { + message: "Invalid fragmented record.", + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unexpected_message + } + }); + } + } + c2.record.ready = true; + } + } + return rval; + }; + c.handshake = function(sessionId) { + if (c.entity !== tls.ConnectionEnd.client) { + c.error(c, { + message: "Cannot initiate handshake as a server.", + fatal: false + }); + } else if (c.handshaking) { + c.error(c, { + message: "Handshake already in progress.", + fatal: false + }); + } else { + if (c.fail && !c.open && c.handshakes === 0) { + c.fail = false; + } + c.handshaking = true; + sessionId = sessionId || ""; + var session = null; + if (sessionId.length > 0) { + if (c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + } + if (session === null) { + sessionId = ""; + } + } + if (sessionId.length === 0 && c.sessionCache) { + session = c.sessionCache.getSession(); + if (session !== null) { + sessionId = session.id; + } + } + c.session = { + id: sessionId, + version: null, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + certificateRequest: null, + clientCertificate: null, + sp: {}, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + if (session) { + c.version = session.version; + c.session.sp = session.sp; + } + c.session.sp.client_random = tls.createRandom().getBytes(); + c.open = true; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientHello(c) + })); + tls.flush(c); + } + }; + c.process = function(data) { + var rval = 0; + if (data) { + c.input.putBytes(data); + } + if (!c.fail) { + if (c.record !== null && c.record.ready && c.record.fragment.isEmpty()) { + c.record = null; + } + if (c.record === null) { + rval = _readRecordHeader(c); + } + if (!c.fail && c.record !== null && !c.record.ready) { + rval = _readRecord(c); + } + if (!c.fail && c.record !== null && c.record.ready) { + _update(c, c.record); + } + } + return rval; + }; + c.prepare = function(data) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.application_data, + data: forge.util.createBuffer(data) + })); + return tls.flush(c); + }; + c.prepareHeartbeatRequest = function(payload, payloadLength) { + if (payload instanceof forge.util.ByteBuffer) { + payload = payload.bytes(); + } + if (typeof payloadLength === "undefined") { + payloadLength = payload.length; + } + c.expectedHeartbeatPayload = payload; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_request, + payload, + payloadLength + ) + })); + return tls.flush(c); + }; + c.close = function(clearFail) { + if (!c.fail && c.sessionCache && c.session) { + var session = { + id: c.session.id, + version: c.session.version, + sp: c.session.sp + }; + session.sp.keys = null; + c.sessionCache.setSession(session.id, session); + } + if (c.open) { + c.open = false; + c.input.clear(); + if (c.isConnected || c.handshaking) { + c.isConnected = c.handshaking = false; + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.close_notify + })); + tls.flush(c); + } + c.closed(c); + } + c.reset(clearFail); + }; + return c; + }; + module2.exports = forge.tls = forge.tls || {}; + for (key in tls) { + if (typeof tls[key] !== "function") { + forge.tls[key] = tls[key]; + } + } + var key; + forge.tls.prf_tls1 = prf_TLS1; + forge.tls.hmac_sha1 = hmac_sha1; + forge.tls.createSessionCache = tls.createSessionCache; + forge.tls.createConnection = tls.createConnection; + } +}); + +// node_modules/node-forge/lib/aesCipherSuites.js +var require_aesCipherSuites = __commonJS({ + "node_modules/node-forge/lib/aesCipherSuites.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_tls(); + var tls = module2.exports = forge.tls; + tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"] = { + id: [0, 47], + name: "TLS_RSA_WITH_AES_128_CBC_SHA", + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 16; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState + }; + tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"] = { + id: [0, 53], + name: "TLS_RSA_WITH_AES_256_CBC_SHA", + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 32; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState + }; + function initConnectionState(state, c, sp) { + var client = c.entity === forge.tls.ConnectionEnd.client; + state.read.cipherState = { + init: false, + cipher: forge.cipher.createDecipher("AES-CBC", client ? sp.keys.server_write_key : sp.keys.client_write_key), + iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV + }; + state.write.cipherState = { + init: false, + cipher: forge.cipher.createCipher("AES-CBC", client ? sp.keys.client_write_key : sp.keys.server_write_key), + iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV + }; + state.read.cipherFunction = decrypt_aes_cbc_sha1; + state.write.cipherFunction = encrypt_aes_cbc_sha1; + state.read.macLength = state.write.macLength = sp.mac_length; + state.read.macFunction = state.write.macFunction = tls.hmac_sha1; + } + function encrypt_aes_cbc_sha1(record, s) { + var rval = false; + var mac = s.macFunction(s.macKey, s.sequenceNumber, record); + record.fragment.putBytes(mac); + s.updateSequenceNumber(); + var iv; + if (record.version.minor === tls.Versions.TLS_1_0.minor) { + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = forge.random.getBytesSync(16); + } + s.cipherState.init = true; + var cipher = s.cipherState.cipher; + cipher.start({ iv }); + if (record.version.minor >= tls.Versions.TLS_1_1.minor) { + cipher.output.putBytes(iv); + } + cipher.update(record.fragment); + if (cipher.finish(encrypt_aes_cbc_sha1_padding)) { + record.fragment = cipher.output; + record.length = record.fragment.length(); + rval = true; + } + return rval; + } + function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { + if (!decrypt) { + var padding = blockSize - input.length() % blockSize; + input.fillWithByte(padding - 1, padding); + } + return true; + } + function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { + var rval = true; + if (decrypt) { + var len = output.length(); + var paddingLength = output.last(); + for (var i = len - 1 - paddingLength; i < len - 1; ++i) { + rval = rval && output.at(i) == paddingLength; + } + if (rval) { + output.truncate(paddingLength + 1); + } + } + return rval; + } + function decrypt_aes_cbc_sha1(record, s) { + var rval = false; + var iv; + if (record.version.minor === tls.Versions.TLS_1_0.minor) { + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = record.fragment.getBytes(16); + } + s.cipherState.init = true; + var cipher = s.cipherState.cipher; + cipher.start({ iv }); + cipher.update(record.fragment); + rval = cipher.finish(decrypt_aes_cbc_sha1_padding); + var macLen = s.macLength; + var mac = forge.random.getBytesSync(macLen); + var len = cipher.output.length(); + if (len >= macLen) { + record.fragment = cipher.output.getBytes(len - macLen); + mac = cipher.output.getBytes(macLen); + } else { + record.fragment = cipher.output.getBytes(); + } + record.fragment = forge.util.createBuffer(record.fragment); + record.length = record.fragment.length(); + var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); + s.updateSequenceNumber(); + rval = compareMacs(s.macKey, mac, mac2) && rval; + return rval; + } + function compareMacs(key, mac1, mac2) { + var hmac = forge.hmac.create(); + hmac.start("SHA1", key); + hmac.update(mac1); + mac1 = hmac.digest().getBytes(); + hmac.start(null, null); + hmac.update(mac2); + mac2 = hmac.digest().getBytes(); + return mac1 === mac2; + } + } +}); + +// node_modules/node-forge/lib/sha512.js +var require_sha512 = __commonJS({ + "node_modules/node-forge/lib/sha512.js"(exports2, module2) { + var forge = require_forge(); + require_md(); + require_util8(); + var sha512 = module2.exports = forge.sha512 = forge.sha512 || {}; + forge.md.sha512 = forge.md.algorithms.sha512 = sha512; + var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; + sha384.create = function() { + return sha512.create("SHA-384"); + }; + forge.md.sha384 = forge.md.algorithms.sha384 = sha384; + forge.sha512.sha256 = forge.sha512.sha256 || { + create: function() { + return sha512.create("SHA-512/256"); + } + }; + forge.md["sha512/256"] = forge.md.algorithms["sha512/256"] = forge.sha512.sha256; + forge.sha512.sha224 = forge.sha512.sha224 || { + create: function() { + return sha512.create("SHA-512/224"); + } + }; + forge.md["sha512/224"] = forge.md.algorithms["sha512/224"] = forge.sha512.sha224; + sha512.create = function(algorithm) { + if (!_initialized) { + _init(); + } + if (typeof algorithm === "undefined") { + algorithm = "SHA-512"; + } + if (!(algorithm in _states)) { + throw new Error("Invalid SHA-512 algorithm: " + algorithm); + } + var _state = _states[algorithm]; + var _h = null; + var _input = forge.util.createBuffer(); + var _w = new Array(80); + for (var wi = 0; wi < 80; ++wi) { + _w[wi] = new Array(2); + } + var digestLength = 64; + switch (algorithm) { + case "SHA-384": + digestLength = 48; + break; + case "SHA-512/256": + digestLength = 32; + break; + case "SHA-512/224": + digestLength = 28; + break; + } + var md = { + // SHA-512 => sha512 + algorithm: algorithm.replace("-", "").toLowerCase(), + blockLength: 128, + digestLength, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 16 + }; + md.start = function() { + md.messageLength = 0; + md.fullMessageLength = md.messageLength128 = []; + var int32s = md.messageLengthSize / 4; + for (var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _h = new Array(_state.length); + for (var i = 0; i < _state.length; ++i) { + _h[i] = _state[i].slice(0); + } + return md; + }; + md.start(); + md.update = function(msg, encoding) { + if (encoding === "utf8") { + msg = forge.util.encodeUtf8(msg); + } + var len = msg.length; + md.messageLength += len; + len = [len / 4294967296 >>> 0, len >>> 0]; + for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = len[1] / 4294967296 >>> 0; + } + _input.putBytes(msg); + _update(_h, _w, _input); + if (_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + return md; + }; + md.digest = function() { + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; + var overflow = remaining & md.blockLength - 1; + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = next / 4294967296 >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + var h = new Array(_h.length); + for (var i = 0; i < _h.length; ++i) { + h[i] = _h[i].slice(0); + } + _update(h, _w, finalBlock); + var rval = forge.util.createBuffer(); + var hlen; + if (algorithm === "SHA-512") { + hlen = h.length; + } else if (algorithm === "SHA-384") { + hlen = h.length - 2; + } else { + hlen = h.length - 4; + } + for (var i = 0; i < hlen; ++i) { + rval.putInt32(h[i][0]); + if (i !== hlen - 1 || algorithm !== "SHA-512/224") { + rval.putInt32(h[i][1]); + } + } + return rval; + }; + return md; + }; + var _padding = null; + var _initialized = false; + var _k = null; + var _states = null; + function _init() { + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0), 128); + _k = [ + [1116352408, 3609767458], + [1899447441, 602891725], + [3049323471, 3964484399], + [3921009573, 2173295548], + [961987163, 4081628472], + [1508970993, 3053834265], + [2453635748, 2937671579], + [2870763221, 3664609560], + [3624381080, 2734883394], + [310598401, 1164996542], + [607225278, 1323610764], + [1426881987, 3590304994], + [1925078388, 4068182383], + [2162078206, 991336113], + [2614888103, 633803317], + [3248222580, 3479774868], + [3835390401, 2666613458], + [4022224774, 944711139], + [264347078, 2341262773], + [604807628, 2007800933], + [770255983, 1495990901], + [1249150122, 1856431235], + [1555081692, 3175218132], + [1996064986, 2198950837], + [2554220882, 3999719339], + [2821834349, 766784016], + [2952996808, 2566594879], + [3210313671, 3203337956], + [3336571891, 1034457026], + [3584528711, 2466948901], + [113926993, 3758326383], + [338241895, 168717936], + [666307205, 1188179964], + [773529912, 1546045734], + [1294757372, 1522805485], + [1396182291, 2643833823], + [1695183700, 2343527390], + [1986661051, 1014477480], + [2177026350, 1206759142], + [2456956037, 344077627], + [2730485921, 1290863460], + [2820302411, 3158454273], + [3259730800, 3505952657], + [3345764771, 106217008], + [3516065817, 3606008344], + [3600352804, 1432725776], + [4094571909, 1467031594], + [275423344, 851169720], + [430227734, 3100823752], + [506948616, 1363258195], + [659060556, 3750685593], + [883997877, 3785050280], + [958139571, 3318307427], + [1322822218, 3812723403], + [1537002063, 2003034995], + [1747873779, 3602036899], + [1955562222, 1575990012], + [2024104815, 1125592928], + [2227730452, 2716904306], + [2361852424, 442776044], + [2428436474, 593698344], + [2756734187, 3733110249], + [3204031479, 2999351573], + [3329325298, 3815920427], + [3391569614, 3928383900], + [3515267271, 566280711], + [3940187606, 3454069534], + [4118630271, 4000239992], + [116418474, 1914138554], + [174292421, 2731055270], + [289380356, 3203993006], + [460393269, 320620315], + [685471733, 587496836], + [852142971, 1086792851], + [1017036298, 365543100], + [1126000580, 2618297676], + [1288033470, 3409855158], + [1501505948, 4234509866], + [1607167915, 987167468], + [1816402316, 1246189591] + ]; + _states = {}; + _states["SHA-512"] = [ + [1779033703, 4089235720], + [3144134277, 2227873595], + [1013904242, 4271175723], + [2773480762, 1595750129], + [1359893119, 2917565137], + [2600822924, 725511199], + [528734635, 4215389547], + [1541459225, 327033209] + ]; + _states["SHA-384"] = [ + [3418070365, 3238371032], + [1654270250, 914150663], + [2438529370, 812702999], + [355462360, 4144912697], + [1731405415, 4290775857], + [2394180231, 1750603025], + [3675008525, 1694076839], + [1203062813, 3204075428] + ]; + _states["SHA-512/256"] = [ + [573645204, 4230739756], + [2673172387, 3360449730], + [596883563, 1867755857], + [2520282905, 1497426621], + [2519219938, 2827943907], + [3193839141, 1401305490], + [721525244, 746961066], + [246885852, 2177182882] + ]; + _states["SHA-512/224"] = [ + [2352822216, 424955298], + [1944164710, 2312950998], + [502970286, 855612546], + [1738396948, 1479516111], + [258812777, 2077511080], + [2011393907, 79989058], + [1067287976, 1780299464], + [286451373, 2446758561] + ]; + _initialized = true; + } + function _update(s, w, bytes) { + var t1_hi, t1_lo; + var t2_hi, t2_lo; + var s0_hi, s0_lo; + var s1_hi, s1_lo; + var ch_hi, ch_lo; + var maj_hi, maj_lo; + var a_hi, a_lo; + var b_hi, b_lo; + var c_hi, c_lo; + var d_hi, d_lo; + var e_hi, e_lo; + var f_hi, f_lo; + var g_hi, g_lo; + var h_hi, h_lo; + var i, hi, lo, w2, w7, w15, w16; + var len = bytes.length(); + while (len >= 128) { + for (i = 0; i < 16; ++i) { + w[i][0] = bytes.getInt32() >>> 0; + w[i][1] = bytes.getInt32() >>> 0; + } + for (; i < 80; ++i) { + w2 = w[i - 2]; + hi = w2[0]; + lo = w2[1]; + t1_hi = ((hi >>> 19 | lo << 13) ^ // ROTR 19 + (lo >>> 29 | hi << 3) ^ // ROTR 61/(swap + ROTR 29) + hi >>> 6) >>> 0; + t1_lo = ((hi << 13 | lo >>> 19) ^ // ROTR 19 + (lo << 3 | hi >>> 29) ^ // ROTR 61/(swap + ROTR 29) + (hi << 26 | lo >>> 6)) >>> 0; + w15 = w[i - 15]; + hi = w15[0]; + lo = w15[1]; + t2_hi = ((hi >>> 1 | lo << 31) ^ // ROTR 1 + (hi >>> 8 | lo << 24) ^ // ROTR 8 + hi >>> 7) >>> 0; + t2_lo = ((hi << 31 | lo >>> 1) ^ // ROTR 1 + (hi << 24 | lo >>> 8) ^ // ROTR 8 + (hi << 25 | lo >>> 7)) >>> 0; + w7 = w[i - 7]; + w16 = w[i - 16]; + lo = t1_lo + w7[1] + t2_lo + w16[1]; + w[i][0] = t1_hi + w7[0] + t2_hi + w16[0] + (lo / 4294967296 >>> 0) >>> 0; + w[i][1] = lo >>> 0; + } + a_hi = s[0][0]; + a_lo = s[0][1]; + b_hi = s[1][0]; + b_lo = s[1][1]; + c_hi = s[2][0]; + c_lo = s[2][1]; + d_hi = s[3][0]; + d_lo = s[3][1]; + e_hi = s[4][0]; + e_lo = s[4][1]; + f_hi = s[5][0]; + f_lo = s[5][1]; + g_hi = s[6][0]; + g_lo = s[6][1]; + h_hi = s[7][0]; + h_lo = s[7][1]; + for (i = 0; i < 80; ++i) { + s1_hi = ((e_hi >>> 14 | e_lo << 18) ^ // ROTR 14 + (e_hi >>> 18 | e_lo << 14) ^ // ROTR 18 + (e_lo >>> 9 | e_hi << 23)) >>> 0; + s1_lo = ((e_hi << 18 | e_lo >>> 14) ^ // ROTR 14 + (e_hi << 14 | e_lo >>> 18) ^ // ROTR 18 + (e_lo << 23 | e_hi >>> 9)) >>> 0; + ch_hi = (g_hi ^ e_hi & (f_hi ^ g_hi)) >>> 0; + ch_lo = (g_lo ^ e_lo & (f_lo ^ g_lo)) >>> 0; + s0_hi = ((a_hi >>> 28 | a_lo << 4) ^ // ROTR 28 + (a_lo >>> 2 | a_hi << 30) ^ // ROTR 34/(swap + ROTR 2) + (a_lo >>> 7 | a_hi << 25)) >>> 0; + s0_lo = ((a_hi << 4 | a_lo >>> 28) ^ // ROTR 28 + (a_lo << 30 | a_hi >>> 2) ^ // ROTR 34/(swap + ROTR 2) + (a_lo << 25 | a_hi >>> 7)) >>> 0; + maj_hi = (a_hi & b_hi | c_hi & (a_hi ^ b_hi)) >>> 0; + maj_lo = (a_lo & b_lo | c_lo & (a_lo ^ b_lo)) >>> 0; + lo = h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]; + t1_hi = h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + (lo / 4294967296 >>> 0) >>> 0; + t1_lo = lo >>> 0; + lo = s0_lo + maj_lo; + t2_hi = s0_hi + maj_hi + (lo / 4294967296 >>> 0) >>> 0; + t2_lo = lo >>> 0; + h_hi = g_hi; + h_lo = g_lo; + g_hi = f_hi; + g_lo = f_lo; + f_hi = e_hi; + f_lo = e_lo; + lo = d_lo + t1_lo; + e_hi = d_hi + t1_hi + (lo / 4294967296 >>> 0) >>> 0; + e_lo = lo >>> 0; + d_hi = c_hi; + d_lo = c_lo; + c_hi = b_hi; + c_lo = b_lo; + b_hi = a_hi; + b_lo = a_lo; + lo = t1_lo + t2_lo; + a_hi = t1_hi + t2_hi + (lo / 4294967296 >>> 0) >>> 0; + a_lo = lo >>> 0; + } + lo = s[0][1] + a_lo; + s[0][0] = s[0][0] + a_hi + (lo / 4294967296 >>> 0) >>> 0; + s[0][1] = lo >>> 0; + lo = s[1][1] + b_lo; + s[1][0] = s[1][0] + b_hi + (lo / 4294967296 >>> 0) >>> 0; + s[1][1] = lo >>> 0; + lo = s[2][1] + c_lo; + s[2][0] = s[2][0] + c_hi + (lo / 4294967296 >>> 0) >>> 0; + s[2][1] = lo >>> 0; + lo = s[3][1] + d_lo; + s[3][0] = s[3][0] + d_hi + (lo / 4294967296 >>> 0) >>> 0; + s[3][1] = lo >>> 0; + lo = s[4][1] + e_lo; + s[4][0] = s[4][0] + e_hi + (lo / 4294967296 >>> 0) >>> 0; + s[4][1] = lo >>> 0; + lo = s[5][1] + f_lo; + s[5][0] = s[5][0] + f_hi + (lo / 4294967296 >>> 0) >>> 0; + s[5][1] = lo >>> 0; + lo = s[6][1] + g_lo; + s[6][0] = s[6][0] + g_hi + (lo / 4294967296 >>> 0) >>> 0; + s[6][1] = lo >>> 0; + lo = s[7][1] + h_lo; + s[7][0] = s[7][0] + h_hi + (lo / 4294967296 >>> 0) >>> 0; + s[7][1] = lo >>> 0; + len -= 128; + } + } + } +}); + +// node_modules/node-forge/lib/asn1-validator.js +var require_asn1_validator = __commonJS({ + "node_modules/node-forge/lib/asn1-validator.js"(exports2) { + var forge = require_forge(); + require_asn1(); + var asn1 = forge.asn1; + exports2.privateKeyValidator = { + // PrivateKeyInfo + name: "PrivateKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: "PrivateKeyInfo.version", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: "privateKeyVersion" + }, { + // privateKeyAlgorithm + name: "PrivateKeyInfo.privateKeyAlgorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "privateKeyOid" + }] + }, { + // PrivateKey + name: "PrivateKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: "privateKey" + }] + }; + exports2.publicKeyValidator = { + name: "SubjectPublicKeyInfo", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: "subjectPublicKeyInfo", + value: [ + { + name: "SubjectPublicKeyInfo.AlgorithmIdentifier", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: "AlgorithmIdentifier.algorithm", + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: "publicKeyOid" + }] + }, + // capture group for ed25519PublicKey + { + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + composed: true, + captureBitStringValue: "ed25519PublicKey" + } + // FIXME: this is capture group for rsaPublicKey, use it in this API or + // discard? + /* { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + } */ + ] + }; + } +}); + +// node_modules/node-forge/lib/ed25519.js +var require_ed25519 = __commonJS({ + "node_modules/node-forge/lib/ed25519.js"(exports2, module2) { + var forge = require_forge(); + require_jsbn(); + require_random(); + require_sha512(); + require_util8(); + var asn1Validator = require_asn1_validator(); + var publicKeyValidator = asn1Validator.publicKeyValidator; + var privateKeyValidator = asn1Validator.privateKeyValidator; + if (typeof BigInteger === "undefined") { + BigInteger = forge.jsbn.BigInteger; + } + var BigInteger; + var ByteBuffer = forge.util.ByteBuffer; + var NativeBuffer = typeof Buffer === "undefined" ? Uint8Array : Buffer; + forge.pki = forge.pki || {}; + module2.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; + var ed25519 = forge.ed25519; + ed25519.constants = {}; + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; + ed25519.constants.SEED_BYTE_LENGTH = 32; + ed25519.constants.SIGN_BYTE_LENGTH = 64; + ed25519.constants.HASH_BYTE_LENGTH = 64; + ed25519.generateKeyPair = function(options) { + options = options || {}; + var seed = options.seed; + if (seed === void 0) { + seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); + } else if (typeof seed === "string") { + if (seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { + throw new TypeError( + '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + " bytes in length." + ); + } + } else if (!(seed instanceof Uint8Array)) { + throw new TypeError( + '"seed" must be a node.js Buffer, Uint8Array, or a binary string.' + ); + } + seed = messageToNativeBuffer({ message: seed, encoding: "binary" }); + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + for (var i = 0; i < 32; ++i) { + sk[i] = seed[i]; + } + crypto_sign_keypair(pk, sk); + return { publicKey: pk, privateKey: sk }; + }; + ed25519.privateKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + var valid2 = forge.asn1.validate(obj, privateKeyValidator, capture, errors); + if (!valid2) { + var error4 = new Error("Invalid Key."); + error4.errors = errors; + throw error4; + } + var oid = forge.asn1.derToOid(capture.privateKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if (oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); + } + var privateKey = capture.privateKey; + var privateKeyBytes = messageToNativeBuffer({ + message: forge.asn1.fromDer(privateKey).value, + encoding: "binary" + }); + return { privateKeyBytes }; + }; + ed25519.publicKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + var valid2 = forge.asn1.validate(obj, publicKeyValidator, capture, errors); + if (!valid2) { + var error4 = new Error("Invalid Key."); + error4.errors = errors; + throw error4; + } + var oid = forge.asn1.derToOid(capture.publicKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if (oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); + } + var publicKeyBytes = capture.ed25519PublicKey; + if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new Error("Key length is invalid."); + } + return messageToNativeBuffer({ + message: publicKeyBytes, + encoding: "binary" + }); + }; + ed25519.publicKeyFromPrivateKey = function(options) { + options = options || {}; + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: "binary" + }); + if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH + ); + } + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + for (var i = 0; i < pk.length; ++i) { + pk[i] = privateKey[32 + i]; + } + return pk; + }; + ed25519.sign = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: "binary" + }); + if (privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { + var keyPair = ed25519.generateKeyPair({ seed: privateKey }); + privateKey = keyPair.privateKey; + } else if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + " or " + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH + ); + } + var signedMsg = new NativeBuffer( + ed25519.constants.SIGN_BYTE_LENGTH + msg.length + ); + crypto_sign(signedMsg, msg, msg.length, privateKey); + var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); + for (var i = 0; i < sig.length; ++i) { + sig[i] = signedMsg[i]; + } + return sig; + }; + ed25519.verify = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + if (options.signature === void 0) { + throw new TypeError( + '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.' + ); + } + var sig = messageToNativeBuffer({ + message: options.signature, + encoding: "binary" + }); + if (sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { + throw new TypeError( + '"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH + ); + } + var publicKey = messageToNativeBuffer({ + message: options.publicKey, + encoding: "binary" + }); + if (publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH + ); + } + var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var i; + for (i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { + sm[i] = sig[i]; + } + for (i = 0; i < msg.length; ++i) { + sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; + } + return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; + }; + function messageToNativeBuffer(options) { + var message = options.message; + if (message instanceof Uint8Array || message instanceof NativeBuffer) { + return message; + } + var encoding = options.encoding; + if (message === void 0) { + if (options.md) { + message = options.md.digest().getBytes(); + encoding = "binary"; + } else { + throw new TypeError('"options.message" or "options.md" not specified.'); + } + } + if (typeof message === "string" && !encoding) { + throw new TypeError('"options.encoding" must be "binary" or "utf8".'); + } + if (typeof message === "string") { + if (typeof Buffer !== "undefined") { + return Buffer.from(message, encoding); + } + message = new ByteBuffer(message, encoding); + } else if (!(message instanceof ByteBuffer)) { + throw new TypeError( + '"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.' + ); + } + var buffer = new NativeBuffer(message.length()); + for (var i = 0; i < buffer.length; ++i) { + buffer[i] = message.at(i); + } + return buffer; + } + var gf0 = gf(); + var gf1 = gf([1]); + var D = gf([ + 30883, + 4953, + 19914, + 30187, + 55467, + 16705, + 2637, + 112, + 59544, + 30585, + 16505, + 36039, + 65139, + 11119, + 27886, + 20995 + ]); + var D2 = gf([ + 61785, + 9906, + 39828, + 60374, + 45398, + 33411, + 5274, + 224, + 53552, + 61171, + 33010, + 6542, + 64743, + 22239, + 55772, + 9222 + ]); + var X = gf([ + 54554, + 36645, + 11616, + 51542, + 42930, + 38181, + 51040, + 26924, + 56412, + 64982, + 57905, + 49316, + 21502, + 52590, + 14035, + 8553 + ]); + var Y = gf([ + 26200, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214 + ]); + var L = new Float64Array([ + 237, + 211, + 245, + 92, + 26, + 99, + 18, + 88, + 214, + 156, + 247, + 162, + 222, + 249, + 222, + 20, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 16 + ]); + var I = gf([ + 41136, + 18958, + 6951, + 50414, + 58488, + 44335, + 6150, + 12099, + 55207, + 15867, + 153, + 11085, + 57099, + 20417, + 9344, + 11139 + ]); + function sha512(msg, msgLen) { + var md = forge.md.sha512.create(); + var buffer = new ByteBuffer(msg); + md.update(buffer.getBytes(msgLen), "binary"); + var hash = md.digest().getBytes(); + if (typeof Buffer !== "undefined") { + return Buffer.from(hash, "binary"); + } + var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); + for (var i = 0; i < 64; ++i) { + out[i] = hash.charCodeAt(i); + } + return out; + } + function crypto_sign_keypair(pk, sk) { + var p = [gf(), gf(), gf(), gf()]; + var i; + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + scalarbase(p, d); + pack(pk, p); + for (i = 0; i < 32; ++i) { + sk[i + 32] = pk[i]; + } + return 0; + } + function crypto_sign(sm, m, n, sk) { + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + var smlen = n + 64; + for (i = 0; i < n; ++i) { + sm[64 + i] = m[i]; + } + for (i = 0; i < 32; ++i) { + sm[32 + i] = d[32 + i]; + } + var r = sha512(sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + for (i = 32; i < 64; ++i) { + sm[i] = sk[i]; + } + var h = sha512(sm, n + 64); + reduce(h); + for (i = 32; i < 64; ++i) { + x[i] = 0; + } + for (i = 0; i < 32; ++i) { + x[i] = r[i]; + } + for (i = 0; i < 32; ++i) { + for (j = 0; j < 32; j++) { + x[i + j] += h[i] * d[j]; + } + } + modL(sm.subarray(32), x); + return smlen; + } + function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new NativeBuffer(32); + var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; + mlen = -1; + if (n < 64) { + return -1; + } + if (unpackneg(q, pk)) { + return -1; + } + for (i = 0; i < n; ++i) { + m[i] = sm[i]; + } + for (i = 0; i < 32; ++i) { + m[i + 32] = pk[i]; + } + var h = sha512(m, n); + reduce(h); + scalarmult(p, q, h); + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; ++i) { + m[i] = 0; + } + return -1; + } + for (i = 0; i < n; ++i) { + m[i] = sm[i + 64]; + } + mlen = n; + return mlen; + } + function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = x[j] + 128 >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; ++j) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; ++j) { + x[j] -= carry * L[j]; + } + for (i = 0; i < 32; ++i) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } + } + function reduce(r) { + var x = new Float64Array(64); + for (var i = 0; i < 64; ++i) { + x[i] = r[i]; + r[i] = 0; + } + modL(r, x); + } + function add(p, q) { + var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); + } + function cswap(p, q, b) { + for (var i = 0; i < 4; ++i) { + sel25519(p[i], q[i], b); + } + } + function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; + } + function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; ++i) { + t[i] = n[i]; + } + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; ++j) { + m[0] = t[0] - 65517; + for (i = 1; i < 15; ++i) { + m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1); + m[i - 1] &= 65535; + } + m[15] = t[15] - 32767 - (m[14] >> 16 & 1); + b = m[15] >> 16 & 1; + m[14] &= 65535; + sel25519(t, m, 1 - b); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 255; + o[2 * i + 1] = t[i] >> 8; + } + } + function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) { + M(r[0], r[0], I); + } + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) { + return -1; + } + if (par25519(r[0]) === p[31] >> 7) { + Z(r[0], gf0, r[0]); + } + M(r[3], r[0], r[1]); + return 0; + } + function unpack25519(o, n) { + var i; + for (i = 0; i < 16; ++i) { + o[i] = n[2 * i] + (n[2 * i + 1] << 8); + } + o[15] &= 32767; + } + function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for (a = 250; a >= 0; --a) { + S(c, c); + if (a !== 1) { + M(c, c, i); + } + } + for (a = 0; a < 16; ++a) { + o[a] = c[a]; + } + } + function neq25519(a, b) { + var c = new NativeBuffer(32); + var d = new NativeBuffer(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); + } + function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); + } + function vn(x, xi, y, yi, n) { + var i, d = 0; + for (i = 0; i < n; ++i) { + d |= x[xi + i] ^ y[yi + i]; + } + return (1 & d - 1 >>> 8) - 1; + } + function par25519(a) { + var d = new NativeBuffer(32); + pack25519(d, a); + return d[0] & 1; + } + function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = s[i / 8 | 0] >> (i & 7) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } + } + function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); + } + function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) { + r[i] = a[i] | 0; + } + } + function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for (a = 253; a >= 0; --a) { + S(c, c); + if (a !== 2 && a !== 4) { + M(c, c, i); + } + } + for (a = 0; a < 16; ++a) { + o[a] = c[a]; + } + } + function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; ++i) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c - 1 + 37 * (c - 1); + } + function sel25519(p, q, b) { + var t, c = ~(b - 1); + for (var i = 0; i < 16; ++i) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } + } + function gf(init) { + var i, r = new Float64Array(16); + if (init) { + for (i = 0; i < init.length; ++i) { + r[i] = init[i]; + } + } + return r; + } + function A(o, a, b) { + for (var i = 0; i < 16; ++i) { + o[i] = a[i] + b[i]; + } + } + function Z(o, a, b) { + for (var i = 0; i < 16; ++i) { + o[i] = a[i] - b[i]; + } + } + function S(o, a) { M(o, a, a); } function M(o, a, b) { @@ -38904,1440 +39605,2141 @@ var require_kem = __commonJS({ if (zeros > 0) { r = forge.util.fillString(String.fromCharCode(0), zeros) + r; } - var encapsulation = publicKey.encrypt(r, "NONE"); - var key = kdf.generate(r, keyLength); - return { encapsulation, key }; + var encapsulation = publicKey.encrypt(r, "NONE"); + var key = kdf.generate(r, keyLength); + return { encapsulation, key }; + }; + kem.decrypt = function(privateKey, encapsulation, keyLength) { + var r = privateKey.decrypt(encapsulation, "NONE"); + return kdf.generate(r, keyLength); + }; + return kem; + }; + forge.kem.kdf1 = function(md, digestLength) { + _createKDF(this, md, 0, digestLength || md.digestLength); + }; + forge.kem.kdf2 = function(md, digestLength) { + _createKDF(this, md, 1, digestLength || md.digestLength); + }; + function _createKDF(kdf, md, counterStart, digestLength) { + kdf.generate = function(x, length) { + var key = new forge.util.ByteBuffer(); + var k = Math.ceil(length / digestLength) + counterStart; + var c = new forge.util.ByteBuffer(); + for (var i = counterStart; i < k; ++i) { + c.putInt32(i); + md.start(); + md.update(x + c.getBytes()); + var hash = md.digest(); + key.putBytes(hash.getBytes(digestLength)); + } + key.truncate(key.length() - length); + return key.getBytes(); + }; + } + } +}); + +// node_modules/node-forge/lib/log.js +var require_log = __commonJS({ + "node_modules/node-forge/lib/log.js"(exports2, module2) { + var forge = require_forge(); + require_util8(); + module2.exports = forge.log = forge.log || {}; + forge.log.levels = [ + "none", + "error", + "warning", + "info", + "debug", + "verbose", + "max" + ]; + var sLevelInfo = {}; + var sLoggers = []; + var sConsoleLogger = null; + forge.log.LEVEL_LOCKED = 1 << 1; + forge.log.NO_LEVEL_CHECK = 1 << 2; + forge.log.INTERPOLATE = 1 << 3; + for (i = 0; i < forge.log.levels.length; ++i) { + level = forge.log.levels[i]; + sLevelInfo[level] = { + index: i, + name: level.toUpperCase() + }; + } + var level; + var i; + forge.log.logMessage = function(message) { + var messageLevelIndex = sLevelInfo[message.level].index; + for (var i2 = 0; i2 < sLoggers.length; ++i2) { + var logger2 = sLoggers[i2]; + if (logger2.flags & forge.log.NO_LEVEL_CHECK) { + logger2.f(message); + } else { + var loggerLevelIndex = sLevelInfo[logger2.level].index; + if (messageLevelIndex <= loggerLevelIndex) { + logger2.f(logger2, message); + } + } + } + }; + forge.log.prepareStandard = function(message) { + if (!("standard" in message)) { + message.standard = sLevelInfo[message.level].name + //' ' + +message.timestamp + + " [" + message.category + "] " + message.message; + } + }; + forge.log.prepareFull = function(message) { + if (!("full" in message)) { + var args = [message.message]; + args = args.concat([]); + message.full = forge.util.format.apply(this, args); + } + }; + forge.log.prepareStandardFull = function(message) { + if (!("standardFull" in message)) { + forge.log.prepareStandard(message); + message.standardFull = message.standard; + } + }; + if (true) { + levels = ["error", "warning", "info", "debug", "verbose"]; + for (i = 0; i < levels.length; ++i) { + (function(level2) { + forge.log[level2] = function(category, message) { + var args = Array.prototype.slice.call(arguments).slice(2); + var msg = { + timestamp: /* @__PURE__ */ new Date(), + level: level2, + category, + message, + "arguments": args + /*standard*/ + /*full*/ + /*fullMessage*/ + }; + forge.log.logMessage(msg); + }; + })(levels[i]); + } + } + var levels; + var i; + forge.log.makeLogger = function(logFunction) { + var logger2 = { + flags: 0, + f: logFunction + }; + forge.log.setLevel(logger2, "none"); + return logger2; + }; + forge.log.setLevel = function(logger2, level2) { + var rval = false; + if (logger2 && !(logger2.flags & forge.log.LEVEL_LOCKED)) { + for (var i2 = 0; i2 < forge.log.levels.length; ++i2) { + var aValidLevel = forge.log.levels[i2]; + if (level2 == aValidLevel) { + logger2.level = level2; + rval = true; + break; + } + } + } + return rval; + }; + forge.log.lock = function(logger2, lock2) { + if (typeof lock2 === "undefined" || lock2) { + logger2.flags |= forge.log.LEVEL_LOCKED; + } else { + logger2.flags &= ~forge.log.LEVEL_LOCKED; + } + }; + forge.log.addLogger = function(logger2) { + sLoggers.push(logger2); + }; + if (typeof console !== "undefined" && "log" in console) { + if (console.error && console.warn && console.info && console.debug) { + levelHandlers = { + error: console.error, + warning: console.warn, + info: console.info, + debug: console.debug, + verbose: console.debug + }; + f = function(logger2, message) { + forge.log.prepareStandard(message); + var handler = levelHandlers[message.level]; + var args = [message.standard]; + args = args.concat(message["arguments"].slice()); + handler.apply(console, args); + }; + logger = forge.log.makeLogger(f); + } else { + f = function(logger2, message) { + forge.log.prepareStandardFull(message); + console.log(message.standardFull); + }; + logger = forge.log.makeLogger(f); + } + forge.log.setLevel(logger, "debug"); + forge.log.addLogger(logger); + sConsoleLogger = logger; + } else { + console = { + log: function() { + } + }; + } + var logger; + var levelHandlers; + var f; + if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) { + query = new URL(window.location.href).searchParams; + if (query.has("console.level")) { + forge.log.setLevel( + sConsoleLogger, + query.get("console.level").slice(-1)[0] + ); + } + if (query.has("console.lock")) { + lock = query.get("console.lock").slice(-1)[0]; + if (lock == "true") { + forge.log.lock(sConsoleLogger); + } + } + } + var query; + var lock; + forge.log.consoleLogger = sConsoleLogger; + } +}); + +// node_modules/node-forge/lib/md.all.js +var require_md_all = __commonJS({ + "node_modules/node-forge/lib/md.all.js"(exports2, module2) { + module2.exports = require_md(); + require_md5(); + require_sha1(); + require_sha256(); + require_sha512(); + } +}); + +// node_modules/node-forge/lib/pkcs7.js +var require_pkcs7 = __commonJS({ + "node_modules/node-forge/lib/pkcs7.js"(exports2, module2) { + var forge = require_forge(); + require_aes(); + require_asn1(); + require_des(); + require_oids(); + require_pem(); + require_pkcs7asn1(); + require_random(); + require_util8(); + require_x509(); + var asn1 = forge.asn1; + var p7 = module2.exports = forge.pkcs7 = forge.pkcs7 || {}; + p7.messageFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if (msg.type !== "PKCS7") { + var error4 = new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".'); + error4.headerType = msg.type; + throw error4; + } + if (msg.procType && msg.procType.type === "ENCRYPTED") { + throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted."); + } + var obj = asn1.fromDer(msg.body); + return p7.messageFromAsn1(obj); + }; + p7.messageToPem = function(msg, maxline) { + var pemObj = { + type: "PKCS7", + body: asn1.toDer(msg.toAsn1()).getBytes() + }; + return forge.pem.encode(pemObj, { maxline }); + }; + p7.messageFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { + var error4 = new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo."); + error4.errors = errors; + throw error4; + } + var contentType = asn1.derToOid(capture.contentType); + var msg; + switch (contentType) { + case forge.pki.oids.envelopedData: + msg = p7.createEnvelopedData(); + break; + case forge.pki.oids.encryptedData: + msg = p7.createEncryptedData(); + break; + case forge.pki.oids.signedData: + msg = p7.createSignedData(); + break; + default: + throw new Error("Cannot read PKCS#7 message. ContentType with OID " + contentType + " is not (yet) supported."); + } + msg.fromAsn1(capture.content.value[0]); + return msg; + }; + p7.createSignedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.signedData, + version: 1, + certificates: [], + crls: [], + // TODO: add json-formatted signer stuff here? + signers: [], + // populated during sign() + digestAlgorithmIdentifiers: [], + contentInfo: null, + signerInfos: [], + fromAsn1: function(obj) { + _fromAsn1(msg, obj, p7.asn1.signedDataValidator); + msg.certificates = []; + msg.crls = []; + msg.digestAlgorithmIdentifiers = []; + msg.contentInfo = null; + msg.signerInfos = []; + if (msg.rawCapture.certificates) { + var certs = msg.rawCapture.certificates.value; + for (var i = 0; i < certs.length; ++i) { + msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); + } + } + }, + toAsn1: function() { + if (!msg.contentInfo) { + msg.sign(); + } + var certs = []; + for (var i = 0; i < msg.certificates.length; ++i) { + certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); + } + var crls = []; + var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(msg.version).getBytes() + ), + // DigestAlgorithmIdentifiers + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SET, + true, + msg.digestAlgorithmIdentifiers + ), + // ContentInfo + msg.contentInfo + ]) + ]); + if (certs.length > 0) { + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs) + ); + } + if (crls.length > 0) { + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls) + ); + } + signedData.value[0].value.push( + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SET, + true, + msg.signerInfos + ) + ); + return asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [ + // ContentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(msg.type).getBytes() + ), + // [0] SignedData + signedData + ] + ); + }, + /** + * Add (another) entity to list of signers. + * + * Note: If authenticatedAttributes are provided, then, per RFC 2315, + * they must include at least two attributes: content type and + * message digest. The message digest attribute value will be + * auto-calculated during signing and will be ignored if provided. + * + * Here's an example of providing these two attributes: + * + * forge.pkcs7.createSignedData(); + * p7.addSigner({ + * issuer: cert.issuer.attributes, + * serialNumber: cert.serialNumber, + * key: privateKey, + * digestAlgorithm: forge.pki.oids.sha1, + * authenticatedAttributes: [{ + * type: forge.pki.oids.contentType, + * value: forge.pki.oids.data + * }, { + * type: forge.pki.oids.messageDigest + * }] + * }); + * + * TODO: Support [subjectKeyIdentifier] as signer's ID. + * + * @param signer the signer information: + * key the signer's private key. + * [certificate] a certificate containing the public key + * associated with the signer's private key; use this option as + * an alternative to specifying signer.issuer and + * signer.serialNumber. + * [issuer] the issuer attributes (eg: cert.issuer.attributes). + * [serialNumber] the signer's certificate's serial number in + * hexadecimal (eg: cert.serialNumber). + * [digestAlgorithm] the message digest OID, as a string, to use + * (eg: forge.pki.oids.sha1). + * [authenticatedAttributes] an optional array of attributes + * to also sign along with the content. + */ + addSigner: function(signer) { + var issuer = signer.issuer; + var serialNumber = signer.serialNumber; + if (signer.certificate) { + var cert = signer.certificate; + if (typeof cert === "string") { + cert = forge.pki.certificateFromPem(cert); + } + issuer = cert.issuer.attributes; + serialNumber = cert.serialNumber; + } + var key = signer.key; + if (!key) { + throw new Error( + "Could not add PKCS#7 signer; no private key specified." + ); + } + if (typeof key === "string") { + key = forge.pki.privateKeyFromPem(key); + } + var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; + switch (digestAlgorithm) { + case forge.pki.oids.sha1: + case forge.pki.oids.sha256: + case forge.pki.oids.sha384: + case forge.pki.oids.sha512: + case forge.pki.oids.md5: + break; + default: + throw new Error( + "Could not add PKCS#7 signer; unknown message digest algorithm: " + digestAlgorithm + ); + } + var authenticatedAttributes = signer.authenticatedAttributes || []; + if (authenticatedAttributes.length > 0) { + var contentType = false; + var messageDigest = false; + for (var i = 0; i < authenticatedAttributes.length; ++i) { + var attr = authenticatedAttributes[i]; + if (!contentType && attr.type === forge.pki.oids.contentType) { + contentType = true; + if (messageDigest) { + break; + } + continue; + } + if (!messageDigest && attr.type === forge.pki.oids.messageDigest) { + messageDigest = true; + if (contentType) { + break; + } + continue; + } + } + if (!contentType || !messageDigest) { + throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest."); + } + } + msg.signers.push({ + key, + version: 1, + issuer, + serialNumber, + digestAlgorithm, + signatureAlgorithm: forge.pki.oids.rsaEncryption, + signature: null, + authenticatedAttributes, + unauthenticatedAttributes: [] + }); + }, + /** + * Signs the content. + * @param options Options to apply when signing: + * [detached] boolean. If signing should be done in detached mode. Defaults to false. + */ + sign: function(options) { + options = options || {}; + if (typeof msg.content !== "object" || msg.contentInfo === null) { + msg.contentInfo = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + [ + // ContentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(forge.pki.oids.data).getBytes() + ) + ] + ); + if ("content" in msg) { + var content; + if (msg.content instanceof forge.util.ByteBuffer) { + content = msg.content.bytes(); + } else if (typeof msg.content === "string") { + content = forge.util.encodeUtf8(msg.content); + } + if (options.detached) { + msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); + } else { + msg.contentInfo.value.push( + // [0] EXPLICIT content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + content + ) + ]) + ); + } + } + } + if (msg.signers.length === 0) { + return; + } + var mds = addDigestAlgorithmIds(); + addSignerInfos(mds); + }, + verify: function() { + throw new Error("PKCS#7 signature verification not yet implemented."); + }, + /** + * Add a certificate. + * + * @param cert the certificate to add. + */ + addCertificate: function(cert) { + if (typeof cert === "string") { + cert = forge.pki.certificateFromPem(cert); + } + msg.certificates.push(cert); + }, + /** + * Add a certificate revokation list. + * + * @param crl the certificate revokation list to add. + */ + addCertificateRevokationList: function(crl) { + throw new Error("PKCS#7 CRL support not yet implemented."); + } + }; + return msg; + function addDigestAlgorithmIds() { + var mds = {}; + for (var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + var oid = signer.digestAlgorithm; + if (!(oid in mds)) { + mds[oid] = forge.md[forge.pki.oids[oid]].create(); + } + if (signer.authenticatedAttributes.length === 0) { + signer.md = mds[oid]; + } else { + signer.md = forge.md[forge.pki.oids[oid]].create(); + } + } + msg.digestAlgorithmIdentifiers = []; + for (var oid in mds) { + msg.digestAlgorithmIdentifiers.push( + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(oid).getBytes() + ), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]) + ); + } + return mds; + } + function addSignerInfos(mds) { + var content; + if (msg.detachedContent) { + content = msg.detachedContent; + } else { + content = msg.contentInfo.value[1]; + content = content.value[0]; + } + if (!content) { + throw new Error( + "Could not sign PKCS#7 message; there is no content to sign." + ); + } + var contentType = asn1.derToOid(msg.contentInfo.value[0].value); + var bytes = asn1.toDer(content); + bytes.getByte(); + asn1.getBerValueLength(bytes); + bytes = bytes.getBytes(); + for (var oid in mds) { + mds[oid].start().update(bytes); + } + var signingTime = /* @__PURE__ */ new Date(); + for (var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + if (signer.authenticatedAttributes.length === 0) { + if (contentType !== forge.pki.oids.data) { + throw new Error( + "Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data." + ); + } + } else { + signer.authenticatedAttributesAsn1 = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, + 0, + true, + [] + ); + var attrsAsn1 = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SET, + true, + [] + ); + for (var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { + var attr = signer.authenticatedAttributes[ai]; + if (attr.type === forge.pki.oids.messageDigest) { + attr.value = mds[signer.digestAlgorithm].digest(); + } else if (attr.type === forge.pki.oids.signingTime) { + if (!attr.value) { + attr.value = signingTime; + } + } + attrsAsn1.value.push(_attributeToAsn1(attr)); + signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); + } + bytes = asn1.toDer(attrsAsn1).getBytes(); + signer.md.start().update(bytes); + } + signer.signature = signer.key.sign(signer.md, "RSASSA-PKCS1-V1_5"); + } + msg.signerInfos = _signersToAsn1(msg.signers); + } + }; + p7.createEncryptedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.encryptedData, + version: 0, + encryptedContent: { + algorithm: forge.pki.oids["aes256-CBC"] + }, + /** + * Reads an EncryptedData content block (in ASN.1 format) + * + * @param obj The ASN.1 representation of the EncryptedData content block + */ + fromAsn1: function(obj) { + _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); + }, + /** + * Decrypt encrypted content + * + * @param key The (symmetric) key as a byte buffer + */ + decrypt: function(key) { + if (key !== void 0) { + msg.encryptedContent.key = key; + } + _decryptContent(msg); + } + }; + return msg; + }; + p7.createEnvelopedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.envelopedData, + version: 0, + recipients: [], + encryptedContent: { + algorithm: forge.pki.oids["aes256-CBC"] + }, + /** + * Reads an EnvelopedData content block (in ASN.1 format) + * + * @param obj the ASN.1 representation of the EnvelopedData content block. + */ + fromAsn1: function(obj) { + var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); + msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); + }, + toAsn1: function() { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(msg.type).getBytes() + ), + // [0] EnvelopedData + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(msg.version).getBytes() + ), + // RecipientInfos + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SET, + true, + _recipientsToAsn1(msg.recipients) + ), + // EncryptedContentInfo + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.SEQUENCE, + true, + _encryptedContentToAsn1(msg.encryptedContent) + ) + ]) + ]) + ]); + }, + /** + * Find recipient by X.509 certificate's issuer. + * + * @param cert the certificate with the issuer to look for. + * + * @return the recipient object. + */ + findRecipient: function(cert) { + var sAttr = cert.issuer.attributes; + for (var i = 0; i < msg.recipients.length; ++i) { + var r = msg.recipients[i]; + var rAttr = r.issuer; + if (r.serialNumber !== cert.serialNumber) { + continue; + } + if (rAttr.length !== sAttr.length) { + continue; + } + var match = true; + for (var j = 0; j < sAttr.length; ++j) { + if (rAttr[j].type !== sAttr[j].type || rAttr[j].value !== sAttr[j].value) { + match = false; + break; + } + } + if (match) { + return r; + } + } + return null; + }, + /** + * Decrypt enveloped content + * + * @param recipient The recipient object related to the private key + * @param privKey The (RSA) private key object + */ + decrypt: function(recipient, privKey) { + if (msg.encryptedContent.key === void 0 && recipient !== void 0 && privKey !== void 0) { + switch (recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + case forge.pki.oids.desCBC: + var key = privKey.decrypt(recipient.encryptedContent.content); + msg.encryptedContent.key = forge.util.createBuffer(key); + break; + default: + throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); + } + } + _decryptContent(msg); + }, + /** + * Add (another) entity to list of recipients. + * + * @param cert The certificate of the entity to add. + */ + addRecipient: function(cert) { + msg.recipients.push({ + version: 0, + issuer: cert.issuer.attributes, + serialNumber: cert.serialNumber, + encryptedContent: { + // We simply assume rsaEncryption here, since forge.pki only + // supports RSA so far. If the PKI module supports other + // ciphers one day, we need to modify this one as well. + algorithm: forge.pki.oids.rsaEncryption, + key: cert.publicKey + } + }); + }, + /** + * Encrypt enveloped content. + * + * This function supports two optional arguments, cipher and key, which + * can be used to influence symmetric encryption. Unless cipher is + * provided, the cipher specified in encryptedContent.algorithm is used + * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key + * is (re-)used. If that one's not set, a random key will be generated + * automatically. + * + * @param [key] The key to be used for symmetric encryption. + * @param [cipher] The OID of the symmetric cipher to use. + */ + encrypt: function(key, cipher) { + if (msg.encryptedContent.content === void 0) { + cipher = cipher || msg.encryptedContent.algorithm; + key = key || msg.encryptedContent.key; + var keyLen, ivLen, ciphFn; + switch (cipher) { + case forge.pki.oids["aes128-CBC"]: + keyLen = 16; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + case forge.pki.oids["aes192-CBC"]: + keyLen = 24; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + case forge.pki.oids["aes256-CBC"]: + keyLen = 32; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + case forge.pki.oids["des-EDE3-CBC"]: + keyLen = 24; + ivLen = 8; + ciphFn = forge.des.createEncryptionCipher; + break; + default: + throw new Error("Unsupported symmetric cipher, OID " + cipher); + } + if (key === void 0) { + key = forge.util.createBuffer(forge.random.getBytes(keyLen)); + } else if (key.length() != keyLen) { + throw new Error("Symmetric key has wrong length; got " + key.length() + " bytes, expected " + keyLen + "."); + } + msg.encryptedContent.algorithm = cipher; + msg.encryptedContent.key = key; + msg.encryptedContent.parameter = forge.util.createBuffer( + forge.random.getBytes(ivLen) + ); + var ciph = ciphFn(key); + ciph.start(msg.encryptedContent.parameter.copy()); + ciph.update(msg.content); + if (!ciph.finish()) { + throw new Error("Symmetric encryption failed."); + } + msg.encryptedContent.content = ciph.output; + } + for (var i = 0; i < msg.recipients.length; ++i) { + var recipient = msg.recipients[i]; + if (recipient.encryptedContent.content !== void 0) { + continue; + } + switch (recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt( + msg.encryptedContent.key.data + ); + break; + default: + throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); + } + } + } }; - kem.decrypt = function(privateKey, encapsulation, keyLength) { - var r = privateKey.decrypt(encapsulation, "NONE"); - return kdf.generate(r, keyLength); - }; - return kem; - }; - forge.kem.kdf1 = function(md, digestLength) { - _createKDF(this, md, 0, digestLength || md.digestLength); - }; - forge.kem.kdf2 = function(md, digestLength) { - _createKDF(this, md, 1, digestLength || md.digestLength); + return msg; }; - function _createKDF(kdf, md, counterStart, digestLength) { - kdf.generate = function(x, length) { - var key = new forge.util.ByteBuffer(); - var k = Math.ceil(length / digestLength) + counterStart; - var c = new forge.util.ByteBuffer(); - for (var i = counterStart; i < k; ++i) { - c.putInt32(i); - md.start(); - md.update(x + c.getBytes()); - var hash = md.digest(); - key.putBytes(hash.getBytes(digestLength)); + function _recipientFromAsn1(obj) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { + var error4 = new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo."); + error4.errors = errors; + throw error4; + } + return { + version: capture.version.charCodeAt(0), + issuer: forge.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge.util.createBuffer(capture.serial).toHex(), + encryptedContent: { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: capture.encParameter ? capture.encParameter.value : void 0, + content: capture.encKey } - key.truncate(key.length() - length); - return key.getBytes(); }; } - } -}); - -// node_modules/node-forge/lib/log.js -var require_log = __commonJS({ - "node_modules/node-forge/lib/log.js"(exports2, module2) { - var forge = require_forge(); - require_util8(); - module2.exports = forge.log = forge.log || {}; - forge.log.levels = [ - "none", - "error", - "warning", - "info", - "debug", - "verbose", - "max" - ]; - var sLevelInfo = {}; - var sLoggers = []; - var sConsoleLogger = null; - forge.log.LEVEL_LOCKED = 1 << 1; - forge.log.NO_LEVEL_CHECK = 1 << 2; - forge.log.INTERPOLATE = 1 << 3; - for (i = 0; i < forge.log.levels.length; ++i) { - level = forge.log.levels[i]; - sLevelInfo[level] = { - index: i, - name: level.toUpperCase() - }; + function _recipientToAsn1(obj) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(obj.version).getBytes() + ), + // IssuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Name + forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), + // Serial + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + forge.util.hexToBytes(obj.serialNumber) + ) + ]), + // KeyEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(obj.encryptedContent.algorithm).getBytes() + ), + // Parameter, force NULL, only RSA supported for now. + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]), + // EncryptedKey + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + obj.encryptedContent.content + ) + ]); } - var level; - var i; - forge.log.logMessage = function(message) { - var messageLevelIndex = sLevelInfo[message.level].index; - for (var i2 = 0; i2 < sLoggers.length; ++i2) { - var logger2 = sLoggers[i2]; - if (logger2.flags & forge.log.NO_LEVEL_CHECK) { - logger2.f(message); - } else { - var loggerLevelIndex = sLevelInfo[logger2.level].index; - if (messageLevelIndex <= loggerLevelIndex) { - logger2.f(logger2, message); - } - } + function _recipientsFromAsn1(infos) { + var ret = []; + for (var i = 0; i < infos.length; ++i) { + ret.push(_recipientFromAsn1(infos[i])); } - }; - forge.log.prepareStandard = function(message) { - if (!("standard" in message)) { - message.standard = sLevelInfo[message.level].name + //' ' + +message.timestamp + - " [" + message.category + "] " + message.message; + return ret; + } + function _recipientsToAsn1(recipients) { + var ret = []; + for (var i = 0; i < recipients.length; ++i) { + ret.push(_recipientToAsn1(recipients[i])); } - }; - forge.log.prepareFull = function(message) { - if (!("full" in message)) { - var args = [message.message]; - args = args.concat([]); - message.full = forge.util.format.apply(this, args); + return ret; + } + function _signerToAsn1(obj) { + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + asn1.integerToDer(obj.version).getBytes() + ), + // issuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // name + forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), + // serial + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.INTEGER, + false, + forge.util.hexToBytes(obj.serialNumber) + ) + ]), + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(obj.digestAlgorithm).getBytes() + ), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ]) + ]); + if (obj.authenticatedAttributesAsn1) { + rval.value.push(obj.authenticatedAttributesAsn1); } - }; - forge.log.prepareStandardFull = function(message) { - if (!("standardFull" in message)) { - forge.log.prepareStandard(message); - message.standardFull = message.standard; + rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(obj.signatureAlgorithm).getBytes() + ), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") + ])); + rval.value.push(asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + obj.signature + )); + if (obj.unauthenticatedAttributes.length > 0) { + var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); + for (var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { + var attr = obj.unauthenticatedAttributes[i]; + attrsAsn1.values.push(_attributeToAsn1(attr)); + } + rval.value.push(attrsAsn1); } - }; - if (true) { - levels = ["error", "warning", "info", "debug", "verbose"]; - for (i = 0; i < levels.length; ++i) { - (function(level2) { - forge.log[level2] = function(category, message) { - var args = Array.prototype.slice.call(arguments).slice(2); - var msg = { - timestamp: /* @__PURE__ */ new Date(), - level: level2, - category, - message, - "arguments": args - /*standard*/ - /*full*/ - /*fullMessage*/ - }; - forge.log.logMessage(msg); - }; - })(levels[i]); + return rval; + } + function _signersToAsn1(signers) { + var ret = []; + for (var i = 0; i < signers.length; ++i) { + ret.push(_signerToAsn1(signers[i])); } + return ret; } - var levels; - var i; - forge.log.makeLogger = function(logFunction) { - var logger2 = { - flags: 0, - f: logFunction - }; - forge.log.setLevel(logger2, "none"); - return logger2; - }; - forge.log.setLevel = function(logger2, level2) { - var rval = false; - if (logger2 && !(logger2.flags & forge.log.LEVEL_LOCKED)) { - for (var i2 = 0; i2 < forge.log.levels.length; ++i2) { - var aValidLevel = forge.log.levels[i2]; - if (level2 == aValidLevel) { - logger2.level = level2; - rval = true; - break; + function _attributeToAsn1(attr) { + var value; + if (attr.type === forge.pki.oids.contentType) { + value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(attr.value).getBytes() + ); + } else if (attr.type === forge.pki.oids.messageDigest) { + value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + attr.value.bytes() + ); + } else if (attr.type === forge.pki.oids.signingTime) { + var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); + var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); + var date = attr.value; + if (typeof date === "string") { + var timestamp2 = Date.parse(date); + if (!isNaN(timestamp2)) { + date = new Date(timestamp2); + } else if (date.length === 13) { + date = asn1.utcTimeToDate(date); + } else { + date = asn1.generalizedTimeToDate(date); } } + if (date >= jan_1_1950 && date < jan_1_2050) { + value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.UTCTIME, + false, + asn1.dateToUtcTime(date) + ); + } else { + value = asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.GENERALIZEDTIME, + false, + asn1.dateToGeneralizedTime(date) + ); + } } - return rval; - }; - forge.log.lock = function(logger2, lock2) { - if (typeof lock2 === "undefined" || lock2) { - logger2.flags |= forge.log.LEVEL_LOCKED; - } else { - logger2.flags &= ~forge.log.LEVEL_LOCKED; + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(attr.type).getBytes() + ), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + value + ]) + ]); + } + function _encryptedContentToAsn1(ec) { + return [ + // ContentType, always Data for the moment + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(forge.pki.oids.data).getBytes() + ), + // ContentEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OID, + false, + asn1.oidToDer(ec.algorithm).getBytes() + ), + // Parameters (IV) + !ec.parameter ? void 0 : asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + ec.parameter.getBytes() + ) + ]), + // [0] EncryptedContent + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, + asn1.Type.OCTETSTRING, + false, + ec.content.getBytes() + ) + ]) + ]; + } + function _fromAsn1(msg, obj, validator) { + var capture = {}; + var errors = []; + if (!asn1.validate(obj, validator, capture, errors)) { + var error4 = new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message."); + error4.errors = error4; + throw error4; } - }; - forge.log.addLogger = function(logger2) { - sLoggers.push(logger2); - }; - if (typeof console !== "undefined" && "log" in console) { - if (console.error && console.warn && console.info && console.debug) { - levelHandlers = { - error: console.error, - warning: console.warn, - info: console.info, - debug: console.debug, - verbose: console.debug - }; - f = function(logger2, message) { - forge.log.prepareStandard(message); - var handler = levelHandlers[message.level]; - var args = [message.standard]; - args = args.concat(message["arguments"].slice()); - handler.apply(console, args); - }; - logger = forge.log.makeLogger(f); - } else { - f = function(logger2, message) { - forge.log.prepareStandardFull(message); - console.log(message.standardFull); + var contentType = asn1.derToOid(capture.contentType); + if (contentType !== forge.pki.oids.data) { + throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported."); + } + if (capture.encryptedContent) { + var content = ""; + if (forge.util.isArray(capture.encryptedContent)) { + for (var i = 0; i < capture.encryptedContent.length; ++i) { + if (capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { + throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects."); + } + content += capture.encryptedContent[i].value; + } + } else { + content = capture.encryptedContent; + } + msg.encryptedContent = { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: forge.util.createBuffer(capture.encParameter.value), + content: forge.util.createBuffer(content) }; - logger = forge.log.makeLogger(f); } - forge.log.setLevel(logger, "debug"); - forge.log.addLogger(logger); - sConsoleLogger = logger; - } else { - console = { - log: function() { + if (capture.content) { + var content = ""; + if (forge.util.isArray(capture.content)) { + for (var i = 0; i < capture.content.length; ++i) { + if (capture.content[i].type !== asn1.Type.OCTETSTRING) { + throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects."); + } + content += capture.content[i].value; + } + } else { + content = capture.content; + } + msg.content = forge.util.createBuffer(content); + } + msg.version = capture.version.charCodeAt(0); + msg.rawCapture = capture; + return capture; + } + function _decryptContent(msg) { + if (msg.encryptedContent.key === void 0) { + throw new Error("Symmetric key not available."); + } + if (msg.content === void 0) { + var ciph; + switch (msg.encryptedContent.algorithm) { + case forge.pki.oids["aes128-CBC"]: + case forge.pki.oids["aes192-CBC"]: + case forge.pki.oids["aes256-CBC"]: + ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key); + break; + case forge.pki.oids["desCBC"]: + case forge.pki.oids["des-EDE3-CBC"]: + ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key); + break; + default: + throw new Error("Unsupported symmetric cipher, OID " + msg.encryptedContent.algorithm); } - }; - } - var logger; - var levelHandlers; - var f; - if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) { - query = new URL(window.location.href).searchParams; - if (query.has("console.level")) { - forge.log.setLevel( - sConsoleLogger, - query.get("console.level").slice(-1)[0] - ); - } - if (query.has("console.lock")) { - lock = query.get("console.lock").slice(-1)[0]; - if (lock == "true") { - forge.log.lock(sConsoleLogger); + ciph.start(msg.encryptedContent.parameter); + ciph.update(msg.encryptedContent.content); + if (!ciph.finish()) { + throw new Error("Symmetric decryption failed."); } + msg.content = ciph.output; } } - var query; - var lock; - forge.log.consoleLogger = sConsoleLogger; - } -}); - -// node_modules/node-forge/lib/md.all.js -var require_md_all = __commonJS({ - "node_modules/node-forge/lib/md.all.js"(exports2, module2) { - module2.exports = require_md(); - require_md5(); - require_sha1(); - require_sha256(); - require_sha512(); } }); -// node_modules/node-forge/lib/pkcs7.js -var require_pkcs7 = __commonJS({ - "node_modules/node-forge/lib/pkcs7.js"(exports2, module2) { +// node_modules/node-forge/lib/ssh.js +var require_ssh = __commonJS({ + "node_modules/node-forge/lib/ssh.js"(exports2, module2) { var forge = require_forge(); require_aes(); - require_asn1(); - require_des(); - require_oids(); - require_pem(); - require_pkcs7asn1(); - require_random(); + require_hmac(); + require_md5(); + require_sha1(); require_util8(); - require_x509(); - var asn1 = forge.asn1; - var p7 = module2.exports = forge.pkcs7 = forge.pkcs7 || {}; - p7.messageFromPem = function(pem) { - var msg = forge.pem.decode(pem)[0]; - if (msg.type !== "PKCS7") { - var error4 = new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".'); - error4.headerType = msg.type; - throw error4; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted."); + var ssh = module2.exports = forge.ssh = forge.ssh || {}; + ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { + comment = comment || ""; + passphrase = passphrase || ""; + var algorithm = "ssh-rsa"; + var encryptionAlgorithm = passphrase === "" ? "none" : "aes256-cbc"; + var ppk = "PuTTY-User-Key-File-2: " + algorithm + "\r\n"; + ppk += "Encryption: " + encryptionAlgorithm + "\r\n"; + ppk += "Comment: " + comment + "\r\n"; + var pubbuffer = forge.util.createBuffer(); + _addStringToBuffer(pubbuffer, algorithm); + _addBigIntegerToBuffer(pubbuffer, privateKey.e); + _addBigIntegerToBuffer(pubbuffer, privateKey.n); + var pub = forge.util.encode64(pubbuffer.bytes(), 64); + var length = Math.floor(pub.length / 66) + 1; + ppk += "Public-Lines: " + length + "\r\n"; + ppk += pub; + var privbuffer = forge.util.createBuffer(); + _addBigIntegerToBuffer(privbuffer, privateKey.d); + _addBigIntegerToBuffer(privbuffer, privateKey.p); + _addBigIntegerToBuffer(privbuffer, privateKey.q); + _addBigIntegerToBuffer(privbuffer, privateKey.qInv); + var priv; + if (!passphrase) { + priv = forge.util.encode64(privbuffer.bytes(), 64); + } else { + var encLen = privbuffer.length() + 16 - 1; + encLen -= encLen % 16; + var padding = _sha1(privbuffer.bytes()); + padding.truncate(padding.length() - encLen + privbuffer.length()); + privbuffer.putBuffer(padding); + var aeskey = forge.util.createBuffer(); + aeskey.putBuffer(_sha1("\0\0\0\0", passphrase)); + aeskey.putBuffer(_sha1("\0\0\0", passphrase)); + var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), "CBC"); + cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); + cipher.update(privbuffer.copy()); + cipher.finish(); + var encrypted = cipher.output; + encrypted.truncate(16); + priv = forge.util.encode64(encrypted.bytes(), 64); } - var obj = asn1.fromDer(msg.body); - return p7.messageFromAsn1(obj); + length = Math.floor(priv.length / 66) + 1; + ppk += "\r\nPrivate-Lines: " + length + "\r\n"; + ppk += priv; + var mackey = _sha1("putty-private-key-file-mac-key", passphrase); + var macbuffer = forge.util.createBuffer(); + _addStringToBuffer(macbuffer, algorithm); + _addStringToBuffer(macbuffer, encryptionAlgorithm); + _addStringToBuffer(macbuffer, comment); + macbuffer.putInt32(pubbuffer.length()); + macbuffer.putBuffer(pubbuffer); + macbuffer.putInt32(privbuffer.length()); + macbuffer.putBuffer(privbuffer); + var hmac = forge.hmac.create(); + hmac.start("sha1", mackey); + hmac.update(macbuffer.bytes()); + ppk += "\r\nPrivate-MAC: " + hmac.digest().toHex() + "\r\n"; + return ppk; }; - p7.messageToPem = function(msg, maxline) { - var pemObj = { - type: "PKCS7", - body: asn1.toDer(msg.toAsn1()).getBytes() - }; - return forge.pem.encode(pemObj, { maxline }); + ssh.publicKeyToOpenSSH = function(key, comment) { + var type2 = "ssh-rsa"; + comment = comment || ""; + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type2); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + return type2 + " " + forge.util.encode64(buffer.bytes()) + " " + comment; }; - p7.messageFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { - var error4 = new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo."); - error4.errors = errors; - throw error4; - } - var contentType = asn1.derToOid(capture.contentType); - var msg; - switch (contentType) { - case forge.pki.oids.envelopedData: - msg = p7.createEnvelopedData(); - break; - case forge.pki.oids.encryptedData: - msg = p7.createEncryptedData(); - break; - case forge.pki.oids.signedData: - msg = p7.createSignedData(); - break; - default: - throw new Error("Cannot read PKCS#7 message. ContentType with OID " + contentType + " is not (yet) supported."); + ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { + if (!passphrase) { + return forge.pki.privateKeyToPem(privateKey); } - msg.fromAsn1(capture.content.value[0]); - return msg; + return forge.pki.encryptRsaPrivateKey( + privateKey, + passphrase, + { legacy: true, algorithm: "aes128" } + ); }; - p7.createSignedData = function() { - var msg = null; - msg = { - type: forge.pki.oids.signedData, - version: 1, - certificates: [], - crls: [], - // TODO: add json-formatted signer stuff here? - signers: [], - // populated during sign() - digestAlgorithmIdentifiers: [], - contentInfo: null, - signerInfos: [], - fromAsn1: function(obj) { - _fromAsn1(msg, obj, p7.asn1.signedDataValidator); - msg.certificates = []; - msg.crls = []; - msg.digestAlgorithmIdentifiers = []; - msg.contentInfo = null; - msg.signerInfos = []; - if (msg.rawCapture.certificates) { - var certs = msg.rawCapture.certificates.value; - for (var i = 0; i < certs.length; ++i) { - msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); - } - } - }, - toAsn1: function() { - if (!msg.contentInfo) { - msg.sign(); - } - var certs = []; - for (var i = 0; i < msg.certificates.length; ++i) { - certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); - } - var crls = []; - var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(msg.version).getBytes() - ), - // DigestAlgorithmIdentifiers - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - msg.digestAlgorithmIdentifiers - ), - // ContentInfo - msg.contentInfo - ]) - ]); - if (certs.length > 0) { - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs) - ); - } - if (crls.length > 0) { - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls) - ); - } - signedData.value[0].value.push( - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - msg.signerInfos - ) - ); - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(msg.type).getBytes() - ), - // [0] SignedData - signedData - ] - ); - }, - /** - * Add (another) entity to list of signers. - * - * Note: If authenticatedAttributes are provided, then, per RFC 2315, - * they must include at least two attributes: content type and - * message digest. The message digest attribute value will be - * auto-calculated during signing and will be ignored if provided. - * - * Here's an example of providing these two attributes: - * - * forge.pkcs7.createSignedData(); - * p7.addSigner({ - * issuer: cert.issuer.attributes, - * serialNumber: cert.serialNumber, - * key: privateKey, - * digestAlgorithm: forge.pki.oids.sha1, - * authenticatedAttributes: [{ - * type: forge.pki.oids.contentType, - * value: forge.pki.oids.data - * }, { - * type: forge.pki.oids.messageDigest - * }] - * }); - * - * TODO: Support [subjectKeyIdentifier] as signer's ID. - * - * @param signer the signer information: - * key the signer's private key. - * [certificate] a certificate containing the public key - * associated with the signer's private key; use this option as - * an alternative to specifying signer.issuer and - * signer.serialNumber. - * [issuer] the issuer attributes (eg: cert.issuer.attributes). - * [serialNumber] the signer's certificate's serial number in - * hexadecimal (eg: cert.serialNumber). - * [digestAlgorithm] the message digest OID, as a string, to use - * (eg: forge.pki.oids.sha1). - * [authenticatedAttributes] an optional array of attributes - * to also sign along with the content. - */ - addSigner: function(signer) { - var issuer = signer.issuer; - var serialNumber = signer.serialNumber; - if (signer.certificate) { - var cert = signer.certificate; - if (typeof cert === "string") { - cert = forge.pki.certificateFromPem(cert); - } - issuer = cert.issuer.attributes; - serialNumber = cert.serialNumber; - } - var key = signer.key; - if (!key) { - throw new Error( - "Could not add PKCS#7 signer; no private key specified." - ); - } - if (typeof key === "string") { - key = forge.pki.privateKeyFromPem(key); - } - var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; - switch (digestAlgorithm) { - case forge.pki.oids.sha1: - case forge.pki.oids.sha256: - case forge.pki.oids.sha384: - case forge.pki.oids.sha512: - case forge.pki.oids.md5: - break; - default: - throw new Error( - "Could not add PKCS#7 signer; unknown message digest algorithm: " + digestAlgorithm - ); - } - var authenticatedAttributes = signer.authenticatedAttributes || []; - if (authenticatedAttributes.length > 0) { - var contentType = false; - var messageDigest = false; - for (var i = 0; i < authenticatedAttributes.length; ++i) { - var attr = authenticatedAttributes[i]; - if (!contentType && attr.type === forge.pki.oids.contentType) { - contentType = true; - if (messageDigest) { - break; - } - continue; - } - if (!messageDigest && attr.type === forge.pki.oids.messageDigest) { - messageDigest = true; - if (contentType) { - break; - } - continue; - } - } - if (!contentType || !messageDigest) { - throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest."); - } - } - msg.signers.push({ - key, - version: 1, - issuer, - serialNumber, - digestAlgorithm, - signatureAlgorithm: forge.pki.oids.rsaEncryption, - signature: null, - authenticatedAttributes, - unauthenticatedAttributes: [] - }); - }, - /** - * Signs the content. - * @param options Options to apply when signing: - * [detached] boolean. If signing should be done in detached mode. Defaults to false. - */ - sign: function(options) { - options = options || {}; - if (typeof msg.content !== "object" || msg.contentInfo === null) { - msg.contentInfo = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(forge.pki.oids.data).getBytes() - ) - ] - ); - if ("content" in msg) { - var content; - if (msg.content instanceof forge.util.ByteBuffer) { - content = msg.content.bytes(); - } else if (typeof msg.content === "string") { - content = forge.util.encodeUtf8(msg.content); - } - if (options.detached) { - msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); - } else { - msg.contentInfo.value.push( - // [0] EXPLICIT content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - content - ) - ]) - ); - } - } - } - if (msg.signers.length === 0) { - return; - } - var mds = addDigestAlgorithmIds(); - addSignerInfos(mds); - }, - verify: function() { - throw new Error("PKCS#7 signature verification not yet implemented."); - }, - /** - * Add a certificate. - * - * @param cert the certificate to add. - */ - addCertificate: function(cert) { - if (typeof cert === "string") { - cert = forge.pki.certificateFromPem(cert); - } - msg.certificates.push(cert); - }, - /** - * Add a certificate revokation list. - * - * @param crl the certificate revokation list to add. - */ - addCertificateRevokationList: function(crl) { - throw new Error("PKCS#7 CRL support not yet implemented."); + ssh.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge.md.md5.create(); + var type2 = "ssh-rsa"; + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type2); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + md.start(); + md.update(buffer.getBytes()); + var digest = md.digest(); + if (options.encoding === "hex") { + var hex = digest.toHex(); + if (options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); } - }; - return msg; - function addDigestAlgorithmIds() { - var mds = {}; - for (var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - var oid = signer.digestAlgorithm; - if (!(oid in mds)) { - mds[oid] = forge.md[forge.pki.oids[oid]].create(); - } - if (signer.authenticatedAttributes.length === 0) { - signer.md = mds[oid]; + return hex; + } else if (options.encoding === "binary") { + return digest.getBytes(); + } else if (options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; + }; + function _addBigIntegerToBuffer(buffer, val2) { + var hexVal = val2.toString(16); + if (hexVal[0] >= "8") { + hexVal = "00" + hexVal; + } + var bytes = forge.util.hexToBytes(hexVal); + buffer.putInt32(bytes.length); + buffer.putBytes(bytes); + } + function _addStringToBuffer(buffer, val2) { + buffer.putInt32(val2.length); + buffer.putString(val2); + } + function _sha1() { + var sha = forge.md.sha1.create(); + var num = arguments.length; + for (var i = 0; i < num; ++i) { + sha.update(arguments[i]); + } + return sha.digest(); + } + } +}); + +// node_modules/node-forge/lib/index.js +var require_lib3 = __commonJS({ + "node_modules/node-forge/lib/index.js"(exports2, module2) { + module2.exports = require_forge(); + require_aes(); + require_aesCipherSuites(); + require_asn1(); + require_cipher(); + require_des(); + require_ed25519(); + require_hmac(); + require_kem(); + require_log(); + require_md_all(); + require_mgf1(); + require_pbkdf2(); + require_pem(); + require_pkcs1(); + require_pkcs12(); + require_pkcs7(); + require_pki(); + require_prime(); + require_prng(); + require_pss(); + require_random(); + require_rc2(); + require_ssh(); + require_tls(); + require_util8(); + } +}); + +// node_modules/@actions/github/lib/context.js +var require_context = __commonJS({ + "node_modules/@actions/github/lib/context.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Context = void 0; + var fs_1 = require("fs"); + var os_1 = require("os"); + var Context = class { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: "utf8" })); } else { - signer.md = forge.md[forge.pki.oids[oid]].create(); + const path2 = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path2} does not exist${os_1.EOL}`); } } - msg.digestAlgorithmIdentifiers = []; - for (var oid in mds) { - msg.digestAlgorithmIdentifiers.push( - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oid).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ); + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/"); + return { owner, repo }; } - return mds; + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); } - function addSignerInfos(mds) { - var content; - if (msg.detachedContent) { - content = msg.detachedContent; + }; + exports2.Context = Context; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; } else { - content = msg.contentInfo.value[1]; - content = content.value[0]; - } - if (!content) { - throw new Error( - "Could not sign PKCS#7 message; there is no content to sign." - ); + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - var contentType = asn1.derToOid(msg.contentInfo.value[0].value); - var bytes = asn1.toDer(content); - bytes.getByte(); - asn1.getBerValueLength(bytes); - bytes = bytes.getBytes(); - for (var oid in mds) { - mds[oid].start().update(bytes); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - var signingTime = /* @__PURE__ */ new Date(); - for (var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - if (signer.authenticatedAttributes.length === 0) { - if (contentType !== forge.pki.oids.data) { - throw new Error( - "Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data." - ); - } - } else { - signer.authenticatedAttributesAsn1 = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [] - ); - var attrsAsn1 = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - [] - ); - for (var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { - var attr = signer.authenticatedAttributes[ai]; - if (attr.type === forge.pki.oids.messageDigest) { - attr.value = mds[signer.digestAlgorithm].digest(); - } else if (attr.type === forge.pki.oids.signingTime) { - if (!attr.value) { - attr.value = signingTime; - } - } - attrsAsn1.value.push(_attributeToAsn1(attr)); - signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); - } - bytes = asn1.toDer(attrsAsn1).getBytes(); - signer.md.start().update(bytes); - } - signer.signature = signer.key.sign(signer.md, "RSASSA-PKCS1-V1_5"); + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - msg.signerInfos = _signersToAsn1(msg.signers); + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; } }; - p7.createEncryptedData = function() { - var msg = null; - msg = { - type: forge.pki.oids.encryptedData, - version: 0, - encryptedContent: { - algorithm: forge.pki.oids["aes256-CBC"] - }, - /** - * Reads an EncryptedData content block (in ASN.1 format) - * - * @param obj The ASN.1 representation of the EncryptedData content block - */ - fromAsn1: function(obj) { - _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); - }, - /** - * Decrypt encrypted content - * - * @param key The (symmetric) key as a byte buffer - */ - decrypt: function(key) { - if (key !== void 0) { - msg.encryptedContent.key = key; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - _decryptContent(msg); } - }; - return msg; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - p7.createEnvelopedData = function() { - var msg = null; - msg = { - type: forge.pki.oids.envelopedData, - version: 0, - recipients: [], - encryptedContent: { - algorithm: forge.pki.oids["aes256-CBC"] - }, - /** - * Reads an EnvelopedData content block (in ASN.1 format) - * - * @param obj the ASN.1 representation of the EnvelopedData content block. - */ - fromAsn1: function(obj) { - var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); - msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); - }, - toAsn1: function() { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(msg.type).getBytes() - ), - // [0] EnvelopedData - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(msg.version).getBytes() - ), - // RecipientInfos - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - _recipientsToAsn1(msg.recipients) - ), - // EncryptedContentInfo - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - _encryptedContentToAsn1(msg.encryptedContent) - ) - ]) - ]) - ]); - }, - /** - * Find recipient by X.509 certificate's issuer. - * - * @param cert the certificate with the issuer to look for. - * - * @return the recipient object. - */ - findRecipient: function(cert) { - var sAttr = cert.issuer.attributes; - for (var i = 0; i < msg.recipients.length; ++i) { - var r = msg.recipients[i]; - var rAttr = r.issuer; - if (r.serialNumber !== cert.serialNumber) { - continue; - } - if (rAttr.length !== sAttr.length) { - continue; - } - var match = true; - for (var j = 0; j < sAttr.length; ++j) { - if (rAttr[j].type !== sAttr[j].type || rAttr[j].value !== sAttr[j].value) { - match = false; - break; - } - } - if (match) { - return r; - } + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); + } + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); + }); + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - return null; - }, - /** - * Decrypt enveloped content - * - * @param recipient The recipient object related to the private key - * @param privKey The (RSA) private key object - */ - decrypt: function(recipient, privKey) { - if (msg.encryptedContent.key === void 0 && recipient !== void 0 && privKey !== void 0) { - switch (recipient.encryptedContent.algorithm) { - case forge.pki.oids.rsaEncryption: - case forge.pki.oids.desCBC: - var key = privKey.decrypt(recipient.encryptedContent.content); - msg.encryptedContent.key = forge.util.createBuffer(key); - break; - default: - throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - _decryptContent(msg); - }, - /** - * Add (another) entity to list of recipients. - * - * @param cert The certificate of the entity to add. - */ - addRecipient: function(cert) { - msg.recipients.push({ - version: 0, - issuer: cert.issuer.attributes, - serialNumber: cert.serialNumber, - encryptedContent: { - // We simply assume rsaEncryption here, since forge.pki only - // supports RSA so far. If the PKI module supports other - // ciphers one day, we need to modify this one as well. - algorithm: forge.pki.oids.rsaEncryption, - key: cert.publicKey - } - }); - }, - /** - * Encrypt enveloped content. - * - * This function supports two optional arguments, cipher and key, which - * can be used to influence symmetric encryption. Unless cipher is - * provided, the cipher specified in encryptedContent.algorithm is used - * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key - * is (re-)used. If that one's not set, a random key will be generated - * automatically. - * - * @param [key] The key to be used for symmetric encryption. - * @param [cipher] The OID of the symmetric cipher to use. - */ - encrypt: function(key, cipher) { - if (msg.encryptedContent.content === void 0) { - cipher = cipher || msg.encryptedContent.algorithm; - key = key || msg.encryptedContent.key; - var keyLen, ivLen, ciphFn; - switch (cipher) { - case forge.pki.oids["aes128-CBC"]: - keyLen = 16; - ivLen = 16; - ciphFn = forge.aes.createEncryptionCipher; - break; - case forge.pki.oids["aes192-CBC"]: - keyLen = 24; - ivLen = 16; - ciphFn = forge.aes.createEncryptionCipher; - break; - case forge.pki.oids["aes256-CBC"]: - keyLen = 32; - ivLen = 16; - ciphFn = forge.aes.createEncryptionCipher; - break; - case forge.pki.oids["des-EDE3-CBC"]: - keyLen = 24; - ivLen = 8; - ciphFn = forge.des.createEncryptionCipher; - break; - default: - throw new Error("Unsupported symmetric cipher, OID " + cipher); - } - if (key === void 0) { - key = forge.util.createBuffer(forge.random.getBytes(keyLen)); - } else if (key.length() != keyLen) { - throw new Error("Symmetric key has wrong length; got " + key.length() + " bytes, expected " + keyLen + "."); - } - msg.encryptedContent.algorithm = cipher; - msg.encryptedContent.key = key; - msg.encryptedContent.parameter = forge.util.createBuffer( - forge.random.getBytes(ivLen) - ); - var ciph = ciphFn(key); - ciph.start(msg.encryptedContent.parameter.copy()); - ciph.update(msg.content); - if (!ciph.finish()) { - throw new Error("Symmetric encryption failed."); - } - msg.encryptedContent.content = ciph.output; + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - for (var i = 0; i < msg.recipients.length; ++i) { - var recipient = msg.recipients[i]; - if (recipient.encryptedContent.content !== void 0) { - continue; - } - switch (recipient.encryptedContent.algorithm) { - case forge.pki.oids.rsaEncryption: - recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt( - msg.encryptedContent.key.data - ); - break; - default: - throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); - } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - }; - return msg; - }; - function _recipientFromAsn1(obj) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { - var error4 = new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo."); - error4.errors = errors; - throw error4; } - return { - version: capture.version.charCodeAt(0), - issuer: forge.pki.RDNAttributesAsArray(capture.issuer), - serialNumber: forge.util.createBuffer(capture.serial).toHex(), - encryptedContent: { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: capture.encParameter ? capture.encParameter.value : void 0, - content: capture.encKey - } - }; - } - function _recipientToAsn1(obj) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(obj.version).getBytes() - ), - // IssuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Name - forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), - // Serial - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge.util.hexToBytes(obj.serialNumber) - ) - ]), - // KeyEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.encryptedContent.algorithm).getBytes() - ), - // Parameter, force NULL, only RSA supported for now. - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // EncryptedKey - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - obj.encryptedContent.content - ) - ]); - } - function _recipientsFromAsn1(infos) { - var ret = []; - for (var i = 0; i < infos.length; ++i) { - ret.push(_recipientFromAsn1(infos[i])); + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - return ret; - } - function _recipientsToAsn1(recipients) { - var ret = []; - for (var i = 0; i < recipients.length; ++i) { - ret.push(_recipientToAsn1(recipients[i])); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - return ret; - } - function _signerToAsn1(obj) { - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(obj.version).getBytes() - ), - // issuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // name - forge.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), - // serial - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge.util.hexToBytes(obj.serialNumber) - ) - ]), - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.digestAlgorithm).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ]); - if (obj.authenticatedAttributesAsn1) { - rval.value.push(obj.authenticatedAttributesAsn1); + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.signatureAlgorithm).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ])); - rval.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - obj.signature - )); - if (obj.unauthenticatedAttributes.length > 0) { - var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); - for (var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { - var attr = obj.unauthenticatedAttributes[i]; - attrsAsn1.values.push(_attributeToAsn1(attr)); - } - rval.value.push(attrsAsn1); + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - return rval; - } - function _signersToAsn1(signers) { - var ret = []; - for (var i = 0; i < signers.length; ++i) { - ret.push(_signerToAsn1(signers[i])); + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - return ret; - } - function _attributeToAsn1(attr) { - var value; - if (attr.type === forge.pki.oids.contentType) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.value).getBytes() - ); - } else if (attr.type === forge.pki.oids.messageDigest) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - attr.value.bytes() - ); - } else if (attr.type === forge.pki.oids.signingTime) { - var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); - var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); - var date = attr.value; - if (typeof date === "string") { - var timestamp2 = Date.parse(date); - if (!isNaN(timestamp2)) { - date = new Date(timestamp2); - } else if (date.length === 13) { - date = asn1.utcTimeToDate(date); - } else { - date = asn1.generalizedTimeToDate(date); - } - } - if (date >= jan_1_1950 && date < jan_1_2050) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.UTCTIME, - false, - asn1.dateToUtcTime(date) - ); - } else { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.GENERALIZEDTIME, - false, - asn1.dateToGeneralizedTime(date) - ); - } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - value - ]) - ]); - } - function _encryptedContentToAsn1(ec) { - return [ - // ContentType, always Data for the moment - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(forge.pki.oids.data).getBytes() - ), - // ContentEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(ec.algorithm).getBytes() - ), - // Parameters (IV) - !ec.parameter ? void 0 : asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ec.parameter.getBytes() - ) - ]), - // [0] EncryptedContent - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ec.content.getBytes() - ) - ]) - ]; - } - function _fromAsn1(msg, obj, validator) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, validator, capture, errors)) { - var error4 = new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message."); - error4.errors = error4; - throw error4; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - var contentType = asn1.derToOid(capture.contentType); - if (contentType !== forge.pki.oids.data) { - throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported."); + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - if (capture.encryptedContent) { - var content = ""; - if (forge.util.isArray(capture.encryptedContent)) { - for (var i = 0; i < capture.encryptedContent.length; ++i) { - if (capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { - throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects."); + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); } - content += capture.encryptedContent[i].value; - } - } else { - content = capture.encryptedContent; + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - msg.encryptedContent = { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: forge.util.createBuffer(capture.encParameter.value), - content: forge.util.createBuffer(content) - }; + this._disposed = true; } - if (capture.content) { - var content = ""; - if (forge.util.isArray(capture.content)) { - for (var i = 0; i < capture.content.length; ++i) { - if (capture.content[i].type !== asn1.Type.OCTETSTRING) { - throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects."); + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); + } } - content += capture.content[i].value; + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } - } else { - content = capture.content; + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - msg.content = forge.util.createBuffer(content); - } - msg.version = capture.version.charCodeAt(0); - msg.rawCapture = capture; - return capture; - } - function _decryptContent(msg) { - if (msg.encryptedContent.key === void 0) { - throw new Error("Symmetric key not available."); - } - if (msg.content === void 0) { - var ciph; - switch (msg.encryptedContent.algorithm) { - case forge.pki.oids["aes128-CBC"]: - case forge.pki.oids["aes192-CBC"]: - case forge.pki.oids["aes256-CBC"]: - ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key); - break; - case forge.pki.oids["desCBC"]: - case forge.pki.oids["des-EDE3-CBC"]: - ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key); - break; - default: - throw new Error("Unsupported symmetric cipher, OID " + msg.encryptedContent.algorithm); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - ciph.start(msg.encryptedContent.parameter); - ciph.update(msg.encryptedContent.content); - if (!ciph.finish()) { - throw new Error("Symmetric decryption failed."); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); } - msg.content = ciph.output; } - } - } -}); - -// node_modules/node-forge/lib/ssh.js -var require_ssh = __commonJS({ - "node_modules/node-forge/lib/ssh.js"(exports2, module2) { - var forge = require_forge(); - require_aes(); - require_hmac(); - require_md5(); - require_sha1(); - require_util8(); - var ssh = module2.exports = forge.ssh = forge.ssh || {}; - ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { - comment = comment || ""; - passphrase = passphrase || ""; - var algorithm = "ssh-rsa"; - var encryptionAlgorithm = passphrase === "" ? "none" : "aes256-cbc"; - var ppk = "PuTTY-User-Key-File-2: " + algorithm + "\r\n"; - ppk += "Encryption: " + encryptionAlgorithm + "\r\n"; - ppk += "Comment: " + comment + "\r\n"; - var pubbuffer = forge.util.createBuffer(); - _addStringToBuffer(pubbuffer, algorithm); - _addBigIntegerToBuffer(pubbuffer, privateKey.e); - _addBigIntegerToBuffer(pubbuffer, privateKey.n); - var pub = forge.util.encode64(pubbuffer.bytes(), 64); - var length = Math.floor(pub.length / 66) + 1; - ppk += "Public-Lines: " + length + "\r\n"; - ppk += pub; - var privbuffer = forge.util.createBuffer(); - _addBigIntegerToBuffer(privbuffer, privateKey.d); - _addBigIntegerToBuffer(privbuffer, privateKey.p); - _addBigIntegerToBuffer(privbuffer, privateKey.q); - _addBigIntegerToBuffer(privbuffer, privateKey.qInv); - var priv; - if (!passphrase) { - priv = forge.util.encode64(privbuffer.bytes(), 64); - } else { - var encLen = privbuffer.length() + 16 - 1; - encLen -= encLen % 16; - var padding = _sha1(privbuffer.bytes()); - padding.truncate(padding.length() - encLen + privbuffer.length()); - privbuffer.putBuffer(padding); - var aeskey = forge.util.createBuffer(); - aeskey.putBuffer(_sha1("\0\0\0\0", passphrase)); - aeskey.putBuffer(_sha1("\0\0\0", passphrase)); - var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), "CBC"); - cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); - cipher.update(privbuffer.copy()); - cipher.finish(); - var encrypted = cipher.output; - encrypted.truncate(16); - priv = forge.util.encode64(encrypted.bytes(), 64); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - length = Math.floor(priv.length / 66) + 1; - ppk += "\r\nPrivate-Lines: " + length + "\r\n"; - ppk += priv; - var mackey = _sha1("putty-private-key-file-mac-key", passphrase); - var macbuffer = forge.util.createBuffer(); - _addStringToBuffer(macbuffer, algorithm); - _addStringToBuffer(macbuffer, encryptionAlgorithm); - _addStringToBuffer(macbuffer, comment); - macbuffer.putInt32(pubbuffer.length()); - macbuffer.putBuffer(pubbuffer); - macbuffer.putInt32(privbuffer.length()); - macbuffer.putBuffer(privbuffer); - var hmac = forge.hmac.create(); - hmac.start("sha1", mackey); - hmac.update(macbuffer.bytes()); - ppk += "\r\nPrivate-MAC: " + hmac.digest().toHex() + "\r\n"; - return ppk; - }; - ssh.publicKeyToOpenSSH = function(key, comment) { - var type2 = "ssh-rsa"; - comment = comment || ""; - var buffer = forge.util.createBuffer(); - _addStringToBuffer(buffer, type2); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - return type2 + " " + forge.util.encode64(buffer.bytes()) + " " + comment; - }; - ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { - if (!passphrase) { - return forge.pki.privateKeyToPem(privateKey); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return forge.pki.encryptRsaPrivateKey( - privateKey, - passphrase, - { legacy: true, algorithm: "aes128" } - ); - }; - ssh.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge.md.md5.create(); - var type2 = "ssh-rsa"; - var buffer = forge.util.createBuffer(); - _addStringToBuffer(buffer, type2); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - md.start(); - md.update(buffer.getBytes()); - var digest = md.digest(); - if (options.encoding === "hex") { - var hex = digest.toHex(); - if (options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - return hex; - } else if (options.encoding === "binary") { - return digest.getBytes(); - } else if (options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; } - return digest; - }; - function _addBigIntegerToBuffer(buffer, val2) { - var hexVal = val2.toString(16); - if (hexVal[0] >= "8") { - hexVal = "00" + hexVal; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - var bytes = forge.util.hexToBytes(hexVal); - buffer.putInt32(bytes.length); - buffer.putBytes(bytes); - } - function _addStringToBuffer(buffer, val2) { - buffer.putInt32(val2.length); - buffer.putString(val2); - } - function _sha1() { - var sha = forge.md.sha1.create(); - var num = arguments.length; - for (var i = 0; i < num; ++i) { - sha.update(arguments[i]); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - return sha.digest(); - } - } -}); - -// node_modules/node-forge/lib/index.js -var require_lib2 = __commonJS({ - "node_modules/node-forge/lib/index.js"(exports2, module2) { - module2.exports = require_forge(); - require_aes(); - require_aesCipherSuites(); - require_asn1(); - require_cipher(); - require_des(); - require_ed25519(); - require_hmac(); - require_kem(); - require_log(); - require_md_all(); - require_mgf1(); - require_pbkdf2(); - require_pem(); - require_pkcs1(); - require_pkcs12(); - require_pkcs7(); - require_pki(); - require_prime(); - require_prng(); - require_pss(); - require_random(); - require_rc2(); - require_ssh(); - require_tls(); - require_util8(); - } -}); - -// node_modules/@actions/github/lib/context.js -var require_context = __commonJS({ - "node_modules/@actions/github/lib/context.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Context = void 0; - var fs_1 = require("fs"); - var os_1 = require("os"); - var Context = class { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: "utf8" })); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - const path2 = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path2} does not exist${os_1.EOL}`); + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/"); - return { owner, repo }; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; + if (proxyAgent) { + return proxyAgent; } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); } }; - exports2.Context = Context; + exports2.HttpClient = HttpClient; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -40401,7 +41803,7 @@ var require_utils3 = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + var httpClient = __importStar4(require_lib4()); var undici_1 = require_undici(); function getAuthString(token, options) { if (!token && !options.auth) { @@ -45035,7 +46437,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -47908,7 +49310,7 @@ var require_validator = __commonJS({ }); // node_modules/jsonschema/lib/index.js -var require_lib3 = __commonJS({ +var require_lib5 = __commonJS({ "node_modules/jsonschema/lib/index.js"(exports2, module2) { "use strict"; var Validator2 = module2.exports.Validator = require_validator(); @@ -49756,1091 +51158,2002 @@ var require_semver3 = __commonJS({ re[i] = new RegExp(src[i]); safeRe[i] = new RegExp(makeSafeRe(src[i])); } - } - var i; - exports2.parse = parse; - function parse(version, options) { + } + var i; + exports2.parse = parse; + function parse(version, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (version instanceof SemVer) { + return version; + } + if (typeof version !== "string") { + return null; + } + if (version.length > MAX_LENGTH) { + return null; + } + var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]; + if (!r.test(version)) { + return null; + } + try { + return new SemVer(version, options); + } catch (er) { + return null; + } + } + exports2.valid = valid2; + function valid2(version, options) { + var v = parse(version, options); + return v ? v.version : null; + } + exports2.clean = clean; + function clean(version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ""), options); + return s ? s.version : null; + } + exports2.SemVer = SemVer; + function SemVer(version, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== "string") { + throw new TypeError("Invalid Version: " + version); + } + if (version.length > MAX_LENGTH) { + throw new TypeError("version is longer than " + MAX_LENGTH + " characters"); + } + if (!(this instanceof SemVer)) { + return new SemVer(version, options); + } + debug5("SemVer", version, options); + this.options = options; + this.loose = !!options.loose; + var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]); + if (!m) { + throw new TypeError("Invalid Version: " + version); + } + this.raw = version; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split(".").map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + return id; + }); + } + this.build = m[5] ? m[5].split(".") : []; + this.format(); + } + SemVer.prototype.format = function() { + this.version = this.major + "." + this.minor + "." + this.patch; + if (this.prerelease.length) { + this.version += "-" + this.prerelease.join("."); + } + return this.version; + }; + SemVer.prototype.toString = function() { + return this.version; + }; + SemVer.prototype.compare = function(other) { + debug5("SemVer.compare", this.version, this.options, other); + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + return this.compareMain(other) || this.comparePre(other); + }; + SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + }; + SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + var i2 = 0; + do { + var a = this.prerelease[i2]; + var b = other.prerelease[i2]; + debug5("prerelease compare", i2, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i2); + }; + SemVer.prototype.compareBuild = function(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + var i2 = 0; + do { + var a = this.build[i2]; + var b = other.build[i2]; + debug5("prerelease compare", i2, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i2); + }; + SemVer.prototype.inc = function(release2, identifier) { + switch (release2) { + case "premajor": + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc("pre", identifier); + break; + case "preminor": + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc("pre", identifier); + break; + case "prepatch": + this.prerelease.length = 0; + this.inc("patch", identifier); + this.inc("pre", identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case "prerelease": + if (this.prerelease.length === 0) { + this.inc("patch", identifier); + } + this.inc("pre", identifier); + break; + case "major": + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case "minor": + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break; + case "patch": + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case "pre": + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + var i2 = this.prerelease.length; + while (--i2 >= 0) { + if (typeof this.prerelease[i2] === "number") { + this.prerelease[i2]++; + i2 = -2; + } + } + if (i2 === -1) { + this.prerelease.push(0); + } + } + if (identifier) { + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + break; + default: + throw new Error("invalid increment argument: " + release2); + } + this.format(); + this.raw = this.version; + return this; + }; + exports2.inc = inc; + function inc(version, release2, loose, identifier) { + if (typeof loose === "string") { + identifier = loose; + loose = void 0; + } + try { + return new SemVer(version, loose).inc(release2, identifier).version; + } catch (er) { + return null; + } + } + exports2.diff = diff; + function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + var prefix = ""; + if (v1.prerelease.length || v2.prerelease.length) { + prefix = "pre"; + var defaultResult = "prerelease"; + } + for (var key in v1) { + if (key === "major" || key === "minor" || key === "patch") { + if (v1[key] !== v2[key]) { + return prefix + key; + } + } + } + return defaultResult; + } + } + exports2.compareIdentifiers = compareIdentifiers; + var numeric = /^[0-9]+$/; + function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + if (anum && bnum) { + a = +a; + b = +b; + } + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + } + exports2.rcompareIdentifiers = rcompareIdentifiers; + function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); + } + exports2.major = major; + function major(a, loose) { + return new SemVer(a, loose).major; + } + exports2.minor = minor; + function minor(a, loose) { + return new SemVer(a, loose).minor; + } + exports2.patch = patch; + function patch(a, loose) { + return new SemVer(a, loose).patch; + } + exports2.compare = compare; + function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); + } + exports2.compareLoose = compareLoose; + function compareLoose(a, b) { + return compare(a, b, true); + } + exports2.compareBuild = compareBuild; + function compareBuild(a, b, loose) { + var versionA = new SemVer(a, loose); + var versionB = new SemVer(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB); + } + exports2.rcompare = rcompare; + function rcompare(a, b, loose) { + return compare(b, a, loose); + } + exports2.sort = sort; + function sort(list, loose) { + return list.sort(function(a, b) { + return exports2.compareBuild(a, b, loose); + }); + } + exports2.rsort = rsort; + function rsort(list, loose) { + return list.sort(function(a, b) { + return exports2.compareBuild(b, a, loose); + }); + } + exports2.gt = gt; + function gt(a, b, loose) { + return compare(a, b, loose) > 0; + } + exports2.lt = lt; + function lt(a, b, loose) { + return compare(a, b, loose) < 0; + } + exports2.eq = eq; + function eq(a, b, loose) { + return compare(a, b, loose) === 0; + } + exports2.neq = neq; + function neq(a, b, loose) { + return compare(a, b, loose) !== 0; + } + exports2.gte = gte3; + function gte3(a, b, loose) { + return compare(a, b, loose) >= 0; + } + exports2.lte = lte; + function lte(a, b, loose) { + return compare(a, b, loose) <= 0; + } + exports2.cmp = cmp; + function cmp(a, op, b, loose) { + switch (op) { + case "===": + if (typeof a === "object") + a = a.version; + if (typeof b === "object") + b = b.version; + return a === b; + case "!==": + if (typeof a === "object") + a = a.version; + if (typeof b === "object") + b = b.version; + return a !== b; + case "": + case "=": + case "==": + return eq(a, b, loose); + case "!=": + return neq(a, b, loose); + case ">": + return gt(a, b, loose); + case ">=": + return gte3(a, b, loose); + case "<": + return lt(a, b, loose); + case "<=": + return lte(a, b, loose); + default: + throw new TypeError("Invalid operator: " + op); + } + } + exports2.Comparator = Comparator; + function Comparator(comp, options) { + if (!options || typeof options !== "object") { + options = { + loose: !!options, + includePrerelease: false + }; + } + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + if (!(this instanceof Comparator)) { + return new Comparator(comp, options); + } + comp = comp.trim().split(/\s+/).join(" "); + debug5("comparator", comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + if (this.semver === ANY) { + this.value = ""; + } else { + this.value = this.operator + this.semver.version; + } + debug5("comp", this); + } + var ANY = {}; + Comparator.prototype.parse = function(comp) { + var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; + var m = comp.match(r); + if (!m) { + throw new TypeError("Invalid comparator: " + comp); + } + this.operator = m[1] !== void 0 ? m[1] : ""; + if (this.operator === "=") { + this.operator = ""; + } + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + }; + Comparator.prototype.toString = function() { + return this.value; + }; + Comparator.prototype.test = function(version) { + debug5("Comparator.test", version, this.options.loose); + if (this.semver === ANY || version === ANY) { + return true; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + return cmp(version, this.operator, this.semver, this.options); + }; + Comparator.prototype.intersects = function(comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError("a Comparator is required"); + } if (!options || typeof options !== "object") { options = { loose: !!options, includePrerelease: false }; } - if (version instanceof SemVer) { - return version; - } - if (typeof version !== "string") { - return null; - } - if (version.length > MAX_LENGTH) { - return null; - } - var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]; - if (!r.test(version)) { - return null; - } - try { - return new SemVer(version, options); - } catch (er) { - return null; + var rangeTmp; + if (this.operator === "") { + if (this.value === "") { + return true; + } + rangeTmp = new Range2(comp.value, options); + return satisfies2(this.value, rangeTmp, options); + } else if (comp.operator === "") { + if (comp.value === "") { + return true; + } + rangeTmp = new Range2(this.value, options); + return satisfies2(comp.semver, rangeTmp, options); } - } - exports2.valid = valid2; - function valid2(version, options) { - var v = parse(version, options); - return v ? v.version : null; - } - exports2.clean = clean; - function clean(version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ""), options); - return s ? s.version : null; - } - exports2.SemVer = SemVer; - function SemVer(version, options) { + var sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">"); + var sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<"); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<="); + var oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && ((this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<")); + var oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && ((this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">")); + return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; + }; + exports2.Range = Range2; + function Range2(range, options) { if (!options || typeof options !== "object") { options = { loose: !!options, includePrerelease: false }; } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version; + if (range instanceof Range2) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; } else { - version = version.version; + return new Range2(range.raw, options); } - } else if (typeof version !== "string") { - throw new TypeError("Invalid Version: " + version); } - if (version.length > MAX_LENGTH) { - throw new TypeError("version is longer than " + MAX_LENGTH + " characters"); + if (range instanceof Comparator) { + return new Range2(range.value, options); } - if (!(this instanceof SemVer)) { - return new SemVer(version, options); + if (!(this instanceof Range2)) { + return new Range2(range, options); } - debug5("SemVer", version, options); this.options = options; this.loose = !!options.loose; - var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]); - if (!m) { - throw new TypeError("Invalid Version: " + version); - } - this.raw = version; - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError("Invalid major version"); - } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError("Invalid minor version"); - } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError("Invalid patch version"); - } - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split(".").map(function(id) { - if (/^[0-9]+$/.test(id)) { - var num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num; - } - } - return id; - }); + this.includePrerelease = !!options.includePrerelease; + this.raw = range.trim().split(/\s+/).join(" "); + this.set = this.raw.split("||").map(function(range2) { + return this.parseRange(range2.trim()); + }, this).filter(function(c) { + return c.length; + }); + if (!this.set.length) { + throw new TypeError("Invalid SemVer Range: " + this.raw); } - this.build = m[5] ? m[5].split(".") : []; this.format(); } - SemVer.prototype.format = function() { - this.version = this.major + "." + this.minor + "." + this.patch; - if (this.prerelease.length) { - this.version += "-" + this.prerelease.join("."); - } - return this.version; - }; - SemVer.prototype.toString = function() { - return this.version; + Range2.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(" ").trim(); + }).join("||").trim(); + return this.range; }; - SemVer.prototype.compare = function(other) { - debug5("SemVer.compare", this.version, this.options, other); - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - return this.compareMain(other) || this.comparePre(other); + Range2.prototype.toString = function() { + return this.range; }; - SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); + Range2.prototype.parseRange = function(range) { + var loose = this.options.loose; + var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug5("hyphen replace", range); + range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace); + debug5("comparator trim", range, safeRe[t.COMPARATORTRIM]); + range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace); + range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace); + range = range.split(/\s+/).join(" "); + var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; + var set2 = range.split(" ").map(function(comp) { + return parseComparator(comp, this.options); + }, this).join(" ").split(/\s+/); + if (this.options.loose) { + set2 = set2.filter(function(comp) { + return !!comp.match(compRe); + }); } - return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + set2 = set2.map(function(comp) { + return new Comparator(comp, this.options); + }, this); + return set2; }; - SemVer.prototype.comparePre = function(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - if (this.prerelease.length && !other.prerelease.length) { - return -1; - } else if (!this.prerelease.length && other.prerelease.length) { - return 1; - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0; + Range2.prototype.intersects = function(range, options) { + if (!(range instanceof Range2)) { + throw new TypeError("a Range is required"); } - var i2 = 0; - do { - var a = this.prerelease[i2]; - var b = other.prerelease[i2]; - debug5("prerelease compare", i2, a, b); - if (a === void 0 && b === void 0) { - return 0; - } else if (b === void 0) { - return 1; - } else if (a === void 0) { - return -1; - } else if (a === b) { - continue; - } else { - return compareIdentifiers(a, b); - } - } while (++i2); + return this.set.some(function(thisComparators) { + return isSatisfiable(thisComparators, options) && range.set.some(function(rangeComparators) { + return isSatisfiable(rangeComparators, options) && thisComparators.every(function(thisComparator) { + return rangeComparators.every(function(rangeComparator) { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); }; - SemVer.prototype.compareBuild = function(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); + function isSatisfiable(comparators, options) { + var result = true; + var remainingComparators = comparators.slice(); + var testComparator = remainingComparators.pop(); + while (result && remainingComparators.length) { + result = remainingComparators.every(function(otherComparator) { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); } - var i2 = 0; - do { - var a = this.build[i2]; - var b = other.build[i2]; - debug5("prerelease compare", i2, a, b); - if (a === void 0 && b === void 0) { - return 0; - } else if (b === void 0) { - return 1; - } else if (a === void 0) { - return -1; - } else if (a === b) { - continue; + return result; + } + exports2.toComparators = toComparators; + function toComparators(range, options) { + return new Range2(range, options).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(" ").trim().split(" "); + }); + } + function parseComparator(comp, options) { + debug5("comp", comp, options); + comp = replaceCarets(comp, options); + debug5("caret", comp); + comp = replaceTildes(comp, options); + debug5("tildes", comp); + comp = replaceXRanges(comp, options); + debug5("xrange", comp); + comp = replaceStars(comp, options); + debug5("stars", comp); + return comp; + } + function isX(id) { + return !id || id.toLowerCase() === "x" || id === "*"; + } + function replaceTildes(comp, options) { + return comp.trim().split(/\s+/).map(function(comp2) { + return replaceTilde(comp2, options); + }).join(" "); + } + function replaceTilde(comp, options) { + var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug5("tilde", comp, _, M, m, p, pr); + var ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; + } else if (isX(p)) { + ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; + } else if (pr) { + debug5("replaceTilde pr", pr); + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; } else { - return compareIdentifiers(a, b); + ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; } - } while (++i2); - }; - SemVer.prototype.inc = function(release2, identifier) { - switch (release2) { - case "premajor": - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc("pre", identifier); - break; - case "preminor": - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc("pre", identifier); - break; - case "prepatch": - this.prerelease.length = 0; - this.inc("patch", identifier); - this.inc("pre", identifier); - break; - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case "prerelease": - if (this.prerelease.length === 0) { - this.inc("patch", identifier); - } - this.inc("pre", identifier); - break; - case "major": - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { - this.major++; + debug5("tilde return", ret); + return ret; + }); + } + function replaceCarets(comp, options) { + return comp.trim().split(/\s+/).map(function(comp2) { + return replaceCaret(comp2, options); + }).join(" "); + } + function replaceCaret(comp, options) { + debug5("caret", comp, options); + var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug5("caret", comp, _, M, m, p, pr); + var ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; + } else if (isX(p)) { + if (M === "0") { + ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; + } else { + ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0"; } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case "minor": - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; + } else if (pr) { + debug5("replaceCaret pr", pr); + if (M === "0") { + if (m === "0") { + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1); + } else { + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; + } + } else { + ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0"; } - this.patch = 0; - this.prerelease = []; - break; - case "patch": - if (this.prerelease.length === 0) { - this.patch++; + } else { + debug5("no pr"); + if (M === "0") { + if (m === "0") { + ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1); + } else { + ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; + } + } else { + ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0"; } - this.prerelease = []; - break; - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case "pre": - if (this.prerelease.length === 0) { - this.prerelease = [0]; + } + debug5("caret return", ret); + return ret; + }); + } + function replaceXRanges(comp, options) { + debug5("replaceXRanges", comp, options); + return comp.split(/\s+/).map(function(comp2) { + return replaceXRange(comp2, options); + }).join(" "); + } + function replaceXRange(comp, options) { + comp = comp.trim(); + var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug5("xRange", comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret = "<0.0.0-0"; } else { - var i2 = this.prerelease.length; - while (--i2 >= 0) { - if (typeof this.prerelease[i2] === "number") { - this.prerelease[i2]++; - i2 = -2; - } + ret = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + p = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; } - if (i2 === -1) { - this.prerelease.push(0); + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; } } - if (identifier) { - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; + ret = gtlt + M + "." + m + "." + p + pr; + } else if (xm) { + ret = ">=" + M + ".0.0" + pr + " <" + (+M + 1) + ".0.0" + pr; + } else if (xp) { + ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr; + } + debug5("xRange return", ret); + return ret; + }); + } + function replaceStars(comp, options) { + debug5("replaceStars", comp, options); + return comp.trim().replace(safeRe[t.STAR], ""); + } + function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = ">=" + fM + ".0.0"; + } else if (isX(fp)) { + from = ">=" + fM + "." + fm + ".0"; + } else { + from = ">=" + from; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = "<" + (+tM + 1) + ".0.0"; + } else if (isX(tp)) { + to = "<" + tM + "." + (+tm + 1) + ".0"; + } else if (tpr) { + to = "<=" + tM + "." + tm + "." + tp + "-" + tpr; + } else { + to = "<=" + to; + } + return (from + " " + to).trim(); + } + Range2.prototype.test = function(version) { + if (!version) { + return false; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + for (var i2 = 0; i2 < this.set.length; i2++) { + if (testSet(this.set[i2], version, this.options)) { + return true; + } + } + return false; + }; + function testSet(set2, version, options) { + for (var i2 = 0; i2 < set2.length; i2++) { + if (!set2[i2].test(version)) { + return false; + } + } + if (version.prerelease.length && !options.includePrerelease) { + for (i2 = 0; i2 < set2.length; i2++) { + debug5(set2[i2].semver); + if (set2[i2].semver === ANY) { + continue; + } + if (set2[i2].semver.prerelease.length > 0) { + var allowed = set2[i2].semver; + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; } } - break; - default: - throw new Error("invalid increment argument: " + release2); + } + return false; } - this.format(); - this.raw = this.version; - return this; - }; - exports2.inc = inc; - function inc(version, release2, loose, identifier) { - if (typeof loose === "string") { - identifier = loose; - loose = void 0; + return true; + } + exports2.satisfies = satisfies2; + function satisfies2(version, range, options) { + try { + range = new Range2(range, options); + } catch (er) { + return false; } + return range.test(version); + } + exports2.maxSatisfying = maxSatisfying; + function maxSatisfying(versions, range, options) { + var max = null; + var maxSV = null; try { - return new SemVer(version, loose).inc(release2, identifier).version; + var rangeObj = new Range2(range, options); } catch (er) { return null; } + versions.forEach(function(v) { + if (rangeObj.test(v)) { + if (!max || maxSV.compare(v) === -1) { + max = v; + maxSV = new SemVer(max, options); + } + } + }); + return max; } - exports2.diff = diff; - function diff(version1, version2) { - if (eq(version1, version2)) { + exports2.minSatisfying = minSatisfying; + function minSatisfying(versions, range, options) { + var min = null; + var minSV = null; + try { + var rangeObj = new Range2(range, options); + } catch (er) { return null; - } else { - var v1 = parse(version1); - var v2 = parse(version2); - var prefix = ""; - if (v1.prerelease.length || v2.prerelease.length) { - prefix = "pre"; - var defaultResult = "prerelease"; - } - for (var key in v1) { - if (key === "major" || key === "minor" || key === "patch") { - if (v1[key] !== v2[key]) { - return prefix + key; - } + } + versions.forEach(function(v) { + if (rangeObj.test(v)) { + if (!min || minSV.compare(v) === 1) { + min = v; + minSV = new SemVer(min, options); } } - return defaultResult; + }); + return min; + } + exports2.minVersion = minVersion; + function minVersion(range, loose) { + range = new Range2(range, loose); + var minver = new SemVer("0.0.0"); + if (range.test(minver)) { + return minver; + } + minver = new SemVer("0.0.0-0"); + if (range.test(minver)) { + return minver; + } + minver = null; + for (var i2 = 0; i2 < range.set.length; ++i2) { + var comparators = range.set[i2]; + comparators.forEach(function(comparator) { + var compver = new SemVer(comparator.semver.version); + switch (comparator.operator) { + case ">": + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case "": + case ">=": + if (!minver || gt(minver, compver)) { + minver = compver; + } + break; + case "<": + case "<=": + break; + /* istanbul ignore next */ + default: + throw new Error("Unexpected operation: " + comparator.operator); + } + }); + } + if (minver && range.test(minver)) { + return minver; } + return null; } - exports2.compareIdentifiers = compareIdentifiers; - var numeric = /^[0-9]+$/; - function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); - if (anum && bnum) { - a = +a; - b = +b; + exports2.validRange = validRange; + function validRange(range, options) { + try { + return new Range2(range, options).range || "*"; + } catch (er) { + return null; } - return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; } - exports2.rcompareIdentifiers = rcompareIdentifiers; - function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); + exports2.ltr = ltr; + function ltr(version, range, options) { + return outside(version, range, "<", options); } - exports2.major = major; - function major(a, loose) { - return new SemVer(a, loose).major; + exports2.gtr = gtr; + function gtr(version, range, options) { + return outside(version, range, ">", options); } - exports2.minor = minor; - function minor(a, loose) { - return new SemVer(a, loose).minor; + exports2.outside = outside; + function outside(version, range, hilo, options) { + version = new SemVer(version, options); + range = new Range2(range, options); + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case ">": + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = ">"; + ecomp = ">="; + break; + case "<": + gtfn = lt; + ltefn = gte3; + ltfn = gt; + comp = "<"; + ecomp = "<="; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + if (satisfies2(version, range, options)) { + return false; + } + for (var i2 = 0; i2 < range.set.length; ++i2) { + var comparators = range.set[i2]; + var high = null; + var low = null; + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator(">=0.0.0"); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + if (high.operator === comp || high.operator === ecomp) { + return false; + } + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; } - exports2.patch = patch; - function patch(a, loose) { - return new SemVer(a, loose).patch; + exports2.prerelease = prerelease; + function prerelease(version, options) { + var parsed = parse(version, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; } - exports2.compare = compare; - function compare(a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)); + exports2.intersects = intersects; + function intersects(r1, r2, options) { + r1 = new Range2(r1, options); + r2 = new Range2(r2, options); + return r1.intersects(r2); } - exports2.compareLoose = compareLoose; - function compareLoose(a, b) { - return compare(a, b, true); + exports2.coerce = coerce2; + function coerce2(version, options) { + if (version instanceof SemVer) { + return version; + } + if (typeof version === "number") { + version = String(version); + } + if (typeof version !== "string") { + return null; + } + options = options || {}; + var match = null; + if (!options.rtl) { + match = version.match(safeRe[t.COERCE]); + } else { + var next; + while ((next = safeRe[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + safeRe[t.COERCERTL].lastIndex = -1; + } + if (match === null) { + return null; + } + return parse(match[2] + "." + (match[3] || "0") + "." + (match[4] || "0"), options); } - exports2.compareBuild = compareBuild; - function compareBuild(a, b, loose) { - var versionA = new SemVer(a, loose); - var versionB = new SemVer(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB); + } +}); + +// node_modules/@actions/cache/lib/internal/constants.js +var require_constants7 = __commonJS({ + "node_modules/@actions/cache/lib/internal/constants.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheFileSizeLimit = exports2.ManifestFilename = exports2.TarFilename = exports2.SystemTarPathOnWindows = exports2.GnuTarPathOnWindows = exports2.SocketTimeout = exports2.DefaultRetryDelay = exports2.DefaultRetryAttempts = exports2.ArchiveToolType = exports2.CompressionMethod = exports2.CacheFilename = void 0; + var CacheFilename; + (function(CacheFilename2) { + CacheFilename2["Gzip"] = "cache.tgz"; + CacheFilename2["Zstd"] = "cache.tzst"; + })(CacheFilename || (exports2.CacheFilename = CacheFilename = {})); + var CompressionMethod; + (function(CompressionMethod2) { + CompressionMethod2["Gzip"] = "gzip"; + CompressionMethod2["ZstdWithoutLong"] = "zstd-without-long"; + CompressionMethod2["Zstd"] = "zstd"; + })(CompressionMethod || (exports2.CompressionMethod = CompressionMethod = {})); + var ArchiveToolType; + (function(ArchiveToolType2) { + ArchiveToolType2["GNU"] = "gnu"; + ArchiveToolType2["BSD"] = "bsd"; + })(ArchiveToolType || (exports2.ArchiveToolType = ArchiveToolType = {})); + exports2.DefaultRetryAttempts = 2; + exports2.DefaultRetryDelay = 5e3; + exports2.SocketTimeout = 5e3; + exports2.GnuTarPathOnWindows = `${process.env["PROGRAMFILES"]}\\Git\\usr\\bin\\tar.exe`; + exports2.SystemTarPathOnWindows = `${process.env["SYSTEMDRIVE"]}\\Windows\\System32\\tar.exe`; + exports2.TarFilename = "cache.tar"; + exports2.ManifestFilename = "manifest.txt"; + exports2.CacheFileSizeLimit = 10 * Math.pow(1024, 3); + } +}); + +// node_modules/@actions/cache/lib/internal/cacheUtils.js +var require_cacheUtils = __commonJS({ + "node_modules/@actions/cache/lib/internal/cacheUtils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); + }); + }; + } + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRuntimeToken = exports2.getCacheVersion = exports2.assertDefined = exports2.getGnuTarPathOnWindows = exports2.getCacheFileName = exports2.getCompressionMethod = exports2.unlinkFile = exports2.resolvePaths = exports2.getArchiveFileSizeInBytes = exports2.createTempDirectory = void 0; + var core12 = __importStar4(require_core()); + var exec2 = __importStar4(require_exec()); + var glob = __importStar4(require_glob()); + var io4 = __importStar4(require_io()); + var crypto = __importStar4(require("crypto")); + var fs = __importStar4(require("fs")); + var path2 = __importStar4(require("path")); + var semver5 = __importStar4(require_semver3()); + var util = __importStar4(require("util")); + var constants_1 = require_constants7(); + var versionSalt = "1.0"; + function createTempDirectory() { + return __awaiter4(this, void 0, void 0, function* () { + const IS_WINDOWS = process.platform === "win32"; + let tempDirectory = process.env["RUNNER_TEMP"] || ""; + if (!tempDirectory) { + let baseLocation; + if (IS_WINDOWS) { + baseLocation = process.env["USERPROFILE"] || "C:\\"; + } else { + if (process.platform === "darwin") { + baseLocation = "/Users"; + } else { + baseLocation = "/home"; + } + } + tempDirectory = path2.join(baseLocation, "actions", "temp"); + } + const dest = path2.join(tempDirectory, crypto.randomUUID()); + yield io4.mkdirP(dest); + return dest; + }); } - exports2.rcompare = rcompare; - function rcompare(a, b, loose) { - return compare(b, a, loose); + exports2.createTempDirectory = createTempDirectory; + function getArchiveFileSizeInBytes(filePath) { + return fs.statSync(filePath).size; } - exports2.sort = sort; - function sort(list, loose) { - return list.sort(function(a, b) { - return exports2.compareBuild(a, b, loose); + exports2.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; + function resolvePaths(patterns) { + var _a, e_1, _b, _c; + var _d; + return __awaiter4(this, void 0, void 0, function* () { + const paths = []; + const workspace = (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd(); + const globber = yield glob.create(patterns.join("\n"), { + implicitDescendants: false + }); + try { + for (var _e = true, _f = __asyncValues4(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { + _c = _g.value; + _e = false; + const file = _c; + const relativeFile = path2.relative(workspace, file).replace(new RegExp(`\\${path2.sep}`, "g"), "/"); + core12.debug(`Matched: ${relativeFile}`); + if (relativeFile === "") { + paths.push("."); + } else { + paths.push(`${relativeFile}`); + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); + } finally { + if (e_1) throw e_1.error; + } + } + return paths; }); } - exports2.rsort = rsort; - function rsort(list, loose) { - return list.sort(function(a, b) { - return exports2.compareBuild(b, a, loose); + exports2.resolvePaths = resolvePaths; + function unlinkFile(filePath) { + return __awaiter4(this, void 0, void 0, function* () { + return util.promisify(fs.unlink)(filePath); }); } - exports2.gt = gt; - function gt(a, b, loose) { - return compare(a, b, loose) > 0; + exports2.unlinkFile = unlinkFile; + function getVersion(app, additionalArgs = []) { + return __awaiter4(this, void 0, void 0, function* () { + let versionOutput = ""; + additionalArgs.push("--version"); + core12.debug(`Checking ${app} ${additionalArgs.join(" ")}`); + try { + yield exec2.exec(`${app}`, additionalArgs, { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + } catch (err) { + core12.debug(err.message); + } + versionOutput = versionOutput.trim(); + core12.debug(versionOutput); + return versionOutput; + }); } - exports2.lt = lt; - function lt(a, b, loose) { - return compare(a, b, loose) < 0; + function getCompressionMethod() { + return __awaiter4(this, void 0, void 0, function* () { + const versionOutput = yield getVersion("zstd", ["--quiet"]); + const version = semver5.clean(versionOutput); + core12.debug(`zstd version: ${version}`); + if (versionOutput === "") { + return constants_1.CompressionMethod.Gzip; + } else { + return constants_1.CompressionMethod.ZstdWithoutLong; + } + }); } - exports2.eq = eq; - function eq(a, b, loose) { - return compare(a, b, loose) === 0; + exports2.getCompressionMethod = getCompressionMethod; + function getCacheFileName(compressionMethod) { + return compressionMethod === constants_1.CompressionMethod.Gzip ? constants_1.CacheFilename.Gzip : constants_1.CacheFilename.Zstd; } - exports2.neq = neq; - function neq(a, b, loose) { - return compare(a, b, loose) !== 0; + exports2.getCacheFileName = getCacheFileName; + function getGnuTarPathOnWindows() { + return __awaiter4(this, void 0, void 0, function* () { + if (fs.existsSync(constants_1.GnuTarPathOnWindows)) { + return constants_1.GnuTarPathOnWindows; + } + const versionOutput = yield getVersion("tar"); + return versionOutput.toLowerCase().includes("gnu tar") ? io4.which("tar") : ""; + }); } - exports2.gte = gte3; - function gte3(a, b, loose) { - return compare(a, b, loose) >= 0; + exports2.getGnuTarPathOnWindows = getGnuTarPathOnWindows; + function assertDefined(name, value) { + if (value === void 0) { + throw Error(`Expected ${name} but value was undefiend`); + } + return value; } - exports2.lte = lte; - function lte(a, b, loose) { - return compare(a, b, loose) <= 0; + exports2.assertDefined = assertDefined; + function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) { + const components = paths.slice(); + if (compressionMethod) { + components.push(compressionMethod); + } + if (process.platform === "win32" && !enableCrossOsArchive) { + components.push("windows-only"); + } + components.push(versionSalt); + return crypto.createHash("sha256").update(components.join("|")).digest("hex"); } - exports2.cmp = cmp; - function cmp(a, op, b, loose) { - switch (op) { - case "===": - if (typeof a === "object") - a = a.version; - if (typeof b === "object") - b = b.version; - return a === b; - case "!==": - if (typeof a === "object") - a = a.version; - if (typeof b === "object") - b = b.version; - return a !== b; - case "": - case "=": - case "==": - return eq(a, b, loose); - case "!=": - return neq(a, b, loose); - case ">": - return gt(a, b, loose); - case ">=": - return gte3(a, b, loose); - case "<": - return lt(a, b, loose); - case "<=": - return lte(a, b, loose); - default: - throw new TypeError("Invalid operator: " + op); + exports2.getCacheVersion = getCacheVersion; + function getRuntimeToken() { + const token = process.env["ACTIONS_RUNTIME_TOKEN"]; + if (!token) { + throw new Error("Unable to get the ACTIONS_RUNTIME_TOKEN env variable"); } + return token; } - exports2.Comparator = Comparator; - function Comparator(comp, options) { - if (!options || typeof options !== "object") { - options = { - loose: !!options, - includePrerelease: false - }; + exports2.getRuntimeToken = getRuntimeToken; + } +}); + +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp; + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; } else { - comp = comp.value; + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - } - if (!(this instanceof Comparator)) { - return new Comparator(comp, options); - } - comp = comp.trim().split(/\s+/).join(" "); - debug5("comparator", comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - if (this.semver === ANY) { - this.value = ""; } else { - this.value = this.operator + this.semver.version; + return void 0; } - debug5("comp", this); } - var ANY = {}; - Comparator.prototype.parse = function(comp) { - var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; - var m = comp.match(r); - if (!m) { - throw new TypeError("Invalid comparator: " + comp); - } - this.operator = m[1] !== void 0 ? m[1] : ""; - if (this.operator === "=") { - this.operator = ""; - } - if (!m[2]) { - this.semver = ANY; - } else { - this.semver = new SemVer(m[2], this.options.loose); + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - }; - Comparator.prototype.toString = function() { - return this.value; - }; - Comparator.prototype.test = function(version) { - debug5("Comparator.test", version, this.options.loose); - if (this.semver === ANY || version === ANY) { + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { return true; } - if (typeof version === "string") { - try { - version = new SemVer(version, this.options); - } catch (er) { - return false; - } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - return cmp(version, this.operator, this.semver, this.options); - }; - Comparator.prototype.intersects = function(comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError("a Comparator is required"); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - if (!options || typeof options !== "object") { - options = { - loose: !!options, - includePrerelease: false - }; + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - var rangeTmp; - if (this.operator === "") { - if (this.value === "") { - return true; - } - rangeTmp = new Range2(comp.value, options); - return satisfies2(this.value, rangeTmp, options); - } else if (comp.operator === "") { - if (comp.value === "") { + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { return true; } - rangeTmp = new Range2(this.value, options); - return satisfies2(comp.semver, rangeTmp, options); } - var sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">"); - var sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<"); - var sameSemVer = this.semver.version === comp.semver.version; - var differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<="); - var oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && ((this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<")); - var oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && ((this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">")); - return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; - }; - exports2.Range = Range2; - function Range2(range, options) { - if (!options || typeof options !== "object") { - options = { - loose: !!options, - includePrerelease: false - }; + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - if (range instanceof Range2) { - if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { - return range; - } else { - return new Range2(range.raw, options); - } + get username() { + return this._decodedUsername; } - if (range instanceof Comparator) { - return new Range2(range.value, options); + get password() { + return this._decodedPassword; } - if (!(this instanceof Range2)) { - return new Range2(range, options); + }; + } +}); + +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib6 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - this.raw = range.trim().split(/\s+/).join(" "); - this.set = this.raw.split("||").map(function(range2) { - return this.parseRange(range2.trim()); - }, this).filter(function(c) { - return c.length; - }); - if (!this.set.length) { - throw new TypeError("Invalid SemVer Range: " + this.raw); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - this.format(); - } - Range2.prototype.format = function() { - this.range = this.set.map(function(comps) { - return comps.join(" ").trim(); - }).join("||").trim(); - return this.range; - }; - Range2.prototype.toString = function() { - return this.range; + __setModuleDefault4(result, mod); + return result; }; - Range2.prototype.parseRange = function(range) { - var loose = this.options.loose; - var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - debug5("hyphen replace", range); - range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace); - debug5("comparator trim", range, safeRe[t.COMPARATORTRIM]); - range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace); - range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace); - range = range.split(/\s+/).join(" "); - var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]; - var set2 = range.split(" ").map(function(comp) { - return parseComparator(comp, this.options); - }, this).join(" ").split(/\s+/); - if (this.options.loose) { - set2 = set2.filter(function(comp) { - return !!comp.match(compRe); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); }); } - set2 = set2.map(function(comp) { - return new Comparator(comp, this.options); - }, this); - return set2; + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - Range2.prototype.intersects = function(range, options) { - if (!(range instanceof Range2)) { - throw new TypeError("a Range is required"); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return this.set.some(function(thisComparators) { - return isSatisfiable(thisComparators, options) && range.set.some(function(rangeComparators) { - return isSatisfiable(rangeComparators, options) && thisComparators.every(function(thisComparator) { - return rangeComparators.every(function(rangeComparator) { - return thisComparator.intersects(rangeComparator, options); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); }); - }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); }); - }); - }; - function isSatisfiable(comparators, options) { - var result = true; - var remainingComparators = comparators.slice(); - var testComparator = remainingComparators.pop(); - while (result && remainingComparators.length) { - result = remainingComparators.every(function(otherComparator) { - return testComparator.intersects(otherComparator, options); + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); }); - testComparator = remainingComparators.pop(); } - return result; - } - exports2.toComparators = toComparators; - function toComparators(range, options) { - return new Range2(range, options).set.map(function(comp) { - return comp.map(function(c) { - return c.value; - }).join(" ").trim().split(" "); - }); - } - function parseComparator(comp, options) { - debug5("comp", comp, options); - comp = replaceCarets(comp, options); - debug5("caret", comp); - comp = replaceTildes(comp, options); - debug5("tildes", comp); - comp = replaceXRanges(comp, options); - debug5("xrange", comp); - comp = replaceStars(comp, options); - debug5("stars", comp); - return comp; - } - function isX(id) { - return !id || id.toLowerCase() === "x" || id === "*"; - } - function replaceTildes(comp, options) { - return comp.trim().split(/\s+/).map(function(comp2) { - return replaceTilde(comp2, options); - }).join(" "); - } - function replaceTilde(comp, options) { - var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - debug5("tilde", comp, _, M, m, p, pr); - var ret; - if (isX(M)) { - ret = ""; - } else if (isX(m)) { - ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; - } else if (isX(p)) { - ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; - } else if (pr) { - debug5("replaceTilde pr", pr); - ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; - } else { - ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; - } - debug5("tilde return", ret); - return ret; - }); - } - function replaceCarets(comp, options) { - return comp.trim().split(/\s+/).map(function(comp2) { - return replaceCaret(comp2, options); - }).join(" "); - } - function replaceCaret(comp, options) { - debug5("caret", comp, options); - var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - debug5("caret", comp, _, M, m, p, pr); - var ret; - if (isX(M)) { - ret = ""; - } else if (isX(m)) { - ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0"; - } else if (isX(p)) { - if (M === "0") { - ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0"; - } else { - ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0"; + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - } else if (pr) { - debug5("replaceCaret pr", pr); - if (M === "0") { - if (m === "0") { - ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1); - } else { - ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0"; - } - } else { - ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0"; + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } else { - debug5("no pr"); - if (M === "0") { - if (m === "0") { - ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1); - } else { - ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0"; - } - } else { - ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0"; + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } - debug5("caret return", ret); - return ret; - }); - } - function replaceXRanges(comp, options) { - debug5("replaceXRanges", comp, options); - return comp.split(/\s+/).map(function(comp2) { - return replaceXRange(comp2, options); - }).join(" "); - } - function replaceXRange(comp, options) { - comp = comp.trim(); - var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - debug5("xRange", comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; - if (gtlt === "=" && anyX) { - gtlt = ""; - } - pr = options.includePrerelease ? "-0" : ""; - if (xM) { - if (gtlt === ">" || gtlt === "<") { - ret = "<0.0.0-0"; - } else { - ret = "*"; + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } - } else if (gtlt && anyX) { - if (xm) { - m = 0; + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; } - p = 0; - if (gtlt === ">") { - gtlt = ">="; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === "<=") { - gtlt = "<"; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } - ret = gtlt + M + "." + m + "." + p + pr; - } else if (xm) { - ret = ">=" + M + ".0.0" + pr + " <" + (+M + 1) + ".0.0" + pr; - } else if (xp) { - ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr; } - debug5("xRange return", ret); - return ret; - }); - } - function replaceStars(comp, options) { - debug5("replaceStars", comp, options); - return comp.trim().replace(safeRe[t.STAR], ""); - } - function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = ""; - } else if (isX(fm)) { - from = ">=" + fM + ".0.0"; - } else if (isX(fp)) { - from = ">=" + fM + "." + fm + ".0"; - } else { - from = ">=" + from; } - if (isX(tM)) { - to = ""; - } else if (isX(tm)) { - to = "<" + (+tM + 1) + ".0.0"; - } else if (isX(tp)) { - to = "<" + tM + "." + (+tm + 1) + ".0"; - } else if (tpr) { - to = "<=" + tM + "." + tm + "." + tp + "-" + tpr; - } else { - to = "<=" + to; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - return (from + " " + to).trim(); - } - Range2.prototype.test = function(version) { - if (!version) { - return false; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (typeof version === "string") { - try { - version = new SemVer(version, this.options); - } catch (er) { - return false; - } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - for (var i2 = 0; i2 < this.set.length; i2++) { - if (testSet(this.set[i2], version, this.options)) { - return true; - } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - return false; - }; - function testSet(set2, version, options) { - for (var i2 = 0; i2 < set2.length; i2++) { - if (!set2[i2].test(version)) { - return false; - } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - if (version.prerelease.length && !options.includePrerelease) { - for (i2 = 0; i2 < set2.length; i2++) { - debug5(set2[i2].semver); - if (set2[i2].semver === ANY) { - continue; - } - if (set2[i2].semver.prerelease.length > 0) { - var allowed = set2[i2].semver; - if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { - return true; - } - } - } - return false; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return true; - } - exports2.satisfies = satisfies2; - function satisfies2(version, range, options) { - try { - range = new Range2(range, options); - } catch (er) { - return false; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return range.test(version); - } - exports2.maxSatisfying = maxSatisfying; - function maxSatisfying(versions, range, options) { - var max = null; - var maxSV = null; - try { - var rangeObj = new Range2(range, options); - } catch (er) { - return null; + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - versions.forEach(function(v) { - if (rangeObj.test(v)) { - if (!max || maxSV.compare(v) === -1) { - max = v; - maxSV = new SemVer(max, options); - } - } - }); - return max; - } - exports2.minSatisfying = minSatisfying; - function minSatisfying(versions, range, options) { - var min = null; - var minSV = null; - try { - var rangeObj = new Range2(range, options); - } catch (er) { - return null; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - versions.forEach(function(v) { - if (rangeObj.test(v)) { - if (!min || minSV.compare(v) === 1) { - min = v; - minSV = new SemVer(min, options); - } - } - }); - return min; - } - exports2.minVersion = minVersion; - function minVersion(range, loose) { - range = new Range2(range, loose); - var minver = new SemVer("0.0.0"); - if (range.test(minver)) { - return minver; + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - minver = new SemVer("0.0.0-0"); - if (range.test(minver)) { - return minver; + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - minver = null; - for (var i2 = 0; i2 < range.set.length; ++i2) { - var comparators = range.set[i2]; - comparators.forEach(function(comparator) { - var compver = new SemVer(comparator.semver.version); - switch (comparator.operator) { - case ">": - if (compver.prerelease.length === 0) { - compver.patch++; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); } else { - compver.prerelease.push(0); + return response; } - compver.raw = compver.format(); - /* fallthrough */ - case "": - case ">=": - if (!minver || gt(minver, compver)) { - minver = compver; + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; } - break; - case "<": - case "<=": - break; - /* istanbul ignore next */ - default: - throw new Error("Unexpected operation: " + comparator.operator); - } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); } - if (minver && range.test(minver)) { - return minver; - } - return null; - } - exports2.validRange = validRange; - function validRange(range, options) { - try { - return new Range2(range, options).range || "*"; - } catch (er) { - return null; - } - } - exports2.ltr = ltr; - function ltr(version, range, options) { - return outside(version, range, "<", options); - } - exports2.gtr = gtr; - function gtr(version, range, options) { - return outside(version, range, ">", options); - } - exports2.outside = outside; - function outside(version, range, hilo, options) { - version = new SemVer(version, options); - range = new Range2(range, options); - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case ">": - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = ">"; - ecomp = ">="; - break; - case "<": - gtfn = lt; - ltefn = gte3; - ltfn = gt; - comp = "<"; - ecomp = "<="; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; } - if (satisfies2(version, range, options)) { - return false; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); } - for (var i2 = 0; i2 < range.set.length; ++i2) { - var comparators = range.set[i2]; - var high = null; - var low = null; - comparators.forEach(function(comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator(">=0.0.0"); + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); }); - if (high.operator === comp || high.operator === ecomp) { - return false; + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return true; - } - exports2.prerelease = prerelease; - function prerelease(version, options) { - var parsed = parse(version, options); - return parsed && parsed.prerelease.length ? parsed.prerelease : null; - } - exports2.intersects = intersects; - function intersects(r1, r2, options) { - r1 = new Range2(r1, options); - r2 = new Range2(r2, options); - return r1.intersects(r2); - } - exports2.coerce = coerce2; - function coerce2(version, options) { - if (version instanceof SemVer) { - return version; + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; } - if (typeof version === "number") { - version = String(version); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - if (typeof version !== "string") { - return null; + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - options = options || {}; - var match = null; - if (!options.rtl) { - match = version.match(safeRe[t.COERCE]); - } else { - var next; - while ((next = safeRe[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) { - if (!match || next.index + next[0].length !== match.index + match[0].length) { - match = next; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } - safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - safeRe[t.COERCERTL].lastIndex = -1; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - if (match === null) { - return null; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - return parse(match[2] + "." + (match[3] || "0") + "." + (match[4] || "0"), options); - } - } -}); - -// node_modules/@actions/cache/lib/internal/constants.js -var require_constants7 = __commonJS({ - "node_modules/@actions/cache/lib/internal/constants.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheFileSizeLimit = exports2.ManifestFilename = exports2.TarFilename = exports2.SystemTarPathOnWindows = exports2.GnuTarPathOnWindows = exports2.SocketTimeout = exports2.DefaultRetryDelay = exports2.DefaultRetryAttempts = exports2.ArchiveToolType = exports2.CompressionMethod = exports2.CacheFilename = void 0; - var CacheFilename; - (function(CacheFilename2) { - CacheFilename2["Gzip"] = "cache.tgz"; - CacheFilename2["Zstd"] = "cache.tzst"; - })(CacheFilename || (exports2.CacheFilename = CacheFilename = {})); - var CompressionMethod; - (function(CompressionMethod2) { - CompressionMethod2["Gzip"] = "gzip"; - CompressionMethod2["ZstdWithoutLong"] = "zstd-without-long"; - CompressionMethod2["Zstd"] = "zstd"; - })(CompressionMethod || (exports2.CompressionMethod = CompressionMethod = {})); - var ArchiveToolType; - (function(ArchiveToolType2) { - ArchiveToolType2["GNU"] = "gnu"; - ArchiveToolType2["BSD"] = "bsd"; - })(ArchiveToolType || (exports2.ArchiveToolType = ArchiveToolType = {})); - exports2.DefaultRetryAttempts = 2; - exports2.DefaultRetryDelay = 5e3; - exports2.SocketTimeout = 5e3; - exports2.GnuTarPathOnWindows = `${process.env["PROGRAMFILES"]}\\Git\\usr\\bin\\tar.exe`; - exports2.SystemTarPathOnWindows = `${process.env["SYSTEMDRIVE"]}\\Windows\\System32\\tar.exe`; - exports2.TarFilename = "cache.tar"; - exports2.ManifestFilename = "manifest.txt"; - exports2.CacheFileSizeLimit = 10 * Math.pow(1024, 3); + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/cache/lib/internal/cacheUtils.js -var require_cacheUtils = __commonJS({ - "node_modules/@actions/cache/lib/internal/cacheUtils.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { @@ -50868,182 +53181,76 @@ var require_cacheUtils = __commonJS({ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve2, reject) { - v = o[n](v), settle(resolve2, reject, v.done, v.value); - }); - }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; } - function settle(resolve2, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve2({ value: v2, done: d }); - }, reject); + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); } }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRuntimeToken = exports2.getCacheVersion = exports2.assertDefined = exports2.getGnuTarPathOnWindows = exports2.getCacheFileName = exports2.getCompressionMethod = exports2.unlinkFile = exports2.resolvePaths = exports2.getArchiveFileSizeInBytes = exports2.createTempDirectory = void 0; - var core12 = __importStar4(require_core()); - var exec2 = __importStar4(require_exec()); - var glob = __importStar4(require_glob()); - var io4 = __importStar4(require_io()); - var crypto = __importStar4(require("crypto")); - var fs = __importStar4(require("fs")); - var path2 = __importStar4(require("path")); - var semver5 = __importStar4(require_semver3()); - var util = __importStar4(require("util")); - var constants_1 = require_constants7(); - var versionSalt = "1.0"; - function createTempDirectory() { - return __awaiter4(this, void 0, void 0, function* () { - const IS_WINDOWS = process.platform === "win32"; - let tempDirectory = process.env["RUNNER_TEMP"] || ""; - if (!tempDirectory) { - let baseLocation; - if (IS_WINDOWS) { - baseLocation = process.env["USERPROFILE"] || "C:\\"; - } else { - if (process.platform === "darwin") { - baseLocation = "/Users"; - } else { - baseLocation = "/home"; - } - } - tempDirectory = path2.join(baseLocation, "actions", "temp"); + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); } - const dest = path2.join(tempDirectory, crypto.randomUUID()); - yield io4.mkdirP(dest); - return dest; - }); - } - exports2.createTempDirectory = createTempDirectory; - function getArchiveFileSizeInBytes(filePath) { - return fs.statSync(filePath).size; - } - exports2.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; - function resolvePaths(patterns) { - var _a, e_1, _b, _c; - var _d; - return __awaiter4(this, void 0, void 0, function* () { - const paths = []; - const workspace = (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd(); - const globber = yield glob.create(patterns.join("\n"), { - implicitDescendants: false + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); }); - try { - for (var _e = true, _f = __asyncValues4(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { - _c = _g.value; - _e = false; - const file = _c; - const relativeFile = path2.relative(workspace, file).replace(new RegExp(`\\${path2.sep}`, "g"), "/"); - core12.debug(`Matched: ${relativeFile}`); - if (relativeFile === "") { - paths.push("."); - } else { - paths.push(`${relativeFile}`); - } - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); - } finally { - if (e_1) throw e_1.error; - } - } - return paths; - }); - } - exports2.resolvePaths = resolvePaths; - function unlinkFile(filePath) { - return __awaiter4(this, void 0, void 0, function* () { - return util.promisify(fs.unlink)(filePath); - }); - } - exports2.unlinkFile = unlinkFile; - function getVersion(app, additionalArgs = []) { - return __awaiter4(this, void 0, void 0, function* () { - let versionOutput = ""; - additionalArgs.push("--version"); - core12.debug(`Checking ${app} ${additionalArgs.join(" ")}`); - try { - yield exec2.exec(`${app}`, additionalArgs, { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() - } - }); - } catch (err) { - core12.debug(err.message); - } - versionOutput = versionOutput.trim(); - core12.debug(versionOutput); - return versionOutput; - }); - } - function getCompressionMethod() { - return __awaiter4(this, void 0, void 0, function* () { - const versionOutput = yield getVersion("zstd", ["--quiet"]); - const version = semver5.clean(versionOutput); - core12.debug(`zstd version: ${version}`); - if (versionOutput === "") { - return constants_1.CompressionMethod.Gzip; - } else { - return constants_1.CompressionMethod.ZstdWithoutLong; - } - }); - } - exports2.getCompressionMethod = getCompressionMethod; - function getCacheFileName(compressionMethod) { - return compressionMethod === constants_1.CompressionMethod.Gzip ? constants_1.CacheFilename.Gzip : constants_1.CacheFilename.Zstd; - } - exports2.getCacheFileName = getCacheFileName; - function getGnuTarPathOnWindows() { - return __awaiter4(this, void 0, void 0, function* () { - if (fs.existsSync(constants_1.GnuTarPathOnWindows)) { - return constants_1.GnuTarPathOnWindows; - } - const versionOutput = yield getVersion("tar"); - return versionOutput.toLowerCase().includes("gnu tar") ? io4.which("tar") : ""; - }); - } - exports2.getGnuTarPathOnWindows = getGnuTarPathOnWindows; - function assertDefined(name, value) { - if (value === void 0) { - throw Error(`Expected ${name} but value was undefiend`); } - return value; - } - exports2.assertDefined = assertDefined; - function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) { - const components = paths.slice(); - if (compressionMethod) { - components.push(compressionMethod); + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; } - if (process.platform === "win32" && !enableCrossOsArchive) { - components.push("windows-only"); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; } - components.push(versionSalt); - return crypto.createHash("sha256").update(components.join("|")).digest("hex"); - } - exports2.getCacheVersion = getCacheVersion; - function getRuntimeToken() { - const token = process.env["ACTIONS_RUNTIME_TOKEN"]; - if (!token) { - throw new Error("Unable to get the ACTIONS_RUNTIME_TOKEN env variable"); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - return token; - } - exports2.getRuntimeToken = getRuntimeToken; + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); @@ -86482,7 +88689,7 @@ var require_requestUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; var core12 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib6(); var constants_1 = require_constants7(); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -86650,7 +88857,7 @@ var require_downloadUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; var core12 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib6(); var storage_blob_1 = require_dist7(); var buffer = __importStar4(require("buffer")); var fs = __importStar4(require("fs")); @@ -87227,8 +89434,8 @@ var require_cacheHttpClient = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; var core12 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib6(); + var auth_1 = require_auth2(); var fs = __importStar4(require("fs")); var url_1 = require("url"); var utils = __importStar4(require_cacheUtils()); @@ -92434,8 +94641,8 @@ var require_cacheTwirpClient = __commonJS({ var errors_1 = require_errors2(); var config_1 = require_config(); var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib6(); var cache_twirp_client_1 = require_cache_twirp_client(); var util_1 = require_util11(); var CacheServiceClient = class { @@ -92883,7 +95090,7 @@ var require_cache3 = __commonJS({ var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); var config_1 = require_config(); var tar_1 = require_tar(); - var http_client_1 = require_lib(); + var http_client_1 = require_lib6(); var ValidationError = class _ValidationError extends Error { constructor(message) { super(message); @@ -93249,7 +95456,7 @@ var import_child_process = require("child_process"); var path = __toESM(require("path")); var core11 = __toESM(require_core()); var toolcache = __toESM(require_tool_cache()); -var import_node_forge = __toESM(require_lib2()); +var import_node_forge = __toESM(require_lib3()); // src/actions-util.ts var core4 = __toESM(require_core()); @@ -96350,7 +98557,7 @@ var supportedAnalysisKinds = new Set(Object.values(AnalysisKind)); var core8 = __toESM(require_core()); // src/config/db-config.ts -var jsonschema = __toESM(require_lib3()); +var jsonschema = __toESM(require_lib5()); var semver2 = __toESM(require_semver2()); var PACK_IDENTIFIER_PATTERN = (function() { const alphaNumeric = "[a-z0-9]"; diff --git a/lib/upload-lib.js b/lib/upload-lib.js index 68ef3c775f..15ca289050 100644 --- a/lib/upload-lib.js +++ b/lib/upload-lib.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -21172,9 +21172,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib3 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -21231,737 +21313,826 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url2, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url2, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve6(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve6(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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 (isPlainObject(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, url2] = route.split(" "); - options = Object.assign(url2 ? { method, url: url2 } : { 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(url2, parameters) { - const separator = /\?/.test(url2) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url2; - } - return url2 + 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+)|(?:(? a.concat(b), []); - } - function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - } - function encodeReserved(str2) { - return str2.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(str2) { - return encodeURIComponent(str2).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; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - function isDefined2(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context2, operator, key, modifier) { - var value = context2[key], result = []; - if (isDefined2(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)); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - result.push(encodeValue(operator, value[k], k)); + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; } - }); + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } } - }); + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - } else { - if (operator === ";") { - if (isDefined2(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; - } - function expand(template, context2) { - 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(context2, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve6(res); } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); } - } else { - return encodeReserved(literal); + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } - } - function parse(options) { - let method = options.method.toUpperCase(); - let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url2); - url2 = parseUrl(url2).expand(parameters); - if (!/^http/.test(url2)) { - url2 = options.baseUrl + url2; - } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(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(","); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (url2.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - } - if (["GET", "HEAD"].includes(method)) { - url2 = addQueryParameters(url2, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + req.end(); } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return Object.assign( - { method, url: url2, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); - } - function endpointWithDefaults(defaults, route, options) { - return parse(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 - }); - } - var endpoint = withDefaults(null, DEFAULTS); - } -}); - -// node_modules/deprecation/dist-node/index.js -var require_dist_node3 = __commonJS({ - "node_modules/deprecation/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var Deprecation = class extends Error { - constructor(message) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - this.name = "Deprecation"; + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } + } + return info6; } - }; - exports2.Deprecation = Deprecation; - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - return ret; + return additionalHeaders[header] || clientHeader || _default2; } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true - }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true - }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; - } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; - } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve6) => setTimeout(() => resolve6(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve6(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve6(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node4 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { "use strict"; - var __create2 = Object.create; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - RequestError: () => RequestError + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_deprecation = require_dist_node3(); - var import_once = __toESM2(require_once()); - var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); + } + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url2, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); + }); + return proxyFetch; + } + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; + } + exports2.getApiBaseUrl = getApiBaseUrl; + } +}); + +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); } - requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; - Object.defineProperty(this, "code", { - get() { - logOnceCode( - new import_deprecation.Deprecation( - "[@octokit/request-error] `error.code` is deprecated, use `error.status`." - ) - ); - return statusCode; - } - }); - Object.defineProperty(this, "headers", { - get() { - logOnceHeaders( - new import_deprecation.Deprecation( - "[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`." - ) - ); - return headers || {}; - } - }); + return state.registry[name].reduce(function(method2, registered) { + return registered.hook.bind(null, method2, options); + }, method)(); + }); + } + } +}); + +// node_modules/before-after-hook/lib/add.js +var require_add = __commonJS({ + "node_modules/before-after-hook/lib/add.js"(exports2, module2) { + module2.exports = addHook; + function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; } - }; + if (kind === "before") { + hook = function(method, options) { + return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); + }; + } + if (kind === "after") { + hook = function(method, options) { + var result; + return Promise.resolve().then(method.bind(null, options)).then(function(result_) { + result = result_; + return orig(result, options); + }).then(function() { + return result; + }); + }; + } + if (kind === "error") { + hook = function(method, options) { + return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { + return orig(error4, options); + }); + }; + } + state.registry[name].push({ + hook, + orig + }); + } } }); -// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js -var require_dist_node5 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/before-after-hook/lib/remove.js +var require_remove = __commonJS({ + "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { + module2.exports = removeHook; + function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } + var index = state.registry[name].map(function(registered) { + return registered.orig; + }).indexOf(method); + if (index === -1) { + return; + } + state.registry[name].splice(index, 1); + } + } +}); + +// node_modules/before-after-hook/index.js +var require_before_after_hook = __commonJS({ + "node_modules/before-after-hook/index.js"(exports2, module2) { + var register = require_register(); + var addHook = require_add(); + var removeHook = require_remove(); + var bind = Function.bind; + var bindable = bind.bind(bind); + function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function(kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); + } + function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {} + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; + } + function HookCollection() { + var state = { + registry: {} + }; + var hook = register.bind(null, state); + bindApi(hook, state); + return hook; + } + var collectionHookDeprecationMessageDisplayed = false; + function Hook() { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; + } + return HookCollection(); + } + Hook.Singular = HookSingular.bind(); + Hook.Collection = HookCollection.bind(); + module2.exports = Hook; + module2.exports.Hook = Hook; + module2.exports.Singular = Hook.Singular; + module2.exports.Collection = Hook.Collection; + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node2 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21982,217 +22153,7 @@ var require_dist_node5 = __commonJS({ var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - request: () => request - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node2(); - var import_universal_user_agent = require_dist_node(); - var VERSION = "8.4.1"; - function isPlainObject(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); - } - var import_request_error = require_dist_node4(); - function getBufferResponse(response) { - return response.arrayBuffer(); - } - function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url2; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - 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" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } - }).then(async (response) => { - url2 = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url: url2, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url: url2, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url: url2, - status, - headers, - data - }, - request: requestOptions - }); - throw error4; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url: url2, - headers, - data - }; - }).catch((error4) => { - if (error4 instanceof import_request_error.RequestError) - throw error4; - else if (error4.name === "AbortError") - throw error4; - let message = error4.message; - if (error4.name === "TypeError" && "cause" in error4) { - if (error4.cause instanceof Error) { - message = error4.cause.message; - } else if (typeof error4.cause === "string") { - message = error4.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); - } - 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 getBufferResponse(response); - } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; - } - function withDefaults(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: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - } - var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } - }); - } -}); - -// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node6 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint + endpoint: () => endpoint }); module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); @@ -22515,9 +22476,101 @@ var require_dist_node6 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node7 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/deprecation/dist-node/index.js +var require_dist_node3 = __commonJS({ + "node_modules/deprecation/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var Deprecation = class extends Error { + constructor(message) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "Deprecation"; + } + }; + exports2.Deprecation = Deprecation; + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node4 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; var __create2 = Object.create; var __defProp2 = Object.defineProperty; @@ -22607,9 +22660,9 @@ var require_dist_node7 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js -var require_dist_node8 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js +var require_dist_node5 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -22633,7 +22686,7 @@ var require_dist_node8 = __commonJS({ request: () => request }); module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node6(); + var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; function isPlainObject(value) { @@ -22647,7 +22700,7 @@ var require_dist_node8 = __commonJS({ 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); } - var import_request_error = require_dist_node7(); + var import_request_error = require_dist_node4(); function getBufferResponse(response) { return response.arrayBuffer(); } @@ -22817,9 +22870,9 @@ var require_dist_node8 = __commonJS({ } }); -// node_modules/@octokit/graphql/dist-node/index.js -var require_dist_node9 = __commonJS({ - "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node6 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -22838,129 +22891,340 @@ var require_dist_node9 = __commonJS({ return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export2(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint }); - module2.exports = __toCommonJS2(index_exports); - var import_request3 = require_dist_node8(); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); - var VERSION = "7.1.1"; - var import_request2 = require_dist_node8(); - var import_request = require_dist_node8(); - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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; + }, {}); } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + function isPlainObject(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 (isPlainObject(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]; } } - }; - 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`) - ); + return obj; + } + function merge2(defaults, route, options) { + if (typeof route === "string") { + let [method, url2] = route.split(" "); + options = Object.assign(url2 ? { method, url: url2 } : { 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); } - 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` - ) - ); + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; + } + function addQueryParameters(url2, parameters) { + const separator = /\?/.test(url2) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url2; + } + return url2 + 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+)|(?:(? { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } + function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; } - if (!result.variables) { - result.variables = {}; + } + return result; + } + function encodeReserved(str2) { + return str2.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, "]"); } - 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 part; + }).join(""); + } + function encodeUnreserved(str2) { + return encodeURIComponent(str2).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; } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; + } + function isDefined2(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context2, operator, key, modifier) { + var value = context2[key], result = []; + if (isDefined2(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)); } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(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(",")); + } + } } - return response.data.data; - }); + } else { + if (operator === ";") { + if (isDefined2(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; } - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); + function parseUrl(template) { + return { + expand: expand.bind(null, template) }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); } - var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" - }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" + function expand(template, context2) { + 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(context2, 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 parse(options) { + let method = options.method.toUpperCase(); + let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url2); + url2 = parseUrl(url2).expand(parameters); + if (!/^http/.test(url2)) { + url2 = options.baseUrl + url2; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(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 (url2.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url2 = addQueryParameters(url2, 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: url2, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); + } + function endpointWithDefaults(defaults, route, options) { + return parse(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 }); } + var endpoint = withDefaults(null, DEFAULTS); } }); -// node_modules/@octokit/auth-token/dist-node/index.js -var require_dist_node10 = __commonJS({ - "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node7 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; + var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) @@ -22974,53 +23238,490 @@ var require_dist_node10 = __commonJS({ } return to; }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - createTokenAuth: () => createTokenAuth + RequestError: () => RequestError }); module2.exports = __toCommonJS2(dist_src_exports); - 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, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); - } - 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" - ); + var import_deprecation = require_dist_node3(); + var import_once = __toESM2(require_once()); + var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + request: () => request + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_endpoint = require_dist_node6(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "8.4.1"; + function isPlainObject(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); + } + var import_request_error = require_dist_node7(); + function getBufferResponse(response) { + return response.arrayBuffer(); + } + function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url2; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + 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" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url2 = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url: url2, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url: url2, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url: url2, + status, + headers, + data + }, + request: requestOptions + }); + throw error4; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url: url2, + headers, + data + }; + }).catch((error4) => { + if (error4 instanceof import_request_error.RequestError) + throw error4; + else if (error4.name === "AbortError") + throw error4; + let message = error4.message; + if (error4.name === "TypeError" && "cause" in error4) { + if (error4.cause instanceof Error) { + message = error4.cause.message; + } else if (typeof error4.cause === "string") { + message = error4.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); + } + 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 getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; + } + function withDefaults(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: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + } + var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }); + } +}); + +// node_modules/@octokit/graphql/dist-node/index.js +var require_dist_node9 = __commonJS({ + "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export2(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest + }); + module2.exports = __toCommonJS2(index_exports); + var import_request3 = require_dist_node8(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "7.1.1"; + var import_request2 = require_dist_node8(); + var import_request = require_dist_node8(); + 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.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + }; + 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 withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); + } + } +}); + +// node_modules/@octokit/auth-token/dist-node/index.js +var require_dist_node10 = __commonJS({ + "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + createTokenAuth: () => createTokenAuth + }); + module2.exports = __toCommonJS2(dist_src_exports); + 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, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + 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) + }); }; } }); @@ -27796,7 +28497,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -32511,959 +33212,1764 @@ var require_cacheUtils = __commonJS({ } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); - var HttpPipeline = class _HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = void 0; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - this._policies.push({ - policy, - options - }); - this._orderedPolicies = void 0; + } else { + return void 0; } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { - removedPolicies.push(policyDescriptor.policy); - return false; - } else { - return true; - } - }); - this._orderedPolicies = void 0; - return removedPolicies; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; } - clone() { - return new _HttpPipeline(this._policies); + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - static create() { - return new _HttpPipeline(); + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - orderPolicies() { - const result = []; - const policyMap = /* @__PURE__ */ new Map(); - function createPhase(name) { - return { - name, - policies: /* @__PURE__ */ new Set(), - hasRun: false, - hasAfterPolicies: false - }; - } - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } else if (phase === "Serialize") { - return serializePhase; - } else if (phase === "Deserialize") { - return deserializePhase; - } else if (phase === "Sign") { - return signPhase; - } else { - return noPhase; - } - } - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: /* @__PURE__ */ new Set(), - dependants: /* @__PURE__ */ new Set() - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); - } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); - } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); - } - } - } - } - function walkPhase(phase) { - phase.hasRun = true; - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - continue; - } - if (node.dependsOn.size === 0) { - result.push(node.policy); - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); - } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - walkPhase(noPhase); - } - return; - } - if (phase.hasAfterPolicies) { - walkPhase(noPhase); - } - } - } - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - walkPhases(); - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } - return result; } - }; - function createEmptyPipeline() { - return HttpPipeline.create(); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@azure/logger/dist/index.js -var require_dist = __commonJS({ - "node_modules/@azure/logger/dist/index.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js +var require_lib4 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var os2 = require("os"); - var util = require("util"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); - function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os2.EOL}`); - } - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; - var enabledString; - var enabledNamespaces = []; - var skippedNamespaces = []; - var debuggers = []; - if (debugEnvVariable) { - enable(debugEnvVariable); - } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log - }); - function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); - } else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); - } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - } - function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - } - return false; - } - function disable() { - const result = enabledString || ""; - enable(""); - return result; - } - function createDebugger(namespace) { - const newDebugger = Object.assign(debug5, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend: extend3 - }); - function debug5(...args) { - if (!newDebugger.enabled) { - return; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); } - newDebugger.log(...args); - } - debuggers.push(newDebugger); - return newDebugger; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return false; - } - function extend3(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; - } - var debug4 = debugObj; - var registeredLoggers = /* @__PURE__ */ new Set(); - var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; - var azureLogLevel; - var AzureLogger = debug4("azure"); - AzureLogger.log = (...args) => { - debug4.log(...args); }; - var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; - if (logLevelFromEnv) { - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); - } else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - } - function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve6(output.toString()); + }); + })); + }); } - azureLogLevel = level; - const enabledNamespaces2 = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces2.push(logger.namespace); - } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve6(Buffer.concat(chunks)); + }); + })); + }); } - debug4.enable(enabledNamespaces2.join(",")); - } - function getLogLevel() { - return azureLogLevel; - } - var levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 }; - function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") - }; - } - function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); - }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces2 = debug4.disable(); - debug4.enable(enabledNamespaces2 + "," + logger.namespace); + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - registeredLoggers.add(logger); - return logger; - } - function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); - } - function isAzureLogLevel(logLevel) { - return AZURE_LOG_LEVELS.includes(logLevel); - } - exports2.AzureLogger = AzureLogger; - exports2.createClientLogger = createClientLogger; - exports2.getLogLevel = getLogLevel; - exports2.setLogLevel = setLogLevel; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js -var require_log = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_dist(); - exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); - } -}); - -// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js -var require_createAbortablePromise = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createAbortablePromise = createAbortablePromise; - var abort_controller_1 = require_commonjs(); - function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve6, reject) => { - function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); + } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - function removeListeners() { - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve6(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - function onAbort() { - cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); - removeListeners(); - rejectOnAbort(); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { - return rejectOnAbort(); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - try { - buildPromise((x) => { - removeListeners(); - resolve6(x); - }, (x) => { - removeListeners(); - reject(x); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); }); - } catch (err) { - reject(err); + data.pipe(req); + } else { + req.end(); } - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); - }); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/random.js -var require_random = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - function getRandomIntegerInclusive(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - const offset = Math.floor(Math.random() * (max - min + 1)); - return offset + min; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/delay.js -var require_delay = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay2; - exports2.calculateRetryDelay = calculateRetryDelay; - var createAbortablePromise_js_1 = require_createAbortablePromise(); - var random_js_1 = require_random(); - var StandardAbortMessage = "The delay was aborted."; - function delay2(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve6) => { - token = setTimeout(resolve6, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage - }); - } - function calculateRetryDelay(retryAttempt, config) { - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); - return { retryAfterInMs }; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js -var require_aborterUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cancelablePromiseRace = cancelablePromiseRace; - async function cancelablePromiseRace(abortablePromiseBuilders, options) { - var _a, _b; - const aborter = new AbortController(); - function abortHandler() { - aborter.abort(); } - (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); - try { - return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); - } finally { - aborter.abort(); - (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/object.js -var require_object = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isObject = isObject2; - function isObject2(input) { - return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/error.js -var require_error = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isError = isError; - exports2.getErrorMessage = getErrorMessage2; - var object_js_1 = require_object(); - function isError(e) { - if ((0, object_js_1.isObject)(e)) { - const hasName = typeof e.name === "string"; - const hasMessage = typeof e.message === "string"; - return hasName && hasMessage; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return false; - } - function getErrorMessage2(e) { - if (isError(e)) { - return e.message; - } else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } else { - stringified = String(e); + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - } catch (err) { - stringified = "[unable to stringify input]"; } - return `Unknown error ${stringified}`; + return info6; } - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.computeSha256Hash = computeSha256Hash; - var crypto_1 = require("crypto"); - async function computeSha256Hmac(key, stringToSign, encoding) { - const decodedKey = Buffer.from(key, "base64"); - return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); - } - async function computeSha256Hash(content, encoding) { - return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/typeGuards.js -var require_typeGuards = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isDefined = isDefined2; - exports2.isObjectWithProperties = isObjectWithProperties; - exports2.objectHasProperty = objectHasProperty; - function isDefined2(thing) { - return typeof thing !== "undefined" && thing !== null; - } - function isObjectWithProperties(thing, properties) { - if (!isDefined2(thing) || typeof thing !== "object") { - return false; - } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - return true; - } - function objectHasProperty(thing, property) { - return isDefined2(thing) && typeof thing === "object" && property in thing; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js -var require_uuidUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomUUID = randomUUID2; - var crypto_1 = require("crypto"); - var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; - function randomUUID2() { - return uuidFunction(); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js -var require_checkEnvironment = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { - "use strict"; - var _a; - var _b; - var _c; - var _d; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; - exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; - exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); - exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; - exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; - exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); - exports2.isNode = exports2.isNodeLike; - exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; - exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; - } -}); - -// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js -var require_bytesEncoding = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - function uint8ArrayToString(bytes, format) { - return Buffer.from(bytes).toString(format); - } - function stringToUint8Array(value, format) { - return Buffer.from(value, format); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/index.js -var require_commonjs2 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; - var delay_js_1 = require_delay(); - Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { - return delay_js_1.delay; - } }); - Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { - return delay_js_1.calculateRetryDelay; - } }); - var aborterUtils_js_1 = require_aborterUtils(); - Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { - return aborterUtils_js_1.cancelablePromiseRace; - } }); - var createAbortablePromise_js_1 = require_createAbortablePromise(); - Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { - return createAbortablePromise_js_1.createAbortablePromise; - } }); - var random_js_1 = require_random(); - Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { - return random_js_1.getRandomIntegerInclusive; - } }); - var object_js_1 = require_object(); - Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { - return object_js_1.isObject; - } }); - var error_js_1 = require_error(); - Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { - return error_js_1.isError; - } }); - Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { - return error_js_1.getErrorMessage; - } }); - var sha256_js_1 = require_sha256(); - Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hash; - } }); - Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hmac; - } }); - var typeGuards_js_1 = require_typeGuards(); - Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { - return typeGuards_js_1.isDefined; - } }); - Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { - return typeGuards_js_1.isObjectWithProperties; - } }); - Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { - return typeGuards_js_1.objectHasProperty; - } }); - var uuidUtils_js_1 = require_uuidUtils(); - Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { - return uuidUtils_js_1.randomUUID; - } }); - var checkEnvironment_js_1 = require_checkEnvironment(); - Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBrowser; - } }); - Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBun; - } }); - Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNode; - } }); - Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeLike; - } }); - Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeRuntime; - } }); - Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { - return checkEnvironment_js_1.isDeno; - } }); - Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { - return checkEnvironment_js_1.isReactNative; - } }); - Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { - return checkEnvironment_js_1.isWebWorker; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js -var require_sanitizer = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = void 0; - var core_util_1 = require_commonjs2(); - var RedactedString = "REDACTED"; - var defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate" - ]; - var defaultAllowedQueryParameters = ["api-version"]; - var Sanitizer = class { - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { - allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); - allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); - } - sanitize(obj) { - const seen = /* @__PURE__ */ new Set(); - return JSON.stringify(obj, (key, value) => { - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); - } - if (key === "headers") { - return this.sanitizeHeaders(value); - } else if (key === "url") { - return this.sanitizeUrl(value); - } else if (key === "query") { - return this.sanitizeQuery(value); - } else if (key === "body") { - return void 0; - } else if (key === "response") { - return void 0; - } else if (key === "operationSpec") { - return void 0; - } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - } - return value; - }, 2); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - sanitizeUrl(value) { - if (typeof value !== "string" || value === null || value === "") { - return value; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const url2 = new URL(value); - if (!url2.search) { - return value; + if (!useProxy) { + agent = this._agent; } - for (const [key] of url2.searchParams) { - if (!this.allowedQueryParameters.has(key.toLowerCase())) { - url2.searchParams.set(key, RedactedString); - } + if (agent) { + return agent; } - return url2.toString(); - } - sanitizeHeaders(obj) { - const sanitized = {}; - for (const key of Object.keys(obj)) { - if (this.allowedHeaderNames.has(key.toLowerCase())) { - sanitized[key] = obj[key]; + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - sanitized[key] = RedactedString; + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - return sanitized; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - sanitizeQuery(value) { - if (typeof value !== "object" || value === null) { - return value; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (this.allowedQueryParameters.has(k.toLowerCase())) { - sanitized[k] = value[k]; - } else { - sanitized[k] = RedactedString; - } + if (proxyAgent) { + return proxyAgent; } - return sanitized; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve6) => setTimeout(() => resolve6(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve6(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve6(response); + } + })); + }); } }; - exports2.Sanitizer = Sanitizer; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js -var require_logPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { +// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log(); - var sanitizer_js_1 = require_sanitizer(); - exports2.logPolicyName = "logPolicy"; - function logPolicy(options = {}) { - var _a; - const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - return { - name: exports2.logPolicyName, - async sendRequest(request, next) { - if (!logger.enabled) { - return next(request); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); + } + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - logger(`Request: ${sanitizer.sanitize(request)}`); - const response = await next(request); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); - return response; } - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js -var require_redirectPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - exports2.redirectPolicyName = "redirectPolicy"; - var allowedRedirect = ["GET", "HEAD"]; - function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: exports2.redirectPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return handleRedirect(next, response, maxRetries); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - }; - } - async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { - const url2 = new URL(locationHeader, request.url); - request.url = url2.toString(); - if (status === 303) { - request.method = "GET"; - request.headers.delete("Content-Length"); - delete request.body; + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); } - request.headers.delete("Authorization"); - const res = await next(request); - return handleRedirect(next, res, maxRetries, currentRetries + 1); - } - return response; - } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; + } + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; + } + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } + }; + function createEmptyPipeline() { + return HttpPipeline.create(); + } + } +}); + +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os2 = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; + } + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os2.EOL}`); + } + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); + } + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log + }); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } + } + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; + } + function disable() { + const result = enabledString || ""; + enable(""); + return result; + } + function createDebugger(namespace) { + const newDebugger = Object.assign(debug5, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug5(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; + } + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; + } + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; + } + var debug4 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug4("azure"); + AzureLogger.log = (...args) => { + debug4.log(...args); + }; + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + } + } + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); + } + } + debug4.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 + }; + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; + } + function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; + } + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces2 = debug4.disable(); + debug4.enable(enabledNamespaces2 + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; + } + function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); + } + function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); + } + exports2.AzureLogger = AzureLogger; + exports2.createClientLogger = createClientLogger; + exports2.getLogLevel = getLogLevel; + exports2.setLogLevel = setLogLevel; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js +var require_log = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } + }; + exports2.AbortError = AbortError; + } +}); + +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve6, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve6(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/random.js +var require_random = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; + function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = delay2; + exports2.calculateRetryDelay = calculateRetryDelay; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var random_js_1 = require_random(); + var StandardAbortMessage = "The delay was aborted."; + function delay2(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve6) => { + token = setTimeout(resolve6, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage + }); + } + function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); + } + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/object.js +var require_object = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isObject = isObject2; + function isObject2(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isError = isError; + exports2.getErrorMessage = getErrorMessage2; + var object_js_1 = require_object(); + function isError(e) { + if ((0, object_js_1.isObject)(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; + } + function getErrorMessage2(e) { + if (isError(e)) { + return e.message; + } else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } else { + stringified = String(e); + } + } catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.computeSha256Hmac = computeSha256Hmac; + exports2.computeSha256Hash = computeSha256Hash; + var crypto_1 = require("crypto"); + async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); + } + async function computeSha256Hash(content, encoding) { + return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isDefined = isDefined2; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined2(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined2(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined2(thing) && typeof thing === "object" && property in thing; + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js +var require_uuidUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { + "use strict"; + var _a; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.randomUUID = randomUUID2; + var crypto_1 = require("crypto"); + var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; + function randomUUID2() { + return uuidFunction(); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js +var require_checkEnvironment = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { + "use strict"; + var _a; + var _b; + var _c; + var _d; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; + exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; + exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); + exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; + exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; + exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); + exports2.isNode = exports2.isNodeLike; + exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; + exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; + } +}); + +// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js +var require_bytesEncoding = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.uint8ArrayToString = uint8ArrayToString; + exports2.stringToUint8Array = stringToUint8Array; + function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); + } + function stringToUint8Array(value, format) { + return Buffer.from(value, format); + } + } +}); + +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs2 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; + var delay_js_1 = require_delay(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { + return delay_js_1.calculateRetryDelay; + } }); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var random_js_1 = require_random(); + Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { + return random_js_1.getRandomIntegerInclusive; + } }); + var object_js_1 = require_object(); + Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { + return object_js_1.isObject; + } }); + var error_js_1 = require_error(); + Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { + return error_js_1.isError; + } }); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var sha256_js_1 = require_sha256(); + Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hash; + } }); + Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hmac; + } }); + var typeGuards_js_1 = require_typeGuards(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + var uuidUtils_js_1 = require_uuidUtils(); + Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { + return uuidUtils_js_1.randomUUID; + } }); + var checkEnvironment_js_1 = require_checkEnvironment(); + Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBrowser; + } }); + Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBun; + } }); + Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNode; + } }); + Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeLike; + } }); + Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeRuntime; + } }); + Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { + return checkEnvironment_js_1.isDeno; + } }); + Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { + return checkEnvironment_js_1.isReactNative; + } }); + Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { + return checkEnvironment_js_1.isWebWorker; + } }); + var bytesEncoding_js_1 = require_bytesEncoding(); + Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { + return bytesEncoding_js_1.uint8ArrayToString; + } }); + Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { + return bytesEncoding_js_1.stringToUint8Array; + } }); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js +var require_sanitizer = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Sanitizer = void 0; + var core_util_1 = require_commonjs2(); + var RedactedString = "REDACTED"; + var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" + ]; + var defaultAllowedQueryParameters = ["api-version"]; + var Sanitizer = class { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); + } + if (key === "headers") { + return this.sanitizeHeaders(value); + } else if (key === "url") { + return this.sanitizeUrl(value); + } else if (key === "query") { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }, 2); + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; + } + const url2 = new URL(value); + if (!url2.search) { + return value; + } + for (const [key] of url2.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url2.searchParams.set(key, RedactedString); + } + } + return url2.toString(); + } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } + }; + exports2.Sanitizer = Sanitizer; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js +var require_logPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logPolicyName = void 0; + exports2.logPolicy = logPolicy; + var log_js_1 = require_log(); + var sanitizer_js_1 = require_sanitizer(); + exports2.logPolicyName = "logPolicy"; + function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + return { + name: exports2.logPolicyName, + async sendRequest(request, next) { + if (!logger.enabled) { + return next(request); + } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; + } + }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.redirectPolicyName = void 0; + exports2.redirectPolicy = redirectPolicy; + exports2.redirectPolicyName = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; + return { + name: exports2.redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + } + }; + } + async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url2 = new URL(locationHeader, request.url); + request.url = url2.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; + } + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); + } + return response; + } } }); @@ -67946,7 +69452,7 @@ var require_requestUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0; var core12 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var constants_1 = require_constants7(); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -68114,7 +69620,7 @@ var require_downloadUtils = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0; var core12 = __importStar4(require_core()); - var http_client_1 = require_lib(); + var http_client_1 = require_lib4(); var storage_blob_1 = require_dist7(); var buffer = __importStar4(require("buffer")); var fs12 = __importStar4(require("fs")); @@ -68691,8 +70197,8 @@ var require_cacheHttpClient = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0; var core12 = __importStar4(require_core()); - var http_client_1 = require_lib(); - var auth_1 = require_auth(); + var http_client_1 = require_lib4(); + var auth_1 = require_auth2(); var fs12 = __importStar4(require("fs")); var url_1 = require("url"); var utils = __importStar4(require_cacheUtils()); @@ -69668,2706 +71174,4406 @@ var require_binary_reader = __commonJS({ return this.buf.subarray(start, start + len); } /** - * Read a `string` field, length-delimited data converted to UTF-8 text. + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); + } + }; + exports2.BinaryReader = BinaryReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js +var require_assert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; + function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } + } + exports2.assert = assert; + function assertNever2(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + } + exports2.assertNever = assertNever2; + var FLOAT32_MAX = 34028234663852886e22; + var FLOAT32_MIN = -34028234663852886e22; + var UINT32_MAX = 4294967295; + var INT32_MAX = 2147483647; + var INT32_MIN = -2147483648; + function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid int 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error("invalid int 32: " + arg); + } + exports2.assertInt32 = assertInt32; + function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error("invalid uint 32: " + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error("invalid uint 32: " + arg); + } + exports2.assertUInt32 = assertUInt32; + function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error("invalid float 32: " + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error("invalid float 32: " + arg); + } + exports2.assertFloat32 = assertFloat32; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js +var require_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; + var pb_long_1 = require_pb_long(); + var goog_varint_1 = require_goog_varint(); + var assert_1 = require_assert(); + var defaultsWrite = { + writeUnknownFields: true, + writerFactory: () => new BinaryWriter() + }; + function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.binaryWriteOptions = binaryWriteOptions; + var BinaryWriter = class { + constructor(textEncoder) { + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; + } + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; + } + this.chunks = []; + return bytes; + } + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; + } + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + let chunk = this.finish(); + let prev = this.stack.pop(); + if (!prev) + throw new Error("invalid state, fork stack empty"); + this.chunks = prev.chunks; + this.buf = prev.buf; + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type2) { + return this.uint32((fieldNo << 3 | type2) >>> 0); + } + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; + } + this.chunks.push(chunk); + return this; + } + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); + while (value > 127) { + this.buf.push(value & 127 | 128); + value = value >>> 7; + } + this.buf.push(value); + return this; + } + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; + } + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); + return this.raw(value); + } + /** + * Write a `string` value, length-delimited data converted to UTF-8 text. + */ + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Write a `float` value, 32-bit floating point number. + */ + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `double` value, a 64-bit floating point number. + */ + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); + } + /** + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + */ + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + */ + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + */ + sint32(value) { + assert_1.assertInt32(value); + value = (value << 1 ^ value >> 31) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + */ + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + */ + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `int64` value, a signed 64-bit varint. + */ + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + /** + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. */ - string() { - return this.textDecoder.decode(this.bytes()); + sint64(value) { + let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; + } + /** + * Write a `uint64` value, an unsigned 64-bit varint. + */ + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; } }; - exports2.BinaryReader = BinaryReader; + exports2.BinaryWriter = BinaryWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js -var require_assert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js +var require_json_format_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0; - function assert(condition, msg) { - if (!condition) { - throw new Error(msg); + exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; + var defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0 + }; + var defaultsRead = { + ignoreUnknownFields: false + }; + function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; + } + exports2.jsonReadOptions = jsonReadOptions; + function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + } + exports2.jsonWriteOptions = jsonWriteOptions; + function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; + return c; + } + exports2.mergeJsonOptions = mergeJsonOptions; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js +var require_message_type_contract = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MESSAGE_TYPE = void 0; + exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js +var require_lower_camel_case = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.lowerCamelCase = void 0; + function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == "_") { + capNext = true; + } else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } else if (i == 0) { + sb.push(next.toLowerCase()); + } else { + sb.push(next); + } } + return sb.join(""); } - exports2.assert = assert; - function assertNever2(value, msg) { - throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value); + exports2.lowerCamelCase = lowerCamelCase; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js +var require_reflection_info = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; + var lower_camel_case_1 = require_lower_camel_case(); + var ScalarType; + (function(ScalarType2) { + ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; + ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; + ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; + ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; + ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; + ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; + ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; + ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; + ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; + ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; + ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; + ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; + ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; + ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; + ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; + })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); + var LongType; + (function(LongType2) { + LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; + LongType2[LongType2["STRING"] = 1] = "STRING"; + LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; + })(LongType = exports2.LongType || (exports2.LongType = {})); + var RepeatType; + (function(RepeatType2) { + RepeatType2[RepeatType2["NO"] = 0] = "NO"; + RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; + RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; + })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); + function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; + return field; } - exports2.assertNever = assertNever2; - var FLOAT32_MAX = 34028234663852886e22; - var FLOAT32_MIN = -34028234663852886e22; - var UINT32_MAX = 4294967295; - var INT32_MAX = 2147483647; - var INT32_MIN = -2147483648; - function assertInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid int 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) - throw new Error("invalid int 32: " + arg); + exports2.normalizeFieldInfo = normalizeFieldInfo; + function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; } - exports2.assertInt32 = assertInt32; - function assertUInt32(arg) { - if (typeof arg !== "number") - throw new Error("invalid uint 32: " + typeof arg); - if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) - throw new Error("invalid uint 32: " + arg); + exports2.readFieldOptions = readFieldOptions; + function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; + } + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.assertUInt32 = assertUInt32; - function assertFloat32(arg) { - if (typeof arg !== "number") - throw new Error("invalid float 32: " + typeof arg); - if (!Number.isFinite(arg)) - return; - if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) - throw new Error("invalid float 32: " + arg); + exports2.readFieldOption = readFieldOption; + function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.assertFloat32 = assertFloat32; + exports2.readMessageOption = readMessageOption; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js -var require_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js +var require_oneof = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryWriter = exports2.binaryWriteOptions = void 0; - var pb_long_1 = require_pb_long(); - var goog_varint_1 = require_goog_varint(); - var assert_1 = require_assert(); - var defaultsWrite = { - writeUnknownFields: true, - writerFactory: () => new BinaryWriter() - }; - function binaryWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; + exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; + function isOneofGroup(any) { + if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === void 0) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; + } } - exports2.binaryWriteOptions = binaryWriteOptions; - var BinaryWriter = class { - constructor(textEncoder) { - this.stack = []; - this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); - this.chunks = []; - this.buf = []; + exports2.isOneofGroup = isOneofGroup; + function getOneofValue(oneof, kind) { + return oneof[kind]; + } + exports2.getOneofValue = getOneofValue; + function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; } - /** - * Return all bytes written and reset this writer. - */ - finish() { - this.chunks.push(new Uint8Array(this.buf)); - let len = 0; - for (let i = 0; i < this.chunks.length; i++) - len += this.chunks[i].length; - let bytes = new Uint8Array(len); - let offset = 0; - for (let i = 0; i < this.chunks.length; i++) { - bytes.set(this.chunks[i], offset); - offset += this.chunks[i].length; - } - this.chunks = []; - return bytes; + oneof.oneofKind = kind; + if (value !== void 0) { + oneof[kind] = value; } - /** - * Start a new fork for length-delimited data like a message - * or a packed repeated field. - * - * Must be joined later with `join()`. - */ - fork() { - this.stack.push({ chunks: this.chunks, buf: this.buf }); - this.chunks = []; - this.buf = []; - return this; + } + exports2.setOneofValue = setOneofValue; + function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; } - /** - * Join the last fork. Write its length and bytes, then - * return to the previous state. - */ - join() { - let chunk = this.finish(); - let prev = this.stack.pop(); - if (!prev) - throw new Error("invalid state, fork stack empty"); - this.chunks = prev.chunks; - this.buf = prev.buf; - this.uint32(chunk.byteLength); - return this.raw(chunk); + oneof.oneofKind = kind; + if (value !== void 0 && kind !== void 0) { + oneof[kind] = value; + } + } + exports2.setUnknownOneofValue = setUnknownOneofValue; + function clearOneofValue(oneof) { + if (oneof.oneofKind !== void 0) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = void 0; + } + exports2.clearOneofValue = clearOneofValue; + function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === void 0) { + return void 0; + } + return oneof[oneof.oneofKind]; + } + exports2.getSelectedOneofValue = getSelectedOneofValue; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js +var require_reflection_type_check = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionTypeCheck = void 0; + var reflection_info_1 = require_reflection_info(); + var oneof_1 = require_oneof(); + var ReflectionTypeCheck = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + } + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); + } + } else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; + } + } + } + this.data = { req, known, oneofs: Object.values(oneofs) }; } /** - * Writes a tag (field number and wire type). + * Is the argument a valid message as specified by the + * reflection information? * - * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. * - * Generated code should compute the tag ahead of time and call `uint32()`. + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. */ - tag(fieldNo, type2) { - return this.uint32((fieldNo << 3 | type2) >>> 0); + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === void 0 || typeof message != "object") + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + if (keys.some((k) => !data.known.includes(k))) + return false; + } + if (depth < 1) { + return true; + } + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === void 0) + continue; + const field = this.fields.find((f) => f.localName === group.oneofKind); + if (!field) + return false; + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + for (const field of this.fields) { + if (field.oneof !== void 0) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; + } + return true; } - /** - * Write a chunk of raw bytes. - */ - raw(chunk) { - if (this.buf.length) { - this.chunks.push(new Uint8Array(this.buf)); - this.buf = []; + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === void 0) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === void 0) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != "object" || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } + break; } - this.chunks.push(chunk); - return this; + return true; } - /** - * Write a `uint32` value, an unsigned 32 bit varint. - */ - uint32(value) { - assert_1.assertUInt32(value); - while (value > 127) { - this.buf.push(value & 127 | 128); - value = value >>> 7; + message(arg, type2, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type2.isAssignable(arg, depth); + } + return type2.is(arg, depth); + } + messages(arg, type2, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.isAssignable(arg[i], depth - 1)) + return false; + } else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type2.is(arg[i], depth - 1)) + return false; + } + return true; + } + scalar(arg, type2, longType) { + let argType = typeof arg; + switch (type2) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == "boolean"; + case reflection_info_1.ScalarType.STRING: + return argType == "string"; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == "number" && !isNaN(arg); + default: + return argType == "number" && Number.isInteger(arg); } - this.buf.push(value); - return this; } - /** - * Write a `int32` value, a signed 32 bit varint. - */ - int32(value) { - assert_1.assertInt32(value); - goog_varint_1.varint32write(value, this.buf); - return this; + scalars(arg, type2, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type2, longType)) + return false; + } + return true; } - /** - * Write a `bool` value, a variant. - */ - bool(value) { - this.buf.push(value ? 1 : 0); - return this; + mapKeys(map2, type2, depth) { + let keys = Object.keys(map2); + switch (type2) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); + default: + return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + } } - /** - * Write a `bytes` value, length-delimited arbitrary data. - */ - bytes(value) { - this.uint32(value.byteLength); - return this.raw(value); + }; + exports2.ReflectionTypeCheck = ReflectionTypeCheck; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js +var require_reflection_long_convert = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionLongConvert = void 0; + var reflection_info_1 = require_reflection_info(); + function reflectionLongConvert(long, type2) { + switch (type2) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + return long.toString(); } - /** - * Write a `string` value, length-delimited data converted to UTF-8 text. - */ - string(value) { - let chunk = this.textEncoder.encode(value); - this.uint32(chunk.byteLength); - return this.raw(chunk); + } + exports2.reflectionLongConvert = reflectionLongConvert; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js +var require_reflection_json_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonReader = void 0; + var json_typings_1 = require_json_typings(); + var base64_1 = require_base642(); + var reflection_info_1 = require_reflection_info(); + var pb_long_1 = require_pb_long(); + var assert_1 = require_assert(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var ReflectionJsonReader = class { + constructor(info6) { + this.info = info6; } - /** - * Write a `float` value, 32-bit floating point number. - */ - float(value) { - assert_1.assertFloat32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setFloat32(0, value, true); - return this.raw(chunk); + prepare() { + var _a; + if (this.fMap === void 0) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } + } } - /** - * Write a `double` value, a 64-bit floating point number. - */ - double(value) { - let chunk = new Uint8Array(8); - new DataView(chunk.buffer).setFloat64(0, value, true); - return this.raw(chunk); + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + } } /** - * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. */ - fixed32(value) { - assert_1.assertUInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setUint32(0, value, true); - return this.raw(chunk); + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + let target; + if (field.oneof) { + if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { + continue; + } + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } else { + target = message; + } + if (field.kind == "map") { + if (jsonValue === null) { + continue; + } + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + const fieldObj = target[localName]; + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + let val2; + switch (field.V.kind) { + case "message": + val2 = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val2; + } + } else if (field.repeat) { + if (jsonValue === null) + continue; + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + const fieldArr = target[localName]; + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val2; + switch (field.kind) { + case "message": + val2 = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + break; + case "scalar": + val2 = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val2 !== void 0, field.name, jsonValue); + fieldArr.push(val2); + } + } else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { + this.assert(field.oneof === void 0, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + if (jsonValue === null) + continue; + let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val2 === false) + continue; + target[localName] = val2; + break; + case "scalar": + if (jsonValue === null) + continue; + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } + } } /** - * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). */ - sfixed32(value) { - assert_1.assertInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setInt32(0, value, true); - return this.raw(chunk); + enum(type2, json2, fieldName, ignoreUnknownFields) { + if (type2[0] == "google.protobuf.NullValue") + assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); + if (json2 === null) + return 0; + switch (typeof json2) { + case "number": + assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); + return json2; + case "string": + let localEnumName = json2; + if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) + localEnumName = json2.substring(type2[2].length); + let enumNumber = type2[1][localEnumName]; + if (typeof enumNumber === "undefined" && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); + return enumNumber; + } + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); } - /** - * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. - */ - sint32(value) { - assert_1.assertInt32(value); - value = (value << 1 ^ value >> 31) >>> 0; - goog_varint_1.varint32write(value, this.buf); - return this; + scalar(json2, type2, longType, fieldName) { + let e; + try { + switch (type2) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json2 === null) + return 0; + if (json2 === "NaN") + return Number.NaN; + if (json2 === "Infinity") + return Number.POSITIVE_INFINITY; + if (json2 === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json2 === "") { + e = "empty string"; + break; + } + if (typeof json2 == "string" && json2.trim().length !== json2.length) { + e = "extra whitespace"; + break; + } + if (typeof json2 != "string" && typeof json2 != "number") { + break; + } + let float2 = Number(json2); + if (Number.isNaN(float2)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float2)) { + e = "too large or small"; + break; + } + if (type2 == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float2); + return float2; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json2 === null) + return 0; + let int32; + if (typeof json2 == "number") + int32 = json2; + else if (json2 === "") + e = "empty string"; + else if (typeof json2 == "string") { + if (json2.trim().length !== json2.length) + e = "extra whitespace"; + else + int32 = Number(json2); + } + if (int32 === void 0) + break; + if (type2 == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json2 === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json2 != "number" && typeof json2 != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json2 === null) + return false; + if (typeof json2 !== "boolean") + break; + return json2; + // string: + case reflection_info_1.ScalarType.STRING: + if (json2 === null) + return ""; + if (typeof json2 !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json2); + } catch (e2) { + e2 = "invalid UTF8"; + break; + } + return json2; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json2 === null || json2 === "") + return new Uint8Array(0); + if (typeof json2 !== "string") + break; + return base64_1.base64decode(json2); + } + } catch (error4) { + e = error4.message; + } + this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - /** - * Write a `fixed64` value, a signed, fixed-length 64-bit integer. - */ - sfixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbLong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + }; + exports2.ReflectionJsonReader = ReflectionJsonReader; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js +var require_reflection_json_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReflectionJsonWriter = void 0; + var base64_1 = require_base642(); + var pb_long_1 = require_pb_long(); + var reflection_info_1 = require_reflection_info(); + var assert_1 = require_assert(); + var ReflectionJsonWriter = class { + constructor(info6) { + var _a; + this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; } /** - * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + * Converts the message to a JSON object, based on the field descriptors. */ - fixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbULong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); + write(message, options) { + const json2 = {}, source = message; + for (const field of this.fields) { + if (!field.oneof) { + let jsonValue2 = this.field(field, source[field.localName], options); + if (jsonValue2 !== void 0) + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; + continue; + } + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; + const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== void 0); + json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + } + return json2; } - /** - * Write a `int64` value, a signed 64-bit varint. - */ - int64(value) { - let long = pb_long_1.PbLong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + field(field, value, options) { + let jsonValue = void 0; + if (field.kind == "map") { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val2 = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); + const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonObj[entryKey.toString()] = val2; + } + break; + } + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); + const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val2 = this.message(messageType, value[i], field.name, options); + assert_1.assert(val2 !== void 0); + jsonArr.push(val2); + } + break; + } + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } + } + return jsonValue; } /** - * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + * Returns `null` as the default for google.protobuf.NullValue. */ - sint64(value) { - let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign; - goog_varint_1.varint64write(lo, hi, this.buf); - return this; + enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type2[0] == "google.protobuf.NullValue") + return !emitDefaultValues && !optional ? void 0 : null; + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + if (value === 0 && !emitDefaultValues && !optional) + return void 0; + assert_1.assert(typeof value == "number"); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type2[1].hasOwnProperty(value)) + return value; + if (type2[2]) + return type2[2] + type2[1][value]; + return type2[1][value]; } - /** - * Write a `uint64` value, an unsigned 64-bit varint. - */ - uint64(value) { - let long = pb_long_1.PbULong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + message(type2, value, fieldName, options) { + if (value === void 0) + return options.emitDefaultValues ? null : void 0; + return type2.internalJsonWrite(value, options); } - }; - exports2.BinaryWriter = BinaryWriter; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js -var require_json_format_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0; - var defaultsWrite = { - emitDefaultValues: false, - enumAsInteger: false, - useProtoFieldName: false, - prettySpaces: 0 - }; - var defaultsRead = { - ignoreUnknownFields: false - }; - function jsonReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; - } - exports2.jsonReadOptions = jsonReadOptions; - function jsonWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; - } - exports2.jsonWriteOptions = jsonWriteOptions; - function mergeJsonOptions(a, b) { - var _a, _b; - let c = Object.assign(Object.assign({}, a), b); - c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []]; - return c; - } - exports2.mergeJsonOptions = mergeJsonOptions; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js -var require_message_type_contract = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MESSAGE_TYPE = void 0; - exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js -var require_lower_camel_case = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.lowerCamelCase = void 0; - function lowerCamelCase(snakeCase) { - let capNext = false; - const sb = []; - for (let i = 0; i < snakeCase.length; i++) { - let next = snakeCase.charAt(i); - if (next == "_") { - capNext = true; - } else if (/\d/.test(next)) { - sb.push(next); - capNext = true; - } else if (capNext) { - sb.push(next.toUpperCase()); - capNext = false; - } else if (i == 0) { - sb.push(next.toLowerCase()); - } else { - sb.push(next); + scalar(type2, value, fieldName, optional, emitDefaultValues) { + if (value === void 0) { + assert_1.assert(optional); + return void 0; + } + const ed = emitDefaultValues || optional; + switch (type2) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : void 0; + assert_1.assert(typeof value == "number"); + if (Number.isNaN(value)) + return "NaN"; + if (value === Number.POSITIVE_INFINITY) + return "Infinity"; + if (value === Number.NEGATIVE_INFINITY) + return "-Infinity"; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? "" : void 0; + assert_1.assert(typeof value == "string"); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : void 0; + assert_1.assert(typeof value == "boolean"); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return void 0; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return void 0; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : void 0; + return base64_1.base64encode(value); } } - return sb.join(""); - } - exports2.lowerCamelCase = lowerCamelCase; + }; + exports2.ReflectionJsonWriter = ReflectionJsonWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js -var require_reflection_info = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js +var require_reflection_scalar_default = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0; - var lower_camel_case_1 = require_lower_camel_case(); - var ScalarType; - (function(ScalarType2) { - ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE"; - ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT"; - ScalarType2[ScalarType2["INT64"] = 3] = "INT64"; - ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64"; - ScalarType2[ScalarType2["INT32"] = 5] = "INT32"; - ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64"; - ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32"; - ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL"; - ScalarType2[ScalarType2["STRING"] = 9] = "STRING"; - ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES"; - ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32"; - ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32"; - ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64"; - ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32"; - ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64"; - })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {})); - var LongType; - (function(LongType2) { - LongType2[LongType2["BIGINT"] = 0] = "BIGINT"; - LongType2[LongType2["STRING"] = 1] = "STRING"; - LongType2[LongType2["NUMBER"] = 2] = "NUMBER"; - })(LongType = exports2.LongType || (exports2.LongType = {})); - var RepeatType; - (function(RepeatType2) { - RepeatType2[RepeatType2["NO"] = 0] = "NO"; - RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED"; - RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED"; - })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {})); - function normalizeFieldInfo(field) { - var _a, _b, _c, _d; - field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); - field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); - field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; - field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message"; - return field; - } - exports2.normalizeFieldInfo = normalizeFieldInfo; - function readFieldOptions(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readFieldOptions = readFieldOptions; - function readFieldOption(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; - } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readFieldOption = readFieldOption; - function readMessageOption(messageType, extensionName, extensionType) { - const options = messageType.options; - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + exports2.reflectionScalarDefault = void 0; + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var pb_long_1 = require_pb_long(); + function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { + switch (type2) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + return 0; } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - exports2.readMessageOption = readMessageOption; + exports2.reflectionScalarDefault = reflectionScalarDefault; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js -var require_oneof = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js +var require_reflection_binary_reader = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0; - function isOneofGroup(any) { - if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) { - return false; - } - switch (typeof any.oneofKind) { - case "string": - if (any[any.oneofKind] === void 0) - return false; - return Object.keys(any).length == 2; - case "undefined": - return Object.keys(any).length == 1; - default: - return false; - } - } - exports2.isOneofGroup = isOneofGroup; - function getOneofValue(oneof, kind) { - return oneof[kind]; - } - exports2.getOneofValue = getOneofValue; - function setOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== void 0) { - oneof[kind] = value; + exports2.ReflectionBinaryReader = void 0; + var binary_format_contract_1 = require_binary_format_contract(); + var reflection_info_1 = require_reflection_info(); + var reflection_long_convert_1 = require_reflection_long_convert(); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var ReflectionBinaryReader = class { + constructor(info6) { + this.info = info6; } - } - exports2.setOneofValue = setOneofValue; - function setUnknownOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + } } - oneof.oneofKind = kind; - if (value !== void 0 && kind !== void 0) { - oneof[kind] = value; + /** + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(reader, message, options, length) { + this.prepare(); + const end = length === void 0 ? reader.len : reader.pos + length; + while (reader.pos < end) { + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; + } + let target = message, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + target = target[field.oneof]; + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : void 0; + if (repeated) { + let arr = target[localName]; + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } else + arr.push(this.scalar(reader, T, L)); + } else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + target[localName][mapKey] = mapVal; + break; + } + } } - } - exports2.setUnknownOneofValue = setUnknownOneofValue; - function clearOneofValue(oneof) { - if (oneof.oneofKind !== void 0) { - delete oneof[oneof.oneofKind]; + /** + * Read a map field, expecting key field = 1, value field = 2 + */ + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = void 0; + let val2 = void 0; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val2 = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val2 = reader.int32(); + break; + case "message": + val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } + } + if (key === void 0) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val2 === void 0) + switch (field.V.kind) { + case "scalar": + val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val2 = 0; + break; + case "message": + val2 = field.V.T().create(); + break; + } + return [key, val2]; } - oneof.oneofKind = void 0; - } - exports2.clearOneofValue = clearOneofValue; - function getSelectedOneofValue(oneof) { - if (oneof.oneofKind === void 0) { - return void 0; + scalar(reader, type2, longType) { + switch (type2) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } } - return oneof[oneof.oneofKind]; - } - exports2.getSelectedOneofValue = getSelectedOneofValue; + }; + exports2.ReflectionBinaryReader = ReflectionBinaryReader; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js -var require_reflection_type_check = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js +var require_reflection_binary_writer = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionTypeCheck = void 0; + exports2.ReflectionBinaryWriter = void 0; + var binary_format_contract_1 = require_binary_format_contract(); var reflection_info_1 = require_reflection_info(); - var oneof_1 = require_oneof(); - var ReflectionTypeCheck = class { + var assert_1 = require_assert(); + var pb_long_1 = require_pb_long(); + var ReflectionBinaryWriter = class { constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + this.info = info6; } prepare() { - if (this.data) - return; - const req = [], known = [], oneofs = []; - for (let field of this.fields) { - if (field.oneof) { - if (!oneofs.includes(field.oneof)) { - oneofs.push(field.oneof); - req.push(field.oneof); - known.push(field.oneof); - } - } else { - known.push(field.localName); - switch (field.kind) { - case "scalar": - case "enum": - if (!field.opt || field.repeat) - req.push(field.localName); - break; - case "message": - if (field.repeat) - req.push(field.localName); - break; - case "map": - req.push(field.localName); - break; - } - } + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); } - this.data = { req, known, oneofs: Object.values(oneofs) }; } /** - * Is the argument a valid message as specified by the - * reflection information? - * - * Checks all field types recursively. The `depth` - * specifies how deep into the structure the check will be. - * - * With a depth of 0, only the presence of fields - * is checked. - * - * With a depth of 1 or more, the field types are checked. - * - * With a depth of 2 or more, the members of map, repeated - * and message fields are checked. - * - * Message fields will be checked recursively with depth - 1. - * - * The number of map entries / repeated values being checked - * is < depth. + * Writes the message to binary format. */ - is(message, depth, allowExcessProperties = false) { - if (depth < 0) - return true; - if (message === null || message === void 0 || typeof message != "object") - return false; + write(message, writer, options) { this.prepare(); - let keys = Object.keys(message), data = this.data; - if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n))) - return false; - if (!allowExcessProperties) { - if (keys.some((k) => !data.known.includes(k))) - return false; - } - if (depth < 1) { - return true; - } - for (const name of data.oneofs) { - const group = message[name]; - if (!oneof_1.isOneofGroup(group)) - return false; - if (group.oneofKind === void 0) - continue; - const field = this.fields.find((f) => f.localName === group.oneofKind); - if (!field) - return false; - if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) - return false; - } for (const field of this.fields) { - if (field.oneof !== void 0) - continue; - if (!this.field(message[field.localName], field, allowExcessProperties, depth)) - return false; + let value, emitDefault, repeated = field.repeat, localName = field.localName; + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; + value = group[localName]; + emitDefault = true; + } else { + value = message[localName]; + emitDefault = false; + } + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } else if (value === void 0) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == "object" && value !== null); + for (const [key, val2] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val2); + break; + } } - return true; + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); } - field(arg, field, allowExcessProperties, depth) { - let repeated = field.repeat; - switch (field.kind) { + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); + break; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == "true" || key == "false"); + keyValue = key == "true"; + break; + } + this.scalar(writer, field.K, 1, keyValue, true); + switch (field.V.kind) { case "scalar": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, field.T, depth, field.L); - return this.scalar(arg, field.T, field.L); + this.scalar(writer, field.V.T, 2, value, true); + break; case "enum": - if (arg === void 0) - return field.opt; - if (repeated) - return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); - return this.scalar(arg, reflection_info_1.ScalarType.INT32); + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; case "message": - if (arg === void 0) - return true; - if (repeated) - return this.messages(arg, field.T(), allowExcessProperties, depth); - return this.message(arg, field.T(), allowExcessProperties, depth); - case "map": - if (typeof arg != "object" || arg === null) - return false; - if (depth < 2) - return true; - if (!this.mapKeys(arg, field.K, depth)) - return false; - switch (field.V.kind) { - case "scalar": - return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); - case "enum": - return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); - case "message": - return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); - } + this.message(writer, options, field.V.T(), 2, value); break; } - return true; + writer.join(); } - message(arg, type2, allowExcessProperties, depth) { - if (allowExcessProperties) { - return type2.isAssignable(arg, depth); - } - return type2.is(arg, depth); + message(writer, options, handler, fieldNo, value) { + if (value === void 0) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); } - messages(arg, type2, allowExcessProperties, depth) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (allowExcessProperties) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.isAssignable(arg[i], depth - 1)) - return false; - } else { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type2.is(arg[i], depth - 1)) - return false; + /** + * Write a single scalar value. + */ + scalar(writer, type2, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type2, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); } - return true; } - scalar(arg, type2, longType) { - let argType = typeof arg; + /** + * Write an array of scalar values in packed format. + */ + packed(writer, type2, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + let [, method] = this.scalarInfo(type2); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + writer.join(); + } + /** + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. + */ + scalarInfo(type2, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === void 0; + let d = value === 0; switch (type2) { - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - switch (longType) { - case reflection_info_1.LongType.BIGINT: - return argType == "bigint"; - case reflection_info_1.LongType.NUMBER: - return argType == "number" && !isNaN(arg); - default: - return argType == "string"; - } - case reflection_info_1.ScalarType.BOOL: - return argType == "boolean"; + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; case reflection_info_1.ScalarType.STRING: - return argType == "string"; - case reflection_info_1.ScalarType.BYTES: - return arg instanceof Uint8Array; + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; case reflection_info_1.ScalarType.FLOAT: - return argType == "number" && !isNaN(arg); - default: - return argType == "number" && Number.isInteger(arg); - } - } - scalars(arg, type2, depth, longType) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (Array.isArray(arg)) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!this.scalar(arg[i], type2, longType)) - return false; - } - return true; - } - mapKeys(map2, type2, depth) { - let keys = Object.keys(map2); - switch (type2) { - case reflection_info_1.ScalarType.INT32: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth); - case reflection_info_1.ScalarType.BOOL: - return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth); - default: - return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING); + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; } + return [t, m, i || d]; } }; - exports2.ReflectionTypeCheck = ReflectionTypeCheck; + exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js -var require_reflection_long_convert = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js +var require_reflection_create = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionLongConvert = void 0; + exports2.reflectionCreate = void 0; + var reflection_scalar_default_1 = require_reflection_scalar_default(); + var message_type_contract_1 = require_message_type_contract(); + function reflectionCreate(type2) { + const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); + for (let field of type2.fields) { + let name = field.localName; + if (field.opt) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: void 0 }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } + } + return msg; + } + exports2.reflectionCreate = reflectionCreate; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js +var require_reflection_merge_partial = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionMergePartial = void 0; + function reflectionMergePartial(info6, target, source) { + let fieldValue, input = source, output; + for (let field of info6.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { + continue; + } + fieldValue = group[name]; + output = target[field.oneof]; + output.oneofKind = group.oneofKind; + if (fieldValue == void 0) { + delete output[name]; + continue; + } + } else { + fieldValue = input[name]; + output = target; + if (fieldValue == void 0) { + continue; + } + } + if (field.repeat) + output[name].length = fieldValue.length; + switch (field.kind) { + case "scalar": + case "enum": + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; + else + output[name] = fieldValue; + break; + case "message": + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === void 0) + output[name] = T.create(fieldValue); + else + T.mergePartial(output[name], fieldValue); + break; + case "map": + switch (field.V.kind) { + case "scalar": + case "enum": + Object.assign(output[name], fieldValue); + break; + case "message": + let T2 = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T2.create(fieldValue[k]); + break; + } + break; + } + } + } + exports2.reflectionMergePartial = reflectionMergePartial; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js +var require_reflection_equals = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.reflectionEquals = void 0; var reflection_info_1 = require_reflection_info(); - function reflectionLongConvert(long, type2) { - switch (type2) { - case reflection_info_1.LongType.BIGINT: - return long.toBigInt(); - case reflection_info_1.LongType.NUMBER: - return long.toNumber(); - default: - return long.toString(); + function reflectionEquals(info6, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info6.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) + return false; + break; + } } + return true; + } + exports2.reflectionEquals = reflectionEquals; + var objectValues = Object.values; + function primitiveEq(type2, a, b) { + if (a === b) + return true; + if (type2 !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; + } + function repeatedPrimitiveEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type2, a[i], b[i])) + return false; + return true; + } + function repeatedMsgEq(type2, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type2.equals(a[i], b[i])) + return false; + return true; } - exports2.reflectionLongConvert = reflectionLongConvert; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js -var require_reflection_json_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js +var require_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonReader = void 0; - var json_typings_1 = require_json_typings(); - var base64_1 = require_base642(); + exports2.MessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); var reflection_info_1 = require_reflection_info(); - var pb_long_1 = require_pb_long(); - var assert_1 = require_assert(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var ReflectionJsonReader = class { - constructor(info6) { - this.info = info6; + var reflection_type_check_1 = require_reflection_type_check(); + var reflection_json_reader_1 = require_reflection_json_reader(); + var reflection_json_writer_1 = require_reflection_json_writer(); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + var reflection_create_1 = require_reflection_create(); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + var json_typings_1 = require_json_typings(); + var json_format_contract_1 = require_json_format_contract(); + var reflection_equals_1 = require_reflection_equals(); + var binary_writer_1 = require_binary_writer(); + var binary_reader_1 = require_binary_reader(); + var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); + var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; + var MessageType = class { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + messageTypeDescriptor.value = this; + this.messagePrototype = Object.create(null, baseDescriptors); + this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); + this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); + this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } - prepare() { - var _a; - if (this.fMap === void 0) { - this.fMap = {}; - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - for (const field of fieldsInput) { - this.fMap[field.name] = field; - this.fMap[field.jsonName] = field; - this.fMap[field.localName] = field; - } + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== void 0) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); } + return message; } - // Cannot parse JSON for #. - assert(condition, fieldName, jsonValue) { - if (!condition) { - let what = json_typings_1.typeofJsonValue(jsonValue); - if (what == "number" || what == "boolean") - what = jsonValue.toString(); - throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + /** + * Clone the message. + * + * Unknown fields are discarded. + */ + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; + } + /** + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. + */ + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); + } + /** + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); + } + /** + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); + } + /** + * Copy partial data into the target message. + */ + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); + } + /** + * Create a new message from binary format. + */ + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + } + /** + * Read a new message from a JSON value. + */ + fromJson(json2, options) { + return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + } + /** + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. + */ + fromJsonString(json2, options) { + let value = JSON.parse(json2); + return this.fromJson(value, options); + } + /** + * Write the message to canonical JSON value. + */ + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + } + /** + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` + */ + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + } + /** + * Write the message to binary format. + */ + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + } + /** + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. + */ + internalJsonRead(json2, options, target) { + if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json2, message, options); + return message; } + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); } /** - * Reads a message from canonical JSON format into the target message. + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); + } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. * - * If a message field is already present, it will be merged with the - * new data. + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. */ - read(input, message, options) { - this.prepare(); - const oneofsHandled = []; - for (const [jsonKey, jsonValue] of Object.entries(input)) { - const field = this.fMap[jsonKey]; - if (!field) { - if (!options.ignoreUnknownFields) - throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); - continue; - } - const localName = field.localName; - let target; - if (field.oneof) { - if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) { - continue; - } - if (oneofsHandled.includes(field.oneof)) - throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); - oneofsHandled.push(field.oneof); - target = message[field.oneof] = { - oneofKind: localName - }; - } else { - target = message; - } - if (field.kind == "map") { - if (jsonValue === null) { - continue; - } - this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); - const fieldObj = target[localName]; - for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { - this.assert(jsonObjValue !== null, field.name + " map value", null); - let val2; - switch (field.V.kind) { - case "message": - val2 = field.V.T().internalJsonRead(jsonObjValue, options); - break; - case "enum": - val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name + " map value", jsonObjValue); - let key = jsonObjKey; - if (field.K == reflection_info_1.ScalarType.BOOL) - key = key == "true" ? true : key == "false" ? false : key; - key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); - fieldObj[key] = val2; - } - } else if (field.repeat) { - if (jsonValue === null) - continue; - this.assert(Array.isArray(jsonValue), field.name, jsonValue); - const fieldArr = target[localName]; - for (const jsonItem of jsonValue) { - this.assert(jsonItem !== null, field.name, null); - let val2; - switch (field.kind) { - case "message": - val2 = field.T().internalJsonRead(jsonItem, options); - break; - case "enum": - val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - break; - case "scalar": - val2 = this.scalar(jsonItem, field.T, field.L, field.name); - break; - } - this.assert(val2 !== void 0, field.name, jsonValue); - fieldArr.push(val2); - } - } else { - switch (field.kind) { - case "message": - if (jsonValue === null && field.T().typeName != "google.protobuf.Value") { - this.assert(field.oneof === void 0, field.name + " (oneof member)", null); - continue; - } - target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); - break; - case "enum": - if (jsonValue === null) - continue; - let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); - if (val2 === false) - continue; - target[localName] = val2; - break; - case "scalar": - if (jsonValue === null) - continue; - target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); - break; - } - } - } + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; } /** - * Returns `false` for unrecognized string representations. + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. * - * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. */ - enum(type2, json2, fieldName, ignoreUnknownFields) { - if (type2[0] == "google.protobuf.NullValue") - assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`); - if (json2 === null) - return 0; - switch (typeof json2) { - case "number": - assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`); - return json2; - case "string": - let localEnumName = json2; - if (type2[2] && json2.substring(0, type2[2].length) === type2[2]) - localEnumName = json2.substring(type2[2].length); - let enumNumber = type2[1][localEnumName]; - if (typeof enumNumber === "undefined" && ignoreUnknownFields) { - return false; - } - assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`); - return enumNumber; - } - assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`); + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; } - scalar(json2, type2, longType, fieldName) { - let e; - try { - switch (type2) { - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - if (json2 === null) - return 0; - if (json2 === "NaN") - return Number.NaN; - if (json2 === "Infinity") - return Number.POSITIVE_INFINITY; - if (json2 === "-Infinity") - return Number.NEGATIVE_INFINITY; - if (json2 === "") { - e = "empty string"; - break; - } - if (typeof json2 == "string" && json2.trim().length !== json2.length) { - e = "extra whitespace"; - break; - } - if (typeof json2 != "string" && typeof json2 != "number") { - break; - } - let float2 = Number(json2); - if (Number.isNaN(float2)) { - e = "not a number"; - break; - } - if (!Number.isFinite(float2)) { - e = "too large or small"; - break; - } - if (type2 == reflection_info_1.ScalarType.FLOAT) - assert_1.assertFloat32(float2); - return float2; - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - if (json2 === null) - return 0; - let int32; - if (typeof json2 == "number") - int32 = json2; - else if (json2 === "") - e = "empty string"; - else if (typeof json2 == "string") { - if (json2.trim().length !== json2.length) - e = "extra whitespace"; - else - int32 = Number(json2); - } - if (int32 === void 0) - break; - if (type2 == reflection_info_1.ScalarType.UINT32) - assert_1.assertUInt32(int32); - else - assert_1.assertInt32(int32); - return int32; - // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType); - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.UINT64: - if (json2 === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - if (typeof json2 != "number" && typeof json2 != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType); - // bool: - case reflection_info_1.ScalarType.BOOL: - if (json2 === null) - return false; - if (typeof json2 !== "boolean") - break; - return json2; - // string: - case reflection_info_1.ScalarType.STRING: - if (json2 === null) - return ""; - if (typeof json2 !== "string") { - e = "extra whitespace"; - break; - } - try { - encodeURIComponent(json2); - } catch (e2) { - e2 = "invalid UTF8"; - break; - } - return json2; - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - if (json2 === null || json2 === "") - return new Uint8Array(0); - if (typeof json2 !== "string") - break; - return base64_1.base64decode(json2); - } - } catch (error4) { - e = error4.message; + }; + exports2.MessageType = MessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js +var require_reflection_contains_message_type = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.containsMessageType = void 0; + var message_type_contract_1 = require_message_type_contract(); + function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; + } + exports2.containsMessageType = containsMessageType; + } +}); + +// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js +var require_enum_object = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; + function isEnumObject(arg) { + if (typeof arg != "object" || arg === null) { + return false; + } + if (!arg.hasOwnProperty(0)) { + return false; + } + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + let nam = arg[num]; + if (nam === void 0) + return false; + if (arg[nam] !== num) + return false; + } else { + let num2 = arg[k]; + if (num2 === void 0) + return false; + if (typeof num2 !== "number") + return false; + if (arg[num2] === void 0) + return false; } - this.assert(false, fieldName + (e ? " - " + e : ""), json2); } - }; - exports2.ReflectionJsonReader = ReflectionJsonReader; + return true; + } + exports2.isEnumObject = isEnumObject; + function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; + } + exports2.listEnumValues = listEnumValues; + function listEnumNames(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.name); + } + exports2.listEnumNames = listEnumNames; + function listEnumNumbers(enumObject) { + return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + } + exports2.listEnumNumbers = listEnumNumbers; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js -var require_reflection_json_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime/build/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionJsonWriter = void 0; + var json_typings_1 = require_json_typings(); + Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { + return json_typings_1.typeofJsonValue; + } }); + Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { + return json_typings_1.isJsonObject; + } }); var base64_1 = require_base642(); + Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { + return base64_1.base64decode; + } }); + Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { + return base64_1.base64encode; + } }); + var protobufjs_utf8_1 = require_protobufjs_utf8(); + Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { + return protobufjs_utf8_1.utf8read; + } }); + var binary_format_contract_1 = require_binary_format_contract(); + Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { + return binary_format_contract_1.WireType; + } }); + Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { + return binary_format_contract_1.mergeBinaryOptions; + } }); + Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { + return binary_format_contract_1.UnknownFieldHandler; + } }); + var binary_reader_1 = require_binary_reader(); + Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { + return binary_reader_1.BinaryReader; + } }); + Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { + return binary_reader_1.binaryReadOptions; + } }); + var binary_writer_1 = require_binary_writer(); + Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { + return binary_writer_1.BinaryWriter; + } }); + Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { + return binary_writer_1.binaryWriteOptions; + } }); var pb_long_1 = require_pb_long(); + Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { + return pb_long_1.PbLong; + } }); + Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { + return pb_long_1.PbULong; + } }); + var json_format_contract_1 = require_json_format_contract(); + Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonReadOptions; + } }); + Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { + return json_format_contract_1.jsonWriteOptions; + } }); + Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { + return json_format_contract_1.mergeJsonOptions; + } }); + var message_type_contract_1 = require_message_type_contract(); + Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { + return message_type_contract_1.MESSAGE_TYPE; + } }); + var message_type_1 = require_message_type(); + Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { + return message_type_1.MessageType; + } }); var reflection_info_1 = require_reflection_info(); + Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { + return reflection_info_1.ScalarType; + } }); + Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { + return reflection_info_1.LongType; + } }); + Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { + return reflection_info_1.RepeatType; + } }); + Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { + return reflection_info_1.normalizeFieldInfo; + } }); + Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { + return reflection_info_1.readFieldOptions; + } }); + Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { + return reflection_info_1.readFieldOption; + } }); + Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { + return reflection_info_1.readMessageOption; + } }); + var reflection_type_check_1 = require_reflection_type_check(); + Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { + return reflection_type_check_1.ReflectionTypeCheck; + } }); + var reflection_create_1 = require_reflection_create(); + Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { + return reflection_create_1.reflectionCreate; + } }); + var reflection_scalar_default_1 = require_reflection_scalar_default(); + Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { + return reflection_scalar_default_1.reflectionScalarDefault; + } }); + var reflection_merge_partial_1 = require_reflection_merge_partial(); + Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { + return reflection_merge_partial_1.reflectionMergePartial; + } }); + var reflection_equals_1 = require_reflection_equals(); + Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { + return reflection_equals_1.reflectionEquals; + } }); + var reflection_binary_reader_1 = require_reflection_binary_reader(); + Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { + return reflection_binary_reader_1.ReflectionBinaryReader; + } }); + var reflection_binary_writer_1 = require_reflection_binary_writer(); + Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { + return reflection_binary_writer_1.ReflectionBinaryWriter; + } }); + var reflection_json_reader_1 = require_reflection_json_reader(); + Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { + return reflection_json_reader_1.ReflectionJsonReader; + } }); + var reflection_json_writer_1 = require_reflection_json_writer(); + Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { + return reflection_json_writer_1.ReflectionJsonWriter; + } }); + var reflection_contains_message_type_1 = require_reflection_contains_message_type(); + Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { + return reflection_contains_message_type_1.containsMessageType; + } }); + var oneof_1 = require_oneof(); + Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { + return oneof_1.isOneofGroup; + } }); + Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { + return oneof_1.setOneofValue; + } }); + Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { + return oneof_1.getOneofValue; + } }); + Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { + return oneof_1.clearOneofValue; + } }); + Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { + return oneof_1.getSelectedOneofValue; + } }); + var enum_object_1 = require_enum_object(); + Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { + return enum_object_1.listEnumValues; + } }); + Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { + return enum_object_1.listEnumNames; + } }); + Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { + return enum_object_1.listEnumNumbers; + } }); + Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { + return enum_object_1.isEnumObject; + } }); + var lower_camel_case_1 = require_lower_camel_case(); + Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { + return lower_camel_case_1.lowerCamelCase; + } }); var assert_1 = require_assert(); - var ReflectionJsonWriter = class { - constructor(info6) { - var _a; - this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : []; + Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { + return assert_1.assert; + } }); + Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { + return assert_1.assertNever; + } }); + Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { + return assert_1.assertInt32; + } }); + Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { + return assert_1.assertUInt32; + } }); + Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { + return assert_1.assertFloat32; + } }); + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js +var require_reflection_info2 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + var runtime_1 = require_commonjs11(); + function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + m.serverStreaming = !!m.serverStreaming; + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; + return m; + } + exports2.normalizeMethodInfo = normalizeMethodInfo; + function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; + } + exports2.readMethodOptions = readMethodOptions; + function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return void 0; } - /** - * Converts the message to a JSON object, based on the field descriptors. - */ - write(message, options) { - const json2 = {}, source = message; - for (const field of this.fields) { - if (!field.oneof) { - let jsonValue2 = this.field(field, source[field.localName], options); - if (jsonValue2 !== void 0) - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2; - continue; - } - const group = source[field.oneof]; - if (group.oneofKind !== field.localName) - continue; - const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; - let jsonValue = this.field(field, group[field.localName], opt); - assert_1.assert(jsonValue !== void 0); - json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; - } - return json2; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - field(field, value, options) { - let jsonValue = void 0; - if (field.kind == "map") { - assert_1.assert(typeof value == "object" && value !== null); - const jsonObj = {}; - switch (field.V.kind) { - case "scalar": - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.scalar(field.V.T, entryValue, field.name, false, true); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "message": - const messageType = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - const val2 = this.message(messageType, entryValue, field.name, options); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - case "enum": - const enumInfo = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - assert_1.assert(entryValue === void 0 || typeof entryValue == "number"); - const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonObj[entryKey.toString()] = val2; - } - break; - } - if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) - jsonValue = jsonObj; - } else if (field.repeat) { - assert_1.assert(Array.isArray(value)); - const jsonArr = []; - switch (field.kind) { - case "scalar": - for (let i = 0; i < value.length; i++) { - const val2 = this.scalar(field.T, value[i], field.name, field.opt, true); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "enum": - const enumInfo = field.T(); - for (let i = 0; i < value.length; i++) { - assert_1.assert(value[i] === void 0 || typeof value[i] == "number"); - const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - case "message": - const messageType = field.T(); - for (let i = 0; i < value.length; i++) { - const val2 = this.message(messageType, value[i], field.name, options); - assert_1.assert(val2 !== void 0); - jsonArr.push(val2); - } - break; - } - if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) - jsonValue = jsonArr; - } else { - switch (field.kind) { - case "scalar": - jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); - break; - case "enum": - jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); - break; - case "message": - jsonValue = this.message(field.T(), value, field.name, options); - break; - } - } - return jsonValue; + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readMethodOption = readMethodOption; + function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return void 0; } - /** - * Returns `null` as the default for google.protobuf.NullValue. - */ - enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) { - if (type2[0] == "google.protobuf.NullValue") - return !emitDefaultValues && !optional ? void 0 : null; - if (value === void 0) { - assert_1.assert(optional); - return void 0; - } - if (value === 0 && !emitDefaultValues && !optional) - return void 0; - assert_1.assert(typeof value == "number"); - assert_1.assert(Number.isInteger(value)); - if (enumAsInteger || !type2[1].hasOwnProperty(value)) - return value; - if (type2[2]) - return type2[2] + type2[1][value]; - return type2[1][value]; + const optionVal = options[extensionName]; + if (optionVal === void 0) { + return optionVal; } - message(type2, value, fieldName, options) { - if (value === void 0) - return options.emitDefaultValues ? null : void 0; - return type2.internalJsonWrite(value, options); + return extensionType ? extensionType.fromJson(optionVal) : optionVal; + } + exports2.readServiceOption = readServiceOption; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js +var require_service_type = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServiceType = void 0; + var reflection_info_1 = require_reflection_info2(); + var ServiceType = class { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; } - scalar(type2, value, fieldName, optional, emitDefaultValues) { - if (value === void 0) { - assert_1.assert(optional); - return void 0; + }; + exports2.ServiceType = ServiceType; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js +var require_rpc_error = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcError = void 0; + var RpcError = class extends Error { + constructor(message, code = "UNKNOWN", meta) { + super(message); + this.name = "RpcError"; + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; + } + toString() { + const l = [this.name + ": " + this.message]; + if (this.code) { + l.push(""); + l.push("Code: " + this.code); } - const ed = emitDefaultValues || optional; - switch (type2) { - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertInt32(value); - return value; - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assertUInt32(value); - return value; - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.FLOAT: - assert_1.assertFloat32(value); - case reflection_info_1.ScalarType.DOUBLE: - if (value === 0) - return ed ? 0 : void 0; - assert_1.assert(typeof value == "number"); - if (Number.isNaN(value)) - return "NaN"; - if (value === Number.POSITIVE_INFINITY) - return "Infinity"; - if (value === Number.NEGATIVE_INFINITY) - return "-Infinity"; - return value; - // string: - case reflection_info_1.ScalarType.STRING: - if (value === "") - return ed ? "" : void 0; - assert_1.assert(typeof value == "string"); - return value; - // bool: - case reflection_info_1.ScalarType.BOOL: - if (value === false) - return ed ? false : void 0; - assert_1.assert(typeof value == "boolean"); - return value; - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let ulong = pb_long_1.PbULong.from(value); - if (ulong.isZero() && !ed) - return void 0; - return ulong.toString(); - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint"); - let long = pb_long_1.PbLong.from(value); - if (long.isZero() && !ed) - return void 0; - return long.toString(); - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - assert_1.assert(value instanceof Uint8Array); - if (!value.byteLength) - return ed ? "" : void 0; - return base64_1.base64encode(value); + if (this.serviceName && this.methodName) { + l.push("Method: " + this.serviceName + "/" + this.methodName); + } + let m = Object.entries(this.meta); + if (m.length) { + l.push(""); + l.push("Meta:"); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); + } } + return l.join("\n"); } }; - exports2.ReflectionJsonWriter = ReflectionJsonWriter; + exports2.RpcError = RpcError; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js -var require_reflection_scalar_default = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js +var require_rpc_options = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionScalarDefault = void 0; - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var pb_long_1 = require_pb_long(); - function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) { - switch (type2) { - case reflection_info_1.ScalarType.BOOL: - return false; - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return 0; - case reflection_info_1.ScalarType.BYTES: - return new Uint8Array(0); - case reflection_info_1.ScalarType.STRING: - return ""; - default: - return 0; + exports2.mergeRpcOptions = void 0; + var runtime_1 = require_commonjs11(); + function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val2 = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); + break; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); + break; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); + break; + } + } + return o; + } + exports2.mergeRpcOptions = mergeRpcOptions; + function copy(a, into) { + if (!a) + return; + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; } } - exports2.reflectionScalarDefault = reflectionScalarDefault; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js -var require_reflection_binary_reader = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js +var require_deferred = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryReader = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_long_convert_1 = require_reflection_long_convert(); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var ReflectionBinaryReader = class { - constructor(info6) { - this.info = info6; - } - prepare() { - var _a; - if (!this.fieldNoToField) { - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field])); + exports2.Deferred = exports2.DeferredState = void 0; + var DeferredState; + (function(DeferredState2) { + DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; + DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; + DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; + })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); + var Deferred = class { + /** + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. + */ + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve6, reject) => { + this._resolve = resolve6; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch((_) => { + }); } } /** - * Reads a message from binary format into the target message. + * Get the current state of the promise. + */ + get state() { + return this._state; + } + /** + * Get the deferred promise. + */ + get promise() { + return this._promise; + } + /** + * Resolve the promise. Throws if the promise is already resolved or rejected. + */ + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; + } + /** + * Reject the promise. Throws if the promise is already resolved or rejected. + */ + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; + } + /** + * Resolve the promise. Ignore if not pending. + */ + resolvePending(val2) { + if (this._state === DeferredState.PENDING) + this.resolve(val2); + } + /** + * Reject the promise. Ignore if not pending. + */ + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); + } + }; + exports2.Deferred = Deferred; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js +var require_rpc_output_stream = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RpcOutputStreamController = void 0; + var deferred_1 = require_deferred(); + var runtime_1 = require_commonjs11(); + var RpcOutputStreamController = class { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [] + }; + this._closed = false; + this._itState = { q: [] }; + } + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); + } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); + } + // --- Controller API + /** + * Is this stream already closed by a completion or error? + */ + get closed() { + return this._closed !== false; + } + /** + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. + */ + notifyNext(message, error4, complete) { + runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); + if (message) + this.notifyMessage(message); + if (error4) + this.notifyError(error4); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, "stream is closed"); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach((l) => l(message)); + this._lis.nxt.forEach((l) => l(message, void 0, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. * - * If a message field is already present, it will be merged with the - * new data. + * Triggers onNext and onError callbacks. */ - read(reader, message, options, length) { - this.prepare(); - const end = length === void 0 ? reader.len : reader.pos + length; - while (reader.pos < end) { - const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); - if (!field) { - let u = options.readUnknownField; - if (u == "throw") - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); - continue; - } - let target = message, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - target = target[field.oneof]; - if (target.oneofKind !== localName) - target = message[field.oneof] = { - oneofKind: localName - }; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - let L = field.kind == "scalar" ? field.L : void 0; - if (repeated) { - let arr = target[localName]; - if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { - let e = reader.uint32() + reader.pos; - while (reader.pos < e) - arr.push(this.scalar(reader, T, L)); - } else - arr.push(this.scalar(reader, T, L)); - } else - target[localName] = this.scalar(reader, T, L); - break; - case "message": - if (repeated) { - let arr = target[localName]; - let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); - arr.push(msg); - } else - target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); - break; - case "map": - let [mapKey, mapVal] = this.mapEntry(field, reader, options); - target[localName][mapKey] = mapVal; - break; - } - } + notifyError(error4) { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = error4; + this.pushIt(error4); + this._lis.err.forEach((l) => l(error4)); + this._lis.nxt.forEach((l) => l(void 0, error4, false)); + this.clearLis(); } /** - * Read a map field, expecting key field = 1, value field = 2 + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. */ - mapEntry(field, reader, options) { - let length = reader.uint32(); - let end = reader.pos + length; - let key = void 0; - let val2 = void 0; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case 1: - if (field.K == reflection_info_1.ScalarType.BOOL) - key = reader.bool().toString(); - else - key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); - break; - case 2: - switch (field.V.kind) { - case "scalar": - val2 = this.scalar(reader, field.V.T, field.V.L); - break; - case "enum": - val2 = reader.int32(); - break; - case "message": - val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options); - break; - } - break; - default: - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + notifyComplete() { + runtime_1.assert(!this.closed, "stream is closed"); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach((l) => l()); + this._lis.nxt.forEach((l) => l(void 0, void 0, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); + runtime_1.assert(!state.p, "iterator contract broken"); + let first = state.q.shift(); + if (first) + return "value" in first ? Promise.resolve(first) : Promise.reject(first); + state.p = new deferred_1.Deferred(); + return state.p.promise; } + }; + } + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (state.p) { + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + "value" in result ? p.resolve(result) : p.reject(result); + delete state.p; + } else { + state.q.push(result); } - if (key === void 0) { - let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); - key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + }; + exports2.RpcOutputStreamController = RpcOutputStreamController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js +var require_unary_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); + } + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - if (val2 === void 0) - switch (field.V.kind) { - case "scalar": - val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); - break; - case "enum": - val2 = 0; - break; - case "message": - val2 = field.V.T().create(); - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return [key, val2]; - } - scalar(reader, type2, longType) { - switch (type2) { - case reflection_info_1.ScalarType.INT32: - return reader.int32(); - case reflection_info_1.ScalarType.STRING: - return reader.string(); - case reflection_info_1.ScalarType.BOOL: - return reader.bool(); - case reflection_info_1.ScalarType.DOUBLE: - return reader.double(); - case reflection_info_1.ScalarType.FLOAT: - return reader.float(); - case reflection_info_1.ScalarType.INT64: - return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); - case reflection_info_1.ScalarType.UINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); - case reflection_info_1.ScalarType.FIXED32: - return reader.fixed32(); - case reflection_info_1.ScalarType.BYTES: - return reader.bytes(); - case reflection_info_1.ScalarType.UINT32: - return reader.uint32(); - case reflection_info_1.ScalarType.SFIXED32: - return reader.sfixed32(); - case reflection_info_1.ScalarType.SFIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); - case reflection_info_1.ScalarType.SINT32: - return reader.sint32(); - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); } + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UnaryCall = void 0; + var UnaryCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryReader = ReflectionBinaryReader; + exports2.UnaryCall = UnaryCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js -var require_reflection_binary_writer = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js +var require_server_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReflectionBinaryWriter = void 0; - var binary_format_contract_1 = require_binary_format_contract(); - var reflection_info_1 = require_reflection_info(); - var assert_1 = require_assert(); - var pb_long_1 = require_pb_long(); - var ReflectionBinaryWriter = class { - constructor(info6) { - this.info = info6; - } - prepare() { - if (!this.fields) { - const fieldsInput = this.info.fields ? this.info.fields.concat() : []; - this.fields = fieldsInput.sort((a, b) => a.no - b.no); - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); } - /** - * Writes the message to binary format. - */ - write(message, writer, options) { - this.prepare(); - for (const field of this.fields) { - let value, emitDefault, repeated = field.repeat, localName = field.localName; - if (field.oneof) { - const group = message[field.oneof]; - if (group.oneofKind !== localName) - continue; - value = group[localName]; - emitDefault = true; - } else { - value = message[localName]; - emitDefault = false; - } - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (repeated) { - assert_1.assert(Array.isArray(value)); - if (repeated == reflection_info_1.RepeatType.PACKED) - this.packed(writer, T, field.no, value); - else - for (const item of value) - this.scalar(writer, T, field.no, item, true); - } else if (value === void 0) - assert_1.assert(field.opt); - else - this.scalar(writer, T, field.no, value, emitDefault || field.opt); - break; - case "message": - if (repeated) { - assert_1.assert(Array.isArray(value)); - for (const item of value) - this.message(writer, options, field.T(), field.no, item); - } else { - this.message(writer, options, field.T(), field.no, value); - } - break; - case "map": - assert_1.assert(typeof value == "object" && value !== null); - for (const [key, val2] of Object.entries(value)) - this.mapEntry(writer, options, field, key, val2); - break; + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - let u = options.writeUnknownFields; - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); - } - mapEntry(writer, options, field, key, value) { - writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let keyValue = key; - switch (field.K) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - keyValue = Number.parseInt(key); - break; - case reflection_info_1.ScalarType.BOOL: - assert_1.assert(key == "true" || key == "false"); - keyValue = key == "true"; - break; - } - this.scalar(writer, field.K, 1, keyValue, true); - switch (field.V.kind) { - case "scalar": - this.scalar(writer, field.V.T, 2, value, true); - break; - case "enum": - this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); - break; - case "message": - this.message(writer, options, field.V.T(), 2, value); - break; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - writer.join(); - } - message(writer, options, handler, fieldNo, value) { - if (value === void 0) - return; - handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); - writer.join(); - } - /** - * Write a single scalar value. - */ - scalar(writer, type2, fieldNo, value, emitDefault) { - let [wireType, method, isDefault] = this.scalarInfo(type2, value); - if (!isDefault || emitDefault) { - writer.tag(fieldNo, wireType); - writer[method](value); + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServerStreamingCall = void 0; + var ServerStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } /** - * Write an array of scalar values in packed format. + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. */ - packed(writer, type2, fieldNo, value) { - if (!value.length) - return; - assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING); - writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - let [, method] = this.scalarInfo(type2); - for (let i = 0; i < value.length; i++) - writer[method](value[i]); - writer.join(); + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } - /** - * Get information for writing a scalar value. - * - * Returns tuple: - * [0]: appropriate WireType - * [1]: name of the appropriate method of IBinaryWriter - * [2]: whether the given value is a default value - * - * If argument `value` is omitted, [2] is always false. - */ - scalarInfo(type2, value) { - let t = binary_format_contract_1.WireType.Varint; - let m; - let i = value === void 0; - let d = value === 0; - switch (type2) { - case reflection_info_1.ScalarType.INT32: - m = "int32"; - break; - case reflection_info_1.ScalarType.STRING: - d = i || !value.length; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "string"; - break; - case reflection_info_1.ScalarType.BOOL: - d = value === false; - m = "bool"; - break; - case reflection_info_1.ScalarType.UINT32: - m = "uint32"; - break; - case reflection_info_1.ScalarType.DOUBLE: - t = binary_format_contract_1.WireType.Bit64; - m = "double"; - break; - case reflection_info_1.ScalarType.FLOAT: - t = binary_format_contract_1.WireType.Bit32; - m = "float"; - break; - case reflection_info_1.ScalarType.INT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "int64"; - break; - case reflection_info_1.ScalarType.UINT64: - d = i || pb_long_1.PbULong.from(value).isZero(); - m = "uint64"; - break; - case reflection_info_1.ScalarType.FIXED64: - d = i || pb_long_1.PbULong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "fixed64"; - break; - case reflection_info_1.ScalarType.BYTES: - d = i || !value.byteLength; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "bytes"; - break; - case reflection_info_1.ScalarType.FIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "fixed32"; - break; - case reflection_info_1.ScalarType.SFIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "sfixed32"; - break; - case reflection_info_1.ScalarType.SFIXED64: - d = i || pb_long_1.PbLong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "sfixed64"; - break; - case reflection_info_1.ScalarType.SINT32: - m = "sint32"; - break; - case reflection_info_1.ScalarType.SINT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "sint64"; - break; - } - return [t, m, i || d]; + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers + }; + }); } }; - exports2.ReflectionBinaryWriter = ReflectionBinaryWriter; + exports2.ServerStreamingCall = ServerStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js -var require_reflection_create = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js +var require_client_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionCreate = void 0; - var reflection_scalar_default_1 = require_reflection_scalar_default(); - var message_type_contract_1 = require_message_type_contract(); - function reflectionCreate(type2) { - const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 }); - for (let field of type2.fields) { - let name = field.localName; - if (field.opt) - continue; - if (field.oneof) - msg[field.oneof] = { oneofKind: void 0 }; - else if (field.repeat) - msg[name] = []; - else - switch (field.kind) { - case "scalar": - msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); - break; - case "enum": - msg[name] = 0; - break; - case "map": - msg[name] = {}; - break; - } + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); } - return msg; - } - exports2.reflectionCreate = reflectionCreate; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js -var require_reflection_merge_partial = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionMergePartial = void 0; - function reflectionMergePartial(info6, target, source) { - let fieldValue, input = source, output; - for (let field of info6.fields) { - let name = field.localName; - if (field.oneof) { - const group = input[field.oneof]; - if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) { - continue; - } - fieldValue = group[name]; - output = target[field.oneof]; - output.oneofKind = group.oneofKind; - if (fieldValue == void 0) { - delete output[name]; - continue; + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - } else { - fieldValue = input[name]; - output = target; - if (fieldValue == void 0) { - continue; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - if (field.repeat) - output[name].length = fieldValue.length; - switch (field.kind) { - case "scalar": - case "enum": - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = fieldValue[i]; - else - output[name] = fieldValue; - break; - case "message": - let T = field.T(); - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = T.create(fieldValue[i]); - else if (output[name] === void 0) - output[name] = T.create(fieldValue); - else - T.mergePartial(output[name], fieldValue); - break; - case "map": - switch (field.V.kind) { - case "scalar": - case "enum": - Object.assign(output[name], fieldValue); - break; - case "message": - let T2 = field.V.T(); - for (let k of Object.keys(fieldValue)) - output[name][k] = T2.create(fieldValue[k]); - break; - } - break; + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ClientStreamingCall = void 0; + var ClientStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; } - } - exports2.reflectionMergePartial = reflectionMergePartial; + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); + } + }; + exports2.ClientStreamingCall = ClientStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js -var require_reflection_equals = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js +var require_duplex_streaming_call = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.reflectionEquals = void 0; - var reflection_info_1 = require_reflection_info(); - function reflectionEquals(info6, a, b) { - if (a === b) - return true; - if (!a || !b) - return false; - for (let field of info6.fields) { - let localName = field.localName; - let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; - let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; - switch (field.kind) { - case "enum": - case "scalar": - let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) - return false; - break; - case "map": - if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) - return false; - break; - case "message": - let T = field.T(); - if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) - return false; - break; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); + } + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DuplexStreamingCall = void 0; + var DuplexStreamingCall = class { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter4(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers + }; + }); } - return true; - } - exports2.reflectionEquals = reflectionEquals; - var objectValues = Object.values; - function primitiveEq(type2, a, b) { - if (a === b) - return true; - if (type2 !== reflection_info_1.ScalarType.BYTES) - return false; - let ba = a; - let bb = b; - if (ba.length !== bb.length) - return false; - for (let i = 0; i < ba.length; i++) - if (ba[i] != bb[i]) - return false; - return true; - } - function repeatedPrimitiveEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!primitiveEq(type2, a[i], b[i])) - return false; - return true; - } - function repeatedMsgEq(type2, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!type2.equals(a[i], b[i])) - return false; - return true; - } + }; + exports2.DuplexStreamingCall = DuplexStreamingCall; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js -var require_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js +var require_test_transport = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - var reflection_info_1 = require_reflection_info(); - var reflection_type_check_1 = require_reflection_type_check(); - var reflection_json_reader_1 = require_reflection_json_reader(); - var reflection_json_writer_1 = require_reflection_json_writer(); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - var reflection_create_1 = require_reflection_create(); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - var json_typings_1 = require_json_typings(); - var json_format_contract_1 = require_json_format_contract(); - var reflection_equals_1 = require_reflection_equals(); - var binary_writer_1 = require_binary_writer(); - var binary_reader_1 = require_binary_reader(); - var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); - var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {}; - var MessageType = class { - constructor(name, fields, options) { - this.defaultCheckDepth = 16; - this.typeName = name; - this.fields = fields.map(reflection_info_1.normalizeFieldInfo); - this.options = options !== null && options !== void 0 ? options : {}; - messageTypeDescriptor.value = this; - this.messagePrototype = Object.create(null, baseDescriptors); - this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); - this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); - this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); - this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); - this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); } - create(value) { - let message = reflection_create_1.reflectionCreate(this); - if (value !== void 0) { - reflection_merge_partial_1.reflectionMergePartial(this, message, value); + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - return message; - } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TestTransport = void 0; + var rpc_error_1 = require_rpc_error(); + var runtime_1 = require_commonjs11(); + var rpc_output_stream_1 = require_rpc_output_stream(); + var rpc_options_1 = require_rpc_options(); + var unary_call_1 = require_unary_call(); + var server_streaming_call_1 = require_server_streaming_call(); + var client_streaming_call_1 = require_client_streaming_call(); + var duplex_streaming_call_1 = require_duplex_streaming_call(); + var TestTransport = class _TestTransport { /** - * Clone the message. - * - * Unknown fields are discarded. + * Initialize with mock data. Omitted fields have default value. */ - clone(message) { - let copy = this.create(); - reflection_merge_partial_1.reflectionMergePartial(this, copy, message); - return copy; + constructor(data) { + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; } /** - * Determines whether two message of the same type have the same field values. - * Checks for deep equality, traversing repeated fields, oneof groups, maps - * and messages recursively. - * Will also return true if both messages are `undefined`. + * Sent message(s) during the last operation. */ - equals(a, b) { - return reflection_equals_1.reflectionEquals(this, a, b); + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; + } else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; } /** - * Is the given value assignable to our message type - * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + * Sending message(s) completed? */ - is(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, false); + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } else if (typeof this.lastInput == "object") { + return true; + } + return false; } - /** - * Is the given value assignable to our message type, - * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? - */ - isAssignable(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, true); + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); } - /** - * Copy partial data into the target message. - */ - mergePartial(target, source) { - reflection_merge_partial_1.reflectionMergePartial(this, target, source); + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } else if (this.data.response !== void 0) { + r = this.data.response; + } else { + r = method.O.create(); + } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); } /** - * Create a new message from binary format. + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. */ - fromBinary(data, options) { - let opt = binary_reader_1.binaryReadOptions(options); - return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + streamResponses(method, stream2, abort) { + return __awaiter4(this, void 0, void 0, function* () { + const messages = []; + if (this.data.response === void 0) { + messages.push(method.O.create()); + } else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + try { + yield delay2(this.responseDelay, abort)(void 0); + } catch (error4) { + stream2.notifyError(error4); + return; + } + if (this.data.response instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.response); + return; + } + for (let msg of messages) { + stream2.notifyMessage(msg); + try { + yield delay2(this.betweenResponseDelay, abort)(void 0); + } catch (error4) { + stream2.notifyError(error4); + return; + } + } + if (this.data.status instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.status); + return; + } + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream2.notifyError(this.data.trailers); + return; + } + stream2.notifyComplete(); + }); } - /** - * Read a new message from a JSON value. - */ - fromJson(json2, options) { - return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options)); + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); } - /** - * Read a new message from a JSON string. - * This is equivalent to `T.fromJson(JSON.parse(json))`. - */ - fromJsonString(json2, options) { - let value = JSON.parse(json2); - return this.fromJson(value, options); + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); } - /** - * Write the message to canonical JSON value. - */ - toJson(message, options) { - return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } } - /** - * Convert the message to canonical JSON string. - * This is equivalent to `JSON.stringify(T.toJson(t))` - */ - toJsonString(message, options) { + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); + } + unary(method, input, options) { var _a; - let value = this.toJson(message, options); - return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); } - /** - * Write the message to binary format. - */ - toBinary(message, options) { - let opt = binary_writer_1.binaryWriteOptions(options); - return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); } - /** - * This is an internal method. If you just want to read a message from - * JSON, use `fromJson()` or `fromJsonString()`. - * - * Reads JSON value and merges the fields into the target - * according to protobuf rules. If the target is omitted, - * a new instance is created first. - */ - internalJsonRead(json2, options, target) { - if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refJsonReader.read(json2, message, options); - return message; + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { + }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { + }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { + }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + } + }; + exports2.TestTransport = TestTransport; + TestTransport.defaultHeaders = { + responseHeader: "test" + }; + TestTransport.defaultStatus = { + code: "OK", + detail: "all good" + }; + TestTransport.defaultTrailers = { + responseTrailer: "test" + }; + function delay2(ms, abort) { + return (v) => new Promise((resolve6, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } else { + const id = setTimeout(() => resolve6(v), ms); + if (abort) { + abort.addEventListener("abort", (ev) => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } } - throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`); + }); + } + var TestInputStream = class { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; } - /** - * This is an internal method. If you just want to write a message - * to JSON, use `toJson()` or `toJsonString(). - * - * Writes JSON value and returns it. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.write(message, options); + get sent() { + return this._sent; } - /** - * This is an internal method. If you just want to write a message - * in binary format, use `toBinary()`. - * - * Serializes the message in binary format and appends it to the given - * writer. Returns passed writer. - */ - internalBinaryWrite(message, writer, options) { - this.refBinWriter.write(message, writer, options); - return writer; + get completed() { + return this._completed; } - /** - * This is an internal method. If you just want to read a message from - * binary data, use `fromBinary()`. - * - * Reads data from binary format and merges the fields into - * the target according to protobuf rules. If the target is - * omitted, a new instance is created first. - */ - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refBinReader.read(reader, message, options, length); - return message; + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); + } + const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; + return Promise.resolve(void 0).then(() => { + this._sent.push(message); + }).then(delay2(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); + } + const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; + return Promise.resolve(void 0).then(() => { + this._completed = true; + }).then(delay2(delayMs, this.abort)); } }; - exports2.MessageType = MessageType; - } -}); - -// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js -var require_reflection_contains_message_type = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.containsMessageType = void 0; - var message_type_contract_1 = require_message_type_contract(); - function containsMessageType(msg) { - return msg[message_type_contract_1.MESSAGE_TYPE] != null; - } - exports2.containsMessageType = containsMessageType; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js -var require_enum_object = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js +var require_rpc_interceptor = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0; - function isEnumObject(arg) { - if (typeof arg != "object" || arg === null) { - return false; + exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; + var runtime_1 = require_commonjs11(); + function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + } + return tail(method, input, options); } - if (!arg.hasOwnProperty(0)) { - return false; + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); } - for (let k of Object.keys(arg)) { - let num = parseInt(k); - if (!Number.isNaN(num)) { - let nam = arg[num]; - if (nam === void 0) - return false; - if (arg[nam] !== num) - return false; - } else { - let num2 = arg[k]; - if (num2 === void 0) - return false; - if (typeof num2 !== "number") - return false; - if (arg[num2] === void 0) - return false; + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); } + return tail(method, options); } - return true; + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); + } + runtime_1.assertNever(kind); } - exports2.isEnumObject = isEnumObject; - function listEnumValues(enumObject) { - if (!isEnumObject(enumObject)) - throw new Error("not a typescript enum object"); - let values = []; - for (let [name, number] of Object.entries(enumObject)) - if (typeof number == "number") - values.push({ name, number }); - return values; + exports2.stackIntercept = stackIntercept; + function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); } - exports2.listEnumValues = listEnumValues; - function listEnumNames(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.name); + exports2.stackUnaryInterceptors = stackUnaryInterceptors; + function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); } - exports2.listEnumNames = listEnumNames; - function listEnumNumbers(enumObject) { - return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index); + exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; + function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); } - exports2.listEnumNumbers = listEnumNumbers; + exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; + function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); + } + exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; } }); -// node_modules/@protobuf-ts/runtime/build/commonjs/index.js -var require_commonjs11 = __commonJS({ - "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) { +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js +var require_server_call_context = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var json_typings_1 = require_json_typings(); - Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() { - return json_typings_1.typeofJsonValue; - } }); - Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() { - return json_typings_1.isJsonObject; - } }); - var base64_1 = require_base642(); - Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() { - return base64_1.base64decode; - } }); - Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() { - return base64_1.base64encode; - } }); - var protobufjs_utf8_1 = require_protobufjs_utf8(); - Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() { - return protobufjs_utf8_1.utf8read; - } }); - var binary_format_contract_1 = require_binary_format_contract(); - Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() { - return binary_format_contract_1.WireType; - } }); - Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() { - return binary_format_contract_1.mergeBinaryOptions; - } }); - Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() { - return binary_format_contract_1.UnknownFieldHandler; - } }); - var binary_reader_1 = require_binary_reader(); - Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() { - return binary_reader_1.BinaryReader; - } }); - Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() { - return binary_reader_1.binaryReadOptions; - } }); - var binary_writer_1 = require_binary_writer(); - Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() { - return binary_writer_1.BinaryWriter; - } }); - Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() { - return binary_writer_1.binaryWriteOptions; - } }); - var pb_long_1 = require_pb_long(); - Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() { - return pb_long_1.PbLong; - } }); - Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() { - return pb_long_1.PbULong; - } }); - var json_format_contract_1 = require_json_format_contract(); - Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonReadOptions; - } }); - Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() { - return json_format_contract_1.jsonWriteOptions; - } }); - Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() { - return json_format_contract_1.mergeJsonOptions; - } }); - var message_type_contract_1 = require_message_type_contract(); - Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() { - return message_type_contract_1.MESSAGE_TYPE; - } }); - var message_type_1 = require_message_type(); - Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() { - return message_type_1.MessageType; - } }); - var reflection_info_1 = require_reflection_info(); - Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() { - return reflection_info_1.ScalarType; - } }); - Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() { - return reflection_info_1.LongType; - } }); - Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() { - return reflection_info_1.RepeatType; - } }); - Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() { - return reflection_info_1.normalizeFieldInfo; - } }); - Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() { - return reflection_info_1.readFieldOptions; - } }); - Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() { - return reflection_info_1.readFieldOption; - } }); - Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() { - return reflection_info_1.readMessageOption; - } }); - var reflection_type_check_1 = require_reflection_type_check(); - Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() { - return reflection_type_check_1.ReflectionTypeCheck; - } }); - var reflection_create_1 = require_reflection_create(); - Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() { - return reflection_create_1.reflectionCreate; - } }); - var reflection_scalar_default_1 = require_reflection_scalar_default(); - Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() { - return reflection_scalar_default_1.reflectionScalarDefault; - } }); - var reflection_merge_partial_1 = require_reflection_merge_partial(); - Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() { - return reflection_merge_partial_1.reflectionMergePartial; - } }); - var reflection_equals_1 = require_reflection_equals(); - Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() { - return reflection_equals_1.reflectionEquals; - } }); - var reflection_binary_reader_1 = require_reflection_binary_reader(); - Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() { - return reflection_binary_reader_1.ReflectionBinaryReader; + exports2.ServerCallContextController = void 0; + var ServerCallContextController = class { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; + } + /** + * Set the call cancelled. + * + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. + */ + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } + } + } + /** + * Send response headers. + */ + sendResponseHeaders(data) { + this._sendRH(data); + } + /** + * Is the call cancelled? + * + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. + */ + get cancelled() { + return this._cancelled; + } + /** + * Add a callback for cancellation. + */ + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; + } + }; + exports2.ServerCallContextController = ServerCallContextController; + } +}); + +// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var service_type_1 = require_service_type(); + Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { + return service_type_1.ServiceType; } }); - var reflection_binary_writer_1 = require_reflection_binary_writer(); - Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() { - return reflection_binary_writer_1.ReflectionBinaryWriter; + var reflection_info_1 = require_reflection_info2(); + Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { + return reflection_info_1.readMethodOptions; } }); - var reflection_json_reader_1 = require_reflection_json_reader(); - Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() { - return reflection_json_reader_1.ReflectionJsonReader; + Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { + return reflection_info_1.readMethodOption; } }); - var reflection_json_writer_1 = require_reflection_json_writer(); - Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() { - return reflection_json_writer_1.ReflectionJsonWriter; + Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { + return reflection_info_1.readServiceOption; } }); - var reflection_contains_message_type_1 = require_reflection_contains_message_type(); - Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() { - return reflection_contains_message_type_1.containsMessageType; + var rpc_error_1 = require_rpc_error(); + Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { + return rpc_error_1.RpcError; } }); - var oneof_1 = require_oneof(); - Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() { - return oneof_1.isOneofGroup; + var rpc_options_1 = require_rpc_options(); + Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { + return rpc_options_1.mergeRpcOptions; } }); - Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() { - return oneof_1.setOneofValue; + var rpc_output_stream_1 = require_rpc_output_stream(); + Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { + return rpc_output_stream_1.RpcOutputStreamController; } }); - Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() { - return oneof_1.getOneofValue; + var test_transport_1 = require_test_transport(); + Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { + return test_transport_1.TestTransport; } }); - Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() { - return oneof_1.clearOneofValue; + var deferred_1 = require_deferred(); + Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { + return deferred_1.Deferred; } }); - Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() { - return oneof_1.getSelectedOneofValue; + Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { + return deferred_1.DeferredState; } }); - var enum_object_1 = require_enum_object(); - Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() { - return enum_object_1.listEnumValues; + var duplex_streaming_call_1 = require_duplex_streaming_call(); + Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { + return duplex_streaming_call_1.DuplexStreamingCall; } }); - Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() { - return enum_object_1.listEnumNames; + var client_streaming_call_1 = require_client_streaming_call(); + Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { + return client_streaming_call_1.ClientStreamingCall; } }); - Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() { - return enum_object_1.listEnumNumbers; + var server_streaming_call_1 = require_server_streaming_call(); + Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { + return server_streaming_call_1.ServerStreamingCall; } }); - Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() { - return enum_object_1.isEnumObject; + var unary_call_1 = require_unary_call(); + Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { + return unary_call_1.UnaryCall; } }); - var lower_camel_case_1 = require_lower_camel_case(); - Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() { - return lower_camel_case_1.lowerCamelCase; + var rpc_interceptor_1 = require_rpc_interceptor(); + Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { + return rpc_interceptor_1.stackIntercept; } }); - var assert_1 = require_assert(); - Object.defineProperty(exports2, "assert", { enumerable: true, get: function() { - return assert_1.assert; + Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackDuplexStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() { - return assert_1.assertNever; + Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackClientStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() { - return assert_1.assertInt32; + Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackServerStreamingInterceptors; } }); - Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() { - return assert_1.assertUInt32; + Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { + return rpc_interceptor_1.stackUnaryInterceptors; } }); - Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() { - return assert_1.assertFloat32; + var server_call_context_1 = require_server_call_context(); + Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { + return server_call_context_1.ServerCallContextController; } }); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js -var require_reflection_info2 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js +var require_cachescope = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0; + exports2.CacheScope = void 0; var runtime_1 = require_commonjs11(); - function normalizeMethodInfo(method, service) { - var _a, _b, _c; - let m = method; - m.service = service; - m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); - m.serverStreaming = !!m.serverStreaming; - m.clientStreaming = !!m.clientStreaming; - m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; - m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0; - return m; - } - exports2.normalizeMethodInfo = normalizeMethodInfo; - function readMethodOptions(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0; - } - exports2.readMethodOptions = readMethodOptions; - function readMethodOption(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return void 0; + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var CacheScope$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheScope", [ + { + no: 1, + name: "scope", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 2, + name: "permission", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + } + ]); + } + create(value) { + const message = { scope: "", permission: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string scope */ + 1: + message.scope = reader.string(); + break; + case /* int64 permission */ + 2: + message.permission = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.scope !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); + if (message.permission !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheScope = new CacheScope$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js +var require_cachemetadata = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheMetadata = void 0; + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachescope_1 = require_cachescope(); + var CacheMetadata$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.entities.v1.CacheMetadata", [ + { + no: 1, + name: "repository_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } + ]); + } + create(value) { + const message = { repositoryId: "0", scope: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 repository_id */ + 1: + message.repositoryId = reader.int64().toString(); + break; + case /* repeated github.actions.results.entities.v1.CacheScope scope */ + 2: + message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.repositoryId !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); + for (let i = 0; i < message.scope.length; i++) + cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.CacheMetadata = new CacheMetadata$Type(); + } +}); + +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js +var require_cache2 = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; + var runtime_rpc_1 = require_commonjs12(); + var runtime_1 = require_commonjs11(); + var runtime_2 = require_commonjs11(); + var runtime_3 = require_commonjs11(); + var runtime_4 = require_commonjs11(); + var runtime_5 = require_commonjs11(); + var cachemetadata_1 = require_cachemetadata(); + var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* string version */ + 3: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readMethodOption = readMethodOption; - function readServiceOption(service, extensionName, extensionType) { - const options = service.options; - if (!options) { - return void 0; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.version !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - const optionVal = options[extensionName]; - if (optionVal === void 0) { - return optionVal; + }; + exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); + var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateCacheEntryResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_upload_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; - } - exports2.readServiceOption = readServiceOption; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js -var require_service_type = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceType = void 0; - var reflection_info_1 = require_reflection_info2(); - var ServiceType = class { - constructor(typeName, methods, options) { - this.typeName = typeName; - this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this)); - this.options = options !== null && options !== void 0 ? options : {}; + create(value) { + const message = { ok: false, signedUploadUrl: "", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ + 2: + message.signedUploadUrl = reader.string(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.ServiceType = ServiceType; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js -var require_rpc_error = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcError = void 0; - var RpcError = class extends Error { - constructor(message, code = "UNKNOWN", meta) { - super(message); - this.name = "RpcError"; - Object.setPrototypeOf(this, new.target.prototype); - this.code = code; - this.meta = meta !== null && meta !== void 0 ? meta : {}; + exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); + var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "size_bytes", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); } - toString() { - const l = [this.name + ": " + this.message]; - if (this.code) { - l.push(""); - l.push("Code: " + this.code); - } - if (this.serviceName && this.methodName) { - l.push("Method: " + this.serviceName + "/" + this.methodName); + create(value) { + const message = { key: "", sizeBytes: "0", version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* int64 size_bytes */ + 3: + message.sizeBytes = reader.int64().toString(); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } - let m = Object.entries(this.meta); - if (m.length) { - l.push(""); - l.push("Meta:"); - for (let [k, v] of m) { - l.push(` ${k}: ${v}`); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + if (message.sizeBytes !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); + var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "entry_id", + kind: "scalar", + T: 3 + /*ScalarType.INT64*/ + }, + { + no: 3, + name: "message", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, entryId: "0", message: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* int64 entry_id */ + 2: + message.entryId = reader.int64().toString(); + break; + case /* string message */ + 3: + message.message = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - return l.join("\n"); + return message; + } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.entryId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); + if (message.message !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } }; - exports2.RpcError = RpcError; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js -var require_rpc_options = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.mergeRpcOptions = void 0; - var runtime_1 = require_commonjs11(); - function mergeRpcOptions(defaults, options) { - if (!options) - return defaults; - let o = {}; - copy(defaults, o); - copy(options, o); - for (let key of Object.keys(options)) { - let val2 = options[key]; - switch (key) { - case "jsonOptions": - o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); - break; - case "binaryOptions": - o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); - break; - case "meta": - o.meta = {}; - copy(defaults.meta, o.meta); - copy(options.meta, o.meta); - break; - case "interceptors": - o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat(); - break; + exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); + var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ + { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, + { + no: 2, + name: "key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "restore_keys", + kind: "scalar", + repeat: 2, + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 4, + name: "version", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { key: "", restoreKeys: [], version: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* github.actions.results.entities.v1.CacheMetadata metadata */ + 1: + message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); + break; + case /* string key */ + 2: + message.key = reader.string(); + break; + case /* repeated string restore_keys */ + 3: + message.restoreKeys.push(reader.string()); + break; + case /* string version */ + 4: + message.version = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } + return message; } - return o; - } - exports2.mergeRpcOptions = mergeRpcOptions; - function copy(a, into) { - if (!a) - return; - let c = into; - for (let [k, v] of Object.entries(a)) { - if (v instanceof Date) - c[k] = new Date(v.getTime()); - else if (Array.isArray(v)) - c[k] = v.concat(); - else - c[k] = v; + internalBinaryWrite(message, writer, options) { + if (message.metadata) + cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + if (message.key !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); + for (let i = 0; i < message.restoreKeys.length; i++) + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); + if (message.version !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); + var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ + { + no: 1, + name: "ok", + kind: "scalar", + T: 8 + /*ScalarType.BOOL*/ + }, + { + no: 2, + name: "signed_download_url", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + }, + { + no: 3, + name: "matched_key", + kind: "scalar", + T: 9 + /*ScalarType.STRING*/ + } + ]); + } + create(value) { + const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== void 0) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ + 1: + message.ok = reader.bool(); + break; + case /* string signed_download_url */ + 2: + message.signedDownloadUrl = reader.string(); + break; + case /* string matched_key */ + 3: + message.matchedKey = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - } + internalBinaryWrite(message, writer, options) { + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + if (message.signedDownloadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); + if (message.matchedKey !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } + }; + exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); + exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ + { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, + { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, + { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } + ]); } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js -var require_deferred = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) { +// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js +var require_cache_twirp_client = __commonJS({ + "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Deferred = exports2.DeferredState = void 0; - var DeferredState; - (function(DeferredState2) { - DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING"; - DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED"; - DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED"; - })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {})); - var Deferred = class { - /** - * @param preventUnhandledRejectionWarning - prevents the warning - * "Unhandled Promise rejection" by adding a noop rejection handler. - * Working with calls returned from the runtime-rpc package in an - * async function usually means awaiting one call property after - * the other. This means that the "status" is not being awaited when - * an earlier await for the "headers" is rejected. This causes the - * "unhandled promise reject" warning. A more correct behaviour for - * calls might be to become aware whether at least one of the - * promises is handled and swallow the rejection warning for the - * others. - */ - constructor(preventUnhandledRejectionWarning = true) { - this._state = DeferredState.PENDING; - this._promise = new Promise((resolve6, reject) => { - this._resolve = resolve6; - this._reject = reject; + exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; + var cache_1 = require_cache2(); + var CacheServiceClientJSON = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); + } + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false }); - if (preventUnhandledRejectionWarning) { - this._promise.catch((_) => { - }); - } + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Get the current state of the promise. - */ - get state() { - return this._state; + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Get the deferred promise. - */ - get promise() { - return this._promise; + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false + }); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { + ignoreUnknownFields: true + })); } - /** - * Resolve the promise. Throws if the promise is already resolved or rejected. - */ - resolve(value) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); - this._resolve(value); - this._state = DeferredState.RESOLVED; + }; + exports2.CacheServiceClientJSON = CacheServiceClientJSON; + var CacheServiceClientProtobuf = class { + constructor(rpc) { + this.rpc = rpc; + this.CreateCacheEntry.bind(this); + this.FinalizeCacheEntryUpload.bind(this); + this.GetCacheEntryDownloadURL.bind(this); } - /** - * Reject the promise. Throws if the promise is already resolved or rejected. - */ - reject(reason) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); - this._reject(reason); - this._state = DeferredState.REJECTED; + CreateCacheEntry(request) { + const data = cache_1.CreateCacheEntryRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); + return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); } - /** - * Resolve the promise. Ignore if not pending. - */ - resolvePending(val2) { - if (this._state === DeferredState.PENDING) - this.resolve(val2); + FinalizeCacheEntryUpload(request) { + const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); + return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); } - /** - * Reject the promise. Ignore if not pending. - */ - rejectPending(reason) { - if (this._state === DeferredState.PENDING) - this.reject(reason); + GetCacheEntryDownloadURL(request) { + const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); + return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.Deferred = Deferred; + exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js -var require_rpc_output_stream = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) { +// node_modules/@actions/cache/lib/internal/shared/util.js +var require_util10 = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RpcOutputStreamController = void 0; - var deferred_1 = require_deferred(); - var runtime_1 = require_commonjs11(); - var RpcOutputStreamController = class { - constructor() { - this._lis = { - nxt: [], - msg: [], - err: [], - cmp: [] - }; - this._closed = false; - this._itState = { q: [] }; + exports2.maskSecretUrls = exports2.maskSigUrl = void 0; + var core_1 = require_core(); + function maskSigUrl(url2) { + if (!url2) + return; + try { + const parsedUrl = new URL(url2); + const signature = parsedUrl.searchParams.get("sig"); + if (signature) { + (0, core_1.setSecret)(signature); + (0, core_1.setSecret)(encodeURIComponent(signature)); + } + } catch (error4) { + (0, core_1.debug)(`Failed to parse URL: ${url2} ${error4 instanceof Error ? error4.message : String(error4)}`); } - // --- RpcOutputStream callback API - onNext(callback) { - return this.addLis(callback, this._lis.nxt); + } + exports2.maskSigUrl = maskSigUrl; + function maskSecretUrls(body) { + if (typeof body !== "object" || body === null) { + (0, core_1.debug)("body is not an object or is null"); + return; } - onMessage(callback) { - return this.addLis(callback, this._lis.msg); + if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { + maskSigUrl(body.signed_upload_url); } - onError(callback) { - return this.addLis(callback, this._lis.err); + if ("signed_download_url" in body && typeof body.signed_download_url === "string") { + maskSigUrl(body.signed_download_url); } - onComplete(callback) { - return this.addLis(callback, this._lis.cmp); + } + exports2.maskSecretUrls = maskSecretUrls; + } +}); + +// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js +var require_cacheTwirpClient = __commonJS({ + "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { + "use strict"; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); } - addLis(callback, list) { - list.push(callback); - return () => { - let i = list.indexOf(callback); - if (i >= 0) - list.splice(i, 1); - }; + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.internalCacheTwirpClient = void 0; + var core_1 = require_core(); + var user_agent_1 = require_user_agent(); + var errors_1 = require_errors2(); + var config_1 = require_config(); + var cacheUtils_1 = require_cacheUtils(); + var auth_1 = require_auth2(); + var http_client_1 = require_lib4(); + var cache_twirp_client_1 = require_cache_twirp_client(); + var util_1 = require_util10(); + var CacheServiceClient = class { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3e3; + this.retryMultiplier = 1.5; + const token = (0, cacheUtils_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getCacheServiceURL)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; + } + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) + ]); } - // remove all listeners - clearLis() { - for (let l of Object.values(this._lis)) - l.splice(0, l.length); + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { + return __awaiter4(this, void 0, void 0, function* () { + const url2 = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url2}`); + const headers = { + "Content-Type": contentType + }; + try { + const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { + return this.httpClient.post(url2, JSON.stringify(data), headers); + })); + return body; + } catch (error4) { + throw new Error(`Failed to ${method}: ${error4.message}`); + } + }); } - // --- Controller API - /** - * Is this stream already closed by a completion or error? - */ - get closed() { - return this._closed !== false; + retryableRequest(operation) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ""; + let rawBody = ""; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, util_1.maskSecretUrls)(body); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } catch (error4) { + if (error4 instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + } + if (error4 instanceof errors_1.UsageError) { + throw error4; + } + if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { + throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + } + isRetryable = true; + errorMessage = error4.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; + } + throw new Error(`Request failed`); + }); } - /** - * Emit message, close with error, or close successfully, but only one - * at a time. - * Can be used to wrap a stream by using the other stream's `onNext`. - */ - notifyNext(message, error4, complete) { - runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time"); - if (message) - this.notifyMessage(message); - if (error4) - this.notifyError(error4); - if (complete) - this.notifyComplete(); + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; } - /** - * Emits a new message. Throws if stream is closed. - * - * Triggers onNext and onMessage callbacks. - */ - notifyMessage(message) { - runtime_1.assert(!this.closed, "stream is closed"); - this.pushIt({ value: message, done: false }); - this._lis.msg.forEach((l) => l(message)); - this._lis.nxt.forEach((l) => l(message, void 0, false)); + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); } - /** - * Closes the stream with an error. Throws if stream is closed. - * - * Triggers onNext and onError callbacks. - */ - notifyError(error4) { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = error4; - this.pushIt(error4); - this._lis.err.forEach((l) => l(error4)); - this._lis.nxt.forEach((l) => l(void 0, error4, false)); - this.clearLis(); + sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6) => setTimeout(resolve6, milliseconds)); + }); } - /** - * Closes the stream successfully. Throws if stream is closed. - * - * Triggers onNext and onComplete callbacks. - */ - notifyComplete() { - runtime_1.assert(!this.closed, "stream is closed"); - this._closed = true; - this.pushIt({ value: null, done: true }); - this._lis.cmp.forEach((l) => l()); - this._lis.nxt.forEach((l) => l(void 0, void 0, true)); - this.clearLis(); + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error("attempt should be a positive integer"); + } + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } - /** - * Creates an async iterator (that can be used with `for await {...}`) - * to consume the stream. - * - * Some things to note: - * - If an error occurs, the `for await` will throw it. - * - If an error occurred before the `for await` was started, `for await` - * will re-throw it. - * - If the stream is already complete, the `for await` will be empty. - * - If your `for await` consumes slower than the stream produces, - * for example because you are relaying messages in a slow operation, - * messages are queued. - */ - [Symbol.asyncIterator]() { - if (this._closed === true) - this.pushIt({ value: null, done: true }); - else if (this._closed !== false) - this.pushIt(this._closed); - return { - next: () => { - let state = this._itState; - runtime_1.assert(state, "bad state"); - runtime_1.assert(!state.p, "iterator contract broken"); - let first = state.q.shift(); - if (first) - return "value" in first ? Promise.resolve(first) : Promise.reject(first); - state.p = new deferred_1.Deferred(); - return state.p.promise; - } - }; + }; + function internalCacheTwirpClient(options) { + const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new cache_twirp_client_1.CacheServiceClientJSON(client); + } + exports2.internalCacheTwirpClient = internalCacheTwirpClient; + } +}); + +// node_modules/@actions/cache/lib/internal/tar.js +var require_tar = __commonJS({ + "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - // "push" a new iterator result. - // this either resolves a pending promise, or enqueues the result. - pushIt(result) { - let state = this._itState; - if (state.p) { - const p = state.p; - runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); - "value" in result ? p.resolve(result) : p.reject(result); - delete state.p; - } else { - state.q.push(result); - } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.RpcOutputStreamController = RpcOutputStreamController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js -var require_unary_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve6) { @@ -72396,47 +75602,221 @@ var require_unary_call = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UnaryCall = void 0; - var UnaryCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * If you are only interested in the final outcome of this call, - * you can await it to receive a `FinishedUnaryCall`. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - response, - status, - trailers - }; - }); - } - }; - exports2.UnaryCall = UnaryCall; + exports2.createTar = exports2.extractTar = exports2.listTar = void 0; + var exec_1 = require_exec(); + var io6 = __importStar4(require_io()); + var fs_1 = require("fs"); + var path11 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var constants_1 = require_constants7(); + var IS_WINDOWS = process.platform === "win32"; + function getTarPath() { + return __awaiter4(this, void 0, void 0, function* () { + switch (process.platform) { + case "win32": { + const gnuTar = yield utils.getGnuTarPathOnWindows(); + const systemTar = constants_1.SystemTarPathOnWindows; + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else if ((0, fs_1.existsSync)(systemTar)) { + return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; + } + break; + } + case "darwin": { + const gnuTar = yield io6.which("gtar", false); + if (gnuTar) { + return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; + } else { + return { + path: yield io6.which("tar", true), + type: constants_1.ArchiveToolType.BSD + }; + } + } + default: + break; + } + return { + path: yield io6.which("tar", true), + type: constants_1.ArchiveToolType.GNU + }; + }); + } + function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + const args = [`"${tarPath.path}"`]; + const cacheFileName = utils.getCacheFileName(compressionMethod); + const tarFile = "cache.tar"; + const workingDirectory = getWorkingDirectory(); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (type2) { + case "create": + args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); + break; + case "extract": + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path11.sep}`, "g"), "/")); + break; + case "list": + args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "-P"); + break; + } + if (tarPath.type === constants_1.ArchiveToolType.GNU) { + switch (process.platform) { + case "win32": + args.push("--force-local"); + break; + case "darwin": + args.push("--delay-directory-restore"); + break; + } + } + return args; + }); + } + function getCommands(compressionMethod, type2, archivePath = "") { + return __awaiter4(this, void 0, void 0, function* () { + let args; + const tarPath = yield getTarPath(); + const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); + const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + if (BSD_TAR_ZSTD && type2 !== "create") { + args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; + } else { + args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; + } + if (BSD_TAR_ZSTD) { + return args; + } + return [args.join(" ")]; + }); + } + function getWorkingDirectory() { + var _a; + return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); + } + function getDecompressionProgram(tarPath, compressionMethod, archivePath) { + return __awaiter4(this, void 0, void 0, function* () { + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -d --long=30 --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path11.sep}`, "g"), "/") + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -d --force -o", + constants_1.TarFilename, + archivePath.replace(new RegExp(`\\${path11.sep}`, "g"), "/") + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; + default: + return ["-z"]; + } + }); + } + function getCompressionProgram(tarPath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheFileName = utils.getCacheFileName(compressionMethod); + const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --long=30 --force -o", + cacheFileName.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), + constants_1.TarFilename + ] : [ + "--use-compress-program", + IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + ]; + case constants_1.CompressionMethod.ZstdWithoutLong: + return BSD_TAR_ZSTD ? [ + "zstd -T0 --force -o", + cacheFileName.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), + constants_1.TarFilename + ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; + default: + return ["-z"]; + } + }); + } + function execCommands(commands, cwd) { + return __awaiter4(this, void 0, void 0, function* () { + for (const command of commands) { + try { + yield (0, exec_1.exec)(command, void 0, { + cwd, + env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) + }); + } catch (error4) { + throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + } + } + }); + } + function listTar(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const commands = yield getCommands(compressionMethod, "list", archivePath); + yield execCommands(commands); + }); + } + exports2.listTar = listTar; + function extractTar2(archivePath, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + const workingDirectory = getWorkingDirectory(); + yield io6.mkdirP(workingDirectory); + const commands = yield getCommands(compressionMethod, "extract", archivePath); + yield execCommands(commands); + }); + } + exports2.extractTar = extractTar2; + function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter4(this, void 0, void 0, function* () { + (0, fs_1.writeFileSync)(path11.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); + const commands = yield getCommands(compressionMethod, "create"); + yield execCommands(commands, archiveFolder); + }); + } + exports2.createTar = createTar; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js -var require_server_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) { +// node_modules/@actions/cache/lib/cache.js +var require_cache3 = __commonJS({ + "node_modules/@actions/cache/lib/cache.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve6) { @@ -72450,200 +75830,421 @@ var require_server_streaming_call = __commonJS({ } catch (e) { reject(e); } - } - function rejected(value) { + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; + var core12 = __importStar4(require_core()); + var path11 = __importStar4(require("path")); + var utils = __importStar4(require_cacheUtils()); + var cacheHttpClient = __importStar4(require_cacheHttpClient()); + var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); + var config_1 = require_config(); + var tar_1 = require_tar(); + var http_client_1 = require_lib4(); + var ValidationError = class _ValidationError extends Error { + constructor(message) { + super(message); + this.name = "ValidationError"; + Object.setPrototypeOf(this, _ValidationError.prototype); + } + }; + exports2.ValidationError = ValidationError; + var ReserveCacheError = class _ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = "ReserveCacheError"; + Object.setPrototypeOf(this, _ReserveCacheError.prototype); + } + }; + exports2.ReserveCacheError = ReserveCacheError; + var FinalizeCacheError = class _FinalizeCacheError extends Error { + constructor(message) { + super(message); + this.name = "FinalizeCacheError"; + Object.setPrototypeOf(this, _FinalizeCacheError.prototype); + } + }; + exports2.FinalizeCacheError = FinalizeCacheError; + function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); + } + } + function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } + } + function isFeatureAvailable() { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + switch (cacheServiceVersion) { + case "v2": + return !!process.env["ACTIONS_RESULTS_URL"]; + case "v1": + default: + return !!process.env["ACTIONS_CACHE_URL"]; + } + } + exports2.isFeatureAvailable = isFeatureAvailable; + function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core12.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + switch (cacheServiceVersion) { + case "v2": + return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + case "v1": + default: + return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + } + }); + } + exports2.restoreCache = restoreCache3; + function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core12.debug("Resolved Keys:"); + core12.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + let archivePath = ""; + try { + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod, + enableCrossOsArchive + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + return void 0; + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core12.info("Lookup only - skipping download"); + return cacheEntry.cacheKey; + } + archivePath = path11.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core12.debug(`Archive Path: ${archivePath}`); + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core12.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core12.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core12.info("Cache restored successfully"); + return cacheEntry.cacheKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core12.error(`Failed to restore: ${error4.message}`); + } else { + core12.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + yield utils.unlinkFile(archivePath); + } catch (error4) { + core12.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core12.debug("Resolved Keys:"); + core12.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + let archivePath = ""; + try { + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + const compressionMethod = yield utils.getCompressionMethod(); + const request = { + key: primaryKey, + restoreKeys, + version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) + }; + const response = yield twirpClient.GetCacheEntryDownloadURL(request); + if (!response.ok) { + core12.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); + return void 0; + } + const isRestoreKeyMatch = request.key !== response.matchedKey; + if (isRestoreKeyMatch) { + core12.info(`Cache hit for restore-key: ${response.matchedKey}`); + } else { + core12.info(`Cache hit for: ${response.matchedKey}`); + } + if (options === null || options === void 0 ? void 0 : options.lookupOnly) { + core12.info("Lookup only - skipping download"); + return response.matchedKey; + } + archivePath = path11.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core12.debug(`Archive path: ${archivePath}`); + core12.debug(`Starting download of archive to: ${archivePath}`); + yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core12.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + if (core12.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + yield (0, tar_1.extractTar)(archivePath, compressionMethod); + core12.info("Cache restored successfully"); + return response.matchedKey; + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core12.error(`Failed to restore: ${error4.message}`); + } else { + core12.warning(`Failed to restore: ${error4.message}`); + } + } + } finally { + try { + if (archivePath) { + yield utils.unlinkFile(archivePath); + } + } catch (error4) { + core12.debug(`Failed to delete archive: ${error4}`); + } + } + return void 0; + }); + } + function saveCache3(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); + core12.debug(`Cache service version: ${cacheServiceVersion}`); + checkPaths(paths); + checkKey(key); + switch (cacheServiceVersion) { + case "v2": + return yield saveCacheV2(paths, key, options, enableCrossOsArchive); + case "v1": + default: + return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + } + }); + } + exports2.saveCache = saveCache3; + function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { + var _a, _b, _c, _d, _e; + return __awaiter4(this, void 0, void 0, function* () { + const compressionMethod = yield utils.getCompressionMethod(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core12.debug("Cache Paths:"); + core12.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path11.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core12.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core12.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const fileSizeLimit = 10 * 1024 * 1024 * 1024; + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core12.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core12.debug("Reserving Cache"); + const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod, + enableCrossOsArchive, + cacheSize: archiveFileSize + }); + if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { + cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { + throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); + } else { + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); + } + core12.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError.name) { + core12.info(`Failed to save: ${typedError.message}`); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core12.error(`Failed to save: ${typedError.message}`); + } else { + core12.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + yield utils.unlinkFile(archivePath); + } catch (error4) { + core12.debug(`Failed to delete archive: ${error4}`); } } - function step(result) { - result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return cacheId; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerStreamingCall = void 0; - var ServerStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * You should first setup some listeners to the `request` to - * see the actual messages the server replied with. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - status, - trailers + } + function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + return __awaiter4(this, void 0, void 0, function* () { + options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); + const compressionMethod = yield utils.getCompressionMethod(); + const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); + let cacheId = -1; + const cachePaths = yield utils.resolvePaths(paths); + core12.debug("Cache Paths:"); + core12.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path11.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core12.debug(`Archive Path: ${archivePath}`); + try { + yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); + if (core12.isDebug()) { + yield (0, tar_1.listTar)(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core12.debug(`File Size: ${archiveFileSize}`); + options.archiveSizeBytes = archiveFileSize; + core12.debug("Reserving Cache"); + const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); + const request = { + key, + version }; - }); - } - }; - exports2.ServerStreamingCall = ServerStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js -var require_client_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) { - "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve6) { - resolve6(value); - }); - } - return new (P || (P = Promise))(function(resolve6, reject) { - function fulfilled(value) { + let signedUploadUrl; try { - step(generator.next(value)); - } catch (e) { - reject(e); + const response = yield twirpClient.CreateCacheEntry(request); + if (!response.ok) { + if (response.message) { + core12.warning(`Cache reservation failed: ${response.message}`); + } + throw new Error(response.message || "Response was not ok"); + } + signedUploadUrl = response.signedUploadUrl; + } catch (error4) { + core12.debug(`Failed to reserve cache: ${error4}`); + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); } - } - function rejected(value) { + core12.debug(`Attempting to upload cache located at: ${archivePath}`); + yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); + const finalizeRequest = { + key, + version, + sizeBytes: `${archiveFileSize}` + }; + const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); + core12.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); + if (!finalizeResponse.ok) { + if (finalizeResponse.message) { + throw new FinalizeCacheError(finalizeResponse.message); + } + throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); + } + cacheId = parseInt(finalizeResponse.entryId); + } catch (error4) { + const typedError = error4; + if (typedError.name === ValidationError.name) { + throw error4; + } else if (typedError.name === ReserveCacheError.name) { + core12.info(`Failed to save: ${typedError.message}`); + } else if (typedError.name === FinalizeCacheError.name) { + core12.warning(typedError.message); + } else { + if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { + core12.error(`Failed to save: ${typedError.message}`); + } else { + core12.warning(`Failed to save: ${typedError.message}`); + } + } + } finally { try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + yield utils.unlinkFile(archivePath); + } catch (error4) { + core12.debug(`Failed to delete archive: ${error4}`); } } - function step(result) { - result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return cacheId; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ClientStreamingCall = void 0; - var ClientStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - response, - status, - trailers - }; - }); - } - }; - exports2.ClientStreamingCall = ClientStreamingCall; + } } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js -var require_duplex_streaming_call = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) { +// node_modules/@actions/tool-cache/lib/manifest.js +var require_manifest = __commonJS({ + "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { "use strict"; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve6) { - resolve6(value); - }); - } - return new (P || (P = Promise))(function(resolve6, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DuplexStreamingCall = void 0; - var DuplexStreamingCall = class { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - promiseFinished() { - return __awaiter4(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - status, - trailers - }; - }); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } + __setModuleDefault4(result, mod); + return result; }; - exports2.DuplexStreamingCall = DuplexStreamingCall; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js -var require_test_transport = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) { - "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve6) { @@ -72666,1204 +76267,824 @@ var require_test_transport = __commonJS({ } } function step(result) { - result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TestTransport = void 0; - var rpc_error_1 = require_rpc_error(); - var runtime_1 = require_commonjs11(); - var rpc_output_stream_1 = require_rpc_output_stream(); - var rpc_options_1 = require_rpc_options(); - var unary_call_1 = require_unary_call(); - var server_streaming_call_1 = require_server_streaming_call(); - var client_streaming_call_1 = require_client_streaming_call(); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - var TestTransport = class _TestTransport { - /** - * Initialize with mock data. Omitted fields have default value. - */ - constructor(data) { - this.suppressUncaughtRejections = true; - this.headerDelay = 10; - this.responseDelay = 50; - this.betweenResponseDelay = 10; - this.afterResponseDelay = 10; - this.data = data !== null && data !== void 0 ? data : {}; - } - /** - * Sent message(s) during the last operation. - */ - get sentMessages() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.sent; - } else if (typeof this.lastInput == "object") { - return [this.lastInput.single]; - } - return []; - } - /** - * Sending message(s) completed? - */ - get sendComplete() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.completed; - } else if (typeof this.lastInput == "object") { - return true; - } - return false; - } - // Creates a promise for response headers from the mock data. - promiseHeaders() { - var _a; - const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders; - return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); - } - // Creates a promise for a single, valid, message from the mock data. - promiseSingleResponse(method) { - if (this.data.response instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.response); - } - let r; - if (Array.isArray(this.data.response)) { - runtime_1.assert(this.data.response.length > 0); - r = this.data.response[0]; - } else if (this.data.response !== void 0) { - r = this.data.response; - } else { - r = method.O.create(); - } - runtime_1.assert(method.O.is(r)); - return Promise.resolve(r); - } - /** - * Pushes response messages from the mock data to the output stream. - * If an error response, status or trailers are mocked, the stream is - * closed with the respective error. - * Otherwise, stream is completed successfully. - * - * The returned promise resolves when the stream is closed. It should - * not reject. If it does, code is broken. - */ - streamResponses(method, stream2, abort) { - return __awaiter4(this, void 0, void 0, function* () { - const messages = []; - if (this.data.response === void 0) { - messages.push(method.O.create()); - } else if (Array.isArray(this.data.response)) { - for (let msg of this.data.response) { - runtime_1.assert(method.O.is(msg)); - messages.push(msg); - } - } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { - runtime_1.assert(method.O.is(this.data.response)); - messages.push(this.data.response); - } - try { - yield delay2(this.responseDelay, abort)(void 0); - } catch (error4) { - stream2.notifyError(error4); - return; - } - if (this.data.response instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.response); - return; - } - for (let msg of messages) { - stream2.notifyMessage(msg); - try { - yield delay2(this.betweenResponseDelay, abort)(void 0); - } catch (error4) { - stream2.notifyError(error4); - return; - } - } - if (this.data.status instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.status); - return; - } - if (this.data.trailers instanceof rpc_error_1.RpcError) { - stream2.notifyError(this.data.trailers); - return; - } - stream2.notifyComplete(); - }); - } - // Creates a promise for response status from the mock data. - promiseStatus() { - var _a; - const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus; - return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); - } - // Creates a promise for response trailers from the mock data. - promiseTrailers() { - var _a; - const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers; - return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); - } - maybeSuppressUncaught(...promise) { - if (this.suppressUncaughtRejections) { - for (let p of promise) { - p.catch(() => { - }); - } - } - } - mergeOptions(options) { - return rpc_options_1.mergeRpcOptions({}, options); - } - unary(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); - } - serverStreaming(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); - } - clientStreaming(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => { - }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => { - }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); - } - duplex(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => { - }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); - } - }; - exports2.TestTransport = TestTransport; - TestTransport.defaultHeaders = { - responseHeader: "test" - }; - TestTransport.defaultStatus = { - code: "OK", - detail: "all good" - }; - TestTransport.defaultTrailers = { - responseTrailer: "test" + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - function delay2(ms, abort) { - return (v) => new Promise((resolve6, reject) => { - if (abort === null || abort === void 0 ? void 0 : abort.aborted) { - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - } else { - const id = setTimeout(() => resolve6(v), ms); - if (abort) { - abort.addEventListener("abort", (ev) => { - clearTimeout(id); - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; + var semver8 = __importStar4(require_semver2()); + var core_1 = require_core(); + var os2 = require("os"); + var cp = require("child_process"); + var fs12 = require("fs"); + function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter4(this, void 0, void 0, function* () { + const platFilter = os2.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); + if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + file = candidate.files.find((item) => { + (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module2.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } else { + chk = semver8.satisfies(osVersion, item.platform_version); + } + } + return chk; }); + if (file) { + (0, core_1.debug)(`matched ${candidate.version}`); + match = candidate; + break; + } } } + if (match && file) { + result = Object.assign({}, match); + result.files = [file]; + } + return result; }); } - var TestInputStream = class { - constructor(data, abort) { - this._completed = false; - this._sent = []; - this.data = data; - this.abort = abort; - } - get sent() { - return this._sent; - } - get completed() { - return this._completed; - } - send(message) { - if (this.data.inputMessage instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputMessage); + exports2._findMatch = _findMatch; + function _getOsVersion() { + const plat = os2.platform(); + let version = ""; + if (plat === "darwin") { + version = cp.execSync("sw_vers -productVersion").toString(); + } else if (plat === "linux") { + const lsbContents = module2.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split("\n"); + for (const line of lines) { + const parts = line.split("="); + if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { + version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); + break; + } + } } - const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage; - return Promise.resolve(void 0).then(() => { - this._sent.push(message); - }).then(delay2(delayMs, this.abort)); } - complete() { - if (this.data.inputComplete instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputComplete); - } - const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete; - return Promise.resolve(void 0).then(() => { - this._completed = true; - }).then(delay2(delayMs, this.abort)); + return version; + } + exports2._getOsVersion = _getOsVersion; + function _readLinuxVersionFile() { + const lsbReleaseFile = "/etc/lsb-release"; + const osReleaseFile = "/etc/os-release"; + let contents = ""; + if (fs12.existsSync(lsbReleaseFile)) { + contents = fs12.readFileSync(lsbReleaseFile).toString(); + } else if (fs12.existsSync(osReleaseFile)) { + contents = fs12.readFileSync(osReleaseFile).toString(); } - }; + return contents; + } + exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js -var require_rpc_interceptor = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js +var require_proxy4 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0; - var runtime_1 = require_commonjs11(); - function stackIntercept(kind, transport, method, options, input) { - var _a, _b, _c, _d; - if (kind == "unary") { - let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); - for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); - } - return tail(method, input, options); - } - if (kind == "serverStreaming") { - let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); - for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); - } - return tail(method, input, options); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - if (kind == "clientStreaming") { - let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); - for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - return tail(method, options); - } - if (kind == "duplex") { - let tail = (mtd, opt) => transport.duplex(mtd, opt); - for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); } - return tail(method, options); + } else { + return void 0; } - runtime_1.assertNever(kind); - } - exports2.stackIntercept = stackIntercept; - function stackUnaryInterceptors(transport, method, input, options) { - return stackIntercept("unary", transport, method, options, input); - } - exports2.stackUnaryInterceptors = stackUnaryInterceptors; - function stackServerStreamingInterceptors(transport, method, input, options) { - return stackIntercept("serverStreaming", transport, method, options, input); } - exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors; - function stackClientStreamingInterceptors(transport, method, options) { - return stackIntercept("clientStreaming", transport, method, options); - } - exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors; - function stackDuplexStreamingInterceptors(transport, method, options) { - return stackIntercept("duplex", transport, method, options); - } - exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js -var require_server_call_context = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServerCallContextController = void 0; - var ServerCallContextController = class { - constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) { - this._cancelled = false; - this._listeners = []; - this.method = method; - this.headers = headers; - this.deadline = deadline; - this.trailers = {}; - this._sendRH = sendResponseHeadersFn; - this.status = defaultStatus; + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - /** - * Set the call cancelled. - * - * Invokes all callbacks registered with onCancel() and - * sets `cancelled = true`. - */ - notifyCancelled() { - if (!this._cancelled) { - this._cancelled = true; - for (let l of this._listeners) { - l(); - } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - /** - * Send response headers. - */ - sendResponseHeaders(data) { - this._sendRH(data); + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - /** - * Is the call cancelled? - * - * When the client closes the connection before the server - * is done, the call is cancelled. - * - * If you want to cancel a request on the server, throw a - * RpcError with the CANCELLED status code. - */ - get cancelled() { - return this._cancelled; + get username() { + return this._decodedUsername; } - /** - * Add a callback for cancellation. - */ - onCancel(callback) { - const l = this._listeners; - l.push(callback); - return () => { - let i = l.indexOf(callback); - if (i >= 0) - l.splice(i, 1); - }; + get password() { + return this._decodedPassword; } }; - exports2.ServerCallContextController = ServerCallContextController; - } -}); - -// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js -var require_commonjs12 = __commonJS({ - "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var service_type_1 = require_service_type(); - Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() { - return service_type_1.ServiceType; - } }); - var reflection_info_1 = require_reflection_info2(); - Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() { - return reflection_info_1.readMethodOptions; - } }); - Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() { - return reflection_info_1.readMethodOption; - } }); - Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() { - return reflection_info_1.readServiceOption; - } }); - var rpc_error_1 = require_rpc_error(); - Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() { - return rpc_error_1.RpcError; - } }); - var rpc_options_1 = require_rpc_options(); - Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() { - return rpc_options_1.mergeRpcOptions; - } }); - var rpc_output_stream_1 = require_rpc_output_stream(); - Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() { - return rpc_output_stream_1.RpcOutputStreamController; - } }); - var test_transport_1 = require_test_transport(); - Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() { - return test_transport_1.TestTransport; - } }); - var deferred_1 = require_deferred(); - Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() { - return deferred_1.Deferred; - } }); - Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() { - return deferred_1.DeferredState; - } }); - var duplex_streaming_call_1 = require_duplex_streaming_call(); - Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() { - return duplex_streaming_call_1.DuplexStreamingCall; - } }); - var client_streaming_call_1 = require_client_streaming_call(); - Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() { - return client_streaming_call_1.ClientStreamingCall; - } }); - var server_streaming_call_1 = require_server_streaming_call(); - Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() { - return server_streaming_call_1.ServerStreamingCall; - } }); - var unary_call_1 = require_unary_call(); - Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() { - return unary_call_1.UnaryCall; - } }); - var rpc_interceptor_1 = require_rpc_interceptor(); - Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() { - return rpc_interceptor_1.stackIntercept; - } }); - Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackDuplexStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackClientStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackServerStreamingInterceptors; - } }); - Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() { - return rpc_interceptor_1.stackUnaryInterceptors; - } }); - var server_call_context_1 = require_server_call_context(); - Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() { - return server_call_context_1.ServerCallContextController; - } }); } }); -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js -var require_cachescope = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) { +// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js +var require_lib5 = __commonJS({ + "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheScope = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var CacheScope$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheScope", [ - { - no: 1, - name: "scope", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 2, - name: "permission", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve6) { + resolve6(value); + }); + } + return new (P || (P = Promise))(function(resolve6, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - ]); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy4()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - create(value) { - const message = { scope: "", permission: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string scope */ - 1: - message.scope = reader.string(); - break; - case /* int64 permission */ - 2: - message.permission = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve6(output.toString()); + }); + })); + }); } - internalBinaryWrite(message, writer, options) { - if (message.scope !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); - if (message.permission !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve6(Buffer.concat(chunks)); + }); + })); + }); } }; - exports2.CacheScope = new CacheScope$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js -var require_cachemetadata = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheMetadata = void 0; - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachescope_1 = require_cachescope(); - var CacheMetadata$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.entities.v1.CacheMetadata", [ - { - no: 1, - name: "repository_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope } - ]); - } - create(value) { - const message = { repositoryId: "0", scope: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int64 repository_id */ - 1: - message.repositoryId = reader.int64().toString(); - break; - case /* repeated github.actions.results.entities.v1.CacheScope scope */ - 2: - message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options)); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return message; } - internalBinaryWrite(message, writer, options) { - if (message.repositoryId !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); - for (let i = 0; i < message.scope.length; i++) - cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - }; - exports2.CacheMetadata = new CacheMetadata$Type(); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js -var require_cache2 = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0; - var runtime_rpc_1 = require_commonjs12(); - var runtime_1 = require_commonjs11(); - var runtime_2 = require_commonjs11(); - var runtime_3 = require_commonjs11(); - var runtime_4 = require_commonjs11(); - var runtime_5 = require_commonjs11(); - var cachemetadata_1 = require_cachemetadata(); - var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - create(value) { - const message = { key: "", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* string version */ - 3: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.version !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - }; - exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); - var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateCacheEntryResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_upload_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - create(value) { - const message = { ok: false, signedUploadUrl: "", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_upload_url */ - 2: - message.signedUploadUrl = reader.string(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - }; - exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); - var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "size_bytes", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - } - ]); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - create(value) { - const message = { key: "", sizeBytes: "0", version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* int64 size_bytes */ - 3: - message.sizeBytes = reader.int64().toString(); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - return message; + this._disposed = true; } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - if (message.sizeBytes !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve6(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); } - }; - exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); - var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "entry_id", - kind: "scalar", - T: 3 - /*ScalarType.INT64*/ - }, - { - no: 3, - name: "message", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; } - ]); - } - create(value) { - const message = { ok: false, entryId: "0", message: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* int64 entry_id */ - 2: - message.entryId = reader.int64().toString(); - break; - case /* string message */ - 3: - message.message = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.entryId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); - if (message.message !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } - }; - exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); - var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ - { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, - { - no: 2, - name: "key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "restore_keys", - kind: "scalar", - repeat: 2, - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 4, - name: "version", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } - ]); + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); + } else { + req.end(); + } } - create(value) { - const message = { key: "", restoreKeys: [], version: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* github.actions.results.entities.v1.CacheMetadata metadata */ - 1: - message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); - break; - case /* string key */ - 2: - message.key = reader.string(); - break; - case /* repeated string restore_keys */ - 3: - message.restoreKeys.push(reader.string()); - break; - case /* string version */ - 4: - message.version = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - return message; - } - internalBinaryWrite(message, writer, options) { - if (message.metadata) - cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - if (message.key !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); - for (let i = 0; i < message.restoreKeys.length; i++) - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); - if (message.version !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - }; - exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); - var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ - { - no: 1, - name: "ok", - kind: "scalar", - T: 8 - /*ScalarType.BOOL*/ - }, - { - no: 2, - name: "signed_download_url", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ - }, - { - no: 3, - name: "matched_key", - kind: "scalar", - T: 9 - /*ScalarType.STRING*/ + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; + } + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); } - ]); - } - create(value) { - const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== void 0) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + } + return info6; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ - 1: - message.ok = reader.bool(); - break; - case /* string signed_download_url */ - 2: - message.signedDownloadUrl = reader.string(); - break; - case /* string matched_key */ - 3: - message.matchedKey = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - return message; + return lowercaseKeys(headers || {}); } - internalBinaryWrite(message, writer, options) { - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - if (message.signedDownloadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); - if (message.matchedKey !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - }; - exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); - exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ - { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse }, - { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse }, - { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse } - ]); - } -}); - -// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js -var require_cache_twirp_client = __commonJS({ - "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0; - var cache_1 = require_cache2(); - var CacheServiceClientJSON = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false - }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, { - ignoreUnknownFields: true + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve6) => setTimeout(() => resolve6(), ms)); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, { - ignoreUnknownFields: true - })); } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve6(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve6(response); + } + })); }); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, { - ignoreUnknownFields: true - })); - } - }; - exports2.CacheServiceClientJSON = CacheServiceClientJSON; - var CacheServiceClientProtobuf = class { - constructor(rpc) { - this.rpc = rpc; - this.CreateCacheEntry.bind(this); - this.FinalizeCacheEntryUpload.bind(this); - this.GetCacheEntryDownloadURL.bind(this); - } - CreateCacheEntry(request) { - const data = cache_1.CreateCacheEntryRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); - return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2)); - } - FinalizeCacheEntryUpload(request) { - const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); - return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2)); - } - GetCacheEntryDownloadURL(request) { - const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); - return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2)); } }; - exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@actions/cache/lib/internal/shared/util.js -var require_util10 = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) { +// node_modules/@actions/tool-cache/lib/retry-helper.js +var require_retry_helper = __commonJS({ + "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.maskSecretUrls = exports2.maskSigUrl = void 0; - var core_1 = require_core(); - function maskSigUrl(url2) { - if (!url2) - return; - try { - const parsedUrl = new URL(url2); - const signature = parsedUrl.searchParams.get("sig"); - if (signature) { - (0, core_1.setSecret)(signature); - (0, core_1.setSecret)(encodeURIComponent(signature)); - } - } catch (error4) { - (0, core_1.debug)(`Failed to parse URL: ${url2} ${error4 instanceof Error ? error4.message : String(error4)}`); - } - } - exports2.maskSigUrl = maskSigUrl; - function maskSecretUrls(body) { - if (typeof body !== "object" || body === null) { - (0, core_1.debug)("body is not an object or is null"); - return; - } - if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { - maskSigUrl(body.signed_upload_url); + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - if ("signed_download_url" in body && typeof body.signed_download_url === "string") { - maskSigUrl(body.signed_download_url); + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - } - exports2.maskSecretUrls = maskSecretUrls; - } -}); - -// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js -var require_cacheTwirpClient = __commonJS({ - "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) { - "use strict"; + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve6) { @@ -73892,154 +77113,56 @@ var require_cacheTwirpClient = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.internalCacheTwirpClient = void 0; - var core_1 = require_core(); - var user_agent_1 = require_user_agent(); - var errors_1 = require_errors2(); - var config_1 = require_config(); - var cacheUtils_1 = require_cacheUtils(); - var auth_1 = require_auth(); - var http_client_1 = require_lib(); - var cache_twirp_client_1 = require_cache_twirp_client(); - var util_1 = require_util10(); - var CacheServiceClient = class { - constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { - this.maxAttempts = 5; - this.baseRetryIntervalMilliseconds = 3e3; - this.retryMultiplier = 1.5; - const token = (0, cacheUtils_1.getRuntimeToken)(); - this.baseUrl = (0, config_1.getCacheServiceURL)(); - if (maxAttempts) { - this.maxAttempts = maxAttempts; - } - if (baseRetryIntervalMilliseconds) { - this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + exports2.RetryHelper = void 0; + var core12 = __importStar4(require_core()); + var RetryHelper = class { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error("max attempts should be greater than or equal to 1"); } - if (retryMultiplier) { - this.retryMultiplier = retryMultiplier; + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error("min seconds should be less than or equal to max seconds"); } - this.httpClient = new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(token) - ]); - } - // This function satisfies the Rpc interface. It is compatible with the JSON - // JSON generated client. - request(service, method, contentType, data) { - return __awaiter4(this, void 0, void 0, function* () { - const url2 = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; - (0, core_1.debug)(`[Request] ${method} ${url2}`); - const headers = { - "Content-Type": contentType - }; - try { - const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { - return this.httpClient.post(url2, JSON.stringify(data), headers); - })); - return body; - } catch (error4) { - throw new Error(`Failed to ${method}: ${error4.message}`); - } - }); } - retryableRequest(operation) { + execute(action, isRetryable) { return __awaiter4(this, void 0, void 0, function* () { - let attempt = 0; - let errorMessage = ""; - let rawBody = ""; + let attempt = 1; while (attempt < this.maxAttempts) { - let isRetryable = false; try { - const response = yield operation(); - const statusCode = response.message.statusCode; - rawBody = yield response.readBody(); - (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); - (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); - const body = JSON.parse(rawBody); - (0, util_1.maskSecretUrls)(body); - (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); - if (this.isSuccessStatusCode(statusCode)) { - return { response, body }; - } - isRetryable = this.isRetryableHttpStatusCode(statusCode); - errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; - if (body.msg) { - if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { - throw new errors_1.UsageError(); - } - errorMessage = `${errorMessage}: ${body.msg}`; - } - } catch (error4) { - if (error4 instanceof SyntaxError) { - (0, core_1.debug)(`Raw Body: ${rawBody}`); - } - if (error4 instanceof errors_1.UsageError) { - throw error4; - } - if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { - throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + return yield action(); + } catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; } - isRetryable = true; - errorMessage = error4.message; - } - if (!isRetryable) { - throw new Error(`Received non-retryable error: ${errorMessage}`); - } - if (attempt + 1 === this.maxAttempts) { - throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + core12.info(err.message); } - const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); - (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); - yield this.sleep(retryTimeMilliseconds); + const seconds = this.getSleepAmount(); + core12.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); attempt++; } - throw new Error(`Request failed`); + return yield action(); }); } - isSuccessStatusCode(statusCode) { - if (!statusCode) - return false; - return statusCode >= 200 && statusCode < 300; - } - isRetryableHttpStatusCode(statusCode) { - if (!statusCode) - return false; - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.GatewayTimeout, - http_client_1.HttpCodes.InternalServerError, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.TooManyRequests - ]; - return retryableStatusCodes.includes(statusCode); + getSleepAmount() { + return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; } - sleep(milliseconds) { + sleep(seconds) { return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve6) => setTimeout(resolve6, milliseconds)); + return new Promise((resolve6) => setTimeout(resolve6, seconds * 1e3)); }); } - getExponentialRetryTimeMilliseconds(attempt) { - if (attempt < 0) { - throw new Error("attempt should be a positive integer"); - } - if (attempt === 0) { - return this.baseRetryIntervalMilliseconds; - } - const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); - const maxTime = minTime * this.retryMultiplier; - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); - } }; - function internalCacheTwirpClient(options) { - const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); - return new cache_twirp_client_1.CacheServiceClientJSON(client); - } - exports2.internalCacheTwirpClient = internalCacheTwirpClient; + exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/cache/lib/internal/tar.js -var require_tar = __commonJS({ - "node_modules/@actions/cache/lib/internal/tar.js"(exports2) { +// node_modules/@actions/tool-cache/lib/tool-cache.js +var require_tool_cache = __commonJS({ + "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74096,866 +77219,610 @@ var require_tar = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTar = exports2.extractTar = exports2.listTar = void 0; - var exec_1 = require_exec(); + exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; + var core12 = __importStar4(require_core()); var io6 = __importStar4(require_io()); - var fs_1 = require("fs"); + var crypto = __importStar4(require("crypto")); + var fs12 = __importStar4(require("fs")); + var mm = __importStar4(require_manifest()); + var os2 = __importStar4(require("os")); var path11 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var constants_1 = require_constants7(); + var httpm = __importStar4(require_lib5()); + var semver8 = __importStar4(require_semver2()); + var stream2 = __importStar4(require("stream")); + var util = __importStar4(require("util")); + var assert_1 = require("assert"); + var exec_1 = require_exec(); + var retry_helper_1 = require_retry_helper(); + var HTTPError2 = class extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + exports2.HTTPError = HTTPError2; var IS_WINDOWS = process.platform === "win32"; - function getTarPath() { + var IS_MAC = process.platform === "darwin"; + var userAgent = "actions/tool-cache"; + function downloadTool2(url2, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - switch (process.platform) { - case "win32": { - const gnuTar = yield utils.getGnuTarPathOnWindows(); - const systemTar = constants_1.SystemTarPathOnWindows; - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else if ((0, fs_1.existsSync)(systemTar)) { - return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; - } - break; - } - case "darwin": { - const gnuTar = yield io6.which("gtar", false); - if (gnuTar) { - return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; - } else { - return { - path: yield io6.which("tar", true), - type: constants_1.ArchiveToolType.BSD - }; + dest = dest || path11.join(_getTempDirectory(), crypto.randomUUID()); + yield io6.mkdirP(path11.dirname(dest)); + core12.debug(`Downloading ${url2}`); + core12.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); + const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url2, dest || "", auth, headers); + }), (err) => { + if (err instanceof HTTPError2 && err.httpStatusCode) { + if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { + return false; } } - default: - break; - } - return { - path: yield io6.which("tar", true), - type: constants_1.ArchiveToolType.GNU - }; + return true; + }); }); } - function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") { + exports2.downloadTool = downloadTool2; + function downloadToolAttempt(url2, dest, auth, headers) { return __awaiter4(this, void 0, void 0, function* () { - const args = [`"${tarPath.path}"`]; - const cacheFileName = utils.getCacheFileName(compressionMethod); - const tarFile = "cache.tar"; - const workingDirectory = getWorkingDirectory(); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (type2) { - case "create": - args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); - break; - case "extract": - args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path11.sep}`, "g"), "/")); - break; - case "list": - args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), "-P"); - break; + if (fs12.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); } - if (tarPath.type === constants_1.ArchiveToolType.GNU) { - switch (process.platform) { - case "win32": - args.push("--force-local"); - break; - case "darwin": - args.push("--delay-directory-restore"); - break; + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core12.debug("set auth"); + if (headers === void 0) { + headers = {}; } + headers.authorization = auth; } - return args; - }); - } - function getCommands(compressionMethod, type2, archivePath = "") { - return __awaiter4(this, void 0, void 0, function* () { - let args; - const tarPath = yield getTarPath(); - const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath); - const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - if (BSD_TAR_ZSTD && type2 !== "create") { - args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")]; - } else { - args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")]; - } - if (BSD_TAR_ZSTD) { - return args; + const response = yield http.get(url2, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError2(response.message.statusCode); + core12.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; } - return [args.join(" ")]; - }); - } - function getWorkingDirectory() { - var _a; - return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd(); - } - function getDecompressionProgram(tarPath, compressionMethod, archivePath) { - return __awaiter4(this, void 0, void 0, function* () { - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -d --long=30 --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path11.sep}`, "g"), "/") - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" - ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -d --force -o", - constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path11.sep}`, "g"), "/") - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; - default: - return ["-z"]; + const pipeline = util.promisify(stream2.pipeline); + const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; + try { + yield pipeline(readStream, fs12.createWriteStream(dest)); + core12.debug("download complete"); + succeeded = true; + return dest; + } finally { + if (!succeeded) { + core12.debug("download failed"); + try { + yield io6.rmRF(dest); + } catch (err) { + core12.debug(`Failed to delete '${dest}'. ${err.message}`); + } + } } }); } - function getCompressionProgram(tarPath, compressionMethod) { + function extract7z(file, dest, _7zPath) { return __awaiter4(this, void 0, void 0, function* () { - const cacheFileName = utils.getCacheFileName(compressionMethod); - const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --long=30 --force -o", - cacheFileName.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), - constants_1.TarFilename - ] : [ - "--use-compress-program", - IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30" + (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { + try { + const logLevel = core12.isDebug() ? "-bb1" : "-bb0"; + const args = [ + "x", + logLevel, + "-bd", + "-sccUTF-8", + file ]; - case constants_1.CompressionMethod.ZstdWithoutLong: - return BSD_TAR_ZSTD ? [ - "zstd -T0 --force -o", - cacheFileName.replace(new RegExp(`\\${path11.sep}`, "g"), "/"), - constants_1.TarFilename - ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; - default: - return ["-z"]; - } - }); - } - function execCommands(commands, cwd) { - return __awaiter4(this, void 0, void 0, function* () { - for (const command of commands) { + const options = { + silent: true + }; + yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); + } finally { + process.chdir(originalCwd); + } + } else { + const escapedScript = path11.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + command + ]; + const options = { + silent: true + }; try { - yield (0, exec_1.exec)(command, void 0, { - cwd, - env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" }) - }); - } catch (error4) { - throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`); + const powershellPath = yield io6.which("powershell", true); + yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); + } finally { + process.chdir(originalCwd); } } + return dest; }); } - function listTar(archivePath, compressionMethod) { - return __awaiter4(this, void 0, void 0, function* () { - const commands = yield getCommands(compressionMethod, "list", archivePath); - yield execCommands(commands); - }); - } - exports2.listTar = listTar; - function extractTar2(archivePath, compressionMethod) { + exports2.extract7z = extract7z; + function extractTar2(file, dest, flags = "xz") { return __awaiter4(this, void 0, void 0, function* () { - const workingDirectory = getWorkingDirectory(); - yield io6.mkdirP(workingDirectory); - const commands = yield getCommands(compressionMethod, "extract", archivePath); - yield execCommands(commands); + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + core12.debug("Checking tar --version"); + let versionOutput = ""; + yield (0, exec_1.exec)("tar --version", [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => versionOutput += data.toString(), + stderr: (data) => versionOutput += data.toString() + } + }); + core12.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + if (core12.isDebug() && !flags.includes("v")) { + args.push("-v"); + } + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push("--force-local"); + destArg = dest.replace(/\\/g, "/"); + fileArg = file.replace(/\\/g, "/"); + } + if (isGnuTar) { + args.push("--warning=no-unknown-keyword"); + args.push("--overwrite"); + } + args.push("-C", destArg, "-f", fileArg); + yield (0, exec_1.exec)(`tar`, args); + return dest; }); } exports2.extractTar = extractTar2; - function createTar(archiveFolder, sourceDirectories, compressionMethod) { + function extractXar(file, dest, flags = []) { return __awaiter4(this, void 0, void 0, function* () { - (0, fs_1.writeFileSync)(path11.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); - const commands = yield getCommands(compressionMethod, "create"); - yield execCommands(commands, archiveFolder); + (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); + (0, assert_1.ok)(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } else { + args = [flags]; + } + args.push("-x", "-C", dest, "-f", file); + if (core12.isDebug()) { + args.push("-v"); + } + const xarPath = yield io6.which("xar", true); + yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); + return dest; }); } - exports2.createTar = createTar; - } -}); - -// node_modules/@actions/cache/lib/cache.js -var require_cache3 = __commonJS({ - "node_modules/@actions/cache/lib/cache.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve6) { - resolve6(value); - }); - } - return new (P || (P = Promise))(function(resolve6, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + exports2.extractXar = extractXar; + function extractZip(file, dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); } - function step(result) { - result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } else { + yield extractZipNix(file, dest); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return dest; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0; - var core12 = __importStar4(require_core()); - var path11 = __importStar4(require("path")); - var utils = __importStar4(require_cacheUtils()); - var cacheHttpClient = __importStar4(require_cacheHttpClient()); - var cacheTwirpClient = __importStar4(require_cacheTwirpClient()); - var config_1 = require_config(); - var tar_1 = require_tar(); - var http_client_1 = require_lib(); - var ValidationError = class _ValidationError extends Error { - constructor(message) { - super(message); - this.name = "ValidationError"; - Object.setPrototypeOf(this, _ValidationError.prototype); - } - }; - exports2.ValidationError = ValidationError; - var ReserveCacheError = class _ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = "ReserveCacheError"; - Object.setPrototypeOf(this, _ReserveCacheError.prototype); - } - }; - exports2.ReserveCacheError = ReserveCacheError; - var FinalizeCacheError = class _FinalizeCacheError extends Error { - constructor(message) { - super(message); - this.name = "FinalizeCacheError"; - Object.setPrototypeOf(this, _FinalizeCacheError.prototype); - } - }; - exports2.FinalizeCacheError = FinalizeCacheError; - function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } - } - function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); - } - } - function isFeatureAvailable() { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - switch (cacheServiceVersion) { - case "v2": - return !!process.env["ACTIONS_RESULTS_URL"]; - case "v1": - default: - return !!process.env["ACTIONS_CACHE_URL"]; - } } - exports2.isFeatureAvailable = isFeatureAvailable; - function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + exports2.extractZip = extractZip; + function extractZipWin(file, dest) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core12.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - switch (cacheServiceVersion) { - case "v2": - return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); - case "v1": - default: - return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const pwshPath = yield io6.which("pwsh", false); + if (pwshPath) { + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(" "); + const args = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + pwshCommand + ]; + core12.debug(`Using pwsh at path: ${pwshPath}`); + yield (0, exec_1.exec)(`"${pwshPath}"`, args); + } else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(" "); + const args = [ + "-NoLogo", + "-Sta", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Unrestricted", + "-Command", + powershellCommand + ]; + const powershellPath = yield io6.which("powershell", true); + core12.debug(`Using powershell at path: ${powershellPath}`); + yield (0, exec_1.exec)(`"${powershellPath}"`, args); } }); } - exports2.restoreCache = restoreCache3; - function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + function extractZipNix(file, dest) { return __awaiter4(this, void 0, void 0, function* () { - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core12.debug("Resolved Keys:"); - core12.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); - } - const compressionMethod = yield utils.getCompressionMethod(); - let archivePath = ""; - try { - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod, - enableCrossOsArchive - }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - return void 0; - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core12.info("Lookup only - skipping download"); - return cacheEntry.cacheKey; - } - archivePath = path11.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core12.debug(`Archive Path: ${archivePath}`); - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core12.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core12.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core12.info("Cache restored successfully"); - return cacheEntry.cacheKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core12.error(`Failed to restore: ${error4.message}`); - } else { - core12.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core12.debug(`Failed to delete archive: ${error4}`); - } + const unzipPath = yield io6.which("unzip", true); + const args = [file]; + if (!core12.isDebug()) { + args.unshift("-q"); } - return void 0; + args.unshift("-o"); + yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); }); } - function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + function cacheDir(sourceDir, tool, version, arch2) { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core12.debug("Resolved Keys:"); - core12.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); + version = semver8.clean(version) || version; + arch2 = arch2 || os2.arch(); + core12.debug(`Caching tool ${tool} ${version} ${arch2}`); + core12.debug(`source dir: ${sourceDir}`); + if (!fs12.statSync(sourceDir).isDirectory()) { + throw new Error("sourceDir is not a directory"); } - let archivePath = ""; - try { - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - const compressionMethod = yield utils.getCompressionMethod(); - const request = { - key: primaryKey, - restoreKeys, - version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) - }; - const response = yield twirpClient.GetCacheEntryDownloadURL(request); - if (!response.ok) { - core12.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`); - return void 0; - } - const isRestoreKeyMatch = request.key !== response.matchedKey; - if (isRestoreKeyMatch) { - core12.info(`Cache hit for restore-key: ${response.matchedKey}`); - } else { - core12.info(`Cache hit for: ${response.matchedKey}`); - } - if (options === null || options === void 0 ? void 0 : options.lookupOnly) { - core12.info("Lookup only - skipping download"); - return response.matchedKey; - } - archivePath = path11.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core12.debug(`Archive path: ${archivePath}`); - core12.debug(`Starting download of archive to: ${archivePath}`); - yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core12.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - if (core12.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - yield (0, tar_1.extractTar)(archivePath, compressionMethod); - core12.info("Cache restored successfully"); - return response.matchedKey; - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core12.error(`Failed to restore: ${error4.message}`); - } else { - core12.warning(`Failed to restore: ${error4.message}`); - } - } - } finally { - try { - if (archivePath) { - yield utils.unlinkFile(archivePath); - } - } catch (error4) { - core12.debug(`Failed to delete archive: ${error4}`); - } + const destPath = yield _createToolPath(tool, version, arch2); + for (const itemName of fs12.readdirSync(sourceDir)) { + const s = path11.join(sourceDir, itemName); + yield io6.cp(s, destPath, { recursive: true }); } - return void 0; + _completeToolPath(tool, version, arch2); + return destPath; }); } - function saveCache3(paths, key, options, enableCrossOsArchive = false) { + exports2.cacheDir = cacheDir; + function cacheFile(sourceFile, targetFile, tool, version, arch2) { return __awaiter4(this, void 0, void 0, function* () { - const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); - core12.debug(`Cache service version: ${cacheServiceVersion}`); - checkPaths(paths); - checkKey(key); - switch (cacheServiceVersion) { - case "v2": - return yield saveCacheV2(paths, key, options, enableCrossOsArchive); - case "v1": - default: - return yield saveCacheV1(paths, key, options, enableCrossOsArchive); + version = semver8.clean(version) || version; + arch2 = arch2 || os2.arch(); + core12.debug(`Caching tool ${tool} ${version} ${arch2}`); + core12.debug(`source file: ${sourceFile}`); + if (!fs12.statSync(sourceFile).isFile()) { + throw new Error("sourceFile is not a file"); } + const destFolder = yield _createToolPath(tool, version, arch2); + const destPath = path11.join(destFolder, targetFile); + core12.debug(`destination file ${destPath}`); + yield io6.cp(sourceFile, destPath); + _completeToolPath(tool, version, arch2); + return destFolder; }); } - exports2.saveCache = saveCache3; - function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { - var _a, _b, _c, _d, _e; - return __awaiter4(this, void 0, void 0, function* () { - const compressionMethod = yield utils.getCompressionMethod(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core12.debug("Cache Paths:"); - core12.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + exports2.cacheFile = cacheFile; + function find2(toolName, versionSpec, arch2) { + if (!toolName) { + throw new Error("toolName parameter is required"); + } + if (!versionSpec) { + throw new Error("versionSpec parameter is required"); + } + arch2 = arch2 || os2.arch(); + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions2(toolName, arch2); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; + } + let toolPath = ""; + if (versionSpec) { + versionSpec = semver8.clean(versionSpec) || ""; + const cachePath = path11.join(_getCacheDirectory(), toolName, versionSpec, arch2); + core12.debug(`checking cache: ${cachePath}`); + if (fs12.existsSync(cachePath) && fs12.existsSync(`${cachePath}.complete`)) { + core12.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); + toolPath = cachePath; + } else { + core12.debug("not found"); } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path11.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core12.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core12.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const fileSizeLimit = 10 * 1024 * 1024 * 1024; - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core12.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); - } - core12.debug("Reserving Cache"); - const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod, - enableCrossOsArchive, - cacheSize: archiveFileSize - }); - if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { - cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; - } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { - throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); - } else { - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); - } - core12.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, "", options); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError.name) { - core12.info(`Failed to save: ${typedError.message}`); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core12.error(`Failed to save: ${typedError.message}`); - } else { - core12.warning(`Failed to save: ${typedError.message}`); + } + return toolPath; + } + exports2.find = find2; + function findAllVersions2(toolName, arch2) { + const versions = []; + arch2 = arch2 || os2.arch(); + const toolPath = path11.join(_getCacheDirectory(), toolName); + if (fs12.existsSync(toolPath)) { + const children = fs12.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path11.join(toolPath, child, arch2 || ""); + if (fs12.existsSync(fullPath) && fs12.existsSync(`${fullPath}.complete`)) { + versions.push(child); } } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core12.debug(`Failed to delete archive: ${error4}`); - } } - return cacheId; - }); + } + return versions; } - function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { + exports2.findAllVersions = findAllVersions2; + function getManifestFromRepo(owner, repo, auth, branch = "master") { return __awaiter4(this, void 0, void 0, function* () { - options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); - const compressionMethod = yield utils.getCompressionMethod(); - const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); - let cacheId = -1; - const cachePaths = yield utils.resolvePaths(paths); - core12.debug("Cache Paths:"); - core12.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient("tool-cache"); + const headers = {}; + if (auth) { + core12.debug("set auth"); + headers.authorization = auth; } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path11.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core12.debug(`Archive Path: ${archivePath}`); - try { - yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); - if (core12.isDebug()) { - yield (0, tar_1.listTar)(archivePath, compressionMethod); - } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core12.debug(`File Size: ${archiveFileSize}`); - options.archiveSizeBytes = archiveFileSize; - core12.debug("Reserving Cache"); - const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); - const request = { - key, - version - }; - let signedUploadUrl; - try { - const response = yield twirpClient.CreateCacheEntry(request); - if (!response.ok) { - if (response.message) { - core12.warning(`Cache reservation failed: ${response.message}`); - } - throw new Error(response.message || "Response was not ok"); - } - signedUploadUrl = response.signedUploadUrl; - } catch (error4) { - core12.debug(`Failed to reserve cache: ${error4}`); - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); - } - core12.debug(`Attempting to upload cache located at: ${archivePath}`); - yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); - const finalizeRequest = { - key, - version, - sizeBytes: `${archiveFileSize}` - }; - const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); - core12.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); - if (!finalizeResponse.ok) { - if (finalizeResponse.message) { - throw new FinalizeCacheError(finalizeResponse.message); - } - throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); - } - cacheId = parseInt(finalizeResponse.entryId); - } catch (error4) { - const typedError = error4; - if (typedError.name === ValidationError.name) { - throw error4; - } else if (typedError.name === ReserveCacheError.name) { - core12.info(`Failed to save: ${typedError.message}`); - } else if (typedError.name === FinalizeCacheError.name) { - core12.warning(typedError.message); - } else { - if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) { - core12.error(`Failed to save: ${typedError.message}`); - } else { - core12.warning(`Failed to save: ${typedError.message}`); - } - } - } finally { - try { - yield utils.unlinkFile(archivePath); - } catch (error4) { - core12.debug(`Failed to delete archive: ${error4}`); - } + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; } - return cacheId; - }); - } - } -}); - -// node_modules/@actions/tool-cache/lib/manifest.js -var require_manifest = __commonJS({ - "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve6) { - resolve6(value); - }); - } - return new (P || (P = Promise))(function(resolve6, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + let manifestUrl = ""; + for (const item of response.result.tree) { + if (item.path === "versions-manifest.json") { + manifestUrl = item.url; + break; } } - function rejected(value) { + headers["accept"] = "application/vnd.github.VERSION.raw"; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + releases = JSON.parse(versionsRaw); + } catch (_a) { + core12.debug("Invalid json"); } } - function step(result) { - result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + return releases; }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0; - var semver8 = __importStar4(require_semver2()); - var core_1 = require_core(); - var os2 = require("os"); - var cp = require("child_process"); - var fs12 = require("fs"); - function _findMatch(versionSpec, stable, candidates, archFilter) { + } + exports2.getManifestFromRepo = getManifestFromRepo; + function findFromManifest(versionSpec, stable, manifest, archFilter = os2.arch()) { return __awaiter4(this, void 0, void 0, function* () { - const platFilter = os2.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { - file = candidate.files.find((item) => { - (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module2.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } else { - chk = semver8.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - (0, core_1.debug)(`matched ${candidate.version}`); - match = candidate; - break; - } - } - } - if (match && file) { - result = Object.assign({}, match); - result.files = [file]; + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; + }); + } + exports2.findFromManifest = findFromManifest; + function _createExtractFolder(dest) { + return __awaiter4(this, void 0, void 0, function* () { + if (!dest) { + dest = path11.join(_getTempDirectory(), crypto.randomUUID()); } - return result; + yield io6.mkdirP(dest); + return dest; }); } - exports2._findMatch = _findMatch; - function _getOsVersion() { - const plat = os2.platform(); + function _createToolPath(tool, version, arch2) { + return __awaiter4(this, void 0, void 0, function* () { + const folderPath = path11.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); + core12.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io6.rmRF(folderPath); + yield io6.rmRF(markerPath); + yield io6.mkdirP(folderPath); + return folderPath; + }); + } + function _completeToolPath(tool, version, arch2) { + const folderPath = path11.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); + const markerPath = `${folderPath}.complete`; + fs12.writeFileSync(markerPath, ""); + core12.debug("finished caching tool"); + } + function isExplicitVersion(versionSpec) { + const c = semver8.clean(versionSpec) || ""; + core12.debug(`isExplicit: ${c}`); + const valid3 = semver8.valid(c) != null; + core12.debug(`explicit? ${valid3}`); + return valid3; + } + exports2.isExplicitVersion = isExplicitVersion; + function evaluateVersions(versions, versionSpec) { let version = ""; - if (plat === "darwin") { - version = cp.execSync("sw_vers -productVersion").toString(); - } else if (plat === "linux") { - const lsbContents = module2.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split("\n"); - for (const line of lines) { - const parts = line.split("="); - if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) { - version = parts[1].trim().replace(/^"/, "").replace(/"$/, ""); - break; - } - } + core12.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver8.gt(a, b)) { + return 1; + } + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver8.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; } } + if (version) { + core12.debug(`matched: ${version}`); + } else { + core12.debug("match not found"); + } return version; } - exports2._getOsVersion = _getOsVersion; - function _readLinuxVersionFile() { - const lsbReleaseFile = "/etc/lsb-release"; - const osReleaseFile = "/etc/os-release"; - let contents = ""; - if (fs12.existsSync(lsbReleaseFile)) { - contents = fs12.readFileSync(lsbReleaseFile).toString(); - } else if (fs12.existsSync(osReleaseFile)) { - contents = fs12.readFileSync(osReleaseFile).toString(); - } - return contents; + exports2.evaluateVersions = evaluateVersions; + function _getCacheDirectory() { + const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; + (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); + return cacheDirectory; + } + function _getTempDirectory() { + const tempDirectory = process.env["RUNNER_TEMP"] || ""; + (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); + return tempDirectory; + } + function _getGlobal(key, defaultValue) { + const value = global[key]; + return value !== void 0 ? value : defaultValue; + } + function _unique(values) { + return Array.from(new Set(values)); } - exports2._readLinuxVersionFile = _readLinuxVersionFile; } }); -// node_modules/@actions/tool-cache/lib/retry-helper.js -var require_retry_helper = __commonJS({ - "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) { +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve6) { - resolve6(value); - }); - } - return new (P || (P = Promise))(function(resolve6, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + module2.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; } - function step(result) { - result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return true; + } + return a !== a && b !== b; }; + } +}); + +// node_modules/@actions/http-client/lib/proxy.js +var require_proxy5 = __commonJS({ + "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RetryHelper = void 0; - var core12 = __importStar4(require_core()); - var RetryHelper = class { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error("max attempts should be greater than or equal to 1"); + exports2.getProxyUrl = getProxyUrl; + exports2.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error("min seconds should be less than or equal to max seconds"); + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; } } - execute(action, isRetryable) { - return __awaiter4(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - try { - return yield action(); - } catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core12.info(err.message); - } - const seconds = this.getSleepAmount(); - core12.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - return yield action(); - }); + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url2, base) { + super(url2, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - getSleepAmount() { - return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; + get username() { + return this._decodedUsername; } - sleep(seconds) { - return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve6) => setTimeout(resolve6, seconds * 1e3)); - }); + get password() { + return this._decodedPassword; } }; - exports2.RetryHelper = RetryHelper; } }); -// node_modules/@actions/tool-cache/lib/tool-cache.js -var require_tool_cache = __commonJS({ - "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) { +// node_modules/@actions/http-client/lib/index.js +var require_lib6 = __commonJS({ + "node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -74975,15 +77842,25 @@ var require_tool_cache = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve6) { @@ -75012,523 +77889,616 @@ var require_tool_cache = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0; - var core12 = __importStar4(require_core()); - var io6 = __importStar4(require_io()); - var crypto = __importStar4(require("crypto")); - var fs12 = __importStar4(require("fs")); - var mm = __importStar4(require_manifest()); - var os2 = __importStar4(require("os")); - var path11 = __importStar4(require("path")); - var httpm = __importStar4(require_lib()); - var semver8 = __importStar4(require_semver2()); - var stream2 = __importStar4(require("stream")); - var util = __importStar4(require("util")); - var assert_1 = require("assert"); - var exec_1 = require_exec(); - var retry_helper_1 = require_retry_helper(); - var HTTPError2 = class extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); + exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + exports2.getProxyUrl = getProxyUrl; + exports2.isHttps = isHttps; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy5()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } }; - exports2.HTTPError = HTTPError2; - var IS_WINDOWS = process.platform === "win32"; - var IS_MAC = process.platform === "darwin"; - var userAgent = "actions/tool-cache"; - function downloadTool2(url2, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - dest = dest || path11.join(_getTempDirectory(), crypto.randomUUID()); - yield io6.mkdirP(path11.dirname(dest)); - core12.debug(`Downloading ${url2}`); - core12.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10); - const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url2, dest || "", auth, headers); - }), (err) => { - if (err instanceof HTTPError2 && err.httpStatusCode) { - if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { - return false; - } - } - return true; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve6(output.toString()); + }); + })); }); - }); - } - exports2.downloadTool = downloadTool2; - function downloadToolAttempt(url2, dest, auth, headers) { - return __awaiter4(this, void 0, void 0, function* () { - if (fs12.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false + } + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve6(Buffer.concat(chunks)); + }); + })); }); - if (auth) { - core12.debug("set auth"); - if (headers === void 0) { - headers = {}; + } + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - headers.authorization = auth; - } - const response = yield http.get(url2, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError2(response.message.statusCode); - core12.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; - } - const pipeline = util.promisify(stream2.pipeline); - const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs12.createWriteStream(dest)); - core12.debug("download complete"); - succeeded = true; - return dest; - } finally { - if (!succeeded) { - core12.debug("download failed"); - try { - yield io6.rmRF(dest); - } catch (err) { - core12.debug(`Failed to delete '${dest}'. ${err.message}`); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } - }); - } - function extract7z(file, dest, _7zPath) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core12.isDebug() ? "-bb1" : "-bb0"; - const args = [ - "x", - logLevel, - "-bd", - "-sccUTF-8", - file - ]; - const options = { - silent: true - }; - yield (0, exec_1.exec)(`"${_7zPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - } else { - const escapedScript = path11.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io6.which("powershell", true); - yield (0, exec_1.exec)(`"${powershellPath}"`, args, options); - } finally { - process.chdir(originalCwd); + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return dest; - }); - } - exports2.extract7z = extract7z; - function extractTar2(file, dest, flags = "xz") { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - core12.debug("Checking tar --version"); - let versionOutput = ""; - yield (0, exec_1.exec)("tar --version", [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => versionOutput += data.toString(), - stderr: (data) => versionOutput += data.toString() + } + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream2, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream2, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } + const parsedUrl = new URL(requestUrl); + let info6 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info6, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info6, data); + } else { + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info6 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info6, data); + redirectsRemaining--; + } + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - core12.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR"); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; - } - if (core12.isDebug() && !flags.includes("v")) { - args.push("-v"); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push("--force-local"); - destArg = dest.replace(/\\/g, "/"); - fileArg = file.replace(/\\/g, "/"); - } - if (isGnuTar) { - args.push("--warning=no-unknown-keyword"); - args.push("--overwrite"); - } - args.push("-C", destArg, "-f", fileArg); - yield (0, exec_1.exec)(`tar`, args); - return dest; - }); - } - exports2.extractTar = extractTar2; - function extractXar(file, dest, flags = []) { - return __awaiter4(this, void 0, void 0, function* () { - (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS"); - (0, assert_1.ok)(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } else { - args = [flags]; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - args.push("-x", "-C", dest, "-f", file); - if (core12.isDebug()) { - args.push("-v"); + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info6, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve6(res); + } + } + this.requestRawWithCallback(info6, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info6, data, onResult) { + if (typeof data === "string") { + if (!info6.options.headers) { + info6.options.headers = {}; + } + info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - const xarPath = yield io6.which("xar", true); - yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args)); - return dest; - }); - } - exports2.extractXar = extractXar; - function extractZip(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } else { - yield extractZipNix(file, dest); + const req = info6.httpModule.request(info6.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info6.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - return dest; - }); - } - exports2.extractZip = extractZip; - function extractZipWin(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); - const pwshPath = yield io6.which("pwsh", false); - if (pwshPath) { - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(" "); - const args = [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - pwshCommand - ]; - core12.debug(`Using pwsh at path: ${pwshPath}`); - yield (0, exec_1.exec)(`"${pwshPath}"`, args); + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(" "); - const args = [ - "-NoLogo", - "-Sta", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Unrestricted", - "-Command", - powershellCommand - ]; - const powershellPath = yield io6.which("powershell", true); - core12.debug(`Using powershell at path: ${powershellPath}`); - yield (0, exec_1.exec)(`"${powershellPath}"`, args); - } - }); - } - function extractZipNix(file, dest) { - return __awaiter4(this, void 0, void 0, function* () { - const unzipPath = yield io6.which("unzip", true); - const args = [file]; - if (!core12.isDebug()) { - args.unshift("-q"); + req.end(); } - args.unshift("-o"); - yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest }); - }); - } - function cacheDir(sourceDir, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch2 = arch2 || os2.arch(); - core12.debug(`Caching tool ${tool} ${version} ${arch2}`); - core12.debug(`source dir: ${sourceDir}`); - if (!fs12.statSync(sourceDir).isDirectory()) { - throw new Error("sourceDir is not a directory"); + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - const destPath = yield _createToolPath(tool, version, arch2); - for (const itemName of fs12.readdirSync(sourceDir)) { - const s = path11.join(sourceDir, itemName); - yield io6.cp(s, destPath, { recursive: true }); + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info6 = {}; + info6.parsedUrl = requestUrl; + const usingSsl = info6.parsedUrl.protocol === "https:"; + info6.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info6.options = {}; + info6.options.host = info6.parsedUrl.hostname; + info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort; + info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || ""); + info6.options.method = method; + info6.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info6.options.headers["user-agent"] = this.userAgent; } - _completeToolPath(tool, version, arch2); - return destPath; - }); - } - exports2.cacheDir = cacheDir; - function cacheFile(sourceFile, targetFile, tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - version = semver8.clean(version) || version; - arch2 = arch2 || os2.arch(); - core12.debug(`Caching tool ${tool} ${version} ${arch2}`); - core12.debug(`source file: ${sourceFile}`); - if (!fs12.statSync(sourceFile).isFile()) { - throw new Error("sourceFile is not a file"); + info6.options.agent = this._getAgent(info6.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info6.options); + } } - const destFolder = yield _createToolPath(tool, version, arch2); - const destPath = path11.join(destFolder, targetFile); - core12.debug(`destination file ${destPath}`); - yield io6.cp(sourceFile, destPath); - _completeToolPath(tool, version, arch2); - return destFolder; - }); - } - exports2.cacheFile = cacheFile; - function find2(toolName, versionSpec, arch2) { - if (!toolName) { - throw new Error("toolName parameter is required"); - } - if (!versionSpec) { - throw new Error("versionSpec parameter is required"); + return info6; } - arch2 = arch2 || os2.arch(); - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions2(toolName, arch2); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - let toolPath = ""; - if (versionSpec) { - versionSpec = semver8.clean(versionSpec) || ""; - const cachePath = path11.join(_getCacheDirectory(), toolName, versionSpec, arch2); - core12.debug(`checking cache: ${cachePath}`); - if (fs12.existsSync(cachePath) && fs12.existsSync(`${cachePath}.complete`)) { - core12.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); - toolPath = cachePath; - } else { - core12.debug("not found"); + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== void 0) { + return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue; } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return toolPath; - } - exports2.find = find2; - function findAllVersions2(toolName, arch2) { - const versions = []; - arch2 = arch2 || os2.arch(); - const toolPath = path11.join(_getCacheDirectory(), toolName); - if (fs12.existsSync(toolPath)) { - const children = fs12.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path11.join(toolPath, child, arch2 || ""); - if (fs12.existsSync(fullPath) && fs12.existsSync(`${fullPath}.complete`)) { - versions.push(child); + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === "number") { + clientHeader = String(headerValue); + } else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(", "); + } else { + clientHeader = headerValue; } } } + const additionalValue = additionalHeaders[Headers.ContentType]; + if (additionalValue !== void 0) { + if (typeof additionalValue === "number") { + return String(additionalValue); + } else if (Array.isArray(additionalValue)) { + return additionalValue.join(", "); + } else { + return additionalValue; + } + } + if (clientHeader !== void 0) { + return clientHeader; + } + return _default2; } - return versions; - } - exports2.findAllVersions = findAllVersions2; - function getManifestFromRepo(owner, repo, auth, branch = "master") { - return __awaiter4(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient("tool-cache"); - const headers = {}; - if (auth) { - core12.debug("set auth"); - headers.authorization = auth; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; + if (!useProxy) { + agent = this._agent; } - let manifestUrl = ""; - for (const item of response.result.tree) { - if (item.path === "versions-manifest.json") { - manifestUrl = item.url; - break; - } + if (agent) { + return agent; } - headers["accept"] = "application/vnd.github.VERSION.raw"; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - versionsRaw = versionsRaw.replace(/^\uFEFF/, ""); - try { - releases = JSON.parse(versionsRaw); - } catch (_a) { - core12.debug("Invalid json"); - } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - return releases; - }); - } - exports2.getManifestFromRepo = getManifestFromRepo; - function findFromManifest(versionSpec, stable, manifest, archFilter = os2.arch()) { - return __awaiter4(this, void 0, void 0, function* () { - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); - } - exports2.findFromManifest = findFromManifest; - function _createExtractFolder(dest) { - return __awaiter4(this, void 0, void 0, function* () { - if (!dest) { - dest = path11.join(_getTempDirectory(), crypto.randomUUID()); + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - yield io6.mkdirP(dest); - return dest; - }); - } - function _createToolPath(tool, version, arch2) { - return __awaiter4(this, void 0, void 0, function* () { - const folderPath = path11.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); - core12.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io6.rmRF(folderPath); - yield io6.rmRF(markerPath); - yield io6.mkdirP(folderPath); - return folderPath; - }); - } - function _completeToolPath(tool, version, arch2) { - const folderPath = path11.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || ""); - const markerPath = `${folderPath}.complete`; - fs12.writeFileSync(markerPath, ""); - core12.debug("finished caching tool"); - } - function isExplicitVersion(versionSpec) { - const c = semver8.clean(versionSpec) || ""; - core12.debug(`isExplicit: ${c}`); - const valid3 = semver8.valid(c) != null; - core12.debug(`explicit? ${valid3}`); - return valid3; - } - exports2.isExplicitVersion = isExplicitVersion; - function evaluateVersions(versions, versionSpec) { - let version = ""; - core12.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver8.gt(a, b)) { - return 1; + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver8.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } + return agent; } - if (version) { - core12.debug(`matched: ${version}`); - } else { - core12.debug("match not found"); - } - return version; - } - exports2.evaluateVersions = evaluateVersions; - function _getCacheDirectory() { - const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || ""; - (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined"); - return cacheDirectory; - } - function _getTempDirectory() { - const tempDirectory = process.env["RUNNER_TEMP"] || ""; - (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined"); - return tempDirectory; - } - function _getGlobal(key, defaultValue) { - const value = global[key]; - return value !== void 0 ? value : defaultValue; - } - function _unique(values) { - return Array.from(new Set(values)); - } - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - module2.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; + if (proxyAgent) { + return proxyAgent; } - return true; + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve6) => setTimeout(() => resolve6(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve6, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve6(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve6(response); + } + })); + }); } - return a !== a && b !== b; }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); @@ -83245,7 +86215,7 @@ var os = __toESM(require("os")); var path6 = __toESM(require("path")); var import_perf_hooks = require("perf_hooks"); var core9 = __toESM(require_core()); -var import_http_client = __toESM(require_lib()); +var import_http_client = __toESM(require_lib6()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); var semver6 = __toESM(require_semver2()); diff --git a/lib/upload-sarif-action-post.js b/lib/upload-sarif-action-post.js index 7851208512..3ec0059b91 100644 --- a/lib/upload-sarif-action-post.js +++ b/lib/upload-sarif-action-post.js @@ -216,9 +216,9 @@ var require_file_command = __commonJS({ } }); -// node_modules/@actions/http-client/lib/proxy.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js var require_proxy = __commonJS({ - "node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkBypass = exports2.getProxyUrl = void 0; @@ -17292,9 +17292,9 @@ var require_undici = __commonJS({ } }); -// node_modules/@actions/http-client/lib/index.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js var require_lib = __commonJS({ - "node_modules/@actions/http-client/lib/index.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -17911,9 +17911,9 @@ var require_lib = __commonJS({ } }); -// node_modules/@actions/http-client/lib/auth.js +// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js var require_auth = __commonJS({ - "node_modules/@actions/http-client/lib/auth.js"(exports2) { + "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { @@ -19875,9 +19875,91 @@ var require_context = __commonJS({ } }); -// node_modules/@actions/github/lib/internal/utils.js -var require_utils3 = __commonJS({ - "node_modules/@actions/github/lib/internal/utils.js"(exports2) { +// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js +var require_proxy2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; + } + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { + return false; + } + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; + } + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } + } + return false; + } + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); + } + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; + } +}); + +// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -19934,737 +20016,826 @@ var require_utils3 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; - var httpClient = __importStar4(require_lib()); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy2()); + var tunnel = __importStar4(require_tunnel2()); var undici_1 = require_undici(); - function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error("Parameter token or opts.auth is required"); - } else if (token && options.auth) { - throw new Error("Parameters token and opts.auth may not both be specified"); - } - return typeof options.auth === "string" ? options.auth : `token ${token}`; - } - exports2.getAuthString = getAuthString; - function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - exports2.getProxyAgent = getProxyAgent; - function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); - } - exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; - function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; - } - exports2.getProxyFetch = getProxyFetch; - function getApiBaseUrl() { - return process.env["GITHUB_API_URL"] || "https://api.github.com"; + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; } - exports2.getApiBaseUrl = getApiBaseUrl; - } -}); - -// node_modules/universal-user-agent/dist-node/index.js -var require_dist_node = __commonJS({ - "node_modules/universal-user-agent/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - return ""; - } - exports2.getUserAgent = getUserAgent; - } -}); - -// node_modules/before-after-hook/lib/register.js -var require_register = __commonJS({ - "node_modules/before-after-hook/lib/register.js"(exports2, module2) { - module2.exports = register; - function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; } - if (!options) { - options = {}; + readBody() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); + }); } - if (Array.isArray(name)) { - return name.reverse().reduce(function(callback, name2) { - return register.bind(null, state, name2, callback, options); - }, method)(); + readBodyBuffer() { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); + }); } - return Promise.resolve().then(function() { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function(method2, registered) { - return registered.hook.bind(null, method2, options); - }, method)(); - }); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; } - } -}); - -// node_modules/before-after-hook/lib/add.js -var require_add = __commonJS({ - "node_modules/before-after-hook/lib/add.js"(exports2, module2) { - module2.exports = addHook; - function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - if (kind === "before") { - hook = function(method, options) { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; + options(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "after") { - hook = function(method, options) { - var result; - return Promise.resolve().then(method.bind(null, options)).then(function(result_) { - result = result_; - return orig(result, options); - }).then(function() { - return result; - }); - }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - if (kind === "error") { - hook = function(method, options) { - return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { - return orig(error4, options); - }); - }; + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - state.registry[name].push({ - hook, - orig - }); - } - } -}); - -// node_modules/before-after-hook/lib/remove.js -var require_remove = __commonJS({ - "node_modules/before-after-hook/lib/remove.js"(exports2, module2) { - module2.exports = removeHook; - function removeHook(state, name, method) { - if (!state.registry[name]) { - return; + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - var index = state.registry[name].map(function(registered) { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - state.registry[name].splice(index, 1); - } - } -}); - -// node_modules/before-after-hook/index.js -var require_before_after_hook = __commonJS({ - "node_modules/before-after-hook/index.js"(exports2, module2) { - var register = require_register(); - var addHook = require_add(); - var removeHook = require_remove(); - var bind = Function.bind; - var bindable = bind.bind(bind); - function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function(kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); - } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {} - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; - } - function HookCollection() { - var state = { - registry: {} - }; - var hook = register.bind(null, state); - bindApi(hook, state); - return hook; - } - var collectionHookDeprecationMessageDisplayed = false; - function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - return HookCollection(); - } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); - module2.exports = Hook; - module2.exports.Hook = Hook; - module2.exports.Singular = Hook.Singular; - module2.exports.Collection = Hook.Collection; - } -}); - -// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node2 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); + }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_universal_user_agent = require_dist_node(); - var VERSION = "9.0.6"; - var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - }; - function lowercaseKeys(object) { - if (!object) { - return {}; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function isPlainObject(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 (isPlainObject(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+)|(?:(? a.concat(b), []); - } - function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - return result; - } - function encodeReserved(str2) { - return str2.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(str2) { - return encodeURIComponent(str2).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; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - function isDefined2(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context2, operator, key, modifier) { - var value = context2[key], result = []; - if (isDefined2(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)); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - result.push(encodeValue(operator, value[k], k)); + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; } - }); + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; + } } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined2).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined2(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); + } + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } } - }); + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - } else { - if (operator === ";") { - if (isDefined2(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; - } - function expand(template, context2) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_2, 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(context2, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); } - } else { - return encodeReserved(literal); + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } - } - function parse(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 = omit(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 = omit(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(","); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + req.end(); } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); - } - function endpointWithDefaults(defaults, route, options) { - return parse(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 - }); - } - var endpoint = withDefaults(null, DEFAULTS); - } -}); - -// node_modules/deprecation/dist-node/index.js -var require_dist_node3 = __commonJS({ - "node_modules/deprecation/dist-node/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var Deprecation = class extends Error { - constructor(message) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; } - this.name = "Deprecation"; + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } + } + return info7; } - }; - exports2.Deprecation = Deprecation; - } -}); - -// node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/wrappy/wrappy.js"(exports2, module2) { - module2.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k) { - wrapper[k] = fn[k]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k) { - ret[k] = cb2[k]; - }); + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - return ret; + return additionalHeaders[header] || clientHeader || _default2; } - } - } -}); - -// node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/once/once.js"(exports2, module2) { - var wrappy = require_wrappy(); - module2.exports = wrappy(once); - module2.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); + } + }; + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); + } +}); + +// node_modules/@actions/github/lib/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/@actions/github/lib/internal/utils.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0; + var httpClient = __importStar4(require_lib2()); + var undici_1 = require_undici(); + function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error("Parameter token or opts.auth is required"); + } else if (token && options.auth) { + throw new Error("Parameters token and opts.auth may not both be specified"); + } + return typeof options.auth === "string" ? options.auth : `token ${token}`; + } + exports2.getAuthString = getAuthString; + function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + exports2.getProxyAgent = getProxyAgent; + function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); + } + exports2.getProxyAgentDispatcher = getProxyAgentDispatcher; + function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter4(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); }); - }); - function once(fn) { - var f = function() { - if (f.called) return f.value; - f.called = true; - return f.value = fn.apply(this, arguments); - }; - f.called = false; - return f; + return proxyFetch; } - function onceStrict(fn) { - var f = function() { - if (f.called) - throw new Error(f.onceError); - f.called = true; - return f.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f; + exports2.getProxyFetch = getProxyFetch; + function getApiBaseUrl() { + return process.env["GITHUB_API_URL"] || "https://api.github.com"; } + exports2.getApiBaseUrl = getApiBaseUrl; } }); -// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node4 = __commonJS({ - "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/universal-user-agent/dist-node/index.js +var require_dist_node = __commonJS({ + "node_modules/universal-user-agent/dist-node/index.js"(exports2) { "use strict"; - var __create2 = Object.create; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf2 = Object.getPrototypeOf; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + Object.defineProperty(exports2, "__esModule", { value: true }); + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } - return to; - }; - var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( - // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - RequestError: () => RequestError - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_deprecation = require_dist_node3(); - var import_once = __toESM2(require_once()); - var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); - var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; + } + exports2.getUserAgent = getUserAgent; + } +}); + +// node_modules/before-after-hook/lib/register.js +var require_register = __commonJS({ + "node_modules/before-after-hook/lib/register.js"(exports2, module2) { + module2.exports = register; + 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(function(callback, name2) { + return register.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(function() { + if (!state.registry[name]) { + return method(options); } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - request: () => request - }); - module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node2(); - var import_universal_user_agent = require_dist_node(); - var VERSION = "8.4.1"; - function isPlainObject(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); - } - var import_request_error = require_dist_node4(); - function getBufferResponse(response) { - return response.arrayBuffer(); - } - function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - 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" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } - }).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error4; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error4) => { - if (error4 instanceof import_request_error.RequestError) - throw error4; - else if (error4.name === "AbortError") - throw error4; - let message = error4.message; - if (error4.name === "TypeError" && "cause" in error4) { - if (error4.cause instanceof Error) { - message = error4.cause.message; - } else if (typeof error4.cause === "string") { - message = error4.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); - } - 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 getBufferResponse(response); - } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; - } - function withDefaults(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: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - } - var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } - }); - } -}); - -// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js -var require_dist_node6 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { - "use strict"; - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps2 = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var dist_src_exports = {}; - __export2(dist_src_exports, { - endpoint: () => endpoint + endpoint: () => endpoint }); module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); @@ -21218,9 +21179,101 @@ var require_dist_node6 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js -var require_dist_node7 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { +// node_modules/deprecation/dist-node/index.js +var require_dist_node3 = __commonJS({ + "node_modules/deprecation/dist-node/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var Deprecation = class extends Error { + constructor(message) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "Deprecation"; + } + }; + exports2.Deprecation = Deprecation; + } +}); + +// node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/wrappy/wrappy.js"(exports2, module2) { + module2.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + } +}); + +// node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/once/once.js"(exports2, module2) { + var wrappy = require_wrappy(); + module2.exports = wrappy(once); + module2.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + } +}); + +// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node4 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; var __create2 = Object.create; var __defProp2 = Object.defineProperty; @@ -21310,9 +21363,9 @@ var require_dist_node7 = __commonJS({ } }); -// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js -var require_dist_node8 = __commonJS({ - "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js +var require_dist_node5 = __commonJS({ + "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21336,7 +21389,7 @@ var require_dist_node8 = __commonJS({ request: () => request }); module2.exports = __toCommonJS2(dist_src_exports); - var import_endpoint = require_dist_node6(); + var import_endpoint = require_dist_node2(); var import_universal_user_agent = require_dist_node(); var VERSION = "8.4.1"; function isPlainObject(value) { @@ -21350,7 +21403,7 @@ var require_dist_node8 = __commonJS({ 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); } - var import_request_error = require_dist_node7(); + var import_request_error = require_dist_node4(); function getBufferResponse(response) { return response.arrayBuffer(); } @@ -21520,9 +21573,9 @@ var require_dist_node8 = __commonJS({ } }); -// node_modules/@octokit/graphql/dist-node/index.js -var require_dist_node9 = __commonJS({ - "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js +var require_dist_node6 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; @@ -21541,129 +21594,340 @@ var require_dist_node9 = __commonJS({ return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - __export2(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest + var dist_src_exports = {}; + __export2(dist_src_exports, { + endpoint: () => endpoint }); - module2.exports = __toCommonJS2(index_exports); - var import_request3 = require_dist_node8(); + module2.exports = __toCommonJS2(dist_src_exports); var import_universal_user_agent = require_dist_node(); - var VERSION = "7.1.1"; - var import_request2 = require_dist_node8(); - var import_request = require_dist_node8(); - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + var VERSION = "9.0.6"; + var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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; + }, {}); } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + function isPlainObject(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 (isPlainObject(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]; } } - }; - 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`) - ); + 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); } - 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` - ) - ); + 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+)|(?:(? { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } + function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; } - if (!result.variables) { - result.variables = {}; + } + return result; + } + function encodeReserved(str2) { + return str2.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, "]"); } - 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 part; + }).join(""); + } + function encodeUnreserved(str2) { + return encodeURIComponent(str2).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; } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; + } + function isDefined2(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context2, operator, key, modifier) { + var value = context2[key], result = []; + if (isDefined2(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)); } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined2).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined2(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(",")); + } + } } - return response.data.data; - }); + } else { + if (operator === ";") { + if (isDefined2(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; } - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); + function parseUrl(template) { + return { + expand: expand.bind(null, template) }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); } - var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" - }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" + function expand(template, context2) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_2, 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(context2, 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 parse(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 = omit(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 = omit(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(/(? { + 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 parse(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 }); } + var endpoint = withDefaults(null, DEFAULTS); } }); -// node_modules/@octokit/auth-token/dist-node/index.js -var require_dist_node10 = __commonJS({ - "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { +// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js +var require_dist_node7 = __commonJS({ + "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) { "use strict"; + var __create2 = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) @@ -21677,53 +21941,490 @@ var require_dist_node10 = __commonJS({ } return to; }; + var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( + // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, + mod + )); var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var dist_src_exports = {}; __export2(dist_src_exports, { - createTokenAuth: () => createTokenAuth + RequestError: () => RequestError }); module2.exports = __toCommonJS2(dist_src_exports); - 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, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); - } - 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" - ); + var import_deprecation = require_dist_node3(); + var import_once = __toESM2(require_once()); + var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); + var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + request: () => request + }); + module2.exports = __toCommonJS2(dist_src_exports); + var import_endpoint = require_dist_node6(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "8.4.1"; + function isPlainObject(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); + } + var import_request_error = require_dist_node7(); + function getBufferResponse(response) { + return response.arrayBuffer(); + } + function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + 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" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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" } + }).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error4 = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error4; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error4) => { + if (error4 instanceof import_request_error.RequestError) + throw error4; + else if (error4.name === "AbortError") + throw error4; + let message = error4.message; + if (error4.name === "TypeError" && "cause" in error4) { + if (error4.cause instanceof Error) { + message = error4.cause.message; + } else if (typeof error4.cause === "string") { + message = error4.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); + } + 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 getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; + } + function withDefaults(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: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + } + var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }); + } +}); + +// node_modules/@octokit/graphql/dist-node/index.js +var require_dist_node9 = __commonJS({ + "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var index_exports = {}; + __export2(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest + }); + module2.exports = __toCommonJS2(index_exports); + var import_request3 = require_dist_node8(); + var import_universal_user_agent = require_dist_node(); + var VERSION = "7.1.1"; + var import_request2 = require_dist_node8(); + var import_request = require_dist_node8(); + 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.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + }; + 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 withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); + } + } +}); + +// node_modules/@octokit/auth-token/dist-node/index.js +var require_dist_node10 = __commonJS({ + "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) { + "use strict"; + var __defProp2 = Object.defineProperty; + var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames2 = Object.getOwnPropertyNames; + var __hasOwnProp2 = Object.prototype.hasOwnProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps2 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames2(from)) + if (!__hasOwnProp2.call(to, key) && key !== except) + __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); + var dist_src_exports = {}; + __export2(dist_src_exports, { + createTokenAuth: () => createTokenAuth + }); + module2.exports = __toCommonJS2(dist_src_exports); + 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, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + 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) + }); }; } }); @@ -26499,7 +27200,7 @@ var require_package = __commonJS({ "@actions/exec": "^1.1.1", "@actions/github": "^6.0.0", "@actions/glob": "^0.5.0", - "@actions/http-client": "^2.2.3", + "@actions/http-client": "^3.0.0", "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.2", "@octokit/plugin-retry": "^6.0.0", @@ -34519,231 +35220,91 @@ The following characters are not allowed in files that are uploaded due to limit } }); -// node_modules/@actions/artifact/package.json -var require_package2 = __commonJS({ - "node_modules/@actions/artifact/package.json"(exports2, module2) { - module2.exports = { - name: "@actions/artifact", - version: "4.0.0", - preview: true, - description: "Actions artifact lib", - keywords: [ - "github", - "actions", - "artifact" - ], - homepage: "https://github.com/actions/toolkit/tree/main/packages/artifact", - license: "MIT", - main: "lib/artifact.js", - types: "lib/artifact.d.ts", - directories: { - lib: "lib", - test: "__tests__" - }, - files: [ - "lib", - "!.DS_Store" - ], - publishConfig: { - access: "public" - }, - repository: { - type: "git", - url: "git+https://github.com/actions/toolkit.git", - directory: "packages/artifact" - }, - scripts: { - "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", - test: "cd ../../ && npm run test ./packages/artifact", - bootstrap: "cd ../../ && npm run bootstrap", - "tsc-run": "tsc", - tsc: "npm run bootstrap && npm run tsc-run", - "gen:docs": "typedoc --plugin typedoc-plugin-markdown --out docs/generated src/artifact.ts --githubPages false --readme none" - }, - bugs: { - url: "https://github.com/actions/toolkit/issues" - }, - dependencies: { - "@actions/core": "^1.10.0", - "@actions/github": "^6.0.1", - "@actions/http-client": "^2.1.0", - "@azure/core-http": "^3.0.5", - "@azure/storage-blob": "^12.15.0", - "@octokit/core": "^5.2.1", - "@octokit/plugin-request-log": "^1.0.4", - "@octokit/plugin-retry": "^3.0.9", - "@octokit/request": "^8.4.1", - "@octokit/request-error": "^5.1.1", - "@protobuf-ts/plugin": "^2.2.3-alpha.1", - archiver: "^7.0.1", - "jwt-decode": "^3.1.2", - "unzip-stream": "^0.3.1" - }, - devDependencies: { - "@types/archiver": "^5.3.2", - "@types/unzip-stream": "^0.3.4", - typedoc: "^0.28.13", - "typedoc-plugin-markdown": "^3.17.1", - typescript: "^5.2.2" - }, - overrides: { - "uri-js": "npm:uri-js-replace@^1.0.1", - "node-fetch": "^3.3.2" - } - }; - } -}); - -// node_modules/@actions/artifact/lib/internal/shared/user-agent.js -var require_user_agent = __commonJS({ - "node_modules/@actions/artifact/lib/internal/shared/user-agent.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUserAgentString = getUserAgentString; - var packageJson = require_package2(); - function getUserAgentString() { - return `@actions/artifact-${packageJson.version}`; - } - } -}); - -// node_modules/@actions/artifact/lib/internal/shared/errors.js -var require_errors2 = __commonJS({ - "node_modules/@actions/artifact/lib/internal/shared/errors.js"(exports2) { +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/proxy.js +var require_proxy3 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/proxy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UsageError = exports2.NetworkError = exports2.GHESNotSupportedError = exports2.ArtifactNotFoundError = exports2.InvalidResponseError = exports2.FilesNotFoundError = void 0; - var FilesNotFoundError = class extends Error { - constructor(files = []) { - let message = "No files were found to upload"; - if (files.length > 0) { - message += `: ${files.join(", ")}`; - } - super(message); - this.files = files; - this.name = "FilesNotFoundError"; - } - }; - exports2.FilesNotFoundError = FilesNotFoundError; - var InvalidResponseError = class extends Error { - constructor(message) { - super(message); - this.name = "InvalidResponseError"; + exports2.checkBypass = exports2.getProxyUrl = void 0; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === "https:"; + if (checkBypass(reqUrl)) { + return void 0; } - }; - exports2.InvalidResponseError = InvalidResponseError; - var ArtifactNotFoundError = class extends Error { - constructor(message = "Artifact not found") { - super(message); - this.name = "ArtifactNotFoundError"; + const proxyVar = (() => { + if (usingSsl) { + return process.env["https_proxy"] || process.env["HTTPS_PROXY"]; + } else { + return process.env["http_proxy"] || process.env["HTTP_PROXY"]; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } catch (_a) { + if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://")) + return new DecodedURL(`http://${proxyVar}`); + } + } else { + return void 0; } - }; - exports2.ArtifactNotFoundError = ArtifactNotFoundError; - var GHESNotSupportedError = class extends Error { - constructor(message = "@actions/artifact v2.0.0+, upload-artifact@v4+ and download-artifact@v4+ are not currently supported on GHES.") { - super(message); - this.name = "GHESNotSupportedError"; + } + exports2.getProxyUrl = getProxyUrl; + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - }; - exports2.GHESNotSupportedError = GHESNotSupportedError; - var NetworkError = class extends Error { - constructor(code) { - const message = `Unable to make request: ${code} -If you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`; - super(message); - this.code = code; - this.name = "NetworkError"; + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - }; - exports2.NetworkError = NetworkError; - NetworkError.isNetworkErrorCode = (code) => { - if (!code) + const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ""; + if (!noProxy) { return false; - return [ - "ECONNRESET", - "ENOTFOUND", - "ETIMEDOUT", - "ECONNREFUSED", - "EHOSTUNREACH" - ].includes(code); - }; - var UsageError = class extends Error { - constructor() { - const message = `Artifact storage quota has been hit. Unable to upload any new artifacts. Usage is recalculated every 6-12 hours. -More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; - super(message); - this.name = "UsageError"; } - }; - exports2.UsageError = UsageError; - UsageError.isUsageErrorMessage = (msg) => { - if (!msg) - return false; - return msg.includes("insufficient usage"); - }; - } -}); - -// node_modules/jwt-decode/build/jwt-decode.cjs.js -var require_jwt_decode_cjs = __commonJS({ - "node_modules/jwt-decode/build/jwt-decode.cjs.js"(exports2, module2) { - "use strict"; - function e(e2) { - this.message = e2; - } - e.prototype = new Error(), e.prototype.name = "InvalidCharacterError"; - var r = "undefined" != typeof window && window.atob && window.atob.bind(window) || function(r2) { - var t2 = String(r2).replace(/=+$/, ""); - if (t2.length % 4 == 1) throw new e("'atob' failed: The string to be decoded is not correctly encoded."); - for (var n2, o2, a2 = 0, i = 0, c = ""; o2 = t2.charAt(i++); ~o2 && (n2 = a2 % 4 ? 64 * n2 + o2 : o2, a2++ % 4) ? c += String.fromCharCode(255 & n2 >> (-2 * a2 & 6)) : 0) o2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o2); - return c; - }; - function t(e2) { - var t2 = e2.replace(/-/g, "+").replace(/_/g, "/"); - switch (t2.length % 4) { - case 0: - break; - case 2: - t2 += "=="; - break; - case 3: - t2 += "="; - break; - default: - throw "Illegal base64url string!"; + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } else if (reqUrl.protocol === "http:") { + reqPort = 80; + } else if (reqUrl.protocol === "https:") { + reqPort = 443; } - try { - return (function(e3) { - return decodeURIComponent(r(e3).replace(/(.)/g, (function(e4, r2) { - var t3 = r2.charCodeAt(0).toString(16).toUpperCase(); - return t3.length < 2 && (t3 = "0" + t3), "%" + t3; - }))); - })(t2); - } catch (e3) { - return r(t2); + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === "number") { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) { + if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) { + return true; + } } + return false; } - function n(e2) { - this.message = e2; + exports2.checkBypass = checkBypass; + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]"); } - function o(e2, r2) { - if ("string" != typeof e2) throw new n("Invalid token specified"); - var o2 = true === (r2 = r2 || {}).header ? 0 : 1; - try { - return JSON.parse(t(e2.split(".")[o2])); - } catch (e3) { - throw new n("Invalid token specified: " + e3.message); + var DecodedURL = class extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - } - n.prototype = new Error(), n.prototype.name = "InvalidTokenError"; - var a = o; - a.default = o, a.InvalidTokenError = n, module2.exports = a; + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + }; } }); -// node_modules/@actions/artifact/lib/internal/shared/util.js -var require_util8 = __commonJS({ - "node_modules/@actions/artifact/lib/internal/shared/util.js"(exports2) { +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/index.js +var require_lib3 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/index.js"(exports2) { "use strict"; var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; @@ -34763,98 +35324,15 @@ var require_util8 = __commonJS({ }) : function(o, v) { o["default"] = v; }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); - } - __setModuleDefault4(result, mod); - return result; - }; - })(); - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getBackendIdsFromToken = getBackendIdsFromToken; - exports2.maskSigUrl = maskSigUrl; - exports2.maskSecretUrls = maskSecretUrls; - var core14 = __importStar4(require_core()); - var config_1 = require_config(); - var jwt_decode_1 = __importDefault4(require_jwt_decode_cjs()); - var core_1 = require_core(); - var InvalidJwtError = new Error("Failed to get backend IDs: The provided JWT token is invalid and/or missing claims"); - function getBackendIdsFromToken() { - const token = (0, config_1.getRuntimeToken)(); - const decoded = (0, jwt_decode_1.default)(token); - if (!decoded.scp) { - throw InvalidJwtError; - } - const scpParts = decoded.scp.split(" "); - if (scpParts.length === 0) { - throw InvalidJwtError; - } - for (const scopes of scpParts) { - const scopeParts = scopes.split(":"); - if ((scopeParts === null || scopeParts === void 0 ? void 0 : scopeParts[0]) !== "Actions.Results") { - continue; - } - if (scopeParts.length !== 3) { - throw InvalidJwtError; - } - const ids = { - workflowRunBackendId: scopeParts[1], - workflowJobRunBackendId: scopeParts[2] - }; - core14.debug(`Workflow Run Backend ID: ${ids.workflowRunBackendId}`); - core14.debug(`Workflow Job Run Backend ID: ${ids.workflowJobRunBackendId}`); - return ids; - } - throw InvalidJwtError; - } - function maskSigUrl(url) { - if (!url) - return; - try { - const parsedUrl = new URL(url); - const signature = parsedUrl.searchParams.get("sig"); - if (signature) { - (0, core_1.setSecret)(signature); - (0, core_1.setSecret)(encodeURIComponent(signature)); - } - } catch (error4) { - (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); - } - } - function maskSecretUrls(body) { - if (typeof body !== "object" || body === null) { - (0, core_1.debug)("body is not an object or is null"); - return; - } - if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { - maskSigUrl(body.signed_upload_url); - } - if ("signed_url" in body && typeof body.signed_url === "string") { - maskSigUrl(body.signed_url); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); } - } - } -}); - -// node_modules/@actions/artifact/lib/internal/shared/artifact-twirp-client.js -var require_artifact_twirp_client2 = __commonJS({ - "node_modules/@actions/artifact/lib/internal/shared/artifact-twirp-client.js"(exports2) { - "use strict"; + __setModuleDefault4(result, mod); + return result; + }; var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve2) { @@ -34883,5866 +35361,4364 @@ var require_artifact_twirp_client2 = __commonJS({ }); }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.internalArtifactTwirpClient = internalArtifactTwirpClient; - var http_client_1 = require_lib(); - var auth_1 = require_auth(); - var core_1 = require_core(); - var generated_1 = require_generated(); - var config_1 = require_config(); - var user_agent_1 = require_user_agent(); - var errors_1 = require_errors2(); - var util_1 = require_util8(); - var ArtifactHttpClient = class { - constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { - this.maxAttempts = 5; - this.baseRetryIntervalMilliseconds = 3e3; - this.retryMultiplier = 1.5; - const token = (0, config_1.getRuntimeToken)(); - this.baseUrl = (0, config_1.getResultsServiceUrl)(); - if (maxAttempts) { - this.maxAttempts = maxAttempts; - } - if (baseRetryIntervalMilliseconds) { - this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; - } - if (retryMultiplier) { - this.retryMultiplier = retryMultiplier; - } - this.httpClient = new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(token) - ]); + exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + var pm = __importStar4(require_proxy3()); + var tunnel = __importStar4(require_tunnel2()); + var undici_1 = require_undici(); + var HttpCodes; + (function(HttpCodes2) { + HttpCodes2[HttpCodes2["OK"] = 200] = "OK"; + HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther"; + HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified"; + HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy"; + HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest"; + HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden"; + HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound"; + HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict"; + HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone"; + HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway"; + HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (exports2.HttpCodes = HttpCodes = {})); + var Headers; + (function(Headers2) { + Headers2["Accept"] = "accept"; + Headers2["ContentType"] = "content-type"; + })(Headers || (exports2.Headers = Headers = {})); + var MediaTypes; + (function(MediaTypes2) { + MediaTypes2["ApplicationJson"] = "application/json"; + })(MediaTypes || (exports2.MediaTypes = MediaTypes = {})); + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ""; + } + exports2.getProxyUrl = getProxyUrl; + var HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + var HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"]; + var ExponentialBackoffCeiling = 10; + var ExponentialBackoffTimeSlice = 5; + var HttpClientError = class _HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "HttpClientError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, _HttpClientError.prototype); } - // This function satisfies the Rpc interface. It is compatible with the JSON - // JSON generated client. - request(service, method, contentType, data) { + }; + exports2.HttpClientError = HttpClientError; + var HttpClientResponse = class { + constructor(message) { + this.message = message; + } + readBody() { return __awaiter4(this, void 0, void 0, function* () { - const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; - (0, core_1.debug)(`[Request] ${method} ${url}`); - const headers = { - "Content-Type": contentType - }; - try { - const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { - return this.httpClient.post(url, JSON.stringify(data), headers); - })); - return body; - } catch (error4) { - throw new Error(`Failed to ${method}: ${error4.message}`); - } + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on("data", (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on("end", () => { + resolve2(output.toString()); + }); + })); }); } - retryableRequest(operation) { + readBodyBuffer() { return __awaiter4(this, void 0, void 0, function* () { - let attempt = 0; - let errorMessage = ""; - let rawBody = ""; - while (attempt < this.maxAttempts) { - let isRetryable = false; - try { - const response = yield operation(); - const statusCode = response.message.statusCode; - rawBody = yield response.readBody(); - (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); - (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); - const body = JSON.parse(rawBody); - (0, util_1.maskSecretUrls)(body); - (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); - if (this.isSuccessStatusCode(statusCode)) { - return { response, body }; - } - isRetryable = this.isRetryableHttpStatusCode(statusCode); - errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; - if (body.msg) { - if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { - throw new errors_1.UsageError(); - } - errorMessage = `${errorMessage}: ${body.msg}`; - } - } catch (error4) { - if (error4 instanceof SyntaxError) { - (0, core_1.debug)(`Raw Body: ${rawBody}`); - } - if (error4 instanceof errors_1.UsageError) { - throw error4; - } - if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { - throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); - } - isRetryable = true; - errorMessage = error4.message; - } - if (!isRetryable) { - throw new Error(`Received non-retryable error: ${errorMessage}`); - } - if (attempt + 1 === this.maxAttempts) { - throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); - } - const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); - (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); - yield this.sleep(retryTimeMilliseconds); - attempt++; - } - throw new Error(`Request failed`); + return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () { + const chunks = []; + this.message.on("data", (chunk) => { + chunks.push(chunk); + }); + this.message.on("end", () => { + resolve2(Buffer.concat(chunks)); + }); + })); }); } - isSuccessStatusCode(statusCode) { - if (!statusCode) - return false; - return statusCode >= 200 && statusCode < 300; - } - isRetryableHttpStatusCode(statusCode) { - if (!statusCode) - return false; - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.GatewayTimeout, - http_client_1.HttpCodes.InternalServerError, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.TooManyRequests - ]; - return retryableStatusCodes.includes(statusCode); + }; + exports2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === "https:"; + } + exports2.isHttps = isHttps; + var HttpClient2 = class { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - sleep(milliseconds) { + options(requestUrl, additionalHeaders) { return __awaiter4(this, void 0, void 0, function* () { - return new Promise((resolve2) => setTimeout(resolve2, milliseconds)); + return this.request("OPTIONS", requestUrl, null, additionalHeaders || {}); }); } - getExponentialRetryTimeMilliseconds(attempt) { - if (attempt < 0) { - throw new Error("attempt should be a positive integer"); - } - if (attempt === 0) { - return this.baseRetryIntervalMilliseconds; - } - const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); - const maxTime = minTime * this.retryMultiplier; - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); - } - }; - function internalArtifactTwirpClient(options) { - const client = new ArtifactHttpClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); - return new generated_1.ArtifactServiceClientJSON(client); - } - } -}); - -// node_modules/@actions/artifact/lib/internal/upload/upload-zip-specification.js -var require_upload_zip_specification = __commonJS({ - "node_modules/@actions/artifact/lib/internal/upload/upload-zip-specification.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + get(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("GET", requestUrl, null, additionalHeaders || {}); + }); } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); - } - __setModuleDefault4(result, mod); - return result; - }; - })(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.validateRootDirectory = validateRootDirectory; - exports2.getUploadZipSpecification = getUploadZipSpecification; - var fs2 = __importStar4(require("fs")); - var core_1 = require_core(); - var path_1 = require("path"); - var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation(); - function validateRootDirectory(rootDirectory) { - if (!fs2.existsSync(rootDirectory)) { - throw new Error(`The provided rootDirectory ${rootDirectory} does not exist`); + del(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("DELETE", requestUrl, null, additionalHeaders || {}); + }); } - if (!fs2.statSync(rootDirectory).isDirectory()) { - throw new Error(`The provided rootDirectory ${rootDirectory} is not a valid directory`); + post(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("POST", requestUrl, data, additionalHeaders || {}); + }); } - (0, core_1.info)(`Root directory input is valid!`); - } - function getUploadZipSpecification(filesToZip, rootDirectory) { - const specification = []; - rootDirectory = (0, path_1.normalize)(rootDirectory); - rootDirectory = (0, path_1.resolve)(rootDirectory); - for (let file of filesToZip) { - const stats = fs2.lstatSync(file, { throwIfNoEntry: false }); - if (!stats) { - throw new Error(`File ${file} does not exist`); - } - if (!stats.isDirectory()) { - file = (0, path_1.normalize)(file); - file = (0, path_1.resolve)(file); - if (!file.startsWith(rootDirectory)) { - throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); - } - const uploadPath = file.replace(rootDirectory, ""); - (0, path_and_artifact_name_validation_1.validateFilePath)(uploadPath); - specification.push({ - sourcePath: file, - destinationPath: uploadPath, - stats - }); - } else { - const directoryPath = file.replace(rootDirectory, ""); - (0, path_and_artifact_name_validation_1.validateFilePath)(directoryPath); - specification.push({ - sourcePath: null, - destinationPath: directoryPath, - stats - }); - } + patch(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PATCH", requestUrl, data, additionalHeaders || {}); + }); } - return specification; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createEmptyPipeline = createEmptyPipeline; - var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); - var HttpPipeline = class _HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = void 0; + put(requestUrl, data, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("PUT", requestUrl, data, additionalHeaders || {}); + }); } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); - } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); - } - this._policies.push({ - policy, - options + head(requestUrl, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request("HEAD", requestUrl, null, additionalHeaders || {}); }); - this._orderedPolicies = void 0; } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { - removedPolicies.push(policyDescriptor.policy); - return false; - } else { - return true; - } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter4(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); }); - this._orderedPolicies = void 0; - return removedPolicies; } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - clone() { - return new _HttpPipeline(this._policies); + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - static create() { - return new _HttpPipeline(); + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter4(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - orderPolicies() { - const result = []; - const policyMap = /* @__PURE__ */ new Map(); - function createPhase(name) { - return { - name, - policies: /* @__PURE__ */ new Set(), - hasRun: false, - hasAfterPolicies: false - }; - } - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } else if (phase === "Serialize") { - return serializePhase; - } else if (phase === "Deserialize") { - return deserializePhase; - } else if (phase === "Sign") { - return signPhase; - } else { - return noPhase; - } - } - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: /* @__PURE__ */ new Set(), - dependants: /* @__PURE__ */ new Set() - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter4(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error("Client has already been disposed."); } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); + const parsedUrl = new URL(requestUrl); + let info7 = this._prepareRequest(verb, parsedUrl, headers); + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info7, data); + if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info7, data); + } else { + return response; } } - } - } - function walkPhase(phase) { - phase.hasRun = true; - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - continue; - } - if (node.dependsOn.size === 0) { - result.push(node.policy); - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { + const redirectUrl = response.message.headers["location"]; + if (!redirectUrl) { + break; } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - walkPhase(noPhase); + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { + throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); } - return; + yield response.readBody(); + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + if (header.toLowerCase() === "authorization") { + delete headers[header]; + } + } + } + info7 = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info7, data); + redirectsRemaining--; } - if (phase.hasAfterPolicies) { - walkPhase(noPhase); + if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { + return response; } - } - } - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - walkPhases(); - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - return result; + this._disposed = true; } - }; - function createEmptyPipeline() { - return HttpPipeline.create(); - } - } -}); - -// node_modules/@azure/logger/dist/index.js -var require_dist = __commonJS({ - "node_modules/@azure/logger/dist/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var os = require("os"); - var util = require("util"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); - function log(message, ...args) { - process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); - } - var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; - var enabledString; - var enabledNamespaces = []; - var skippedNamespaces = []; - var debuggers = []; - if (debugEnvVariable) { - enable(debugEnvVariable); - } - var debugObj = Object.assign((namespace) => { - return createDebugger(namespace); - }, { - enable, - enabled, - disable, - log - }); - function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info7, data) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } else if (!res) { + reject(new Error("Unknown error")); + } else { + resolve2(res); + } + } + this.requestRawWithCallback(info7, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info7, data, onResult) { + if (typeof data === "string") { + if (!info7.options.headers) { + info7.options.headers = {}; + } + info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8"); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info7.httpModule.request(info7.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(void 0, res); + }); + let socket; + req.on("socket", (sock) => { + socket = sock; + }); + req.setTimeout(this._socketTimeout || 3 * 6e4, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info7.options.path}`)); + }); + req.on("error", function(err) { + handleResult(err); + }); + if (data && typeof data === "string") { + req.write(data, "utf8"); + } + if (data && typeof data !== "string") { + data.on("close", function() { + req.end(); + }); + data.pipe(req); } else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); + req.end(); } } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); - } - } - function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; - } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - return false; - } - function disable() { - const result = enabledString || ""; - enable(""); - return result; - } - function createDebugger(namespace) { - const newDebugger = Object.assign(debug5, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend: extend3 - }); - function debug5(...args) { - if (!newDebugger.enabled) { - return; + _prepareRequest(method, requestUrl, headers) { + const info7 = {}; + info7.parsedUrl = requestUrl; + const usingSsl = info7.parsedUrl.protocol === "https:"; + info7.httpModule = usingSsl ? https2 : http; + const defaultPort = usingSsl ? 443 : 80; + info7.options = {}; + info7.options.host = info7.parsedUrl.hostname; + info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort; + info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || ""); + info7.options.method = method; + info7.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info7.options.headers["user-agent"] = this.userAgent; } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; + info7.options.agent = this._getAgent(info7.parsedUrl); + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info7.options); + } } - newDebugger.log(...args); + return info7; } - debuggers.push(newDebugger); - return newDebugger; - } - function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - return false; - } - function extend3(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; - } - var debug4 = debugObj; - var registeredLoggers = /* @__PURE__ */ new Set(); - var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; - var azureLogLevel; - var AzureLogger = debug4("azure"); - AzureLogger.log = (...args) => { - debug4.log(...args); - }; - var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; - if (logLevelFromEnv) { - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); - } else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + _getExistingOrDefaultHeader(additionalHeaders, header, _default2) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default2; } - } - function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === "https:"; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === "https:"; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https2.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - azureLogLevel = level; - const enabledNamespaces2 = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces2.push(logger.namespace); + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === "https:"; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}` + })); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); } + return proxyAgent; } - debug4.enable(enabledNamespaces2.join(",")); - } - function getLogLevel() { - return azureLogLevel; - } - var levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 - }; - function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") - }; - } - function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); - }; - } - function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces2 = debug4.disable(); - debug4.enable(enabledNamespaces2 + "," + logger.namespace); + _performExponentialBackoff(retryNumber) { + return __awaiter4(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise((resolve2) => setTimeout(() => resolve2(), ms)); + }); } - registeredLoggers.add(logger); - return logger; - } - function shouldEnable(logger) { - return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); - } - function isAzureLogLevel(logLevel) { - return AZURE_LOG_LEVELS.includes(logLevel); - } - exports2.AzureLogger = AzureLogger; - exports2.createClientLogger = createClientLogger; - exports2.getLogLevel = getLogLevel; - exports2.setLogLevel = setLogLevel; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js -var require_log = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_dist(); - exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + _processResponse(res, options) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + if (statusCode === HttpCodes.NotFound) { + resolve2(response); + } + function dateTimeDeserializer(key, value) { + if (typeof value === "string") { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } catch (err) { + } + if (statusCode > 299) { + let msg; + if (obj && obj.message) { + msg = obj.message; + } else if (contents && contents.length > 0) { + msg = contents; + } else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } else { + resolve2(response); + } + })); + }); } }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs3 = __commonJS({ - "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); + exports2.HttpClient = HttpClient2; + var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); } }); -// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js -var require_createAbortablePromise = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { +// node_modules/@actions/artifact/node_modules/@actions/http-client/lib/auth.js +var require_auth2 = __commonJS({ + "node_modules/@actions/artifact/node_modules/@actions/http-client/lib/auth.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createAbortablePromise = createAbortablePromise; - var abort_controller_1 = require_commonjs3(); - function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve2, reject) => { - function rejectOnAbort() { - reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); - } - function removeListeners() { - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); - } - function onAbort() { - cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); - removeListeners(); - rejectOnAbort(); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { - return rejectOnAbort(); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - try { - buildPromise((x) => { - removeListeners(); - resolve2(x); - }, (x) => { - removeListeners(); - reject(x); - }); - } catch (err) { - reject(err); + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); } - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/random.js -var require_random = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { - "use strict"; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; - function getRandomIntegerInclusive(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - const offset = Math.floor(Math.random() * (max - min + 1)); - return offset + min; - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/delay.js -var require_delay = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay; - exports2.calculateRetryDelay = calculateRetryDelay; - var createAbortablePromise_js_1 = require_createAbortablePromise(); - var random_js_1 = require_random(); - var StandardAbortMessage = "The delay was aborted."; - function delay(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve2) => { - token = setTimeout(resolve2, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage - }); - } - function calculateRetryDelay(retryAttempt, config) { - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); - return { retryAfterInMs }; - } + exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0; + var BasicCredentialHandler = class { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BasicCredentialHandler = BasicCredentialHandler; + var BearerCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.BearerCredentialHandler = BearerCredentialHandler; + var PersonalAccessTokenCredentialHandler = class { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error("The request has no headers"); + } + options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter4(this, void 0, void 0, function* () { + throw new Error("not implemented"); + }); + } + }; + exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; } }); -// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js -var require_aborterUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.cancelablePromiseRace = cancelablePromiseRace; - async function cancelablePromiseRace(abortablePromiseBuilders, options) { - var _a, _b; - const aborter = new AbortController(); - function abortHandler() { - aborter.abort(); - } - (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); - try { - return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); - } finally { - aborter.abort(); - (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); +// node_modules/@actions/artifact/package.json +var require_package2 = __commonJS({ + "node_modules/@actions/artifact/package.json"(exports2, module2) { + module2.exports = { + name: "@actions/artifact", + version: "4.0.0", + preview: true, + description: "Actions artifact lib", + keywords: [ + "github", + "actions", + "artifact" + ], + homepage: "https://github.com/actions/toolkit/tree/main/packages/artifact", + license: "MIT", + main: "lib/artifact.js", + types: "lib/artifact.d.ts", + directories: { + lib: "lib", + test: "__tests__" + }, + files: [ + "lib", + "!.DS_Store" + ], + publishConfig: { + access: "public" + }, + repository: { + type: "git", + url: "git+https://github.com/actions/toolkit.git", + directory: "packages/artifact" + }, + scripts: { + "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", + test: "cd ../../ && npm run test ./packages/artifact", + bootstrap: "cd ../../ && npm run bootstrap", + "tsc-run": "tsc", + tsc: "npm run bootstrap && npm run tsc-run", + "gen:docs": "typedoc --plugin typedoc-plugin-markdown --out docs/generated src/artifact.ts --githubPages false --readme none" + }, + bugs: { + url: "https://github.com/actions/toolkit/issues" + }, + dependencies: { + "@actions/core": "^1.10.0", + "@actions/github": "^6.0.1", + "@actions/http-client": "^2.1.0", + "@azure/core-http": "^3.0.5", + "@azure/storage-blob": "^12.15.0", + "@octokit/core": "^5.2.1", + "@octokit/plugin-request-log": "^1.0.4", + "@octokit/plugin-retry": "^3.0.9", + "@octokit/request": "^8.4.1", + "@octokit/request-error": "^5.1.1", + "@protobuf-ts/plugin": "^2.2.3-alpha.1", + archiver: "^7.0.1", + "jwt-decode": "^3.1.2", + "unzip-stream": "^0.3.1" + }, + devDependencies: { + "@types/archiver": "^5.3.2", + "@types/unzip-stream": "^0.3.4", + typedoc: "^0.28.13", + "typedoc-plugin-markdown": "^3.17.1", + typescript: "^5.2.2" + }, + overrides: { + "uri-js": "npm:uri-js-replace@^1.0.1", + "node-fetch": "^3.3.2" } - } + }; } }); -// node_modules/@azure/core-util/dist/commonjs/object.js -var require_object = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { +// node_modules/@actions/artifact/lib/internal/shared/user-agent.js +var require_user_agent = __commonJS({ + "node_modules/@actions/artifact/lib/internal/shared/user-agent.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isObject = isObject2; - function isObject2(input) { - return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); + exports2.getUserAgentString = getUserAgentString; + var packageJson = require_package2(); + function getUserAgentString() { + return `@actions/artifact-${packageJson.version}`; } } }); -// node_modules/@azure/core-util/dist/commonjs/error.js -var require_error = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { +// node_modules/@actions/artifact/lib/internal/shared/errors.js +var require_errors2 = __commonJS({ + "node_modules/@actions/artifact/lib/internal/shared/errors.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isError = isError; - exports2.getErrorMessage = getErrorMessage2; - var object_js_1 = require_object(); - function isError(e) { - if ((0, object_js_1.isObject)(e)) { - const hasName = typeof e.name === "string"; - const hasMessage = typeof e.message === "string"; - return hasName && hasMessage; - } - return false; - } - function getErrorMessage2(e) { - if (isError(e)) { - return e.message; - } else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } else { - stringified = String(e); - } - } catch (err) { - stringified = "[unable to stringify input]"; + exports2.UsageError = exports2.NetworkError = exports2.GHESNotSupportedError = exports2.ArtifactNotFoundError = exports2.InvalidResponseError = exports2.FilesNotFoundError = void 0; + var FilesNotFoundError = class extends Error { + constructor(files = []) { + let message = "No files were found to upload"; + if (files.length > 0) { + message += `: ${files.join(", ")}`; } - return `Unknown error ${stringified}`; + super(message); + this.files = files; + this.name = "FilesNotFoundError"; } - } + }; + exports2.FilesNotFoundError = FilesNotFoundError; + var InvalidResponseError = class extends Error { + constructor(message) { + super(message); + this.name = "InvalidResponseError"; + } + }; + exports2.InvalidResponseError = InvalidResponseError; + var ArtifactNotFoundError = class extends Error { + constructor(message = "Artifact not found") { + super(message); + this.name = "ArtifactNotFoundError"; + } + }; + exports2.ArtifactNotFoundError = ArtifactNotFoundError; + var GHESNotSupportedError = class extends Error { + constructor(message = "@actions/artifact v2.0.0+, upload-artifact@v4+ and download-artifact@v4+ are not currently supported on GHES.") { + super(message); + this.name = "GHESNotSupportedError"; + } + }; + exports2.GHESNotSupportedError = GHESNotSupportedError; + var NetworkError = class extends Error { + constructor(code) { + const message = `Unable to make request: ${code} +If you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`; + super(message); + this.code = code; + this.name = "NetworkError"; + } + }; + exports2.NetworkError = NetworkError; + NetworkError.isNetworkErrorCode = (code) => { + if (!code) + return false; + return [ + "ECONNRESET", + "ENOTFOUND", + "ETIMEDOUT", + "ECONNREFUSED", + "EHOSTUNREACH" + ].includes(code); + }; + var UsageError = class extends Error { + constructor() { + const message = `Artifact storage quota has been hit. Unable to upload any new artifacts. Usage is recalculated every 6-12 hours. +More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; + super(message); + this.name = "UsageError"; + } + }; + exports2.UsageError = UsageError; + UsageError.isUsageErrorMessage = (msg) => { + if (!msg) + return false; + return msg.includes("insufficient usage"); + }; } }); -// node_modules/@azure/core-util/dist/commonjs/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { +// node_modules/jwt-decode/build/jwt-decode.cjs.js +var require_jwt_decode_cjs = __commonJS({ + "node_modules/jwt-decode/build/jwt-decode.cjs.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.computeSha256Hmac = computeSha256Hmac; - exports2.computeSha256Hash = computeSha256Hash; - var crypto_1 = require("crypto"); - async function computeSha256Hmac(key, stringToSign, encoding) { - const decodedKey = Buffer.from(key, "base64"); - return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); + function e(e2) { + this.message = e2; } - async function computeSha256Hash(content, encoding) { - return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); + e.prototype = new Error(), e.prototype.name = "InvalidCharacterError"; + var r = "undefined" != typeof window && window.atob && window.atob.bind(window) || function(r2) { + var t2 = String(r2).replace(/=+$/, ""); + if (t2.length % 4 == 1) throw new e("'atob' failed: The string to be decoded is not correctly encoded."); + for (var n2, o2, a2 = 0, i = 0, c = ""; o2 = t2.charAt(i++); ~o2 && (n2 = a2 % 4 ? 64 * n2 + o2 : o2, a2++ % 4) ? c += String.fromCharCode(255 & n2 >> (-2 * a2 & 6)) : 0) o2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o2); + return c; + }; + function t(e2) { + var t2 = e2.replace(/-/g, "+").replace(/_/g, "/"); + switch (t2.length % 4) { + case 0: + break; + case 2: + t2 += "=="; + break; + case 3: + t2 += "="; + break; + default: + throw "Illegal base64url string!"; + } + try { + return (function(e3) { + return decodeURIComponent(r(e3).replace(/(.)/g, (function(e4, r2) { + var t3 = r2.charCodeAt(0).toString(16).toUpperCase(); + return t3.length < 2 && (t3 = "0" + t3), "%" + t3; + }))); + })(t2); + } catch (e3) { + return r(t2); + } + } + function n(e2) { + this.message = e2; + } + function o(e2, r2) { + if ("string" != typeof e2) throw new n("Invalid token specified"); + var o2 = true === (r2 = r2 || {}).header ? 0 : 1; + try { + return JSON.parse(t(e2.split(".")[o2])); + } catch (e3) { + throw new n("Invalid token specified: " + e3.message); + } } + n.prototype = new Error(), n.prototype.name = "InvalidTokenError"; + var a = o; + a.default = o, a.InvalidTokenError = n, module2.exports = a; } }); -// node_modules/@azure/core-util/dist/commonjs/typeGuards.js -var require_typeGuards = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { +// node_modules/@actions/artifact/lib/internal/shared/util.js +var require_util8 = __commonJS({ + "node_modules/@actions/artifact/lib/internal/shared/util.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isDefined = isDefined2; - exports2.isObjectWithProperties = isObjectWithProperties; - exports2.objectHasProperty = objectHasProperty; - function isDefined2(thing) { - return typeof thing !== "undefined" && thing !== null; - } - function isObjectWithProperties(thing, properties) { - if (!isDefined2(thing) || typeof thing !== "object") { - return false; + exports2.getBackendIdsFromToken = getBackendIdsFromToken; + exports2.maskSigUrl = maskSigUrl; + exports2.maskSecretUrls = maskSecretUrls; + var core14 = __importStar4(require_core()); + var config_1 = require_config(); + var jwt_decode_1 = __importDefault4(require_jwt_decode_cjs()); + var core_1 = require_core(); + var InvalidJwtError = new Error("Failed to get backend IDs: The provided JWT token is invalid and/or missing claims"); + function getBackendIdsFromToken() { + const token = (0, config_1.getRuntimeToken)(); + const decoded = (0, jwt_decode_1.default)(token); + if (!decoded.scp) { + throw InvalidJwtError; } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; + const scpParts = decoded.scp.split(" "); + if (scpParts.length === 0) { + throw InvalidJwtError; + } + for (const scopes of scpParts) { + const scopeParts = scopes.split(":"); + if ((scopeParts === null || scopeParts === void 0 ? void 0 : scopeParts[0]) !== "Actions.Results") { + continue; } + if (scopeParts.length !== 3) { + throw InvalidJwtError; + } + const ids = { + workflowRunBackendId: scopeParts[1], + workflowJobRunBackendId: scopeParts[2] + }; + core14.debug(`Workflow Run Backend ID: ${ids.workflowRunBackendId}`); + core14.debug(`Workflow Job Run Backend ID: ${ids.workflowJobRunBackendId}`); + return ids; } - return true; + throw InvalidJwtError; } - function objectHasProperty(thing, property) { - return isDefined2(thing) && typeof thing === "object" && property in thing; + function maskSigUrl(url) { + if (!url) + return; + try { + const parsedUrl = new URL(url); + const signature = parsedUrl.searchParams.get("sig"); + if (signature) { + (0, core_1.setSecret)(signature); + (0, core_1.setSecret)(encodeURIComponent(signature)); + } + } catch (error4) { + (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`); + } } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js -var require_uuidUtils = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomUUID = randomUUID; - var crypto_1 = require("crypto"); - var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; - function randomUUID() { - return uuidFunction(); + function maskSecretUrls(body) { + if (typeof body !== "object" || body === null) { + (0, core_1.debug)("body is not an object or is null"); + return; + } + if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") { + maskSigUrl(body.signed_upload_url); + } + if ("signed_url" in body && typeof body.signed_url === "string") { + maskSigUrl(body.signed_url); + } } } }); -// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js -var require_checkEnvironment = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { +// node_modules/@actions/artifact/lib/internal/shared/artifact-twirp-client.js +var require_artifact_twirp_client2 = __commonJS({ + "node_modules/@actions/artifact/lib/internal/shared/artifact-twirp-client.js"(exports2) { "use strict"; - var _a; - var _b; - var _c; - var _d; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; - exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; - exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); - exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; - exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; - exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); - exports2.isNode = exports2.isNodeLike; - exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; - exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; - } -}); - -// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js -var require_bytesEncoding = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.uint8ArrayToString = uint8ArrayToString; - exports2.stringToUint8Array = stringToUint8Array; - function uint8ArrayToString(bytes, format) { - return Buffer.from(bytes).toString(format); - } - function stringToUint8Array(value, format) { - return Buffer.from(value, format); - } - } -}); - -// node_modules/@azure/core-util/dist/commonjs/index.js -var require_commonjs4 = __commonJS({ - "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; - var delay_js_1 = require_delay(); - Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { - return delay_js_1.delay; - } }); - Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { - return delay_js_1.calculateRetryDelay; - } }); - var aborterUtils_js_1 = require_aborterUtils(); - Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { - return aborterUtils_js_1.cancelablePromiseRace; - } }); - var createAbortablePromise_js_1 = require_createAbortablePromise(); - Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { - return createAbortablePromise_js_1.createAbortablePromise; - } }); - var random_js_1 = require_random(); - Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { - return random_js_1.getRandomIntegerInclusive; - } }); - var object_js_1 = require_object(); - Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { - return object_js_1.isObject; - } }); - var error_js_1 = require_error(); - Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { - return error_js_1.isError; - } }); - Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { - return error_js_1.getErrorMessage; - } }); - var sha256_js_1 = require_sha256(); - Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hash; - } }); - Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { - return sha256_js_1.computeSha256Hmac; - } }); - var typeGuards_js_1 = require_typeGuards(); - Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { - return typeGuards_js_1.isDefined; - } }); - Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { - return typeGuards_js_1.isObjectWithProperties; - } }); - Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { - return typeGuards_js_1.objectHasProperty; - } }); - var uuidUtils_js_1 = require_uuidUtils(); - Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { - return uuidUtils_js_1.randomUUID; - } }); - var checkEnvironment_js_1 = require_checkEnvironment(); - Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBrowser; - } }); - Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { - return checkEnvironment_js_1.isBun; - } }); - Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNode; - } }); - Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeLike; - } }); - Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { - return checkEnvironment_js_1.isNodeRuntime; - } }); - Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { - return checkEnvironment_js_1.isDeno; - } }); - Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { - return checkEnvironment_js_1.isReactNative; - } }); - Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { - return checkEnvironment_js_1.isWebWorker; - } }); - var bytesEncoding_js_1 = require_bytesEncoding(); - Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { - return bytesEncoding_js_1.uint8ArrayToString; - } }); - Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { - return bytesEncoding_js_1.stringToUint8Array; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js -var require_sanitizer = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Sanitizer = void 0; - var core_util_1 = require_commonjs4(); - var RedactedString = "REDACTED"; - var defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate" - ]; - var defaultAllowedQueryParameters = ["api-version"]; - var Sanitizer = class { - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { - allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); - allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); } - sanitize(obj) { - const seen = /* @__PURE__ */ new Set(); - return JSON.stringify(obj, (key, value) => { - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - if (key === "headers") { - return this.sanitizeHeaders(value); - } else if (key === "url") { - return this.sanitizeUrl(value); - } else if (key === "query") { - return this.sanitizeQuery(value); - } else if (key === "body") { - return void 0; - } else if (key === "response") { - return void 0; - } else if (key === "operationSpec") { - return void 0; - } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return value; - }, 2); - } - sanitizeUrl(value) { - if (typeof value !== "string" || value === null || value === "") { - return value; } - const url = new URL(value); - if (!url.search) { - return value; + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); } - for (const [key] of url.searchParams) { - if (!this.allowedQueryParameters.has(key.toLowerCase())) { - url.searchParams.set(key, RedactedString); - } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.internalArtifactTwirpClient = internalArtifactTwirpClient; + var http_client_1 = require_lib3(); + var auth_1 = require_auth2(); + var core_1 = require_core(); + var generated_1 = require_generated(); + var config_1 = require_config(); + var user_agent_1 = require_user_agent(); + var errors_1 = require_errors2(); + var util_1 = require_util8(); + var ArtifactHttpClient = class { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3e3; + this.retryMultiplier = 1.5; + const token = (0, config_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getResultsServiceUrl)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; } - return url.toString(); + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) + ]); } - sanitizeHeaders(obj) { - const sanitized = {}; - for (const key of Object.keys(obj)) { - if (this.allowedHeaderNames.has(key.toLowerCase())) { - sanitized[key] = obj[key]; - } else { - sanitized[key] = RedactedString; + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { + return __awaiter4(this, void 0, void 0, function* () { + const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url}`); + const headers = { + "Content-Type": contentType + }; + try { + const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () { + return this.httpClient.post(url, JSON.stringify(data), headers); + })); + return body; + } catch (error4) { + throw new Error(`Failed to ${method}: ${error4.message}`); } - } - return sanitized; + }); } - sanitizeQuery(value) { - if (typeof value !== "object" || value === null) { - return value; - } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (this.allowedQueryParameters.has(k.toLowerCase())) { - sanitized[k] = value[k]; - } else { - sanitized[k] = RedactedString; + retryableRequest(operation) { + return __awaiter4(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ""; + let rawBody = ""; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, util_1.maskSecretUrls)(body); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } catch (error4) { + if (error4 instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + } + if (error4 instanceof errors_1.UsageError) { + throw error4; + } + if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) { + throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code); + } + isRetryable = true; + errorMessage = error4.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; } + throw new Error(`Request failed`); + }); + } + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; + } + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); + } + sleep(milliseconds) { + return __awaiter4(this, void 0, void 0, function* () { + return new Promise((resolve2) => setTimeout(resolve2, milliseconds)); + }); + } + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error("attempt should be a positive integer"); } - return sanitized; + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } }; - exports2.Sanitizer = Sanitizer; + function internalArtifactTwirpClient(options) { + const client = new ArtifactHttpClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new generated_1.ArtifactServiceClientJSON(client); + } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js -var require_logPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { +// node_modules/@actions/artifact/lib/internal/upload/upload-zip-specification.js +var require_upload_zip_specification = __commonJS({ + "node_modules/@actions/artifact/lib/internal/upload/upload-zip-specification.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]); + } + __setModuleDefault4(result, mod); + return result; + }; + })(); Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logPolicyName = void 0; - exports2.logPolicy = logPolicy; - var log_js_1 = require_log(); - var sanitizer_js_1 = require_sanitizer(); - exports2.logPolicyName = "logPolicy"; - function logPolicy(options = {}) { - var _a; - const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - return { - name: exports2.logPolicyName, - async sendRequest(request, next) { - if (!logger.enabled) { - return next(request); + exports2.validateRootDirectory = validateRootDirectory; + exports2.getUploadZipSpecification = getUploadZipSpecification; + var fs2 = __importStar4(require("fs")); + var core_1 = require_core(); + var path_1 = require("path"); + var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation(); + function validateRootDirectory(rootDirectory) { + if (!fs2.existsSync(rootDirectory)) { + throw new Error(`The provided rootDirectory ${rootDirectory} does not exist`); + } + if (!fs2.statSync(rootDirectory).isDirectory()) { + throw new Error(`The provided rootDirectory ${rootDirectory} is not a valid directory`); + } + (0, core_1.info)(`Root directory input is valid!`); + } + function getUploadZipSpecification(filesToZip, rootDirectory) { + const specification = []; + rootDirectory = (0, path_1.normalize)(rootDirectory); + rootDirectory = (0, path_1.resolve)(rootDirectory); + for (let file of filesToZip) { + const stats = fs2.lstatSync(file, { throwIfNoEntry: false }); + if (!stats) { + throw new Error(`File ${file} does not exist`); + } + if (!stats.isDirectory()) { + file = (0, path_1.normalize)(file); + file = (0, path_1.resolve)(file); + if (!file.startsWith(rootDirectory)) { + throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); } - logger(`Request: ${sanitizer.sanitize(request)}`); - const response = await next(request); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); - return response; + const uploadPath = file.replace(rootDirectory, ""); + (0, path_and_artifact_name_validation_1.validateFilePath)(uploadPath); + specification.push({ + sourcePath: file, + destinationPath: uploadPath, + stats + }); + } else { + const directoryPath = file.replace(rootDirectory, ""); + (0, path_and_artifact_name_validation_1.validateFilePath)(directoryPath); + specification.push({ + sourcePath: null, + destinationPath: directoryPath, + stats + }); } - }; + } + return specification; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js -var require_redirectPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.redirectPolicyName = void 0; - exports2.redirectPolicy = redirectPolicy; - exports2.redirectPolicyName = "redirectPolicy"; - var allowedRedirect = ["GET", "HEAD"]; - function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: exports2.redirectPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return handleRedirect(next, response, maxRetries); - } - }; - } - async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { - const url = new URL(locationHeader, request.url); - request.url = url.toString(); - if (status === 303) { - request.method = "GET"; - request.headers.delete("Content-Length"); - delete request.body; + exports2.createEmptyPipeline = createEmptyPipeline; + var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); + var HttpPipeline = class _HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); } - request.headers.delete("Authorization"); - const res = await next(request); - return handleRedirect(next, res, maxRetries, currentRetries + 1); + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; } - return response; + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; + } + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name) { + return { + name, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; + } + } + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } + }; + function createEmptyPipeline() { + return HttpPipeline.create(); } } }); -// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs -var tslib_es6_exports = {}; -__export(tslib_es6_exports, { - __addDisposableResource: () => __addDisposableResource, - __assign: () => __assign, - __asyncDelegator: () => __asyncDelegator, - __asyncGenerator: () => __asyncGenerator, - __asyncValues: () => __asyncValues, - __await: () => __await, - __awaiter: () => __awaiter, - __classPrivateFieldGet: () => __classPrivateFieldGet, - __classPrivateFieldIn: () => __classPrivateFieldIn, - __classPrivateFieldSet: () => __classPrivateFieldSet, - __createBinding: () => __createBinding, - __decorate: () => __decorate, - __disposeResources: () => __disposeResources, - __esDecorate: () => __esDecorate, - __exportStar: () => __exportStar, - __extends: () => __extends, - __generator: () => __generator, - __importDefault: () => __importDefault, - __importStar: () => __importStar, - __makeTemplateObject: () => __makeTemplateObject, - __metadata: () => __metadata, - __param: () => __param, - __propKey: () => __propKey, - __read: () => __read, - __rest: () => __rest, - __runInitializers: () => __runInitializers, - __setFunctionName: () => __setFunctionName, - __spread: () => __spread, - __spreadArray: () => __spreadArray, - __spreadArrays: () => __spreadArrays, - __values: () => __values2, - default: () => tslib_es6_default -}); -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; +// node_modules/@azure/logger/dist/index.js +var require_dist = __commonJS({ + "node_modules/@azure/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var os = require("os"); + var util = require("util"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; } - return t; -} -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _2, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context2 = {}; - for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; - context2.addInitializer = function(f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); - }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_2 = accept(result.get)) descriptor.get = _2; - if (_2 = accept(result.set)) descriptor.set = _2; - if (_2 = accept(result.init)) initializers.unshift(_2); - } else if (_2 = accept(result)) { - if (kind === "field") initializers.unshift(_2); - else descriptor[key] = _2; + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util); + function log(message, ...args) { + process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`); } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} -function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -} -function __propKey(x) { - return typeof x === "symbol" ? x : "".concat(x); -} -function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); -} -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); + var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0; + var enabledString; + var enabledNamespaces = []; + var skippedNamespaces = []; + var debuggers = []; + if (debugEnvVariable) { + enable(debugEnvVariable); + } + var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); + }, { + enable, + enabled, + disable, + log }); - } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); } } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } } + return false; } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + function disable() { + const result = enabledString || ""; + enable(""); + return result; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _2 = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_2 = 0)), _2) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _2.label++; - return { value: op[1], done: false }; - case 5: - _2.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _2.ops.pop(); - _2.trys.pop(); - continue; - default: - if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _2 = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _2.label = op[1]; - break; - } - if (op[0] === 6 && _2.label < t[1]) { - _2.label = t[1]; - t = op; - break; - } - if (t && _2.label < t[2]) { - _2.label = t[2]; - _2.ops.push(op); - break; - } - if (t[2]) _2.ops.pop(); - _2.trys.pop(); - continue; + function createDebugger(namespace) { + const newDebugger = Object.assign(debug5, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend: extend3 + }); + function debug5(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); } - op = body.call(thisArg, _2); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; + debuggers.push(newDebugger); + return newDebugger; } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -} -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} -function __values2(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function() { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error4) { - e = { error: error4 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; + function extend3(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; } - } - return ar; -} -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; + var debug4 = debugObj; + var registeredLoggers = /* @__PURE__ */ new Set(); + var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0; + var azureLogLevel; + var AzureLogger = debug4("azure"); + AzureLogger.log = (...args) => { + debug4.log(...args); + }; + var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; + if (logLevelFromEnv) { + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + } } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); + function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces2 = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces2.push(logger.namespace); + } + } + debug4.enable(enabledNamespaces2.join(",")); + } + function getLogLevel() { + return azureLogLevel; + } + var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); + function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") }; - if (f) i[n] = f(i[n]); } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); + function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function(e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function() { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function(v) { - return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; - } : f; - } -} -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve2, reject) { - v = o[n](v), settle(resolve2, reject, v.done, v.value); + function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level }); - }; - } - function settle(resolve2, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve2({ value: v2, done: d }); - }, reject); - } -} -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - } - __setModuleDefault(result, mod); - return result; -} -function __importDefault(mod) { - return mod && mod.__esModule ? mod : { default: mod }; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldIn(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} -function __addDisposableResource(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces2 = debug4.disable(); + debug4.enable(enabledNamespaces2 + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; + function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { - try { - inner.call(this); - } catch (e) { - return Promise.reject(e); - } - }; - env.stack.push({ value, dispose, async }); - } else if (async) { - env.stack.push({ async: true }); - } - return value; -} -function __disposeResources(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { - fail(e); - return next(); - }); - } else s |= 1; - } catch (e) { - fail(e); - } + function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; + exports2.AzureLogger = AzureLogger; + exports2.createClientLogger = createClientLogger; + exports2.getLogLevel = getLogLevel; + exports2.setLogLevel = setLogLevel; } - return next(); -} -var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; -var init_tslib_es6 = __esm({ - "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() { - extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics(d, b); - }; - __assign = function() { - __assign = Object.assign || function __assign4(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - }); - __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; - }; - tslib_es6_default = { - __extends, - __assign, - __rest, - __decorate, - __param, - __metadata, - __awaiter, - __generator, - __createBinding, - __exportStar, - __values: __values2, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn, - __addDisposableResource, - __disposeResources - }; +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js +var require_log = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js -var require_userAgentPlatform = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getHeaderName = getHeaderName; - exports2.setPlatformSpecificData = setPlatformSpecificData; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var os = tslib_1.__importStar(require("node:os")); - var process2 = tslib_1.__importStar(require("node:process")); - function getHeaderName() { - return "User-Agent"; - } - async function setPlatformSpecificData(map2) { - if (process2 && process2.versions) { - const versions = process2.versions; - if (versions.bun) { - map2.set("Bun", versions.bun); - } else if (versions.deno) { - map2.set("Deno", versions.deno); - } else if (versions.node) { - map2.set("Node", versions.node); - } + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } - map2.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`); - } + }; + exports2.AbortError = AbortError; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js -var require_constants7 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { +// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs3 = __commonJS({ + "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; - exports2.SDK_VERSION = "1.17.0"; - exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js -var require_userAgent = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js +var require_createAbortablePromise = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getUserAgentHeaderName = getUserAgentHeaderName; - exports2.getUserAgentValue = getUserAgentValue; - var userAgentPlatform_js_1 = require_userAgentPlatform(); - var constants_js_1 = require_constants7(); - function getUserAgentString(telemetryInfo) { - const parts = []; - for (const [key, value] of telemetryInfo) { - const token = value ? `${key}/${value}` : key; - parts.push(token); - } - return parts.join(" "); - } - function getUserAgentHeaderName() { - return (0, userAgentPlatform_js_1.getHeaderName)(); - } - async function getUserAgentValue(prefix) { - const runtimeInfo = /* @__PURE__ */ new Map(); - runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); - await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); - const defaultAgent = getUserAgentString(runtimeInfo); - const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; - return userAgentValue; + exports2.createAbortablePromise = createAbortablePromise; + var abort_controller_1 = require_commonjs3(); + function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve2, reject) => { + function rejectOnAbort() { + reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve2(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js -var require_userAgentPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/random.js +var require_random = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.userAgentPolicyName = void 0; - exports2.userAgentPolicy = userAgentPolicy; - var userAgent_js_1 = require_userAgent(); - var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); - exports2.userAgentPolicyName = "userAgentPolicy"; - function userAgentPolicy(options = {}) { - const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); - return { - name: exports2.userAgentPolicyName, - async sendRequest(request, next) { - if (!request.headers.has(UserAgentHeaderName)) { - request.headers.set(UserAgentHeaderName, await userAgentValue); - } - return next(request); - } - }; + exports2.getRandomIntegerInclusive = getRandomIntegerInclusive; + function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js -var require_typeGuards2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/delay.js +var require_delay = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isNodeReadableStream = isNodeReadableStream; - exports2.isWebReadableStream = isWebReadableStream; - exports2.isReadableStream = isReadableStream; - exports2.isBlob = isBlob; - function isNodeReadableStream(x) { - return Boolean(x && typeof x["pipe"] === "function"); - } - function isWebReadableStream(x) { - return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); - } - function isReadableStream(x) { - return isNodeReadableStream(x) || isWebReadableStream(x); + exports2.delay = delay; + exports2.calculateRetryDelay = calculateRetryDelay; + var createAbortablePromise_js_1 = require_createAbortablePromise(); + var random_js_1 = require_random(); + var StandardAbortMessage = "The delay was aborted."; + function delay(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve2) => { + token = setTimeout(resolve2, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage + }); } - function isBlob(x) { - return typeof x.stream === "function"; + function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js -var require_file2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js +var require_aborterUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getRawContent = getRawContent; - exports2.createFileFromStream = createFileFromStream; - exports2.createFile = createFile; - var core_util_1 = require_commonjs4(); - var typeGuards_js_1 = require_typeGuards2(); - var unimplementedMethods = { - arrayBuffer: () => { - throw new Error("Not implemented"); - }, - slice: () => { - throw new Error("Not implemented"); - }, - text: () => { - throw new Error("Not implemented"); - } - }; - var rawContent = Symbol("rawContent"); - function hasRawContent(x) { - return typeof x[rawContent] === "function"; - } - function getRawContent(blob) { - if (hasRawContent(blob)) { - return blob[rawContent](); - } else { - return blob.stream(); + exports2.cancelablePromiseRace = cancelablePromiseRace; + async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new AbortController(); + function abortHandler() { + aborter.abort(); } - } - function createFileFromStream(stream, name, options = {}) { - var _a, _b, _c, _d; - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { - const s = stream(); - if ((0, typeGuards_js_1.isNodeReadableStream)(s)) { - throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); - } - return s; - }, [rawContent]: stream }); - } - function createFile(content, name, options = {}) { - var _a, _b, _c; - if (core_util_1.isNodeLike) { - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); - } else { - return new File([content], name, options); + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); } } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js -var require_concat = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/object.js +var require_object = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.concat = concat; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var node_stream_1 = require("node:stream"); - var typeGuards_js_1 = require_typeGuards2(); - var file_js_1 = require_file2(); - function streamAsyncIterator() { - return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { - const reader = this.getReader(); - try { - while (true) { - const { done, value } = yield tslib_1.__await(reader.read()); - if (done) { - return yield tslib_1.__await(void 0); - } - yield yield tslib_1.__await(value); - } - } finally { - reader.releaseLock(); - } - }); - } - function makeAsyncIterable(webStream) { - if (!webStream[Symbol.asyncIterator]) { - webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); - } - if (!webStream.values) { - webStream.values = streamAsyncIterator.bind(webStream); - } - } - function ensureNodeStream(stream) { - if (stream instanceof ReadableStream) { - makeAsyncIterable(stream); - return node_stream_1.Readable.fromWeb(stream); - } else { - return stream; - } - } - function toStream(source) { - if (source instanceof Uint8Array) { - return node_stream_1.Readable.from(Buffer.from(source)); - } else if ((0, typeGuards_js_1.isBlob)(source)) { - return toStream((0, file_js_1.getRawContent)(source)); - } else { - return ensureNodeStream(source); - } - } - async function concat(sources) { - return function() { - const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); - return node_stream_1.Readable.from((function() { - return tslib_1.__asyncGenerator(this, arguments, function* () { - var _a, e_1, _b, _c; - for (const stream of streams) { - try { - for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { - _c = stream_1_1.value; - _d = false; - const chunk = _c; - yield yield tslib_1.__await(chunk); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1)); - } finally { - if (e_1) throw e_1.error; - } - } - } - }); - })()); - }; + exports2.isObject = isObject2; + function isObject2(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js -var require_multipartPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/error.js +var require_error = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.multipartPolicyName = void 0; - exports2.multipartPolicy = multipartPolicy; - var core_util_1 = require_commonjs4(); - var concat_js_1 = require_concat(); - var typeGuards_js_1 = require_typeGuards2(); - function generateBoundary() { - return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; - } - function encodeHeaders(headers) { - let result = ""; - for (const [key, value] of headers) { - result += `${key}: ${value}\r -`; + exports2.isError = isError; + exports2.getErrorMessage = getErrorMessage2; + var object_js_1 = require_object(); + function isError(e) { + if ((0, object_js_1.isObject)(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; } - return result; + return false; } - function getLength(source) { - if (source instanceof Uint8Array) { - return source.byteLength; - } else if ((0, typeGuards_js_1.isBlob)(source)) { - return source.size === -1 ? void 0 : source.size; + function getErrorMessage2(e) { + if (isError(e)) { + return e.message; } else { - return void 0; - } - } - function getTotalLength(sources) { - let total = 0; - for (const source of sources) { - const partLength = getLength(source); - if (partLength === void 0) { - return void 0; - } else { - total += partLength; - } - } - return total; - } - async function buildRequestBody(request, parts, boundary) { - const sources = [ - (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"), - ...parts.flatMap((part) => [ - (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), - (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), - (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), - part.body, - (0, core_util_1.stringToUint8Array)(`\r ---${boundary}`, "utf-8") - ]), - (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8") - ]; - const contentLength = getTotalLength(sources); - if (contentLength) { - request.headers.set("Content-Length", contentLength); - } - request.body = await (0, concat_js_1.concat)(sources); - } - exports2.multipartPolicyName = "multipartPolicy"; - var maxBoundaryLength = 70; - var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); - function assertValidBoundary(boundary) { - if (boundary.length > maxBoundaryLength) { - throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); - } - if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { - throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); - } - } - function multipartPolicy() { - return { - name: exports2.multipartPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.multipartBody) { - return next(request); - } - if (request.body) { - throw new Error("multipartBody and regular body cannot be set at the same time"); - } - let boundary = request.multipartBody.boundary; - const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; - const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); - if (!parsedHeader) { - throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); - } - const [, contentType, parsedBoundary] = parsedHeader; - if (parsedBoundary && boundary && parsedBoundary !== boundary) { - throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); - } - boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary; - if (boundary) { - assertValidBoundary(boundary); + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); } else { - boundary = generateBoundary(); + stringified = String(e); } - request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); - await buildRequestBody(request, request.multipartBody.parts, boundary); - request.multipartBody = void 0; - return next(request); + } catch (err) { + stringified = "[unable to stringify input]"; } - }; + return `Unknown error ${stringified}`; + } } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js -var require_decompressResponsePolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decompressResponsePolicyName = void 0; - exports2.decompressResponsePolicy = decompressResponsePolicy; - exports2.decompressResponsePolicyName = "decompressResponsePolicy"; - function decompressResponsePolicy() { - return { - name: exports2.decompressResponsePolicyName, - async sendRequest(request, next) { - if (request.method !== "HEAD") { - request.headers.set("Accept-Encoding", "gzip,deflate"); - } - return next(request); - } - }; + exports2.computeSha256Hmac = computeSha256Hmac; + exports2.computeSha256Hash = computeSha256Hash; + var crypto_1 = require("crypto"); + async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding); + } + async function computeSha256Hash(content, encoding) { + return (0, crypto_1.createHash)("sha256").update(content).digest(encoding); } } }); -// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError2 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/typeGuards.js +var require_typeGuards = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + exports2.isDefined = isDefined2; + exports2.isObjectWithProperties = isObjectWithProperties; + exports2.objectHasProperty = objectHasProperty; + function isDefined2(thing) { + return typeof thing !== "undefined" && thing !== null; + } + function isObjectWithProperties(thing, properties) { + if (!isDefined2(thing) || typeof thing !== "object") { + return false; } - }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs5 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError2(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; + } + function objectHasProperty(thing, property) { + return isDefined2(thing) && typeof thing === "object" && property in thing; + } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js -var require_helpers = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js +var require_uuidUtils = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) { "use strict"; + var _a; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = delay; - exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; - var abort_controller_1 = require_commonjs5(); - var StandardAbortMessage = "The operation was aborted."; - function delay(delayInMs, value, options) { - return new Promise((resolve2, reject) => { - let timer = void 0; - let onAborted = void 0; - const rejectOnAbort = () => { - return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); - }; - const removeListeners = () => { - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { - options.abortSignal.removeEventListener("abort", onAborted); - } - }; - onAborted = () => { - if (timer) { - clearTimeout(timer); - } - removeListeners(); - return rejectOnAbort(); - }; - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { - return rejectOnAbort(); - } - timer = setTimeout(() => { - removeListeners(); - resolve2(value); - }, delayInMs); - if (options === null || options === void 0 ? void 0 : options.abortSignal) { - options.abortSignal.addEventListener("abort", onAborted); - } - }); - } - function parseHeaderValueAsNumber(response, headerName) { - const value = response.headers.get(headerName); - if (!value) - return; - const valueAsNum = Number(value); - if (Number.isNaN(valueAsNum)) - return; - return valueAsNum; + exports2.randomUUID = randomUUID; + var crypto_1 = require("crypto"); + var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID; + function randomUUID() { + return uuidFunction(); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js -var require_throttlingRetryStrategy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js +var require_checkEnvironment = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) { "use strict"; + var _a; + var _b; + var _c; + var _d; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; - exports2.throttlingRetryStrategy = throttlingRetryStrategy; - var helpers_js_1 = require_helpers(); - var RetryAfterHeader = "Retry-After"; - var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; - function getRetryAfterInMs(response) { - if (!(response && [429, 503].includes(response.status))) - return void 0; - try { - for (const header of AllRetryAfterHeaders) { - const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); - if (retryAfterValue === 0 || retryAfterValue) { - const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; - return retryAfterValue * multiplyingFactor; - } - } - const retryAfterHeader = response.headers.get(RetryAfterHeader); - if (!retryAfterHeader) - return; - const date = Date.parse(retryAfterHeader); - const diff = date - Date.now(); - return Number.isFinite(diff) ? Math.max(0, diff) : void 0; - } catch (_a) { - return void 0; - } - } - function isThrottlingRetryResponse(response) { - return Number.isFinite(getRetryAfterInMs(response)); - } - function throttlingRetryStrategy() { - return { - name: "throttlingRetryStrategy", - retry({ response }) { - const retryAfterInMs = getRetryAfterInMs(response); - if (!Number.isFinite(retryAfterInMs)) { - return { skipStrategy: true }; - } - return { - retryAfterInMs - }; - } - }; - } + exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0; + exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; + exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); + exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; + exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; + exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); + exports2.isNode = exports2.isNodeLike; + exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno; + exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js -var require_exponentialRetryStrategy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js +var require_bytesEncoding = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryStrategy = exponentialRetryStrategy; - exports2.isExponentialRetryResponse = isExponentialRetryResponse; - exports2.isSystemError = isSystemError; - var core_util_1 = require_commonjs4(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; - var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; - function exponentialRetryStrategy(options = {}) { - var _a, _b; - const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; - const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - let retryAfterInMs = retryInterval; - return { - name: "exponentialRetryStrategy", - retry({ retryCount, response, responseError }) { - const matchedSystemError = isSystemError(responseError); - const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; - const isExponential = isExponentialRetryResponse(response); - const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; - const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); - if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { - return { skipStrategy: true }; - } - if (responseError && !matchedSystemError && !isExponential) { - return { errorToThrow: responseError }; - } - const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); - const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); - retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2); - return { retryAfterInMs }; - } - }; - } - function isExponentialRetryResponse(response) { - return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); + exports2.uint8ArrayToString = uint8ArrayToString; + exports2.stringToUint8Array = stringToUint8Array; + function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); } - function isSystemError(err) { - if (!err) { - return false; - } - return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; + function stringToUint8Array(value, format) { + return Buffer.from(value, format); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js -var require_retryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { +// node_modules/@azure/core-util/dist/commonjs/index.js +var require_commonjs4 = __commonJS({ + "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.retryPolicy = retryPolicy; - var helpers_js_1 = require_helpers(); - var logger_1 = require_dist(); - var abort_controller_1 = require_commonjs5(); - var constants_js_1 = require_constants7(); - var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); - var retryPolicyName = "retryPolicy"; - function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { - const logger = options.logger || retryPolicyLogger; - return { - name: retryPolicyName, - async sendRequest(request, next) { - var _a, _b; - let response; - let responseError; - let retryCount = -1; - retryRequest: while (true) { - retryCount += 1; - response = void 0; - responseError = void 0; - try { - logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); - response = await next(request); - logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); - } catch (e) { - logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); - responseError = e; - if (!e || responseError.name !== "RestError") { - throw e; - } - response = responseError.response; - } - if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - logger.error(`Retry ${retryCount}: Request aborted.`); - const abortError = new abort_controller_1.AbortError(); - throw abortError; - } - if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { - logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); - if (responseError) { - throw responseError; - } else if (response) { - return response; - } else { - throw new Error("Maximum retries reached with no response or error to throw"); - } - } - logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); - strategiesLoop: for (const strategy of strategies) { - const strategyLogger = strategy.logger || retryPolicyLogger; - strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); - const modifiers = strategy.retry({ - retryCount, - response, - responseError - }); - if (modifiers.skipStrategy) { - strategyLogger.info(`Retry ${retryCount}: Skipped.`); - continue strategiesLoop; - } - const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; - if (errorToThrow) { - strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); - throw errorToThrow; - } - if (retryAfterInMs || retryAfterInMs === 0) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); - await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); - continue retryRequest; - } - if (redirectTo) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); - request.url = redirectTo; - continue retryRequest; - } - } - if (responseError) { - logger.info(`None of the retry strategies could work with the received error. Throwing it.`); - throw responseError; - } - if (response) { - logger.info(`None of the retry strategies could work with the received response. Returning it.`); - return response; - } - } - } - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js -var require_defaultRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.defaultRetryPolicyName = void 0; - exports2.defaultRetryPolicy = defaultRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants7(); - exports2.defaultRetryPolicyName = "defaultRetryPolicy"; - function defaultRetryPolicy(options = {}) { - var _a; - return { - name: exports2.defaultRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest - }; - } + exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0; + var delay_js_1 = require_delay(); + Object.defineProperty(exports2, "delay", { enumerable: true, get: function() { + return delay_js_1.delay; + } }); + Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() { + return delay_js_1.calculateRetryDelay; + } }); + var aborterUtils_js_1 = require_aborterUtils(); + Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() { + return aborterUtils_js_1.cancelablePromiseRace; + } }); + var createAbortablePromise_js_1 = require_createAbortablePromise(); + Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() { + return createAbortablePromise_js_1.createAbortablePromise; + } }); + var random_js_1 = require_random(); + Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() { + return random_js_1.getRandomIntegerInclusive; + } }); + var object_js_1 = require_object(); + Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() { + return object_js_1.isObject; + } }); + var error_js_1 = require_error(); + Object.defineProperty(exports2, "isError", { enumerable: true, get: function() { + return error_js_1.isError; + } }); + Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() { + return error_js_1.getErrorMessage; + } }); + var sha256_js_1 = require_sha256(); + Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hash; + } }); + Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() { + return sha256_js_1.computeSha256Hmac; + } }); + var typeGuards_js_1 = require_typeGuards(); + Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() { + return typeGuards_js_1.isDefined; + } }); + Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() { + return typeGuards_js_1.isObjectWithProperties; + } }); + Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() { + return typeGuards_js_1.objectHasProperty; + } }); + var uuidUtils_js_1 = require_uuidUtils(); + Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() { + return uuidUtils_js_1.randomUUID; + } }); + var checkEnvironment_js_1 = require_checkEnvironment(); + Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBrowser; + } }); + Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() { + return checkEnvironment_js_1.isBun; + } }); + Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNode; + } }); + Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeLike; + } }); + Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() { + return checkEnvironment_js_1.isNodeRuntime; + } }); + Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() { + return checkEnvironment_js_1.isDeno; + } }); + Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() { + return checkEnvironment_js_1.isReactNative; + } }); + Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() { + return checkEnvironment_js_1.isWebWorker; + } }); + var bytesEncoding_js_1 = require_bytesEncoding(); + Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() { + return bytesEncoding_js_1.uint8ArrayToString; + } }); + Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() { + return bytesEncoding_js_1.stringToUint8Array; + } }); } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js -var require_httpHeaders = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js +var require_sanitizer = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createHttpHeaders = createHttpHeaders; - function normalizeName(name) { - return name.toLowerCase(); - } - function* headerIterator(map2) { - for (const entry of map2.values()) { - yield [entry.name, entry.value]; + exports2.Sanitizer = void 0; + var core_util_1 = require_commonjs4(); + var RedactedString = "REDACTED"; + var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" + ]; + var defaultAllowedQueryParameters = ["api-version"]; + var Sanitizer = class { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); } - } - var HttpHeadersImpl = class { - constructor(rawHeaders) { - this._headersMap = /* @__PURE__ */ new Map(); - if (rawHeaders) { - for (const headerName of Object.keys(rawHeaders)) { - this.set(headerName, rawHeaders[headerName]); + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); } - } - } - /** - * Set a header in this collection with the provided name and value. The name is - * case-insensitive. - * @param name - The name of the header to set. This value is case-insensitive. - * @param value - The value of the header to set. - */ - set(name, value) { - this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); - } - /** - * Get the header value for the provided header name, or undefined if no header exists in this - * collection with the provided name. - * @param name - The name of the header. This value is case-insensitive. - */ - get(name) { - var _a; - return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; - } - /** - * Get whether or not this header collection contains a header entry for the provided header name. - * @param name - The name of the header to set. This value is case-insensitive. - */ - has(name) { - return this._headersMap.has(normalizeName(name)); - } - /** - * Remove the header with the provided headerName. - * @param name - The name of the header to remove. - */ - delete(name) { - this._headersMap.delete(normalizeName(name)); - } - /** - * Get the JSON object representation of this HTTP header collection. - */ - toJSON(options = {}) { - const result = {}; - if (options.preserveCase) { - for (const entry of this._headersMap.values()) { - result[entry.name] = entry.value; + if (key === "headers") { + return this.sanitizeHeaders(value); + } else if (key === "url") { + return this.sanitizeUrl(value); + } else if (key === "query") { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); } - } else { - for (const [normalizedName, entry] of this._headersMap) { - result[normalizedName] = entry.value; + return value; + }, 2); + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; + } + const url = new URL(value); + if (!url.search) { + return value; + } + for (const [key] of url.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url.searchParams.set(key, RedactedString); } } - return result; + return url.toString(); } - /** - * Get the string representation of this HTTP header collection. - */ - toString() { - return JSON.stringify(this.toJSON({ preserveCase: true })); + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; } - /** - * Iterate over tuples of header [name, value] pairs. - */ - [Symbol.iterator]() { - return headerIterator(this._headersMap); + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; } }; - function createHttpHeaders(rawHeaders) { - return new HttpHeadersImpl(rawHeaders); - } + exports2.Sanitizer = Sanitizer; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js -var require_formDataPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js +var require_logPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.formDataPolicyName = void 0; - exports2.formDataPolicy = formDataPolicy; - var core_util_1 = require_commonjs4(); - var httpHeaders_js_1 = require_httpHeaders(); - exports2.formDataPolicyName = "formDataPolicy"; - function formDataToFormDataMap(formData) { + exports2.logPolicyName = void 0; + exports2.logPolicy = logPolicy; + var log_js_1 = require_log(); + var sanitizer_js_1 = require_sanitizer(); + exports2.logPolicyName = "logPolicy"; + function logPolicy(options = {}) { var _a; - const formDataMap = {}; - for (const [key, value] of formData.entries()) { - (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = []; - formDataMap[key].push(value); - } - return formDataMap; - } - function formDataPolicy() { + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info; + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); return { - name: exports2.formDataPolicyName, + name: exports2.logPolicyName, async sendRequest(request, next) { - if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { - request.formData = formDataToFormDataMap(request.body); - request.body = void 0; - } - if (request.formData) { - const contentType = request.headers.get("Content-Type"); - if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { - request.body = wwwFormUrlEncode(request.formData); - } else { - await prepareFormData(request.formData, request); - } - request.formData = void 0; + if (!logger.enabled) { + return next(request); } - return next(request); + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; } }; } - function wwwFormUrlEncode(formData) { - const urlSearchParams = new URLSearchParams(); - for (const [key, value] of Object.entries(formData)) { - if (Array.isArray(value)) { - for (const subValue of value) { - urlSearchParams.append(key, subValue.toString()); - } - } else { - urlSearchParams.append(key, value.toString()); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js +var require_redirectPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.redirectPolicyName = void 0; + exports2.redirectPolicy = redirectPolicy; + exports2.redirectPolicyName = "redirectPolicy"; + var allowedRedirect = ["GET", "HEAD"]; + function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; + return { + name: exports2.redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); } - } - return urlSearchParams.toString(); + }; } - async function prepareFormData(formData, request) { - const contentType = request.headers.get("Content-Type"); - if (contentType && !contentType.startsWith("multipart/form-data")) { - return; - } - request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); - const parts = []; - for (const [fieldName, values] of Object.entries(formData)) { - for (const value of Array.isArray(values) ? values : [values]) { - if (typeof value === "string") { - parts.push({ - headers: (0, httpHeaders_js_1.createHttpHeaders)({ - "Content-Disposition": `form-data; name="${fieldName}"` - }), - body: (0, core_util_1.stringToUint8Array)(value, "utf-8") - }); - } else if (value === void 0 || value === null || typeof value !== "object") { - throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); - } else { - const fileName = value.name || "blob"; - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); - headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); - headers.set("Content-Type", value.type || "application/octet-stream"); - parts.push({ - headers, - body: value - }); - } + async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url = new URL(locationHeader, request.url); + request.url = url.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; } + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); } - request.multipartBody = { parts }; + return response; } } }); -// node_modules/ms/index.js -var require_ms = __commonJS({ - "node_modules/ms/index.js"(exports2, module2) { - var s = 1e3; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - module2.exports = function(val2, options) { - options = options || {}; - var type2 = typeof val2; - if (type2 === "string" && val2.length > 0) { - return parse(val2); - } else if (type2 === "number" && isFinite(val2)) { - return options.long ? fmtLong(val2) : fmtShort(val2); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2) - ); +// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __addDisposableResource: () => __addDisposableResource, + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __disposeResources: () => __disposeResources, + __esDecorate: () => __esDecorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __propKey: () => __propKey, + __read: () => __read, + __rest: () => __rest, + __runInitializers: () => __runInitializers, + __setFunctionName: () => __setFunctionName, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values2, + default: () => tslib_es6_default +}); +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _2, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context2 = {}; + for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; + context2.addInitializer = function(f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); }; - function parse(str2) { - str2 = String(str2); - if (str2.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str2 - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type2 = (match[2] || "ms").toLowerCase(); - switch (type2) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "weeks": - case "week": - case "w": - return n * w; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return void 0; - } + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_2 = accept(result.get)) descriptor.get = _2; + if (_2 = accept(result.set)) descriptor.set = _2; + if (_2 = accept(result.init)) initializers.unshift(_2); + } else if (_2 = accept(result)) { + if (kind === "field") initializers.unshift(_2); + else descriptor[key] = _2; } - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; - } - if (msAbs >= m) { - return Math.round(ms / m) + "m"; - } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - return ms + "ms"; } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, "minute"); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return ms + " ms"; } - function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _2 = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n) { + return function(v) { + return step([n, v]); + }; } -}); - -// node_modules/debug/src/common.js -var require_common = __commonJS({ - "node_modules/debug/src/common.js"(exports2, module2) { - function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce3; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require_ms(); - createDebug.destroy = destroy; - Object.keys(env).forEach((key) => { - createDebug[key] = env[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash = 0; - for (let i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; - } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug4(...args) { - if (!debug4.enabled) { - return; - } - const self2 = debug4; - const curr = Number(/* @__PURE__ */ new Date()); - const ms = curr - (prevTime || curr); - self2.diff = ms; - self2.prev = prevTime; - self2.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); - } - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - if (match === "%%") { - return "%"; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === "function") { - const val2 = args[index]; - match = formatter.call(self2, val2); - args.splice(index, 1); - index--; - } - return match; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); - } - debug4.namespace = namespace; - debug4.useColors = createDebug.useColors(); - debug4.color = createDebug.selectColor(namespace); - debug4.extend = extend3; - debug4.destroy = createDebug.destroy; - Object.defineProperty(debug4, "enabled", { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, - set: (v) => { - enableOverride = v; - } - }); - if (typeof createDebug.init === "function") { - createDebug.init(debug4); - } - return debug4; - } - function extend3(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns of split) { - if (ns[0] === "-") { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_2 = 0)), _2) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _2.label++; + return { value: op[1], done: false }; + case 5: + _2.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; + continue; } - } - } - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { - if (template[templateIndex] === "*") { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _2.label = op[1]; + break; } - } - while (templateIndex < template.length && template[templateIndex] === "*") { - templateIndex++; - } - return templateIndex === template.length; - } - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; - } - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; + if (op[0] === 6 && _2.label < t[1]) { + _2.label = t[1]; + t = op; + break; } - } - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; + if (t && _2.label < t[2]) { + _2.label = t[2]; + _2.ops.push(op); + break; } - } - return false; - } - function coerce3(val2) { - if (val2 instanceof Error) { - return val2.stack || val2.message; - } - return val2; - } - function destroy() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + if (t[2]) _2.ops.pop(); + _2.trys.pop(); + continue; } - createDebug.enable(createDebug.load()); - return createDebug; + op = body.call(thisArg, _2); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; } - module2.exports = setup; + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; } -}); - -// node_modules/debug/src/browser.js -var require_browser = __commonJS({ - "node_modules/debug/src/browser.js"(exports2, module2) { - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load2; - exports2.useColors = useColors; - exports2.storage = localstorage(); - exports2.destroy = /* @__PURE__ */ (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - }; - })(); - exports2.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - let m; - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 - typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker - typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); +} +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} +function __values2(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function() { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - function formatArgs(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; - } - index++; - if (match === "%c") { - lastC = index; - } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error4) { + e = { error: error4 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function(e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function() { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function(v) { + return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; + } : f; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); }); - args.splice(lastC, 0, c); + }; + } + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; } - exports2.log = console.debug || console.log || (() => { - }); - function save(namespaces) { - try { - if (namespaces) { - exports2.storage.setItem("debug", namespaces); - } else { - exports2.storage.removeItem("debug"); - } - } catch (error4) { - } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; } - function load2() { - let r; + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { - r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); - } catch (error4) { - } - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; + inner.call(this); + } catch (e) { + return Promise.reject(e); } - return r; - } - function localstorage() { + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { try { - return localStorage; - } catch (error4) { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); } } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error4) { - return "[UnexpectedJSONParseError]: " + error4.message; + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; +var init_tslib_es6 = __esm({ + "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() { + extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + __assign = function() { + __assign = Object.assign || function __assign4(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; + }; + tslib_es6_default = { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values: __values2, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources }; } }); -// node_modules/has-flag/index.js -var require_has_flag = __commonJS({ - "node_modules/has-flag/index.js"(exports2, module2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js +var require_userAgentPlatform = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) { "use strict"; - module2.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf("--"); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); - }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getHeaderName = getHeaderName; + exports2.setPlatformSpecificData = setPlatformSpecificData; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var os = tslib_1.__importStar(require("node:os")); + var process2 = tslib_1.__importStar(require("node:process")); + function getHeaderName() { + return "User-Agent"; + } + async function setPlatformSpecificData(map2) { + if (process2 && process2.versions) { + const versions = process2.versions; + if (versions.bun) { + map2.set("Bun", versions.bun); + } else if (versions.deno) { + map2.set("Deno", versions.deno); + } else if (versions.node) { + map2.set("Node", versions.node); + } + } + map2.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`); + } } }); -// node_modules/supports-color/index.js -var require_supports_color = __commonJS({ - "node_modules/supports-color/index.js"(exports2, module2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js +var require_constants7 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) { "use strict"; - var os = require("os"); - var tty = require("tty"); - var hasFlag = require_has_flag(); - var { env } = process; - var forceColor; - if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { - forceColor = 0; - } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { - forceColor = 1; - } - if ("FORCE_COLOR" in env) { - if (env.FORCE_COLOR === "true") { - forceColor = 1; - } else if (env.FORCE_COLOR === "false") { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0; + exports2.SDK_VERSION = "1.17.0"; + exports2.DEFAULT_RETRY_POLICY_COUNT = 3; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js +var require_userAgent = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getUserAgentHeaderName = getUserAgentHeaderName; + exports2.getUserAgentValue = getUserAgentValue; + var userAgentPlatform_js_1 = require_userAgentPlatform(); + var constants_js_1 = require_constants7(); + function getUserAgentString(telemetryInfo) { + const parts = []; + for (const [key, value] of telemetryInfo) { + const token = value ? `${key}/${value}` : key; + parts.push(token); } + return parts.join(" "); } - function translateLevel(level) { - if (level === 0) { - return false; - } + function getUserAgentHeaderName() { + return (0, userAgentPlatform_js_1.getHeaderName)(); + } + async function getUserAgentValue(prefix) { + const runtimeInfo = /* @__PURE__ */ new Map(); + runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION); + await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo); + const defaultAgent = getUserAgentString(runtimeInfo); + const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; + return userAgentValue; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js +var require_userAgentPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.userAgentPolicyName = void 0; + exports2.userAgentPolicy = userAgentPolicy; + var userAgent_js_1 = require_userAgent(); + var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); + exports2.userAgentPolicyName = "userAgentPolicy"; + function userAgentPolicy(options = {}) { + const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 + name: exports2.userAgentPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(UserAgentHeaderName)) { + request.headers.set(UserAgentHeaderName, await userAgentValue); + } + return next(request); + } }; } - function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } - if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { - return 3; - } - if (hasFlag("color=256")) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === void 0) { - return 0; - } - const min = forceColor || 0; - if (env.TERM === "dumb") { - return min; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js +var require_typeGuards2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isNodeReadableStream = isNodeReadableStream; + exports2.isWebReadableStream = isWebReadableStream; + exports2.isReadableStream = isReadableStream; + exports2.isBlob = isBlob; + function isNodeReadableStream(x) { + return Boolean(x && typeof x["pipe"] === "function"); + } + function isWebReadableStream(x) { + return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function"); + } + function isReadableStream(x) { + return isNodeReadableStream(x) || isWebReadableStream(x); + } + function isBlob(x) { + return typeof x.stream === "function"; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js +var require_file2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getRawContent = getRawContent; + exports2.createFileFromStream = createFileFromStream; + exports2.createFile = createFile; + var core_util_1 = require_commonjs4(); + var typeGuards_js_1 = require_typeGuards2(); + var unimplementedMethods = { + arrayBuffer: () => { + throw new Error("Not implemented"); + }, + slice: () => { + throw new Error("Not implemented"); + }, + text: () => { + throw new Error("Not implemented"); } - if (process.platform === "win32") { - const osRelease = os.release().split("."); - if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - return 1; + }; + var rawContent = Symbol("rawContent"); + function hasRawContent(x) { + return typeof x[rawContent] === "function"; + } + function getRawContent(blob) { + if (hasRawContent(blob)) { + return blob[rawContent](); + } else { + return blob.stream(); } - if ("CI" in env) { - if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { - return 1; + } + function createFileFromStream(stream, name, options = {}) { + var _a, _b, _c, _d; + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { + const s = stream(); + if ((0, typeGuards_js_1.isNodeReadableStream)(s)) { + throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); } - return min; - } - if ("TEAMCITY_VERSION" in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - if (env.COLORTERM === "truecolor") { - return 3; + return s; + }, [rawContent]: stream }); + } + function createFile(content, name, options = {}) { + var _a, _b, _c; + if (core_util_1.isNodeLike) { + return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); + } else { + return new File([content], name, options); } - if ("TERM_PROGRAM" in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (env.TERM_PROGRAM) { - case "iTerm.app": - return version >= 3 ? 3 : 2; - case "Apple_Terminal": - return 2; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js +var require_concat = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.concat = concat; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var node_stream_1 = require("node:stream"); + var typeGuards_js_1 = require_typeGuards2(); + var file_js_1 = require_file2(); + function streamAsyncIterator() { + return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { + const reader = this.getReader(); + try { + while (true) { + const { done, value } = yield tslib_1.__await(reader.read()); + if (done) { + return yield tslib_1.__await(void 0); + } + yield yield tslib_1.__await(value); + } + } finally { + reader.releaseLock(); } + }); + } + function makeAsyncIterable(webStream) { + if (!webStream[Symbol.asyncIterator]) { + webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; + if (!webStream.values) { + webStream.values = streamAsyncIterator.bind(webStream); } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; + } + function ensureNodeStream(stream) { + if (stream instanceof ReadableStream) { + makeAsyncIterable(stream); + return node_stream_1.Readable.fromWeb(stream); + } else { + return stream; } - if ("COLORTERM" in env) { - return 1; + } + function toStream(source) { + if (source instanceof Uint8Array) { + return node_stream_1.Readable.from(Buffer.from(source)); + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return toStream((0, file_js_1.getRawContent)(source)); + } else { + return ensureNodeStream(source); } - return min; } - function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); + async function concat(sources) { + return function() { + const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); + return node_stream_1.Readable.from((function() { + return tslib_1.__asyncGenerator(this, arguments, function* () { + var _a, e_1, _b, _c; + for (const stream of streams) { + try { + for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { + _c = stream_1_1.value; + _d = false; + const chunk = _c; + yield yield tslib_1.__await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1)); + } finally { + if (e_1) throw e_1.error; + } + } + } + }); + })()); + }; } - module2.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) - }; } }); -// node_modules/debug/src/node.js -var require_node = __commonJS({ - "node_modules/debug/src/node.js"(exports2, module2) { - var tty = require("tty"); - var util = require("util"); - exports2.init = init; - exports2.log = log; - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load2; - exports2.useColors = useColors; - exports2.destroy = util.deprecate( - () => { - }, - "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." - ); - exports2.colors = [6, 2, 3, 4, 5, 1]; - try { - const supportsColor = require_supports_color(); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports2.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } - } catch (error4) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js +var require_multipartPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.multipartPolicyName = void 0; + exports2.multipartPolicy = multipartPolicy; + var core_util_1 = require_commonjs4(); + var concat_js_1 = require_concat(); + var typeGuards_js_1 = require_typeGuards2(); + function generateBoundary() { + return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; } - exports2.inspectOpts = Object.keys(process.env).filter((key) => { - return /^debug_/i.test(key); - }).reduce((obj, key) => { - const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_2, k) => { - return k.toUpperCase(); - }); - let val2 = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val2)) { - val2 = true; - } else if (/^(no|off|false|disabled)$/i.test(val2)) { - val2 = false; - } else if (val2 === "null") { - val2 = null; - } else { - val2 = Number(val2); + function encodeHeaders(headers) { + let result = ""; + for (const [key, value] of headers) { + result += `${key}: ${value}\r +`; } - obj[prop] = val2; - return obj; - }, {}); - function useColors() { - return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); + return result; } - function formatArgs(args) { - const { namespace: name, useColors: useColors2 } = this; - if (useColors2) { - const c = this.color; - const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); - const prefix = ` ${colorCode};1m${name} \x1B[0m`; - args[0] = prefix + args[0].split("\n").join("\n" + prefix); - args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + function getLength(source) { + if (source instanceof Uint8Array) { + return source.byteLength; + } else if ((0, typeGuards_js_1.isBlob)(source)) { + return source.size === -1 ? void 0 : source.size; } else { - args[0] = getDate() + name + " " + args[0]; + return void 0; } } - function getDate() { - if (exports2.inspectOpts.hideDate) { - return ""; + function getTotalLength(sources) { + let total = 0; + for (const source of sources) { + const partLength = getLength(source); + if (partLength === void 0) { + return void 0; + } else { + total += partLength; + } } - return (/* @__PURE__ */ new Date()).toISOString() + " "; - } - function log(...args) { - return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + return total; } - function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - delete process.env.DEBUG; + async function buildRequestBody(request, parts, boundary) { + const sources = [ + (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"), + ...parts.flatMap((part) => [ + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"), + (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"), + part.body, + (0, core_util_1.stringToUint8Array)(`\r +--${boundary}`, "utf-8") + ]), + (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8") + ]; + const contentLength = getTotalLength(sources); + if (contentLength) { + request.headers.set("Content-Length", contentLength); } + request.body = await (0, concat_js_1.concat)(sources); } - function load2() { - return process.env.DEBUG; - } - function init(debug4) { - debug4.inspectOpts = {}; - const keys = Object.keys(exports2.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug4.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + exports2.multipartPolicyName = "multipartPolicy"; + var maxBoundaryLength = 70; + var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); + function assertValidBoundary(boundary) { + if (boundary.length > maxBoundaryLength) { + throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); + } + if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { + throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); } } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" "); - }; - formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); - }; + function multipartPolicy() { + return { + name: exports2.multipartPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.multipartBody) { + return next(request); + } + if (request.body) { + throw new Error("multipartBody and regular body cannot be set at the same time"); + } + let boundary = request.multipartBody.boundary; + const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; + const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); + if (!parsedHeader) { + throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); + } + const [, contentType, parsedBoundary] = parsedHeader; + if (parsedBoundary && boundary && parsedBoundary !== boundary) { + throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); + } + boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary; + if (boundary) { + assertValidBoundary(boundary); + } else { + boundary = generateBoundary(); + } + request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); + await buildRequestBody(request, request.multipartBody.parts, boundary); + request.multipartBody = void 0; + return next(request); + } + }; + } } }); -// node_modules/debug/src/index.js -var require_src = __commonJS({ - "node_modules/debug/src/index.js"(exports2, module2) { - if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { - module2.exports = require_browser(); - } else { - module2.exports = require_node(); +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js +var require_decompressResponsePolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.decompressResponsePolicyName = void 0; + exports2.decompressResponsePolicy = decompressResponsePolicy; + exports2.decompressResponsePolicyName = "decompressResponsePolicy"; + function decompressResponsePolicy() { + return { + name: exports2.decompressResponsePolicyName, + async sendRequest(request, next) { + if (request.method !== "HEAD") { + request.headers.set("Accept-Encoding", "gzip,deflate"); + } + return next(request); + } + }; } } }); -// node_modules/agent-base/dist/helpers.js -var require_helpers2 = __commonJS({ - "node_modules/agent-base/dist/helpers.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError2 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } - __setModuleDefault4(result, mod); - return result; }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.req = exports2.json = exports2.toBuffer = void 0; - var http = __importStar4(require("http")); - var https2 = __importStar4(require("https")); - async function toBuffer(stream) { - let length = 0; - const chunks = []; - for await (const chunk of stream) { - length += chunk.length; - chunks.push(chunk); - } - return Buffer.concat(chunks, length); - } - exports2.toBuffer = toBuffer; - async function json2(stream) { - const buf = await toBuffer(stream); - const str2 = buf.toString("utf8"); - try { - return JSON.parse(str2); - } catch (_err) { - const err = _err; - err.message += ` (input: ${str2})`; - throw err; - } - } - exports2.json = json2; - function req(url, opts = {}) { - const href = typeof url === "string" ? url : url.href; - const req2 = (href.startsWith("https:") ? https2 : http).request(url, opts); - const promise = new Promise((resolve2, reject) => { - req2.once("response", resolve2).once("error", reject).end(); - }); - req2.then = promise.then.bind(promise); - return req2; - } - exports2.req = req; + exports2.AbortError = AbortError; } }); -// node_modules/agent-base/dist/index.js -var require_dist2 = __commonJS({ - "node_modules/agent-base/dist/index.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs5 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Agent = void 0; - var net = __importStar4(require("net")); - var http = __importStar4(require("http")); - var https_1 = require("https"); - __exportStar4(require_helpers2(), exports2); - var INTERNAL = Symbol("AgentBaseInternalState"); - var Agent = class extends http.Agent { - constructor(opts) { - super(opts); - this[INTERNAL] = {}; - } - /** - * Determine whether this is an `http` or `https` request. - */ - isSecureEndpoint(options) { - if (options) { - if (typeof options.secureEndpoint === "boolean") { - return options.secureEndpoint; - } - if (typeof options.protocol === "string") { - return options.protocol === "https:"; - } - } - const { stack } = new Error(); - if (typeof stack !== "string") - return false; - return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); - } - // In order to support async signatures in `connect()` and Node's native - // connection pooling in `http.Agent`, the array of sockets for each origin - // has to be updated synchronously. This is so the length of the array is - // accurate when `addRequest()` is next called. We achieve this by creating a - // fake socket and adding it to `sockets[origin]` and incrementing - // `totalSocketCount`. - incrementSockets(name) { - if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { - return null; - } - if (!this.sockets[name]) { - this.sockets[name] = []; - } - const fakeSocket = new net.Socket({ writable: false }); - this.sockets[name].push(fakeSocket); - this.totalSocketCount++; - return fakeSocket; - } - decrementSockets(name, socket) { - if (!this.sockets[name] || socket === null) { - return; - } - const sockets = this.sockets[name]; - const index = sockets.indexOf(socket); - if (index !== -1) { - sockets.splice(index, 1); - this.totalSocketCount--; - if (sockets.length === 0) { - delete this.sockets[name]; - } - } - } - // In order to properly update the socket pool, we need to call `getName()` on - // the core `https.Agent` if it is a secureEndpoint. - getName(options) { - const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options); - if (secureEndpoint) { - return https_1.Agent.prototype.getName.call(this, options); - } - return super.getName(options); - } - createSocket(req, options, cb) { - const connectOpts = { - ...options, - secureEndpoint: this.isSecureEndpoint(options) - }; - const name = this.getName(connectOpts); - const fakeSocket = this.incrementSockets(name); - Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { - this.decrementSockets(name, fakeSocket); - if (socket instanceof http.Agent) { - try { - return socket.addRequest(req, connectOpts); - } catch (err) { - return cb(err); - } - } - this[INTERNAL].currentSocket = socket; - super.createSocket(req, options, cb); - }, (err) => { - this.decrementSockets(name, fakeSocket); - cb(err); - }); - } - createConnection() { - const socket = this[INTERNAL].currentSocket; - this[INTERNAL].currentSocket = void 0; - if (!socket) { - throw new Error("No socket was returned in the `connect()` function"); - } - return socket; - } - get defaultPort() { - return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); - } - set defaultPort(v) { - if (this[INTERNAL]) { - this[INTERNAL].defaultPort = v; - } - } - get protocol() { - return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); - } - set protocol(v) { - if (this[INTERNAL]) { - this[INTERNAL].protocol = v; - } - } - }; - exports2.Agent = Agent; + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError2(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); } }); -// node_modules/https-proxy-agent/dist/parse-proxy-response.js -var require_parse_proxy_response = __commonJS({ - "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js +var require_helpers = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) { "use strict"; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.parseProxyResponse = void 0; - var debug_1 = __importDefault4(require_src()); - var debug4 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); - function parseProxyResponse(socket) { + exports2.delay = delay; + exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber; + var abort_controller_1 = require_commonjs5(); + var StandardAbortMessage = "The operation was aborted."; + function delay(delayInMs, value, options) { return new Promise((resolve2, reject) => { - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once("readable", read); - } - function cleanup() { - socket.removeListener("end", onend); - socket.removeListener("error", onerror); - socket.removeListener("readable", read); - } - function onend() { - cleanup(); - debug4("onend"); - reject(new Error("Proxy connection ended before receiving CONNECT response")); - } - function onerror(err) { - cleanup(); - debug4("onerror %o", err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf("\r\n\r\n"); - if (endOfHeaders === -1) { - debug4("have not received end of HTTP headers yet..."); - read(); - return; - } - const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); - const firstLine = headerParts.shift(); - if (!firstLine) { - socket.destroy(); - return reject(new Error("No header received from proxy CONNECT response")); + let timer = void 0; + let onAborted = void 0; + const rejectOnAbort = () => { + return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); } - const firstLineParts = firstLine.split(" "); - const statusCode = +firstLineParts[1]; - const statusText = firstLineParts.slice(2).join(" "); - const headers = {}; - for (const header of headerParts) { - if (!header) - continue; - const firstColon = header.indexOf(":"); - if (firstColon === -1) { - socket.destroy(); - return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); - } - const key = header.slice(0, firstColon).toLowerCase(); - const value = header.slice(firstColon + 1).trimStart(); - const current = headers[key]; - if (typeof current === "string") { - headers[key] = [current, value]; - } else if (Array.isArray(current)) { - current.push(value); - } else { - headers[key] = value; - } + }; + onAborted = () => { + if (timer) { + clearTimeout(timer); } - debug4("got proxy server response: %o %o", firstLine, headers); - cleanup(); - resolve2({ - connect: { - statusCode, - statusText, - headers - }, - buffered - }); + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve2(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); } - socket.on("error", onerror); - socket.on("end", onend); - read(); }); } - exports2.parseProxyResponse = parseProxyResponse; + function parseHeaderValueAsNumber(response, headerName) { + const value = response.headers.get(headerName); + if (!value) + return; + const valueAsNum = Number(value); + if (Number.isNaN(valueAsNum)) + return; + return valueAsNum; + } } }); -// node_modules/https-proxy-agent/dist/index.js -var require_dist3 = __commonJS({ - "node_modules/https-proxy-agent/dist/index.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js +var require_throttlingRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) { "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpsProxyAgent = void 0; - var net = __importStar4(require("net")); - var tls = __importStar4(require("tls")); - var assert_1 = __importDefault4(require("assert")); - var debug_1 = __importDefault4(require_src()); - var agent_base_1 = require_dist2(); - var url_1 = require("url"); - var parse_proxy_response_1 = require_parse_proxy_response(); - var debug4 = (0, debug_1.default)("https-proxy-agent"); - var setServernameFromNonIpHost = (options) => { - if (options.servername === void 0 && options.host && !net.isIP(options.host)) { - return { - ...options, - servername: options.host - }; - } - return options; - }; - var HttpsProxyAgent = class extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.options = { path: void 0 }; - this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug4("Creating new HttpsProxyAgent instance: %o", this.proxy.href); - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); - const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; - this.connectOpts = { - // Attempt to negotiate http/1.1 for proxy servers that support http/2 - ALPNProtocols: ["http/1.1"], - ...opts ? omit(opts, "headers") : null, - host, - port - }; - } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - */ - async connect(req, opts) { - const { proxy } = this; - if (!opts.host) { - throw new TypeError('No "host" provided'); - } - let socket; - if (proxy.protocol === "https:") { - debug4("Creating `tls.Socket`: %o", this.connectOpts); - socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); - } else { - debug4("Creating `net.Socket`: %o", this.connectOpts); - socket = net.connect(this.connectOpts); - } - const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; - const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; - let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r -`; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; - } - headers.Host = `${host}:${opts.port}`; - if (!headers["Proxy-Connection"]) { - headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; - } - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r -`; - } - const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); - socket.write(`${payload}\r -`); - const { connect, buffered } = await proxyResponsePromise; - req.emit("proxyConnect", connect); - this.emit("proxyConnect", connect, req); - if (connect.statusCode === 200) { - req.once("socket", resume); - if (opts.secureEndpoint) { - debug4("Upgrading socket connection to TLS"); - return tls.connect({ - ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), - socket - }); + exports2.isThrottlingRetryResponse = isThrottlingRetryResponse; + exports2.throttlingRetryStrategy = throttlingRetryStrategy; + var helpers_js_1 = require_helpers(); + var RetryAfterHeader = "Retry-After"; + var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; + function getRetryAfterInMs(response) { + if (!(response && [429, 503].includes(response.status))) + return void 0; + try { + for (const header of AllRetryAfterHeaders) { + const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header); + if (retryAfterValue === 0 || retryAfterValue) { + const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; + return retryAfterValue * multiplyingFactor; } - return socket; } - socket.destroy(); - const fakeSocket = new net.Socket({ writable: false }); - fakeSocket.readable = true; - req.once("socket", (s) => { - debug4("Replaying proxy buffer for failed request"); - (0, assert_1.default)(s.listenerCount("data") > 0); - s.push(buffered); - s.push(null); - }); - return fakeSocket; + const retryAfterHeader = response.headers.get(RetryAfterHeader); + if (!retryAfterHeader) + return; + const date = Date.parse(retryAfterHeader); + const diff = date - Date.now(); + return Number.isFinite(diff) ? Math.max(0, diff) : void 0; + } catch (_a) { + return void 0; } - }; - HttpsProxyAgent.protocols = ["http", "https"]; - exports2.HttpsProxyAgent = HttpsProxyAgent; - function resume(socket) { - socket.resume(); } - function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; + function isThrottlingRetryResponse(response) { + return Number.isFinite(getRetryAfterInMs(response)); + } + function throttlingRetryStrategy() { + return { + name: "throttlingRetryStrategy", + retry({ response }) { + const retryAfterInMs = getRetryAfterInMs(response); + if (!Number.isFinite(retryAfterInMs)) { + return { skipStrategy: true }; + } + return { + retryAfterInMs + }; } - } - return ret; + }; } } }); -// node_modules/http-proxy-agent/dist/index.js -var require_dist4 = __commonJS({ - "node_modules/http-proxy-agent/dist/index.js"(exports2) { - "use strict"; - var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }); - var __importStar4 = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); - } - __setModuleDefault4(result, mod); - return result; - }; - var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpProxyAgent = void 0; - var net = __importStar4(require("net")); - var tls = __importStar4(require("tls")); - var debug_1 = __importDefault4(require_src()); - var events_1 = require("events"); - var agent_base_1 = require_dist2(); - var url_1 = require("url"); - var debug4 = (0, debug_1.default)("http-proxy-agent"); - var HttpProxyAgent = class extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug4("Creating new HttpProxyAgent instance: %o", this.proxy.href); - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); - const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; - this.connectOpts = { - ...opts ? omit(opts, "headers") : null, - host, - port - }; - } - addRequest(req, opts) { - req._header = null; - this.setRequestProps(req, opts); - super.addRequest(req, opts); - } - setRequestProps(req, opts) { - const { proxy } = this; - const protocol = opts.secureEndpoint ? "https:" : "http:"; - const hostname = req.getHeader("host") || "localhost"; - const base = `${protocol}//${hostname}`; - const url = new url_1.URL(req.path, base); - if (opts.port !== 80) { - url.port = String(opts.port); - } - req.path = String(url); - const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; - } - if (!headers["Proxy-Connection"]) { - headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; - } - for (const name of Object.keys(headers)) { - const value = headers[name]; - if (value) { - req.setHeader(name, value); - } - } - } - async connect(req, opts) { - req._header = null; - if (!req.path.includes("://")) { - this.setRequestProps(req, opts); - } - let first; - let endOfHeaders; - debug4("Regenerating stored HTTP header string for request"); - req._implicitHeader(); - if (req.outputData && req.outputData.length > 0) { - debug4("Patching connection write() output buffer with updated header"); - first = req.outputData[0].data; - endOfHeaders = first.indexOf("\r\n\r\n") + 4; - req.outputData[0].data = req._header + first.substring(endOfHeaders); - debug4("Output buffer: %o", req.outputData[0].data); - } - let socket; - if (this.proxy.protocol === "https:") { - debug4("Creating `tls.Socket`: %o", this.connectOpts); - socket = tls.connect(this.connectOpts); - } else { - debug4("Creating `net.Socket`: %o", this.connectOpts); - socket = net.connect(this.connectOpts); - } - await (0, events_1.once)(socket, "connect"); - return socket; - } - }; - HttpProxyAgent.protocols = ["http", "https"]; - exports2.HttpProxyAgent = HttpProxyAgent; - function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js -var require_proxyPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js +var require_exponentialRetryStrategy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; - exports2.loadNoProxy = loadNoProxy; - exports2.getDefaultProxySettings = getDefaultProxySettings; - exports2.proxyPolicy = proxyPolicy; - var https_proxy_agent_1 = require_dist3(); - var http_proxy_agent_1 = require_dist4(); - var log_js_1 = require_log(); - var HTTPS_PROXY = "HTTPS_PROXY"; - var HTTP_PROXY = "HTTP_PROXY"; - var ALL_PROXY = "ALL_PROXY"; - var NO_PROXY = "NO_PROXY"; - exports2.proxyPolicyName = "proxyPolicy"; - exports2.globalNoProxyList = []; - var noProxyListLoaded = false; - var globalBypassedMap = /* @__PURE__ */ new Map(); - function getEnvironmentValue(name) { - if (process.env[name]) { - return process.env[name]; - } else if (process.env[name.toLowerCase()]) { - return process.env[name.toLowerCase()]; - } - return void 0; - } - function loadEnvironmentProxyValue() { - if (!process) { - return void 0; - } - const httpsProxy = getEnvironmentValue(HTTPS_PROXY); - const allProxy = getEnvironmentValue(ALL_PROXY); - const httpProxy = getEnvironmentValue(HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; - } - function isBypassed(uri, noProxyList, bypassedMap) { - if (noProxyList.length === 0) { - return false; - } - const host = new URL(uri).hostname; - if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { - return bypassedMap.get(host); - } - let isBypassedFlag = false; - for (const pattern of noProxyList) { - if (pattern[0] === ".") { - if (host.endsWith(pattern)) { - isBypassedFlag = true; - } else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } + exports2.exponentialRetryStrategy = exponentialRetryStrategy; + exports2.isExponentialRetryResponse = isExponentialRetryResponse; + exports2.isSystemError = isSystemError; + var core_util_1 = require_commonjs4(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; + var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; + function exponentialRetryStrategy(options = {}) { + var _a, _b; + const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; + const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + let retryAfterInMs = retryInterval; + return { + name: "exponentialRetryStrategy", + retry({ retryCount, response, responseError }) { + const matchedSystemError = isSystemError(responseError); + const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; + const isExponential = isExponentialRetryResponse(response); + const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; + const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential); + if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { + return { skipStrategy: true }; } - } else { - if (host === pattern) { - isBypassedFlag = true; + if (responseError && !matchedSystemError && !isExponential) { + return { errorToThrow: responseError }; } + const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); + const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); + retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2); + return { retryAfterInMs }; } - } - bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); - return isBypassedFlag; - } - function loadNoProxy() { - const noProxy = getEnvironmentValue(NO_PROXY); - noProxyListLoaded = true; - if (noProxy) { - return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); - } - return []; - } - function getDefaultProxySettings(proxyUrl) { - if (!proxyUrl) { - proxyUrl = loadEnvironmentProxyValue(); - if (!proxyUrl) { - return void 0; - } - } - const parsedUrl = new URL(proxyUrl); - const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; - return { - host: schema2 + parsedUrl.hostname, - port: Number.parseInt(parsedUrl.port || "80"), - username: parsedUrl.username, - password: parsedUrl.password }; } - function getDefaultProxySettingsInternal() { - const envProxy = loadEnvironmentProxyValue(); - return envProxy ? new URL(envProxy) : void 0; - } - function getUrlFromProxySettings(settings) { - let parsedProxyUrl; - try { - parsedProxyUrl = new URL(settings.host); - } catch (_a) { - throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); - } - parsedProxyUrl.port = String(settings.port); - if (settings.username) { - parsedProxyUrl.username = settings.username; - } - if (settings.password) { - parsedProxyUrl.password = settings.password; - } - return parsedProxyUrl; - } - function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { - if (request.agent) { - return; - } - const url = new URL(request.url); - const isInsecure = url.protocol !== "https:"; - if (request.tlsSettings) { - log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); - } - const headers = request.headers.toJSON(); - if (isInsecure) { - if (!cachedAgents.httpProxyAgent) { - cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpProxyAgent; - } else { - if (!cachedAgents.httpsProxyAgent) { - cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpsProxyAgent; - } + function isExponentialRetryResponse(response) { + return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); } - function proxyPolicy(proxySettings, options) { - if (!noProxyListLoaded) { - exports2.globalNoProxyList.push(...loadNoProxy()); + function isSystemError(err) { + if (!err) { + return false; } - const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); - const cachedAgents = {}; - return { - name: exports2.proxyPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) { - setProxyAgentOnRequest(request, cachedAgents, defaultProxy); - } else if (request.proxySettings) { - setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); - } - return next(request); - } - }; + return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js -var require_setClientRequestIdPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js +var require_retryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.setClientRequestIdPolicyName = void 0; - exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; - exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; - function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + exports2.retryPolicy = retryPolicy; + var helpers_js_1 = require_helpers(); + var logger_1 = require_dist(); + var abort_controller_1 = require_commonjs5(); + var constants_js_1 = require_constants7(); + var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); + var retryPolicyName = "retryPolicy"; + function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { + const logger = options.logger || retryPolicyLogger; return { - name: exports2.setClientRequestIdPolicyName, + name: retryPolicyName, async sendRequest(request, next) { - if (!request.headers.has(requestIdHeaderName)) { - request.headers.set(requestIdHeaderName, request.requestId); + var _a, _b; + let response; + let responseError; + let retryCount = -1; + retryRequest: while (true) { + retryCount += 1; + response = void 0; + responseError = void 0; + try { + logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); + response = await next(request); + logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); + } catch (e) { + logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); + responseError = e; + if (!e || responseError.name !== "RestError") { + throw e; + } + response = responseError.response; + } + if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + logger.error(`Retry ${retryCount}: Request aborted.`); + const abortError = new abort_controller_1.AbortError(); + throw abortError; + } + if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { + logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + if (responseError) { + throw responseError; + } else if (response) { + return response; + } else { + throw new Error("Maximum retries reached with no response or error to throw"); + } + } + logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + strategiesLoop: for (const strategy of strategies) { + const strategyLogger = strategy.logger || retryPolicyLogger; + strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); + const modifiers = strategy.retry({ + retryCount, + response, + responseError + }); + if (modifiers.skipStrategy) { + strategyLogger.info(`Retry ${retryCount}: Skipped.`); + continue strategiesLoop; + } + const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; + if (errorToThrow) { + strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); + throw errorToThrow; + } + if (retryAfterInMs || retryAfterInMs === 0) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); + await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); + continue retryRequest; + } + if (redirectTo) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); + request.url = redirectTo; + continue retryRequest; + } + } + if (responseError) { + logger.info(`None of the retry strategies could work with the received error. Throwing it.`); + throw responseError; + } + if (response) { + logger.info(`None of the retry strategies could work with the received response. Returning it.`); + return response; + } } - return next(request); } }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js -var require_tlsPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js +var require_defaultRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tlsPolicyName = void 0; - exports2.tlsPolicy = tlsPolicy; - exports2.tlsPolicyName = "tlsPolicy"; - function tlsPolicy(tlsSettings) { + exports2.defaultRetryPolicyName = void 0; + exports2.defaultRetryPolicy = defaultRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants7(); + exports2.defaultRetryPolicyName = "defaultRetryPolicy"; + function defaultRetryPolicy(options = {}) { + var _a; return { - name: exports2.tlsPolicyName, - sendRequest: async (req, next) => { - if (!req.tlsSettings) { - req.tlsSettings = tlsSettings; - } - return next(req); - } + name: exports2.defaultRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest }; } } }); -// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js -var require_tracingContext = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js +var require_httpHeaders = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0; - exports2.knownContextKeys = { - span: Symbol.for("@azure/core-tracing span"), - namespace: Symbol.for("@azure/core-tracing namespace") - }; - function createTracingContext(options = {}) { - let context2 = new TracingContextImpl(options.parentContext); - if (options.span) { - context2 = context2.setValue(exports2.knownContextKeys.span, options.span); - } - if (options.namespace) { - context2 = context2.setValue(exports2.knownContextKeys.namespace, options.namespace); + exports2.createHttpHeaders = createHttpHeaders; + function normalizeName(name) { + return name.toLowerCase(); + } + function* headerIterator(map2) { + for (const entry of map2.values()) { + yield [entry.name, entry.value]; } - return context2; } - exports2.createTracingContext = createTracingContext; - var TracingContextImpl = class _TracingContextImpl { - constructor(initialContext) { - this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); + var HttpHeadersImpl = class { + constructor(rawHeaders) { + this._headersMap = /* @__PURE__ */ new Map(); + if (rawHeaders) { + for (const headerName of Object.keys(rawHeaders)) { + this.set(headerName, rawHeaders[headerName]); + } + } } - setValue(key, value) { - const newContext = new _TracingContextImpl(this); - newContext._contextMap.set(key, value); - return newContext; + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param name - The name of the header to set. This value is case-insensitive. + * @param value - The value of the header to set. + */ + set(name, value) { + this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); } - getValue(key) { - return this._contextMap.get(key); + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param name - The name of the header. This value is case-insensitive. + */ + get(name) { + var _a; + return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; } - deleteValue(key) { - const newContext = new _TracingContextImpl(this); - newContext._contextMap.delete(key); - return newContext; + /** + * Get whether or not this header collection contains a header entry for the provided header name. + * @param name - The name of the header to set. This value is case-insensitive. + */ + has(name) { + return this._headersMap.has(normalizeName(name)); } - }; - exports2.TracingContextImpl = TracingContextImpl; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/state.js -var require_state = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.state = void 0; - exports2.state = { - instrumenterImplementation: void 0 - }; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js -var require_instrumenter = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0; - var tracingContext_js_1 = require_tracingContext(); - var state_js_1 = require_state(); - function createDefaultTracingSpan() { - return { - end: () => { - }, - isRecording: () => false, - recordException: () => { - }, - setAttribute: () => { - }, - setStatus: () => { - } - }; - } - exports2.createDefaultTracingSpan = createDefaultTracingSpan; - function createDefaultInstrumenter() { - return { - createRequestHeaders: () => { - return {}; - }, - parseTraceparentHeader: () => { - return void 0; - }, - startSpan: (_name, spanOptions) => { - return { - span: createDefaultTracingSpan(), - tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }) - }; - }, - withContext(_context, callback, ...callbackArgs) { - return callback(...callbackArgs); - } - }; - } - exports2.createDefaultInstrumenter = createDefaultInstrumenter; - function useInstrumenter(instrumenter) { - state_js_1.state.instrumenterImplementation = instrumenter; - } - exports2.useInstrumenter = useInstrumenter; - function getInstrumenter() { - if (!state_js_1.state.instrumenterImplementation) { - state_js_1.state.instrumenterImplementation = createDefaultInstrumenter(); - } - return state_js_1.state.instrumenterImplementation; - } - exports2.getInstrumenter = getInstrumenter; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js -var require_tracingClient = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTracingClient = void 0; - var instrumenter_js_1 = require_instrumenter(); - var tracingContext_js_1 = require_tracingContext(); - function createTracingClient(options) { - const { namespace, packageName, packageVersion } = options; - function startSpan(name, operationOptions, spanOptions) { - var _a; - const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); - let tracingContext = startSpanResult.tracingContext; - const span = startSpanResult.span; - if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { - tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace); - } - span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); - const updatedOptions = Object.assign({}, operationOptions, { - tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }) - }); - return { - span, - updatedOptions - }; + /** + * Remove the header with the provided headerName. + * @param name - The name of the header to remove. + */ + delete(name) { + this._headersMap.delete(normalizeName(name)); } - async function withSpan(name, operationOptions, callback, spanOptions) { - const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); - try { - const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); - span.setStatus({ status: "success" }); - return result; - } catch (err) { - span.setStatus({ status: "error", error: err }); - throw err; - } finally { - span.end(); + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJSON(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const entry of this._headersMap.values()) { + result[entry.name] = entry.value; + } + } else { + for (const [normalizedName, entry] of this._headersMap) { + result[normalizedName] = entry.value; + } } + return result; } - function withContext(context2, callback, ...callbackArgs) { - return (0, instrumenter_js_1.getInstrumenter)().withContext(context2, callback, ...callbackArgs); - } - function parseTraceparentHeader(traceparentHeader) { - return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader); - } - function createRequestHeaders(tracingContext) { - return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext); - } - return { - startSpan, - withSpan, - withContext, - parseTraceparentHeader, - createRequestHeaders - }; - } - exports2.createTracingClient = createTracingClient; - } -}); - -// node_modules/@azure/core-tracing/dist/commonjs/index.js -var require_commonjs6 = __commonJS({ - "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createTracingClient = exports2.useInstrumenter = void 0; - var instrumenter_js_1 = require_instrumenter(); - Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() { - return instrumenter_js_1.useInstrumenter; - } }); - var tracingClient_js_1 = require_tracingClient(); - Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() { - return tracingClient_js_1.createTracingClient; - } }); - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js -var require_inspect = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.custom = void 0; - var node_util_1 = require("node:util"); - exports2.custom = node_util_1.inspect.custom; - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js -var require_restError = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RestError = void 0; - exports2.isRestError = isRestError; - var core_util_1 = require_commonjs4(); - var inspect_js_1 = require_inspect(); - var sanitizer_js_1 = require_sanitizer(); - var errorSanitizer = new sanitizer_js_1.Sanitizer(); - var RestError = class _RestError extends Error { - constructor(message, options = {}) { - super(message); - this.name = "RestError"; - this.code = options.code; - this.statusCode = options.statusCode; - Object.defineProperty(this, "request", { value: options.request, enumerable: false }); - Object.defineProperty(this, "response", { value: options.response, enumerable: false }); - Object.setPrototypeOf(this, _RestError.prototype); + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJSON({ preserveCase: true })); } /** - * Logging method for util.inspect in Node + * Iterate over tuples of header [name, value] pairs. */ - [inspect_js_1.custom]() { - return `RestError: ${this.message} - ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; + [Symbol.iterator]() { + return headerIterator(this._headersMap); } }; - exports2.RestError = RestError; - RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; - RestError.PARSE_ERROR = "PARSE_ERROR"; - function isRestError(e) { - if (e instanceof RestError) { - return true; - } - return (0, core_util_1.isError)(e) && e.name === "RestError"; + function createHttpHeaders(rawHeaders) { + return new HttpHeadersImpl(rawHeaders); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js -var require_tracingPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js +var require_formDataPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.tracingPolicyName = void 0; - exports2.tracingPolicy = tracingPolicy; - var core_tracing_1 = require_commonjs6(); - var constants_js_1 = require_constants7(); - var userAgent_js_1 = require_userAgent(); - var log_js_1 = require_log(); + exports2.formDataPolicyName = void 0; + exports2.formDataPolicy = formDataPolicy; var core_util_1 = require_commonjs4(); - var restError_js_1 = require_restError(); - var sanitizer_js_1 = require_sanitizer(); - exports2.tracingPolicyName = "tracingPolicy"; - function tracingPolicy(options = {}) { - const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); - const sanitizer = new sanitizer_js_1.Sanitizer({ - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters - }); - const tracingClient = tryCreateTracingClient(); + var httpHeaders_js_1 = require_httpHeaders(); + exports2.formDataPolicyName = "formDataPolicy"; + function formDataToFormDataMap(formData) { + var _a; + const formDataMap = {}; + for (const [key, value] of formData.entries()) { + (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = []; + formDataMap[key].push(value); + } + return formDataMap; + } + function formDataPolicy() { return { - name: exports2.tracingPolicyName, + name: exports2.formDataPolicyName, async sendRequest(request, next) { - var _a; - if (!tracingClient) { - return next(request); - } - const userAgent = await userAgentPromise; - const spanAttributes = { - "http.url": sanitizer.sanitizeUrl(request.url), - "http.method": request.method, - "http.user_agent": userAgent, - requestId: request.requestId - }; - if (userAgent) { - spanAttributes["http.user_agent"] = userAgent; - } - const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; - if (!span || !tracingContext) { - return next(request); + if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { + request.formData = formDataToFormDataMap(request.body); + request.body = void 0; } - try { - const response = await tracingClient.withContext(tracingContext, next, request); - tryProcessResponse(span, response); - return response; - } catch (err) { - tryProcessError(span, err); - throw err; + if (request.formData) { + const contentType = request.headers.get("Content-Type"); + if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { + request.body = wwwFormUrlEncode(request.formData); + } else { + await prepareFormData(request.formData, request); + } + request.formData = void 0; } + return next(request); } }; } - function tryCreateTracingClient() { - try { - return (0, core_tracing_1.createTracingClient)({ - namespace: "", - packageName: "@azure/core-rest-pipeline", - packageVersion: constants_js_1.SDK_VERSION - }); - } catch (e) { - log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); - return void 0; - } - } - function tryCreateSpan(tracingClient, request, spanAttributes) { - try { - const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { - spanKind: "client", - spanAttributes - }); - if (!span.isRecording()) { - span.end(); - return void 0; - } - const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); - for (const [key, value] of Object.entries(headers)) { - request.headers.set(key, value); + function wwwFormUrlEncode(formData) { + const urlSearchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(formData)) { + if (Array.isArray(value)) { + for (const subValue of value) { + urlSearchParams.append(key, subValue.toString()); + } + } else { + urlSearchParams.append(key, value.toString()); } - return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; - } catch (e) { - log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); - return void 0; } + return urlSearchParams.toString(); } - function tryProcessError(span, error4) { - try { - span.setStatus({ - status: "error", - error: (0, core_util_1.isError)(error4) ? error4 : void 0 - }); - if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) { - span.setAttribute("http.status_code", error4.statusCode); - } - span.end(); - } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); + async function prepareFormData(formData, request) { + const contentType = request.headers.get("Content-Type"); + if (contentType && !contentType.startsWith("multipart/form-data")) { + return; } - } - function tryProcessResponse(span, response) { - try { - span.setAttribute("http.status_code", response.status); - const serviceRequestId = response.headers.get("x-ms-request-id"); - if (serviceRequestId) { - span.setAttribute("serviceRequestId", serviceRequestId); + request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); + const parts = []; + for (const [fieldName, values] of Object.entries(formData)) { + for (const value of Array.isArray(values) ? values : [values]) { + if (typeof value === "string") { + parts.push({ + headers: (0, httpHeaders_js_1.createHttpHeaders)({ + "Content-Disposition": `form-data; name="${fieldName}"` + }), + body: (0, core_util_1.stringToUint8Array)(value, "utf-8") + }); + } else if (value === void 0 || value === null || typeof value !== "object") { + throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); + } else { + const fileName = value.name || "blob"; + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); + headers.set("Content-Type", value.type || "application/octet-stream"); + parts.push({ + headers, + body: value + }); + } } - span.setStatus({ - status: "success" - }); - span.end(); - } catch (e) { - log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); } + request.multipartBody = { parts }; } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js -var require_createPipelineFromOptions = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineFromOptions = createPipelineFromOptions; - var logPolicy_js_1 = require_logPolicy(); - var pipeline_js_1 = require_pipeline(); - var redirectPolicy_js_1 = require_redirectPolicy(); - var userAgentPolicy_js_1 = require_userAgentPolicy(); - var multipartPolicy_js_1 = require_multipartPolicy(); - var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); - var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); - var formDataPolicy_js_1 = require_formDataPolicy(); - var core_util_1 = require_commonjs4(); - var proxyPolicy_js_1 = require_proxyPolicy(); - var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); - var tlsPolicy_js_1 = require_tlsPolicy(); - var tracingPolicy_js_1 = require_tracingPolicy(); - function createPipelineFromOptions(options) { - var _a; - const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); - if (core_util_1.isNodeLike) { - if (options.tlsOptions) { - pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); - } - pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); - pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); +// node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/ms/index.js"(exports2, module2) { + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module2.exports = function(val2, options) { + options = options || {}; + var type2 = typeof val2; + if (type2 === "string" && val2.length > 0) { + return parse(val2); + } else if (type2 === "number" && isFinite(val2)) { + return options.long ? fmtLong(val2) : fmtShort(val2); } - pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); - pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); - pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); - pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); - pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); - pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { - afterPhase: "Retry" - }); - if (core_util_1.isNodeLike) { - pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2) + ); + }; + function parse(str2) { + str2 = String(str2); + if (str2.length > 100) { + return; } - pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); - return pipeline; + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str2 + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type2 = (match[2] || "ms").toLowerCase(); + switch (type2) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } + } + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; + } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); } } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js -var require_nodeHttpClient = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getBodyLength = getBodyLength; - exports2.createNodeHttpClient = createNodeHttpClient; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var http = tslib_1.__importStar(require("node:http")); - var https2 = tslib_1.__importStar(require("node:https")); - var zlib = tslib_1.__importStar(require("node:zlib")); - var node_stream_1 = require("node:stream"); - var abort_controller_1 = require_commonjs5(); - var httpHeaders_js_1 = require_httpHeaders(); - var restError_js_1 = require_restError(); - var log_js_1 = require_log(); - var DEFAULT_TLS_SETTINGS = {}; - function isReadableStream(body) { - return body && typeof body.pipe === "function"; - } - function isStreamComplete(stream) { - return new Promise((resolve2) => { - const handler = () => { - resolve2(); - stream.removeListener("close", handler); - stream.removeListener("end", handler); - stream.removeListener("error", handler); - }; - stream.on("close", handler); - stream.on("end", handler); - stream.on("error", handler); +// node_modules/debug/src/common.js +var require_common = __commonJS({ + "node_modules/debug/src/common.js"(exports2, module2) { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce3; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; }); - } - function isArrayBuffer(body) { - return body && typeof body.byteLength === "number"; - } - var ReportTransform = class extends node_stream_1.Transform { - // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type - _transform(chunk, _encoding, callback) { - this.push(chunk); - this.loadedBytes += chunk.length; - try { - this.progressCallback({ loadedBytes: this.loadedBytes }); - callback(); - } catch (e) { - callback(e); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } - constructor(progressCallback) { - super(); - this.loadedBytes = 0; - this.progressCallback = progressCallback; - } - }; - var NodeHttpClient = class { - constructor() { - this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); - } - /** - * Makes a request over an underlying transport layer and returns the response. - * @param request - The request to be made. - */ - async sendRequest(request) { - var _a, _b, _c; - const abortController = new AbortController(); - let abortListener; - if (request.abortSignal) { - if (request.abortSignal.aborted) { - throw new abort_controller_1.AbortError("The operation was aborted."); + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug4(...args) { + if (!debug4.enabled) { + return; } - abortListener = (event) => { - if (event.type === "abort") { - abortController.abort(); - } - }; - request.abortSignal.addEventListener("abort", abortListener); - } - if (request.timeout > 0) { - setTimeout(() => { - abortController.abort(); - }, request.timeout); - } - const acceptEncoding = request.headers.get("Accept-Encoding"); - const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); - let body = typeof request.body === "function" ? request.body() : request.body; - if (body && !request.headers.has("Content-Length")) { - const bodyLength = getBodyLength(body); - if (bodyLength !== null) { - request.headers.set("Content-Length", bodyLength); + const self2 = debug4; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); } - } - let responseStream; - try { - if (body && request.onUploadProgress) { - const onUploadProgress = request.onUploadProgress; - const uploadReportStream = new ReportTransform(onUploadProgress); - uploadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in upload progress", e); - }); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } else { - uploadReportStream.end(body); + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; } - body = uploadReportStream; - } - const res = await this.makeRequest(request, abortController, body); - const headers = getResponseHeaders(res); - const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; - const response = { - status, - headers, - request - }; - if (request.method === "HEAD") { - res.resume(); - return response; - } - responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; - const onDownloadProgress = request.onDownloadProgress; - if (onDownloadProgress) { - const downloadReportStream = new ReportTransform(onDownloadProgress); - downloadReportStream.on("error", (e) => { - log_js_1.logger.error("Error in download progress", e); - }); - responseStream.pipe(downloadReportStream); - responseStream = downloadReportStream; - } - if ( - // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code - ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status)) - ) { - response.readableStreamBody = responseStream; - } else { - response.bodyAsText = await streamToText(responseStream); - } - return response; - } finally { - if (request.abortSignal && abortListener) { - let uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val2 = args[index]; + match = formatter.call(self2, val2); + args.splice(index, 1); + index--; } - let downloadStreamDone = Promise.resolve(); - if (isReadableStream(responseStream)) { - downloadStreamDone = isStreamComplete(responseStream); + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug4.namespace = namespace; + debug4.useColors = createDebug.useColors(); + debug4.color = createDebug.selectColor(namespace); + debug4.extend = extend3; + debug4.destroy = createDebug.destroy; + Object.defineProperty(debug4, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; } - Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { - var _a2; - if (abortListener) { - (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener); - } - }).catch((e) => { - log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); - }); + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug4); } + return debug4; } - makeRequest(request, abortController, body) { - var _a; - const url = new URL(request.url); - const isInsecure = url.protocol !== "https:"; - if (isInsecure && !request.allowInsecureConnection) { - throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + function extend3(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } } - const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); - const options = { - agent, - hostname: url.hostname, - path: `${url.pathname}${url.search}`, - port: url.port, - method: request.method, - headers: request.headers.toJSON({ preserveCase: true }) - }; - return new Promise((resolve2, reject) => { - const req = isInsecure ? http.request(options, resolve2) : https2.request(options, resolve2); - req.once("error", (err) => { - var _a2; - reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); - }); - abortController.signal.addEventListener("abort", () => { - const abortError = new abort_controller_1.AbortError("The operation was aborted."); - req.destroy(abortError); - reject(abortError); - }); - if (body && isReadableStream(body)) { - body.pipe(req); - } else if (body) { - if (typeof body === "string" || Buffer.isBuffer(body)) { - req.end(body); - } else if (isArrayBuffer(body)) { - req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; } else { - log_js_1.logger.error("Unrecognized body type", body); - reject(new restError_js_1.RestError("Unrecognized body type")); + searchIndex++; + templateIndex++; } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; } else { - req.end(); - } - }); - } - getOrCreateAgent(request, isInsecure) { - var _a; - const disableKeepAlive = request.disableKeepAlive; - if (isInsecure) { - if (disableKeepAlive) { - return http.globalAgent; - } - if (!this.cachedHttpAgent) { - this.cachedHttpAgent = new http.Agent({ keepAlive: true }); - } - return this.cachedHttpAgent; - } else { - if (disableKeepAlive && !request.tlsSettings) { - return https2.globalAgent; - } - const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; - let agent = this.cachedHttpsAgents.get(tlsSettings); - if (agent && agent.options.keepAlive === !disableKeepAlive) { - return agent; + return false; } - log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); - agent = new https2.Agent(Object.assign({ - // keepAlive is true if disableKeepAlive is false. - keepAlive: !disableKeepAlive - }, tlsSettings)); - this.cachedHttpsAgents.set(tlsSettings, agent); - return agent; } - } - }; - function getResponseHeaders(res) { - const headers = (0, httpHeaders_js_1.createHttpHeaders)(); - for (const header of Object.keys(res.headers)) { - const value = res.headers[header]; - if (Array.isArray(value)) { - if (value.length > 0) { - headers.set(header, value[0]); - } - } else if (value) { - headers.set(header, value); + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; } + return templateIndex === template.length; } - return headers; - } - function getDecodedResponseStream(stream, headers) { - const contentEncoding = headers.get("Content-Encoding"); - if (contentEncoding === "gzip") { - const unzip = zlib.createGunzip(); - stream.pipe(unzip); - return unzip; - } else if (contentEncoding === "deflate") { - const inflate = zlib.createInflate(); - stream.pipe(inflate); - return inflate; + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; } - return stream; - } - function streamToText(stream) { - return new Promise((resolve2, reject) => { - const buffer = []; - stream.on("data", (chunk) => { - if (Buffer.isBuffer(chunk)) { - buffer.push(chunk); - } else { - buffer.push(Buffer.from(chunk)); + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; } - }); - stream.on("end", () => { - resolve2(Buffer.concat(buffer).toString("utf8")); - }); - stream.on("error", (e) => { - if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { - reject(e); - } else { - reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { - code: restError_js_1.RestError.PARSE_ERROR - })); + } + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; } - }); - }); - } - function getBodyLength(body) { - if (!body) { - return 0; - } else if (Buffer.isBuffer(body)) { - return body.length; - } else if (isReadableStream(body)) { - return null; - } else if (isArrayBuffer(body)) { - return body.byteLength; - } else if (typeof body === "string") { - return Buffer.from(body).length; - } else { - return null; + } + return false; } - } - function createNodeHttpClient() { - return new NodeHttpClient(); - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js -var require_defaultHttpClient = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createDefaultHttpClient = createDefaultHttpClient; - var nodeHttpClient_js_1 = require_nodeHttpClient(); - function createDefaultHttpClient() { - return (0, nodeHttpClient_js_1.createNodeHttpClient)(); - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js -var require_pipelineRequest = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createPipelineRequest = createPipelineRequest; - var httpHeaders_js_1 = require_httpHeaders(); - var core_util_1 = require_commonjs4(); - var PipelineRequestImpl = class { - constructor(options) { - var _a, _b, _c, _d, _e, _f, _g; - this.url = options.url; - this.body = options.body; - this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); - this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; - this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; - this.multipartBody = options.multipartBody; - this.formData = options.formData; - this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; - this.proxySettings = options.proxySettings; - this.streamResponseStatusCodes = options.streamResponseStatusCodes; - this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; - this.abortSignal = options.abortSignal; - this.tracingOptions = options.tracingOptions; - this.onUploadProgress = options.onUploadProgress; - this.onDownloadProgress = options.onDownloadProgress; - this.requestId = options.requestId || (0, core_util_1.randomUUID)(); - this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; - this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; + function coerce3(val2) { + if (val2 instanceof Error) { + return val2.stack || val2.message; + } + return val2; } - }; - function createPipelineRequest(options) { - return new PipelineRequestImpl(options); - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js -var require_exponentialRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.exponentialRetryPolicyName = void 0; - exports2.exponentialRetryPolicy = exponentialRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants7(); - exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; - function exponentialRetryPolicy(options = {}) { - var _a; - return (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })) - ], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }); + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; } + module2.exports = setup; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js -var require_systemErrorRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.systemErrorRetryPolicyName = void 0; - exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; - var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants7(); - exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; - function systemErrorRetryPolicy(options = {}) { - var _a; - return { - name: exports2.systemErrorRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([ - (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })) - ], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js -var require_throttlingRetryPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.throttlingRetryPolicyName = void 0; - exports2.throttlingRetryPolicy = throttlingRetryPolicy; - var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); - var retryPolicy_js_1 = require_retryPolicy(); - var constants_js_1 = require_constants7(); - exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; - function throttlingRetryPolicy(options = {}) { - var _a; - return { - name: exports2.throttlingRetryPolicyName, - sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT - }).sendRequest - }; - } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js -var require_tokenCycler = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DEFAULT_CYCLER_OPTIONS = void 0; - exports2.createTokenCycler = createTokenCycler; - var helpers_js_1 = require_helpers(); - exports2.DEFAULT_CYCLER_OPTIONS = { - forcedRefreshWindowInMs: 1e3, - // Force waiting for a refresh 1s before the token expires - retryIntervalInMs: 3e3, - // Allow refresh attempts every 3s - refreshWindowInMs: 1e3 * 60 * 2 - // Start refreshing 2m before expiry - }; - async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { - async function tryGetAccessToken() { - if (Date.now() < refreshTimeout) { - try { - return await getAccessToken(); - } catch (_a) { - return null; - } - } else { - const finalToken = await getAccessToken(); - if (finalToken === null) { - throw new Error("Failed to refresh access token."); - } - return finalToken; +// node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/debug/src/browser.js"(exports2, module2) { + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.storage = localstorage(); + exports2.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } + }; + })(); + exports2.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; } - let token = await tryGetAccessToken(); - while (token === null) { - await (0, helpers_js_1.delay)(retryIntervalInMs); - token = await tryGetAccessToken(); + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; } - return token; + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } - function createTokenCycler(credential, tokenCyclerOptions) { - let refreshWorker = null; - let token = null; - let tenantId; - const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); - const cycler = { - /** - * Produces true if a refresh job is currently in progress. - */ - get isRefreshing() { - return refreshWorker !== null; - }, - /** - * Produces true if the cycler SHOULD refresh (we are within the refresh - * window and not already refreshing) - */ - get shouldRefresh() { - var _a; - if (cycler.isRefreshing) { - return false; - } - if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { - return true; - } - return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); - }, - /** - * Produces true if the cycler MUST refresh (null or nearly-expired - * token). - */ - get mustRefresh() { - return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); - } - }; - function refresh(scopes, getTokenOptions) { - var _a; - if (!cycler.isRefreshing) { - const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); - refreshWorker = beginRefresh( - tryGetAccessToken, - options.retryIntervalInMs, - // If we don't have a token, then we should timeout immediately - (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now() - ).then((_token) => { - refreshWorker = null; - token = _token; - tenantId = getTokenOptions.tenantId; - return token; - }).catch((reason) => { - refreshWorker = null; - token = null; - tenantId = void 0; - throw reason; - }); - } - return refreshWorker; + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); + if (!this.useColors) { + return; } - return async (scopes, tokenOptions) => { - const hasClaimChallenge = Boolean(tokenOptions.claims); - const tenantIdChanged = tenantId !== tokenOptions.tenantId; - if (hasClaimChallenge) { - token = null; - } - const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; - if (mustRefresh) { - return refresh(scopes, tokenOptions); + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; } - if (cycler.shouldRefresh) { - refresh(scopes, tokenOptions); + index++; + if (match === "%c") { + lastC = index; } - return token; - }; + }); + args.splice(lastC, 0, c); } - } -}); - -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js -var require_bearerTokenAuthenticationPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bearerTokenAuthenticationPolicyName = void 0; - exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log(); - exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; - async function defaultAuthorizeRequest(options) { - const { scopes, getAccessToken, request } = options; - const getTokenOptions = { - abortSignal: request.abortSignal, - tracingOptions: request.tracingOptions - }; - const accessToken = await getAccessToken(scopes, getTokenOptions); - if (accessToken) { - options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); + exports2.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports2.storage.setItem("debug", namespaces); + } else { + exports2.storage.removeItem("debug"); + } + } catch (error4) { } } - function getChallenge(response) { - const challenge = response.headers.get("WWW-Authenticate"); - if (response.status === 401 && challenge) { - return challenge; + function load2() { + let r; + try { + r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); + } catch (error4) { } - return; + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; } - function bearerTokenAuthenticationPolicy(options) { - var _a; - const { credential, scopes, challengeCallbacks } = options; - const logger = options.logger || log_js_1.logger; - const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); - const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( - credential - /* , options */ - ) : () => Promise.resolve(null); - return { - name: exports2.bearerTokenAuthenticationPolicyName, - /** - * If there's no challenge parameter: - * - It will try to retrieve the token using the cache, or the credential's getToken. - * - Then it will try the next policy with or without the retrieved token. - * - * It uses the challenge parameters to: - * - Skip a first attempt to get the token from the credential if there's no cached token, - * since it expects the token to be retrievable only after the challenge. - * - Prepare the outgoing request if the `prepareRequest` method has been provided. - * - Send an initial request to receive the challenge if it fails. - * - Process a challenge if the response contains it. - * - Retrieve a token with the challenge information, then re-send the request. - */ - async sendRequest(request, next) { - if (!request.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); - } - await callbacks.authorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - getAccessToken, - logger - }); - let response; - let error4; - try { - response = await next(request); - } catch (err) { - error4 = err; - response = err.response; - } - if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) { - const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - response, - getAccessToken, - logger - }); - if (shouldSendRequest) { - return next(request); - } - } - if (error4) { - throw error4; - } else { - return response; - } - } - }; + function localstorage() { + try { + return localStorage; + } catch (error4) { + } } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error4) { + return "[UnexpectedJSONParseError]: " + error4.message; + } + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js -var require_ndJsonPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { +// node_modules/has-flag/index.js +var require_has_flag = __commonJS({ + "node_modules/has-flag/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ndJsonPolicyName = void 0; - exports2.ndJsonPolicy = ndJsonPolicy; - exports2.ndJsonPolicyName = "ndJsonPolicy"; - function ndJsonPolicy() { - return { - name: exports2.ndJsonPolicyName, - async sendRequest(request, next) { - if (typeof request.body === "string" && request.body.startsWith("[")) { - const body = JSON.parse(request.body); - if (Array.isArray(body)) { - request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); - } - } - return next(request); - } - }; - } + module2.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js -var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { +// node_modules/supports-color/index.js +var require_supports_color = __commonJS({ + "node_modules/supports-color/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; - exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; - var tokenCycler_js_1 = require_tokenCycler(); - var log_js_1 = require_log(); - exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; - var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; - async function sendAuthorizeRequest(options) { - var _a, _b; - const { scopes, getAccessToken, request } = options; - const getTokenOptions = { - abortSignal: request.abortSignal, - tracingOptions: request.tracingOptions - }; - return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; + var os = require("os"); + var tty = require("tty"); + var hasFlag = require_has_flag(); + var { env } = process; + var forceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { + forceColor = 0; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = 1; } - function auxiliaryAuthenticationHeaderPolicy(options) { - const { credentials, scopes } = options; - const logger = options.logger || log_js_1.logger; - const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + forceColor = 1; + } else if (env.FORCE_COLOR === "false") { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } return { - name: exports2.auxiliaryAuthenticationHeaderPolicyName, - async sendRequest(request, next) { - if (!request.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); - } - if (!credentials || credentials.length === 0) { - logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); - return next(request); - } - const tokenPromises = []; - for (const credential of credentials) { - let getAccessToken = tokenCyclerMap.get(credential); - if (!getAccessToken) { - getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); - tokenCyclerMap.set(credential, getAccessToken); - } - tokenPromises.push(sendAuthorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - getAccessToken, - logger - })); - } - const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); - if (auxiliaryTokens.length === 0) { - logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); - return next(request); - } - request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); - return next(request); - } + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 }; } + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; + } + if (hasFlag("color=256")) { + return 2; + } + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (process.platform === "win32") { + const osRelease = os.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { + return 1; + } + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; + } + function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); + } + module2.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) + }; } }); -// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js -var require_commonjs7 = __commonJS({ - "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; - var pipeline_js_1 = require_pipeline(); - Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() { - return pipeline_js_1.createEmptyPipeline; - } }); - var createPipelineFromOptions_js_1 = require_createPipelineFromOptions(); - Object.defineProperty(exports2, "createPipelineFromOptions", { enumerable: true, get: function() { - return createPipelineFromOptions_js_1.createPipelineFromOptions; - } }); - var defaultHttpClient_js_1 = require_defaultHttpClient(); - Object.defineProperty(exports2, "createDefaultHttpClient", { enumerable: true, get: function() { - return defaultHttpClient_js_1.createDefaultHttpClient; - } }); - var httpHeaders_js_1 = require_httpHeaders(); - Object.defineProperty(exports2, "createHttpHeaders", { enumerable: true, get: function() { - return httpHeaders_js_1.createHttpHeaders; - } }); - var pipelineRequest_js_1 = require_pipelineRequest(); - Object.defineProperty(exports2, "createPipelineRequest", { enumerable: true, get: function() { - return pipelineRequest_js_1.createPipelineRequest; - } }); - var restError_js_1 = require_restError(); - Object.defineProperty(exports2, "RestError", { enumerable: true, get: function() { - return restError_js_1.RestError; - } }); - Object.defineProperty(exports2, "isRestError", { enumerable: true, get: function() { - return restError_js_1.isRestError; - } }); - var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); - Object.defineProperty(exports2, "decompressResponsePolicy", { enumerable: true, get: function() { - return decompressResponsePolicy_js_1.decompressResponsePolicy; - } }); - Object.defineProperty(exports2, "decompressResponsePolicyName", { enumerable: true, get: function() { - return decompressResponsePolicy_js_1.decompressResponsePolicyName; - } }); - var exponentialRetryPolicy_js_1 = require_exponentialRetryPolicy(); - Object.defineProperty(exports2, "exponentialRetryPolicy", { enumerable: true, get: function() { - return exponentialRetryPolicy_js_1.exponentialRetryPolicy; - } }); - Object.defineProperty(exports2, "exponentialRetryPolicyName", { enumerable: true, get: function() { - return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; - } }); - var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); - Object.defineProperty(exports2, "setClientRequestIdPolicy", { enumerable: true, get: function() { - return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; - } }); - Object.defineProperty(exports2, "setClientRequestIdPolicyName", { enumerable: true, get: function() { - return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; - } }); - var logPolicy_js_1 = require_logPolicy(); - Object.defineProperty(exports2, "logPolicy", { enumerable: true, get: function() { - return logPolicy_js_1.logPolicy; - } }); - Object.defineProperty(exports2, "logPolicyName", { enumerable: true, get: function() { - return logPolicy_js_1.logPolicyName; - } }); - var multipartPolicy_js_1 = require_multipartPolicy(); - Object.defineProperty(exports2, "multipartPolicy", { enumerable: true, get: function() { - return multipartPolicy_js_1.multipartPolicy; - } }); - Object.defineProperty(exports2, "multipartPolicyName", { enumerable: true, get: function() { - return multipartPolicy_js_1.multipartPolicyName; - } }); - var proxyPolicy_js_1 = require_proxyPolicy(); - Object.defineProperty(exports2, "proxyPolicy", { enumerable: true, get: function() { - return proxyPolicy_js_1.proxyPolicy; - } }); - Object.defineProperty(exports2, "proxyPolicyName", { enumerable: true, get: function() { - return proxyPolicy_js_1.proxyPolicyName; - } }); - Object.defineProperty(exports2, "getDefaultProxySettings", { enumerable: true, get: function() { - return proxyPolicy_js_1.getDefaultProxySettings; - } }); - var redirectPolicy_js_1 = require_redirectPolicy(); - Object.defineProperty(exports2, "redirectPolicy", { enumerable: true, get: function() { - return redirectPolicy_js_1.redirectPolicy; - } }); - Object.defineProperty(exports2, "redirectPolicyName", { enumerable: true, get: function() { - return redirectPolicy_js_1.redirectPolicyName; - } }); - var systemErrorRetryPolicy_js_1 = require_systemErrorRetryPolicy(); - Object.defineProperty(exports2, "systemErrorRetryPolicy", { enumerable: true, get: function() { - return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; - } }); - Object.defineProperty(exports2, "systemErrorRetryPolicyName", { enumerable: true, get: function() { - return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; - } }); - var throttlingRetryPolicy_js_1 = require_throttlingRetryPolicy(); - Object.defineProperty(exports2, "throttlingRetryPolicy", { enumerable: true, get: function() { - return throttlingRetryPolicy_js_1.throttlingRetryPolicy; - } }); - Object.defineProperty(exports2, "throttlingRetryPolicyName", { enumerable: true, get: function() { - return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; - } }); - var retryPolicy_js_1 = require_retryPolicy(); - Object.defineProperty(exports2, "retryPolicy", { enumerable: true, get: function() { - return retryPolicy_js_1.retryPolicy; - } }); - var tracingPolicy_js_1 = require_tracingPolicy(); - Object.defineProperty(exports2, "tracingPolicy", { enumerable: true, get: function() { - return tracingPolicy_js_1.tracingPolicy; - } }); - Object.defineProperty(exports2, "tracingPolicyName", { enumerable: true, get: function() { - return tracingPolicy_js_1.tracingPolicyName; - } }); - var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); - Object.defineProperty(exports2, "defaultRetryPolicy", { enumerable: true, get: function() { - return defaultRetryPolicy_js_1.defaultRetryPolicy; - } }); - var userAgentPolicy_js_1 = require_userAgentPolicy(); - Object.defineProperty(exports2, "userAgentPolicy", { enumerable: true, get: function() { - return userAgentPolicy_js_1.userAgentPolicy; - } }); - Object.defineProperty(exports2, "userAgentPolicyName", { enumerable: true, get: function() { - return userAgentPolicy_js_1.userAgentPolicyName; - } }); - var tlsPolicy_js_1 = require_tlsPolicy(); - Object.defineProperty(exports2, "tlsPolicy", { enumerable: true, get: function() { - return tlsPolicy_js_1.tlsPolicy; - } }); - Object.defineProperty(exports2, "tlsPolicyName", { enumerable: true, get: function() { - return tlsPolicy_js_1.tlsPolicyName; - } }); - var formDataPolicy_js_1 = require_formDataPolicy(); - Object.defineProperty(exports2, "formDataPolicy", { enumerable: true, get: function() { - return formDataPolicy_js_1.formDataPolicy; - } }); - Object.defineProperty(exports2, "formDataPolicyName", { enumerable: true, get: function() { - return formDataPolicy_js_1.formDataPolicyName; - } }); - var bearerTokenAuthenticationPolicy_js_1 = require_bearerTokenAuthenticationPolicy(); - Object.defineProperty(exports2, "bearerTokenAuthenticationPolicy", { enumerable: true, get: function() { - return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; - } }); - Object.defineProperty(exports2, "bearerTokenAuthenticationPolicyName", { enumerable: true, get: function() { - return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; - } }); - var ndJsonPolicy_js_1 = require_ndJsonPolicy(); - Object.defineProperty(exports2, "ndJsonPolicy", { enumerable: true, get: function() { - return ndJsonPolicy_js_1.ndJsonPolicy; - } }); - Object.defineProperty(exports2, "ndJsonPolicyName", { enumerable: true, get: function() { - return ndJsonPolicy_js_1.ndJsonPolicyName; - } }); - var auxiliaryAuthenticationHeaderPolicy_js_1 = require_auxiliaryAuthenticationHeaderPolicy(); - Object.defineProperty(exports2, "auxiliaryAuthenticationHeaderPolicy", { enumerable: true, get: function() { - return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; - } }); - Object.defineProperty(exports2, "auxiliaryAuthenticationHeaderPolicyName", { enumerable: true, get: function() { - return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; - } }); - var file_js_1 = require_file2(); - Object.defineProperty(exports2, "createFile", { enumerable: true, get: function() { - return file_js_1.createFile; - } }); - Object.defineProperty(exports2, "createFileFromStream", { enumerable: true, get: function() { - return file_js_1.createFileFromStream; - } }); - } -}); - -// node_modules/@azure/storage-blob/node_modules/tslib/tslib.es6.mjs -var tslib_es6_exports2 = {}; -__export(tslib_es6_exports2, { - __addDisposableResource: () => __addDisposableResource2, - __assign: () => __assign2, - __asyncDelegator: () => __asyncDelegator2, - __asyncGenerator: () => __asyncGenerator2, - __asyncValues: () => __asyncValues2, - __await: () => __await2, - __awaiter: () => __awaiter2, - __classPrivateFieldGet: () => __classPrivateFieldGet2, - __classPrivateFieldIn: () => __classPrivateFieldIn2, - __classPrivateFieldSet: () => __classPrivateFieldSet2, - __createBinding: () => __createBinding2, - __decorate: () => __decorate2, - __disposeResources: () => __disposeResources2, - __esDecorate: () => __esDecorate2, - __exportStar: () => __exportStar2, - __extends: () => __extends2, - __generator: () => __generator2, - __importDefault: () => __importDefault2, - __importStar: () => __importStar2, - __makeTemplateObject: () => __makeTemplateObject2, - __metadata: () => __metadata2, - __param: () => __param2, - __propKey: () => __propKey2, - __read: () => __read2, - __rest: () => __rest2, - __runInitializers: () => __runInitializers2, - __setFunctionName: () => __setFunctionName2, - __spread: () => __spread2, - __spreadArray: () => __spreadArray2, - __spreadArrays: () => __spreadArrays2, - __values: () => __values3, - default: () => tslib_es6_default2 -}); -function __extends2(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics2(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -function __rest2(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; +// node_modules/debug/src/node.js +var require_node = __commonJS({ + "node_modules/debug/src/node.js"(exports2, module2) { + var tty = require("tty"); + var util = require("util"); + exports2.init = init; + exports2.log = log; + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load2; + exports2.useColors = useColors; + exports2.destroy = util.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports2.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports2.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error4) { } - return t; -} -function __decorate2(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param2(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __esDecorate2(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _2, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context2 = {}; - for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; - context2.addInitializer = function(f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); - }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_2 = accept(result.get)) descriptor.get = _2; - if (_2 = accept(result.set)) descriptor.set = _2; - if (_2 = accept(result.init)) initializers.unshift(_2); - } else if (_2 = accept(result)) { - if (kind === "field") initializers.unshift(_2); - else descriptor[key] = _2; + exports2.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_2, k) => { + return k.toUpperCase(); + }); + let val2 = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val2)) { + val2 = true; + } else if (/^(no|off|false|disabled)$/i.test(val2)) { + val2 = false; + } else if (val2 === "null") { + val2 = null; + } else { + val2 = Number(val2); + } + obj[prop] = val2; + return obj; + }, {}); + function useColors() { + return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} -function __runInitializers2(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -} -function __propKey2(x) { - return typeof x === "symbol" ? x : "".concat(x); -} -function __setFunctionName2(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); -} -function __metadata2(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter2(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); - }); - } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + " " + args[0]; } } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + function getDate() { + if (exports2.inspectOpts.hideDate) { + return ""; } + return (/* @__PURE__ */ new Date()).toISOString() + " "; } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + function log(...args) { + return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator2(thisArg, body) { - var _2 = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_2 = 0)), _2) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _2.label++; - return { value: op[1], done: false }; - case 5: - _2.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _2.ops.pop(); - _2.trys.pop(); - continue; - default: - if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _2 = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _2.label = op[1]; - break; - } - if (op[0] === 6 && _2.label < t[1]) { - _2.label = t[1]; - t = op; - break; - } - if (t && _2.label < t[2]) { - _2.label = t[2]; - _2.ops.push(op); - break; - } - if (t[2]) _2.ops.pop(); - _2.trys.pop(); - continue; + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; } - op = body.call(thisArg, _2); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -} -function __exportStar2(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding2(o, m, p); -} -function __values3(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function() { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read2(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error4) { - e = { error: error4 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; -} -function __spread2() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read2(arguments[i])); - return ar; -} -function __spreadArrays2() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} -function __spreadArray2(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await2(v) { - return this instanceof __await2 ? (this.v = v, this) : new __await2(v); -} -function __asyncGenerator2(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - if (f) i[n] = f(i[n]); + function load2() { + return process.env.DEBUG; } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); + function init(debug4) { + debug4.inspectOpts = {}; + const keys = Object.keys(exports2.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug4.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + } } - } - function step(r) { - r.value instanceof __await2 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} -function __asyncDelegator2(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function(e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function() { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function(v) { - return (p = !p) ? { value: __await2(o[n](v)), done: false } : f ? f(v) : v; - } : f; - } -} -function __asyncValues2(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values3 === "function" ? __values3(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve2, reject) { - v = o[n](v), settle(resolve2, reject, v.done, v.value); - }); + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" "); }; - } - function settle(resolve2, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve2({ value: v2, done: d }); - }, reject); - } -} -function __makeTemplateObject2(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar2(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k); - } - __setModuleDefault2(result, mod); - return result; -} -function __importDefault2(mod) { - return mod && mod.__esModule ? mod : { default: mod }; -} -function __classPrivateFieldGet2(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} -function __classPrivateFieldSet2(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldIn2(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} -function __addDisposableResource2(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { - try { - inner.call(this); - } catch (e) { - return Promise.reject(e); - } + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); }; - env.stack.push({ value, dispose, async }); - } else if (async) { - env.stack.push({ async: true }); } - return value; -} -function __disposeResources2(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { - fail(e); - return next(); - }); - } else s |= 1; - } catch (e) { - fail(e); - } +}); + +// node_modules/debug/src/index.js +var require_src = __commonJS({ + "node_modules/debug/src/index.js"(exports2, module2) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module2.exports = require_browser(); + } else { + module2.exports = require_node(); } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; } - return next(); -} -var extendStatics2, __assign2, __createBinding2, __setModuleDefault2, _SuppressedError2, tslib_es6_default2; -var init_tslib_es62 = __esm({ - "node_modules/@azure/storage-blob/node_modules/tslib/tslib.es6.mjs"() { - extendStatics2 = function(d, b) { - extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics2(d, b); - }; - __assign2 = function() { - __assign2 = Object.assign || function __assign4(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign2.apply(this, arguments); - }; - __createBinding2 = Object.create ? (function(o, m, k, k2) { +}); + +// node_modules/agent-base/dist/helpers.js +var require_helpers2 = __commonJS({ + "node_modules/agent-base/dist/helpers.js"(exports2) { + "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { @@ -40754,9077 +39730,11607 @@ var init_tslib_es62 = __esm({ }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; - }); - __setModuleDefault2 = Object.create ? (function(o, v) { + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; }; - _SuppressedError2 = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; - }; - tslib_es6_default2 = { - __extends: __extends2, - __assign: __assign2, - __rest: __rest2, - __decorate: __decorate2, - __param: __param2, - __metadata: __metadata2, - __awaiter: __awaiter2, - __generator: __generator2, - __createBinding: __createBinding2, - __exportStar: __exportStar2, - __values: __values3, - __read: __read2, - __spread: __spread2, - __spreadArrays: __spreadArrays2, - __spreadArray: __spreadArray2, - __await: __await2, - __asyncGenerator: __asyncGenerator2, - __asyncDelegator: __asyncDelegator2, - __asyncValues: __asyncValues2, - __makeTemplateObject: __makeTemplateObject2, - __importStar: __importStar2, - __importDefault: __importDefault2, - __classPrivateFieldGet: __classPrivateFieldGet2, - __classPrivateFieldSet: __classPrivateFieldSet2, - __classPrivateFieldIn: __classPrivateFieldIn2, - __addDisposableResource: __addDisposableResource2, - __disposeResources: __disposeResources2 - }; - } -}); - -// node_modules/@azure/core-auth/dist/commonjs/azureKeyCredential.js -var require_azureKeyCredential = __commonJS({ - "node_modules/@azure/core-auth/dist/commonjs/azureKeyCredential.js"(exports2) { - "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AzureKeyCredential = void 0; - var AzureKeyCredential = class { - /** - * The value of the key to be used in authentication - */ - get key() { - return this._key; - } - /** - * Create an instance of an AzureKeyCredential for use - * with a service client. - * - * @param key - The initial value of the key to use in authentication - */ - constructor(key) { - if (!key) { - throw new Error("key must be a non-empty string"); - } - this._key = key; + exports2.req = exports2.json = exports2.toBuffer = void 0; + var http = __importStar4(require("http")); + var https2 = __importStar4(require("https")); + async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); } - /** - * Change the value of the key. - * - * Updates will take effect upon the next request after - * updating the key value. - * - * @param newKey - The new key value to be used - */ - update(newKey) { - this._key = newKey; + return Buffer.concat(chunks, length); + } + exports2.toBuffer = toBuffer; + async function json2(stream) { + const buf = await toBuffer(stream); + const str2 = buf.toString("utf8"); + try { + return JSON.parse(str2); + } catch (_err) { + const err = _err; + err.message += ` (input: ${str2})`; + throw err; } - }; - exports2.AzureKeyCredential = AzureKeyCredential; - } -}); - -// node_modules/@azure/core-auth/dist/commonjs/keyCredential.js -var require_keyCredential = __commonJS({ - "node_modules/@azure/core-auth/dist/commonjs/keyCredential.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isKeyCredential = isKeyCredential; - var core_util_1 = require_commonjs4(); - function isKeyCredential(credential) { - return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string"; } + exports2.json = json2; + function req(url, opts = {}) { + const href = typeof url === "string" ? url : url.href; + const req2 = (href.startsWith("https:") ? https2 : http).request(url, opts); + const promise = new Promise((resolve2, reject) => { + req2.once("response", resolve2).once("error", reject).end(); + }); + req2.then = promise.then.bind(promise); + return req2; + } + exports2.req = req; } }); -// node_modules/@azure/core-auth/dist/commonjs/azureNamedKeyCredential.js -var require_azureNamedKeyCredential = __commonJS({ - "node_modules/@azure/core-auth/dist/commonjs/azureNamedKeyCredential.js"(exports2) { +// node_modules/agent-base/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/agent-base/dist/index.js"(exports2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AzureNamedKeyCredential = void 0; - exports2.isNamedKeyCredential = isNamedKeyCredential; - var core_util_1 = require_commonjs4(); - var AzureNamedKeyCredential = class { - /** - * The value of the key to be used in authentication. - */ - get key() { - return this._key; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } - /** - * The value of the name to be used in authentication. - */ - get name() { - return this._name; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Agent = void 0; + var net = __importStar4(require("net")); + var http = __importStar4(require("http")); + var https_1 = require("https"); + __exportStar4(require_helpers2(), exports2); + var INTERNAL = Symbol("AgentBaseInternalState"); + var Agent = class extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; } /** - * Create an instance of an AzureNamedKeyCredential for use - * with a service client. - * - * @param name - The initial value of the name to use in authentication. - * @param key - The initial value of the key to use in authentication. + * Determine whether this is an `http` or `https` request. */ - constructor(name, key) { - if (!name || !key) { - throw new TypeError("name and key must be non-empty strings"); + isSecureEndpoint(options) { + if (options) { + if (typeof options.secureEndpoint === "boolean") { + return options.secureEndpoint; + } + if (typeof options.protocol === "string") { + return options.protocol === "https:"; + } } - this._name = name; - this._key = key; + const { stack } = new Error(); + if (typeof stack !== "string") + return false; + return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); } - /** - * Change the value of the key. - * - * Updates will take effect upon the next request after - * updating the key value. - * - * @param newName - The new name value to be used. - * @param newKey - The new key value to be used. - */ - update(newName, newKey) { - if (!newName || !newKey) { - throw new TypeError("newName and newKey must be non-empty strings"); + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + if (!this.sockets[name]) { + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + this.totalSocketCount--; + if (sockets.length === 0) { + delete this.sockets[name]; + } + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options); + if (secureEndpoint) { + return https_1.Agent.prototype.getName.call(this, options); + } + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options) + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + try { + return socket.addRequest(req, connectOpts); + } catch (err) { + return cb(err); + } + } + this[INTERNAL].currentSocket = socket; + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = void 0; + if (!socket) { + throw new Error("No socket was returned in the `connect()` function"); + } + return socket; + } + get defaultPort() { + return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; } - this._name = newName; - this._key = newKey; } }; - exports2.AzureNamedKeyCredential = AzureNamedKeyCredential; - function isNamedKeyCredential(credential) { - return (0, core_util_1.isObjectWithProperties)(credential, ["name", "key"]) && typeof credential.key === "string" && typeof credential.name === "string"; + exports2.Agent = Agent; + } +}); + +// node_modules/https-proxy-agent/dist/parse-proxy-response.js +var require_parse_proxy_response = __commonJS({ + "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { + "use strict"; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.parseProxyResponse = void 0; + var debug_1 = __importDefault4(require_src()); + var debug4 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); + function parseProxyResponse(socket) { + return new Promise((resolve2, reject) => { + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once("readable", read); + } + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("readable", read); + } + function onend() { + cleanup(); + debug4("onend"); + reject(new Error("Proxy connection ended before receiving CONNECT response")); + } + function onerror(err) { + cleanup(); + debug4("onerror %o", err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf("\r\n\r\n"); + if (endOfHeaders === -1) { + debug4("have not received end of HTTP headers yet..."); + read(); + return; + } + const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error("No header received from proxy CONNECT response")); + } + const firstLineParts = firstLine.split(" "); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(" "); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(":"); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === "string") { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } + } + debug4("got proxy server response: %o %o", firstLine, headers); + cleanup(); + resolve2({ + connect: { + statusCode, + statusText, + headers + }, + buffered + }); + } + socket.on("error", onerror); + socket.on("end", onend); + read(); + }); } + exports2.parseProxyResponse = parseProxyResponse; } }); -// node_modules/@azure/core-auth/dist/commonjs/azureSASCredential.js -var require_azureSASCredential = __commonJS({ - "node_modules/@azure/core-auth/dist/commonjs/azureSASCredential.js"(exports2) { +// node_modules/https-proxy-agent/dist/index.js +var require_dist3 = __commonJS({ + "node_modules/https-proxy-agent/dist/index.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AzureSASCredential = void 0; - exports2.isSASCredential = isSASCredential; - var core_util_1 = require_commonjs4(); - var AzureSASCredential = class { - /** - * The value of the shared access signature to be used in authentication - */ - get signature() { - return this._signature; + exports2.HttpsProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var assert_1 = __importDefault4(require("assert")); + var debug_1 = __importDefault4(require_src()); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var parse_proxy_response_1 = require_parse_proxy_response(); + var debug4 = (0, debug_1.default)("https-proxy-agent"); + var setServernameFromNonIpHost = (options) => { + if (options.servername === void 0 && options.host && !net.isIP(options.host)) { + return { + ...options, + servername: options.host + }; } - /** - * Create an instance of an AzureSASCredential for use - * with a service client. - * - * @param signature - The initial value of the shared access signature to use in authentication - */ - constructor(signature) { - if (!signature) { - throw new Error("shared access signature must be a non-empty string"); - } - this._signature = signature; + return options; + }; + var HttpsProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: void 0 }; + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug4("Creating new HttpsProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ["http/1.1"], + ...opts ? omit(opts, "headers") : null, + host, + port + }; } /** - * Change the value of the signature. - * - * Updates will take effect upon the next request after - * updating the signature value. - * - * @param newSignature - The new shared access signature value to be used + * Called when the node-core HTTP client library is creating a + * new HTTP request. */ - update(newSignature) { - if (!newSignature) { - throw new Error("shared access signature must be a non-empty string"); + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); } - this._signature = newSignature; + let socket; + if (proxy.protocol === "https:") { + debug4("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } else { + debug4("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r +`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r +`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r +`); + const { connect, buffered } = await proxyResponsePromise; + req.emit("proxyConnect", connect); + this.emit("proxyConnect", connect, req); + if (connect.statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debug4("Upgrading socket connection to TLS"); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), + socket + }); + } + return socket; + } + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debug4("Replaying proxy buffer for failed request"); + (0, assert_1.default)(s.listenerCount("data") > 0); + s.push(buffered); + s.push(null); + }); + return fakeSocket; } }; - exports2.AzureSASCredential = AzureSASCredential; - function isSASCredential(credential) { - return (0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string"; + HttpsProxyAgent.protocols = ["http", "https"]; + exports2.HttpsProxyAgent = HttpsProxyAgent; + function resume(socket) { + socket.resume(); + } + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; } } }); -// node_modules/@azure/core-auth/dist/commonjs/tokenCredential.js -var require_tokenCredential = __commonJS({ - "node_modules/@azure/core-auth/dist/commonjs/tokenCredential.js"(exports2) { +// node_modules/http-proxy-agent/dist/index.js +var require_dist4 = __commonJS({ + "node_modules/http-proxy-agent/dist/index.js"(exports2) { "use strict"; + var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar4 = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k); + } + __setModuleDefault4(result, mod); + return result; + }; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isTokenCredential = isTokenCredential; - function isTokenCredential(credential) { - const castCredential = credential; - return castCredential && typeof castCredential.getToken === "function" && (castCredential.signRequest === void 0 || castCredential.getToken.length > 0); + exports2.HttpProxyAgent = void 0; + var net = __importStar4(require("net")); + var tls = __importStar4(require("tls")); + var debug_1 = __importDefault4(require_src()); + var events_1 = require("events"); + var agent_base_1 = require_dist2(); + var url_1 = require("url"); + var debug4 = (0, debug_1.default)("http-proxy-agent"); + var HttpProxyAgent = class extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug4("Creating new HttpProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + addRequest(req, opts) { + req._header = null; + this.setRequestProps(req, opts); + super.addRequest(req, opts); + } + setRequestProps(req, opts) { + const { proxy } = this; + const protocol = opts.secureEndpoint ? "https:" : "http:"; + const hostname = req.getHeader("host") || "localhost"; + const base = `${protocol}//${hostname}`; + const url = new url_1.URL(req.path, base); + if (opts.port !== 80) { + url.port = String(opts.port); + } + req.path = String(url); + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + const value = headers[name]; + if (value) { + req.setHeader(name, value); + } + } + } + async connect(req, opts) { + req._header = null; + if (!req.path.includes("://")) { + this.setRequestProps(req, opts); + } + let first; + let endOfHeaders; + debug4("Regenerating stored HTTP header string for request"); + req._implicitHeader(); + if (req.outputData && req.outputData.length > 0) { + debug4("Patching connection write() output buffer with updated header"); + first = req.outputData[0].data; + endOfHeaders = first.indexOf("\r\n\r\n") + 4; + req.outputData[0].data = req._header + first.substring(endOfHeaders); + debug4("Output buffer: %o", req.outputData[0].data); + } + let socket; + if (this.proxy.protocol === "https:") { + debug4("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(this.connectOpts); + } else { + debug4("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + await (0, events_1.once)(socket, "connect"); + return socket; + } + }; + HttpProxyAgent.protocols = ["http", "https"]; + exports2.HttpProxyAgent = HttpProxyAgent; + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; } } }); -// node_modules/@azure/core-auth/dist/commonjs/index.js -var require_commonjs8 = __commonJS({ - "node_modules/@azure/core-auth/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isTokenCredential = exports2.isSASCredential = exports2.AzureSASCredential = exports2.isNamedKeyCredential = exports2.AzureNamedKeyCredential = exports2.isKeyCredential = exports2.AzureKeyCredential = void 0; - var azureKeyCredential_js_1 = require_azureKeyCredential(); - Object.defineProperty(exports2, "AzureKeyCredential", { enumerable: true, get: function() { - return azureKeyCredential_js_1.AzureKeyCredential; - } }); - var keyCredential_js_1 = require_keyCredential(); - Object.defineProperty(exports2, "isKeyCredential", { enumerable: true, get: function() { - return keyCredential_js_1.isKeyCredential; - } }); - var azureNamedKeyCredential_js_1 = require_azureNamedKeyCredential(); - Object.defineProperty(exports2, "AzureNamedKeyCredential", { enumerable: true, get: function() { - return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; - } }); - Object.defineProperty(exports2, "isNamedKeyCredential", { enumerable: true, get: function() { - return azureNamedKeyCredential_js_1.isNamedKeyCredential; - } }); - var azureSASCredential_js_1 = require_azureSASCredential(); - Object.defineProperty(exports2, "AzureSASCredential", { enumerable: true, get: function() { - return azureSASCredential_js_1.AzureSASCredential; - } }); - Object.defineProperty(exports2, "isSASCredential", { enumerable: true, get: function() { - return azureSASCredential_js_1.isSASCredential; - } }); - var tokenCredential_js_1 = require_tokenCredential(); - Object.defineProperty(exports2, "isTokenCredential", { enumerable: true, get: function() { - return tokenCredential_js_1.isTokenCredential; - } }); +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js +var require_proxyPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.globalNoProxyList = exports2.proxyPolicyName = void 0; + exports2.loadNoProxy = loadNoProxy; + exports2.getDefaultProxySettings = getDefaultProxySettings; + exports2.proxyPolicy = proxyPolicy; + var https_proxy_agent_1 = require_dist3(); + var http_proxy_agent_1 = require_dist4(); + var log_js_1 = require_log(); + var HTTPS_PROXY = "HTTPS_PROXY"; + var HTTP_PROXY = "HTTP_PROXY"; + var ALL_PROXY = "ALL_PROXY"; + var NO_PROXY = "NO_PROXY"; + exports2.proxyPolicyName = "proxyPolicy"; + exports2.globalNoProxyList = []; + var noProxyListLoaded = false; + var globalBypassedMap = /* @__PURE__ */ new Map(); + function getEnvironmentValue(name) { + if (process.env[name]) { + return process.env[name]; + } else if (process.env[name.toLowerCase()]) { + return process.env[name.toLowerCase()]; + } + return void 0; + } + function loadEnvironmentProxyValue() { + if (!process) { + return void 0; + } + const httpsProxy = getEnvironmentValue(HTTPS_PROXY); + const allProxy = getEnvironmentValue(ALL_PROXY); + const httpProxy = getEnvironmentValue(HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; + } + function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = new URL(uri).hostname; + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } + } else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; + } + function loadNoProxy() { + const noProxy = getEnvironmentValue(NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); + } + return []; + } + function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return void 0; + } + } + const parsedUrl = new URL(proxyUrl); + const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; + return { + host: schema2 + parsedUrl.hostname, + port: Number.parseInt(parsedUrl.port || "80"), + username: parsedUrl.username, + password: parsedUrl.password + }; + } + function getDefaultProxySettingsInternal() { + const envProxy = loadEnvironmentProxyValue(); + return envProxy ? new URL(envProxy) : void 0; + } + function getUrlFromProxySettings(settings) { + let parsedProxyUrl; + try { + parsedProxyUrl = new URL(settings.host); + } catch (_a) { + throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); + } + parsedProxyUrl.port = String(settings.port); + if (settings.username) { + parsedProxyUrl.username = settings.username; + } + if (settings.password) { + parsedProxyUrl.password = settings.password; + } + return parsedProxyUrl; + } + function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { + if (request.agent) { + return; + } + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (request.tlsSettings) { + log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); + } + const headers = request.headers.toJSON(); + if (isInsecure) { + if (!cachedAgents.httpProxyAgent) { + cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpProxyAgent; + } else { + if (!cachedAgents.httpsProxyAgent) { + cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers }); + } + request.agent = cachedAgents.httpsProxyAgent; + } + } + function proxyPolicy(proxySettings, options) { + if (!noProxyListLoaded) { + exports2.globalNoProxyList.push(...loadNoProxy()); + } + const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); + const cachedAgents = {}; + return { + name: exports2.proxyPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) { + setProxyAgentOnRequest(request, cachedAgents, defaultProxy); + } else if (request.proxySettings) { + setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); + } + return next(request); + } + }; + } } }); -// node_modules/@azure/core-http-compat/dist/commonjs/policies/disableKeepAlivePolicy.js -var require_disableKeepAlivePolicy = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/policies/disableKeepAlivePolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js +var require_setClientRequestIdPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.pipelineContainsDisableKeepAlivePolicy = exports2.createDisableKeepAlivePolicy = exports2.disableKeepAlivePolicyName = void 0; - exports2.disableKeepAlivePolicyName = "DisableKeepAlivePolicy"; - function createDisableKeepAlivePolicy() { + exports2.setClientRequestIdPolicyName = void 0; + exports2.setClientRequestIdPolicy = setClientRequestIdPolicy; + exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy"; + function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { return { - name: exports2.disableKeepAlivePolicyName, + name: exports2.setClientRequestIdPolicyName, async sendRequest(request, next) { - request.disableKeepAlive = true; + if (!request.headers.has(requestIdHeaderName)) { + request.headers.set(requestIdHeaderName, request.requestId); + } return next(request); } }; } - exports2.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy; - function pipelineContainsDisableKeepAlivePolicy(pipeline) { - return pipeline.getOrderedPolicies().some((policy) => policy.name === exports2.disableKeepAlivePolicyName); - } - exports2.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy; } }); -// node_modules/@azure/core-client/node_modules/tslib/tslib.es6.mjs -var tslib_es6_exports3 = {}; -__export(tslib_es6_exports3, { - __addDisposableResource: () => __addDisposableResource3, - __assign: () => __assign3, - __asyncDelegator: () => __asyncDelegator3, - __asyncGenerator: () => __asyncGenerator3, - __asyncValues: () => __asyncValues3, - __await: () => __await3, - __awaiter: () => __awaiter3, - __classPrivateFieldGet: () => __classPrivateFieldGet3, - __classPrivateFieldIn: () => __classPrivateFieldIn3, - __classPrivateFieldSet: () => __classPrivateFieldSet3, - __createBinding: () => __createBinding3, - __decorate: () => __decorate3, - __disposeResources: () => __disposeResources3, - __esDecorate: () => __esDecorate3, - __exportStar: () => __exportStar3, - __extends: () => __extends3, - __generator: () => __generator3, - __importDefault: () => __importDefault3, - __importStar: () => __importStar3, - __makeTemplateObject: () => __makeTemplateObject3, - __metadata: () => __metadata3, - __param: () => __param3, - __propKey: () => __propKey3, - __read: () => __read3, - __rest: () => __rest3, - __runInitializers: () => __runInitializers3, - __setFunctionName: () => __setFunctionName3, - __spread: () => __spread3, - __spreadArray: () => __spreadArray3, - __spreadArrays: () => __spreadArrays3, - __values: () => __values4, - default: () => tslib_es6_default3 -}); -function __extends3(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics3(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -function __rest3(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js +var require_tlsPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.tlsPolicyName = void 0; + exports2.tlsPolicy = tlsPolicy; + exports2.tlsPolicyName = "tlsPolicy"; + function tlsPolicy(tlsSettings) { + return { + name: exports2.tlsPolicyName, + sendRequest: async (req, next) => { + if (!req.tlsSettings) { + req.tlsSettings = tlsSettings; + } + return next(req); + } + }; } - return t; -} -function __decorate3(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param3(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __esDecorate3(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _2, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context2 = {}; - for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; - context2.addInitializer = function(f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js +var require_tracingContext = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0; + exports2.knownContextKeys = { + span: Symbol.for("@azure/core-tracing span"), + namespace: Symbol.for("@azure/core-tracing namespace") }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_2 = accept(result.get)) descriptor.get = _2; - if (_2 = accept(result.set)) descriptor.set = _2; - if (_2 = accept(result.init)) initializers.unshift(_2); - } else if (_2 = accept(result)) { - if (kind === "field") initializers.unshift(_2); - else descriptor[key] = _2; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} -function __runInitializers3(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -} -function __propKey3(x) { - return typeof x === "symbol" ? x : "".concat(x); -} -function __setFunctionName3(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); -} -function __metadata3(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter3(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve2) { - resolve2(value); - }); - } - return new (P || (P = Promise))(function(resolve2, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + function createTracingContext(options = {}) { + let context2 = new TracingContextImpl(options.parentContext); + if (options.span) { + context2 = context2.setValue(exports2.knownContextKeys.span, options.span); } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + if (options.namespace) { + context2 = context2.setValue(exports2.knownContextKeys.namespace, options.namespace); } + return context2; } - function step(result) { - result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator3(thisArg, body) { - var _2 = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); + exports2.createTracingContext = createTracingContext; + var TracingContextImpl = class _TracingContextImpl { + constructor(initialContext) { + this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); + } + setValue(key, value) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.set(key, value); + return newContext; + } + getValue(key) { + return this._contextMap.get(key); + } + deleteValue(key) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.delete(key); + return newContext; + } }; + exports2.TracingContextImpl = TracingContextImpl; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_2 = 0)), _2) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _2.label++; - return { value: op[1], done: false }; - case 5: - _2.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _2.ops.pop(); - _2.trys.pop(); - continue; - default: - if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _2 = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _2.label = op[1]; - break; - } - if (op[0] === 6 && _2.label < t[1]) { - _2.label = t[1]; - t = op; - break; - } - if (t && _2.label < t[2]) { - _2.label = t[2]; - _2.ops.push(op); - break; - } - if (t[2]) _2.ops.pop(); - _2.trys.pop(); - continue; - } - op = body.call(thisArg, _2); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; +}); + +// node_modules/@azure/core-tracing/dist/commonjs/state.js +var require_state = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.state = void 0; + exports2.state = { + instrumenterImplementation: void 0 + }; } -} -function __exportStar3(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding3(o, m, p); -} -function __values4(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function() { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; +}); + +// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js +var require_instrumenter = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0; + var tracingContext_js_1 = require_tracingContext(); + var state_js_1 = require_state(); + function createDefaultTracingSpan() { + return { + end: () => { + }, + isRecording: () => false, + recordException: () => { + }, + setAttribute: () => { + }, + setStatus: () => { + } + }; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read3(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error4) { - e = { error: error4 }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; -} -function __spread3() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read3(arguments[i])); - return ar; -} -function __spreadArrays3() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} -function __spreadArray3(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await3(v) { - return this instanceof __await3 ? (this.v = v, this) : new __await3(v); -} -function __asyncGenerator3(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); + exports2.createDefaultTracingSpan = createDefaultTracingSpan; + function createDefaultInstrumenter() { + return { + createRequestHeaders: () => { + return {}; + }, + parseTraceparentHeader: () => { + return void 0; + }, + startSpan: (_name, spanOptions) => { + return { + span: createDefaultTracingSpan(), + tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }) + }; + }, + withContext(_context, callback, ...callbackArgs) { + return callback(...callbackArgs); + } }; - if (f) i[n] = f(i[n]); - } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await3 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} -function __asyncDelegator3(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function(e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function() { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function(v) { - return (p = !p) ? { value: __await3(o[n](v)), done: false } : f ? f(v) : v; - } : f; - } -} -function __asyncValues3(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values4 === "function" ? __values4(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve2, reject) { - v = o[n](v), settle(resolve2, reject, v.done, v.value); - }); - }; - } - function settle(resolve2, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve2({ value: v2, done: d }); - }, reject); - } -} -function __makeTemplateObject3(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar3(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding3(result, mod, k); - } - __setModuleDefault3(result, mod); - return result; -} -function __importDefault3(mod) { - return mod && mod.__esModule ? mod : { default: mod }; -} -function __classPrivateFieldGet3(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} -function __classPrivateFieldSet3(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldIn3(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} -function __addDisposableResource3(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; + exports2.createDefaultInstrumenter = createDefaultInstrumenter; + function useInstrumenter(instrumenter) { + state_js_1.state.instrumenterImplementation = instrumenter; } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { - try { - inner.call(this); - } catch (e) { - return Promise.reject(e); - } - }; - env.stack.push({ value, dispose, async }); - } else if (async) { - env.stack.push({ async: true }); - } - return value; -} -function __disposeResources3(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError3(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { - fail(e); - return next(); - }); - } else s |= 1; - } catch (e) { - fail(e); + exports2.useInstrumenter = useInstrumenter; + function getInstrumenter() { + if (!state_js_1.state.instrumenterImplementation) { + state_js_1.state.instrumenterImplementation = createDefaultInstrumenter(); } + return state_js_1.state.instrumenterImplementation; } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; + exports2.getInstrumenter = getInstrumenter; } - return next(); -} -var extendStatics3, __assign3, __createBinding3, __setModuleDefault3, _SuppressedError3, tslib_es6_default3; -var init_tslib_es63 = __esm({ - "node_modules/@azure/core-client/node_modules/tslib/tslib.es6.mjs"() { - extendStatics3 = function(d, b) { - extendStatics3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics3(d, b); - }; - __assign3 = function() { - __assign3 = Object.assign || function __assign4(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; +}); + +// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js +var require_tracingClient = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createTracingClient = void 0; + var instrumenter_js_1 = require_instrumenter(); + var tracingContext_js_1 = require_tracingContext(); + function createTracingClient(options) { + const { namespace, packageName, packageVersion } = options; + function startSpan(name, operationOptions, spanOptions) { + var _a; + const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); + let tracingContext = startSpanResult.tracingContext; + const span = startSpanResult.span; + if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) { + tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace); } - return t; - }; - return __assign3.apply(this, arguments); - }; - __createBinding3 = Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m[k]; - } }; + span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)); + const updatedOptions = Object.assign({}, operationOptions, { + tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }) + }); + return { + span, + updatedOptions + }; } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - }); - __setModuleDefault3 = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - _SuppressedError3 = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; - }; - tslib_es6_default3 = { - __extends: __extends3, - __assign: __assign3, - __rest: __rest3, - __decorate: __decorate3, - __param: __param3, - __metadata: __metadata3, - __awaiter: __awaiter3, - __generator: __generator3, - __createBinding: __createBinding3, - __exportStar: __exportStar3, - __values: __values4, - __read: __read3, - __spread: __spread3, - __spreadArrays: __spreadArrays3, - __spreadArray: __spreadArray3, - __await: __await3, - __asyncGenerator: __asyncGenerator3, - __asyncDelegator: __asyncDelegator3, - __asyncValues: __asyncValues3, - __makeTemplateObject: __makeTemplateObject3, - __importStar: __importStar3, - __importDefault: __importDefault3, - __classPrivateFieldGet: __classPrivateFieldGet3, - __classPrivateFieldSet: __classPrivateFieldSet3, - __classPrivateFieldIn: __classPrivateFieldIn3, - __addDisposableResource: __addDisposableResource3, - __disposeResources: __disposeResources3 - }; + async function withSpan(name, operationOptions, callback, spanOptions) { + const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); + try { + const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); + span.setStatus({ status: "success" }); + return result; + } catch (err) { + span.setStatus({ status: "error", error: err }); + throw err; + } finally { + span.end(); + } + } + function withContext(context2, callback, ...callbackArgs) { + return (0, instrumenter_js_1.getInstrumenter)().withContext(context2, callback, ...callbackArgs); + } + function parseTraceparentHeader(traceparentHeader) { + return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader); + } + function createRequestHeaders(tracingContext) { + return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext); + } + return { + startSpan, + withSpan, + withContext, + parseTraceparentHeader, + createRequestHeaders + }; + } + exports2.createTracingClient = createTracingClient; } }); -// node_modules/@azure/core-client/dist/commonjs/base64.js -var require_base642 = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/base64.js"(exports2) { +// node_modules/@azure/core-tracing/dist/commonjs/index.js +var require_commonjs6 = __commonJS({ + "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decodeStringToString = exports2.decodeString = exports2.encodeByteArray = exports2.encodeString = void 0; - function encodeString(value) { - return Buffer.from(value).toString("base64"); - } - exports2.encodeString = encodeString; - function encodeByteArray(value) { - const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); - return bufferValue.toString("base64"); - } - exports2.encodeByteArray = encodeByteArray; - function decodeString(value) { - return Buffer.from(value, "base64"); - } - exports2.decodeString = decodeString; - function decodeStringToString(value) { - return Buffer.from(value, "base64").toString(); - } - exports2.decodeStringToString = decodeStringToString; + exports2.createTracingClient = exports2.useInstrumenter = void 0; + var instrumenter_js_1 = require_instrumenter(); + Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() { + return instrumenter_js_1.useInstrumenter; + } }); + var tracingClient_js_1 = require_tracingClient(); + Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() { + return tracingClient_js_1.createTracingClient; + } }); } }); -// node_modules/@azure/core-client/dist/commonjs/interfaces.js -var require_interfaces = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/interfaces.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js +var require_inspect = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.XML_CHARKEY = exports2.XML_ATTRKEY = void 0; - exports2.XML_ATTRKEY = "$"; - exports2.XML_CHARKEY = "_"; + exports2.custom = void 0; + var node_util_1 = require("node:util"); + exports2.custom = node_util_1.inspect.custom; } }); -// node_modules/@azure/core-client/dist/commonjs/utils.js -var require_utils5 = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/utils.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js +var require_restError = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.flattenResponse = exports2.isValidUuid = exports2.isDuration = exports2.isPrimitiveBody = void 0; - function isPrimitiveBody(value, mapperTypeName) { - return mapperTypeName !== "Composite" && mapperTypeName !== "Dictionary" && (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !== null || value === void 0 || value === null); - } - exports2.isPrimitiveBody = isPrimitiveBody; - var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; - function isDuration(value) { - return validateISODuration.test(value); - } - exports2.isDuration = isDuration; - var validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; - function isValidUuid(uuid) { - return validUuidRegex.test(uuid); - } - exports2.isValidUuid = isValidUuid; - function handleNullableResponseAndWrappableBody(responseObject) { - const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body); - if (responseObject.hasNullableType && Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) { - return responseObject.shouldWrapBody ? { body: null } : null; - } else { - return responseObject.shouldWrapBody ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody; - } - } - function flattenResponse(fullResponse, responseSpec) { - var _a, _b; - const parsedHeaders = fullResponse.parsedHeaders; - if (fullResponse.request.method === "HEAD") { - return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody }); + exports2.RestError = void 0; + exports2.isRestError = isRestError; + var core_util_1 = require_commonjs4(); + var inspect_js_1 = require_inspect(); + var sanitizer_js_1 = require_sanitizer(); + var errorSanitizer = new sanitizer_js_1.Sanitizer(); + var RestError = class _RestError extends Error { + constructor(message, options = {}) { + super(message); + this.name = "RestError"; + this.code = options.code; + this.statusCode = options.statusCode; + Object.defineProperty(this, "request", { value: options.request, enumerable: false }); + Object.defineProperty(this, "response", { value: options.response, enumerable: false }); + Object.setPrototypeOf(this, _RestError.prototype); } - const bodyMapper = responseSpec && responseSpec.bodyMapper; - const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable); - const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name; - if (expectedBodyTypeName === "Stream") { - return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody }); + /** + * Logging method for util.inspect in Node + */ + [inspect_js_1.custom]() { + return `RestError: ${this.message} + ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; } - const modelProperties = expectedBodyTypeName === "Composite" && bodyMapper.type.modelProperties || {}; - const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); - if (expectedBodyTypeName === "Sequence" || isPageableResponse) { - const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : []; - for (const key of Object.keys(modelProperties)) { - if (modelProperties[key].serializedName) { - arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key]; - } - } - if (parsedHeaders) { - for (const key of Object.keys(parsedHeaders)) { - arrayResponse[key] = parsedHeaders[key]; - } - } - return isNullable && !fullResponse.parsedBody && !parsedHeaders && Object.getOwnPropertyNames(modelProperties).length === 0 ? null : arrayResponse; + }; + exports2.RestError = RestError; + RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; + RestError.PARSE_ERROR = "PARSE_ERROR"; + function isRestError(e) { + if (e instanceof RestError) { + return true; } - return handleNullableResponseAndWrappableBody({ - body: fullResponse.parsedBody, - headers: parsedHeaders, - hasNullableType: isNullable, - shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName) - }); + return (0, core_util_1.isError)(e) && e.name === "RestError"; } - exports2.flattenResponse = flattenResponse; } }); -// node_modules/@azure/core-client/dist/commonjs/serializer.js -var require_serializer = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/serializer.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js +var require_tracingPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MapperTypeNames = exports2.createSerializer = void 0; - var tslib_1 = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3)); - var base64 = tslib_1.__importStar(require_base642()); - var interfaces_js_1 = require_interfaces(); - var utils_js_1 = require_utils5(); - var SerializerImpl = class { - constructor(modelMappers = {}, isXML = false) { - this.modelMappers = modelMappers; - this.isXML = isXML; - } - /** - * @deprecated Removing the constraints validation on client side. - */ - validateConstraints(mapper, value, objectName) { - const failValidation = (constraintName, constraintValue) => { - throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); - }; - if (mapper.constraints && value !== void 0 && value !== null) { - const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems } = mapper.constraints; - if (ExclusiveMaximum !== void 0 && value >= ExclusiveMaximum) { - failValidation("ExclusiveMaximum", ExclusiveMaximum); - } - if (ExclusiveMinimum !== void 0 && value <= ExclusiveMinimum) { - failValidation("ExclusiveMinimum", ExclusiveMinimum); - } - if (InclusiveMaximum !== void 0 && value > InclusiveMaximum) { - failValidation("InclusiveMaximum", InclusiveMaximum); - } - if (InclusiveMinimum !== void 0 && value < InclusiveMinimum) { - failValidation("InclusiveMinimum", InclusiveMinimum); - } - if (MaxItems !== void 0 && value.length > MaxItems) { - failValidation("MaxItems", MaxItems); - } - if (MaxLength !== void 0 && value.length > MaxLength) { - failValidation("MaxLength", MaxLength); - } - if (MinItems !== void 0 && value.length < MinItems) { - failValidation("MinItems", MinItems); - } - if (MinLength !== void 0 && value.length < MinLength) { - failValidation("MinLength", MinLength); - } - if (MultipleOf !== void 0 && value % MultipleOf !== 0) { - failValidation("MultipleOf", MultipleOf); - } - if (Pattern) { - const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; - if (typeof value !== "string" || value.match(pattern) === null) { - failValidation("Pattern", Pattern); - } - } - if (UniqueItems && value.some((item, i, ar) => ar.indexOf(item) !== i)) { - failValidation("UniqueItems", UniqueItems); - } - } - } - /** - * Serialize the given object based on its metadata defined in the mapper - * - * @param mapper - The mapper which defines the metadata of the serializable object - * - * @param object - A valid Javascript object to be serialized - * - * @param objectName - Name of the serialized object - * - * @param options - additional options to serialization - * - * @returns A valid serialized Javascript object - */ - serialize(mapper, object, objectName, options = { xml: {} }) { - var _a, _b, _c; - const updatedOptions = { - xml: { - rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY - } - }; - let payload = {}; - const mapperType = mapper.type.name; - if (!objectName) { - objectName = mapper.serializedName; - } - if (mapperType.match(/^Sequence$/i) !== null) { - payload = []; - } - if (mapper.isConstant) { - object = mapper.defaultValue; - } - const { required, nullable } = mapper; - if (required && nullable && object === void 0) { - throw new Error(`${objectName} cannot be undefined.`); - } - if (required && !nullable && (object === void 0 || object === null)) { - throw new Error(`${objectName} cannot be null or undefined.`); - } - if (!required && nullable === false && object === null) { - throw new Error(`${objectName} cannot be null.`); - } - if (object === void 0 || object === null) { - payload = object; - } else { - if (mapperType.match(/^any$/i) !== null) { - payload = object; - } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { - payload = serializeBasicTypes(mapperType, objectName, object); - } else if (mapperType.match(/^Enum$/i) !== null) { - const enumMapper = mapper; - payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); - } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { - payload = serializeDateTypes(mapperType, object, objectName); - } else if (mapperType.match(/^ByteArray$/i) !== null) { - payload = serializeByteArrayType(objectName, object); - } else if (mapperType.match(/^Base64Url$/i) !== null) { - payload = serializeBase64UrlType(objectName, object); - } else if (mapperType.match(/^Sequence$/i) !== null) { - payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); - } else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); - } else if (mapperType.match(/^Composite$/i) !== null) { - payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); - } - } - return payload; - } - /** - * Deserialize the given object based on its metadata defined in the mapper - * - * @param mapper - The mapper which defines the metadata of the serializable object - * - * @param responseBody - A valid Javascript entity to be deserialized - * - * @param objectName - Name of the deserialized object - * - * @param options - Controls behavior of XML parser and builder. - * - * @returns A valid deserialized Javascript object - */ - deserialize(mapper, responseBody, objectName, options = { xml: {} }) { - var _a, _b, _c, _d; - const updatedOptions = { - xml: { - rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY - }, - ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false - }; - if (responseBody === void 0 || responseBody === null) { - if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { - responseBody = []; + exports2.tracingPolicyName = void 0; + exports2.tracingPolicy = tracingPolicy; + var core_tracing_1 = require_commonjs6(); + var constants_js_1 = require_constants7(); + var userAgent_js_1 = require_userAgent(); + var log_js_1 = require_log(); + var core_util_1 = require_commonjs4(); + var restError_js_1 = require_restError(); + var sanitizer_js_1 = require_sanitizer(); + exports2.tracingPolicyName = "tracingPolicy"; + function tracingPolicy(options = {}) { + const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix); + const sanitizer = new sanitizer_js_1.Sanitizer({ + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + const tracingClient = tryCreateTracingClient(); + return { + name: exports2.tracingPolicyName, + async sendRequest(request, next) { + var _a; + if (!tracingClient) { + return next(request); } - if (mapper.defaultValue !== void 0) { - responseBody = mapper.defaultValue; + const userAgent = await userAgentPromise; + const spanAttributes = { + "http.url": sanitizer.sanitizeUrl(request.url), + "http.method": request.method, + "http.user_agent": userAgent, + requestId: request.requestId + }; + if (userAgent) { + spanAttributes["http.user_agent"] = userAgent; } - return responseBody; - } - let payload; - const mapperType = mapper.type.name; - if (!objectName) { - objectName = mapper.serializedName; - } - if (mapperType.match(/^Composite$/i) !== null) { - payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); - } else { - if (this.isXML) { - const xmlCharKey = updatedOptions.xml.xmlCharKey; - if (responseBody[interfaces_js_1.XML_ATTRKEY] !== void 0 && responseBody[xmlCharKey] !== void 0) { - responseBody = responseBody[xmlCharKey]; - } + const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; + if (!span || !tracingContext) { + return next(request); } - if (mapperType.match(/^Number$/i) !== null) { - payload = parseFloat(responseBody); - if (isNaN(payload)) { - payload = responseBody; - } - } else if (mapperType.match(/^Boolean$/i) !== null) { - if (responseBody === "true") { - payload = true; - } else if (responseBody === "false") { - payload = false; - } else { - payload = responseBody; - } - } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) { - payload = responseBody; - } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) { - payload = new Date(responseBody); - } else if (mapperType.match(/^UnixTime$/i) !== null) { - payload = unixTimeToDate(responseBody); - } else if (mapperType.match(/^ByteArray$/i) !== null) { - payload = base64.decodeString(responseBody); - } else if (mapperType.match(/^Base64Url$/i) !== null) { - payload = base64UrlToByteArray(responseBody); - } else if (mapperType.match(/^Sequence$/i) !== null) { - payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); - } else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); + try { + const response = await tracingClient.withContext(tracingContext, next, request); + tryProcessResponse(span, response); + return response; + } catch (err) { + tryProcessError(span, err); + throw err; } } - if (mapper.isConstant) { - payload = mapper.defaultValue; - } - return payload; - } - }; - function createSerializer(modelMappers = {}, isXML = false) { - return new SerializerImpl(modelMappers, isXML); - } - exports2.createSerializer = createSerializer; - function trimEnd(str2, ch) { - let len = str2.length; - while (len - 1 >= 0 && str2[len - 1] === ch) { - --len; - } - return str2.substr(0, len); - } - function bufferToBase64Url(buffer) { - if (!buffer) { - return void 0; - } - if (!(buffer instanceof Uint8Array)) { - throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); - } - const str2 = base64.encodeByteArray(buffer); - return trimEnd(str2, "=").replace(/\+/g, "-").replace(/\//g, "_"); + }; } - function base64UrlToByteArray(str2) { - if (!str2) { + function tryCreateTracingClient() { + try { + return (0, core_tracing_1.createTracingClient)({ + namespace: "", + packageName: "@azure/core-rest-pipeline", + packageVersion: constants_js_1.SDK_VERSION + }); + } catch (e) { + log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`); return void 0; } - if (str2 && typeof str2.valueOf() !== "string") { - throw new Error("Please provide an input of type string for converting to Uint8Array"); - } - str2 = str2.replace(/-/g, "+").replace(/_/g, "/"); - return base64.decodeString(str2); } - function splitSerializeName(prop) { - const classes = []; - let partialclass = ""; - if (prop) { - const subwords = prop.split("."); - for (const item of subwords) { - if (item.charAt(item.length - 1) === "\\") { - partialclass += item.substr(0, item.length - 1) + "."; - } else { - partialclass += item; - classes.push(partialclass); - partialclass = ""; - } + function tryCreateSpan(tracingClient, request, spanAttributes) { + try { + const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { + spanKind: "client", + spanAttributes + }); + if (!span.isRecording()) { + span.end(); + return void 0; } - } - return classes; - } - function dateToUnixTime(d) { - if (!d) { + const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); + for (const [key, value] of Object.entries(headers)) { + request.headers.set(key, value); + } + return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; + } catch (e) { + log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); return void 0; } - if (typeof d.valueOf() === "string") { - d = new Date(d); - } - return Math.floor(d.getTime() / 1e3); } - function unixTimeToDate(n) { - if (!n) { - return void 0; + function tryProcessError(span, error4) { + try { + span.setStatus({ + status: "error", + error: (0, core_util_1.isError)(error4) ? error4 : void 0 + }); + if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) { + span.setAttribute("http.status_code", error4.statusCode); + } + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); } - return new Date(n * 1e3); } - function serializeBasicTypes(typeName, objectName, value) { - if (value !== null && value !== void 0) { - if (typeName.match(/^Number$/i) !== null) { - if (typeof value !== "number") { - throw new Error(`${objectName} with value ${value} must be of type number.`); - } - } else if (typeName.match(/^String$/i) !== null) { - if (typeof value.valueOf() !== "string") { - throw new Error(`${objectName} with value "${value}" must be of type string.`); - } - } else if (typeName.match(/^Uuid$/i) !== null) { - if (!(typeof value.valueOf() === "string" && (0, utils_js_1.isValidUuid)(value))) { - throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); - } - } else if (typeName.match(/^Boolean$/i) !== null) { - if (typeof value !== "boolean") { - throw new Error(`${objectName} with value ${value} must be of type boolean.`); - } - } else if (typeName.match(/^Stream$/i) !== null) { - const objectType = typeof value; - if (objectType !== "string" && typeof value.pipe !== "function" && // NodeJS.ReadableStream - typeof value.tee !== "function" && // browser ReadableStream - !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && // File objects count as a type of Blob, so we want to use instanceof explicitly - !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) && objectType !== "function") { - throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`); - } + function tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); } + span.setStatus({ + status: "success" + }); + span.end(); + } catch (e) { + log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`); } - return value; } - function serializeEnumType(objectName, allowedValues, value) { - if (!allowedValues) { - throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); - } - const isPresent = allowedValues.some((item) => { - if (typeof item.valueOf() === "string") { - return item.toLowerCase() === value.toLowerCase(); + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js +var require_createPipelineFromOptions = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createPipelineFromOptions = createPipelineFromOptions; + var logPolicy_js_1 = require_logPolicy(); + var pipeline_js_1 = require_pipeline(); + var redirectPolicy_js_1 = require_redirectPolicy(); + var userAgentPolicy_js_1 = require_userAgentPolicy(); + var multipartPolicy_js_1 = require_multipartPolicy(); + var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); + var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); + var formDataPolicy_js_1 = require_formDataPolicy(); + var core_util_1 = require_commonjs4(); + var proxyPolicy_js_1 = require_proxyPolicy(); + var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); + var tlsPolicy_js_1 = require_tlsPolicy(); + var tracingPolicy_js_1 = require_tracingPolicy(); + function createPipelineFromOptions(options) { + var _a; + const pipeline = (0, pipeline_js_1.createEmptyPipeline)(); + if (core_util_1.isNodeLike) { + if (options.tlsOptions) { + pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions)); } - return item === value; + pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions)); + pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)()); + } + pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] }); + pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions)); + pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); + pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" }); + pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" }); + pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { + afterPhase: "Retry" }); - if (!isPresent) { - throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); + if (core_util_1.isNodeLike) { + pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" }); } - return value; + pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" }); + return pipeline; } - function serializeByteArrayType(objectName, value) { - if (value !== void 0 && value !== null) { - if (!(value instanceof Uint8Array)) { - throw new Error(`${objectName} must be of type Uint8Array.`); - } - value = base64.encodeByteArray(value); - } - return value; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js +var require_nodeHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getBodyLength = getBodyLength; + exports2.createNodeHttpClient = createNodeHttpClient; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var http = tslib_1.__importStar(require("node:http")); + var https2 = tslib_1.__importStar(require("node:https")); + var zlib = tslib_1.__importStar(require("node:zlib")); + var node_stream_1 = require("node:stream"); + var abort_controller_1 = require_commonjs5(); + var httpHeaders_js_1 = require_httpHeaders(); + var restError_js_1 = require_restError(); + var log_js_1 = require_log(); + var DEFAULT_TLS_SETTINGS = {}; + function isReadableStream(body) { + return body && typeof body.pipe === "function"; } - function serializeBase64UrlType(objectName, value) { - if (value !== void 0 && value !== null) { - if (!(value instanceof Uint8Array)) { - throw new Error(`${objectName} must be of type Uint8Array.`); - } - value = bufferToBase64Url(value); - } - return value; + function isStreamComplete(stream) { + return new Promise((resolve2) => { + const handler = () => { + resolve2(); + stream.removeListener("close", handler); + stream.removeListener("end", handler); + stream.removeListener("error", handler); + }; + stream.on("close", handler); + stream.on("end", handler); + stream.on("error", handler); + }); } - function serializeDateTypes(typeName, value, objectName) { - if (value !== void 0 && value !== null) { - if (typeName.match(/^Date$/i) !== null) { - if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { - throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); - } - value = value instanceof Date ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10); - } else if (typeName.match(/^DateTime$/i) !== null) { - if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { - throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); - } - value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); - } else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { - if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { - throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); - } - value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); - } else if (typeName.match(/^UnixTime$/i) !== null) { - if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { - throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format for it to be serialized in UnixTime/Epoch format.`); - } - value = dateToUnixTime(value); - } else if (typeName.match(/^TimeSpan$/i) !== null) { - if (!(0, utils_js_1.isDuration)(value)) { - throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); - } - } - } - return value; + function isArrayBuffer(body) { + return body && typeof body.byteLength === "number"; } - function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { - var _a; - if (!Array.isArray(object)) { - throw new Error(`${objectName} must be of type Array.`); + var ReportTransform = class extends node_stream_1.Transform { + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + _transform(chunk, _encoding, callback) { + this.push(chunk); + this.loadedBytes += chunk.length; + try { + this.progressCallback({ loadedBytes: this.loadedBytes }); + callback(); + } catch (e) { + callback(e); + } } - let elementType = mapper.type.element; - if (!elementType || typeof elementType !== "object") { - throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}.`); + constructor(progressCallback) { + super(); + this.loadedBytes = 0; + this.progressCallback = progressCallback; } - if (elementType.type.name === "Composite" && elementType.type.className) { - elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType; + }; + var NodeHttpClient = class { + constructor() { + this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); } - const tempArray = []; - for (let i = 0; i < object.length; i++) { - const serializedValue = serializer.serialize(elementType, object[i], objectName, options); - if (isXml && elementType.xmlNamespace) { - const xmlnsKey = elementType.xmlNamespacePrefix ? `xmlns:${elementType.xmlNamespacePrefix}` : "xmlns"; - if (elementType.type.name === "Composite") { - tempArray[i] = Object.assign({}, serializedValue); - tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; - } else { - tempArray[i] = {}; - tempArray[i][options.xml.xmlCharKey] = serializedValue; - tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + var _a, _b, _c; + const abortController = new AbortController(); + let abortListener; + if (request.abortSignal) { + if (request.abortSignal.aborted) { + throw new abort_controller_1.AbortError("The operation was aborted."); } - } else { - tempArray[i] = serializedValue; - } - } - return tempArray; - } - function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { - if (typeof object !== "object") { - throw new Error(`${objectName} must be of type object.`); - } - const valueType = mapper.type.value; - if (!valueType || typeof valueType !== "object") { - throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}.`); - } - const tempDictionary = {}; - for (const key of Object.keys(object)) { - const serializedValue = serializer.serialize(valueType, object[key], objectName, options); - tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); - } - if (isXml && mapper.xmlNamespace) { - const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; - const result = tempDictionary; - result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; - return result; - } - return tempDictionary; - } - function resolveAdditionalProperties(serializer, mapper, objectName) { - const additionalProperties = mapper.type.additionalProperties; - if (!additionalProperties && mapper.type.className) { - const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); - return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; - } - return additionalProperties; - } - function resolveReferencedMapper(serializer, mapper, objectName) { - const className = mapper.type.className; - if (!className) { - throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, void 0, 2)}".`); - } - return serializer.modelMappers[className]; - } - function resolveModelProperties(serializer, mapper, objectName) { - let modelProps = mapper.type.modelProperties; - if (!modelProps) { - const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); - if (!modelMapper) { - throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); + abortListener = (event) => { + if (event.type === "abort") { + abortController.abort(); + } + }; + request.abortSignal.addEventListener("abort", abortListener); } - modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; - if (!modelProps) { - throw new Error(`modelProperties cannot be null or undefined in the mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); + if (request.timeout > 0) { + setTimeout(() => { + abortController.abort(); + }, request.timeout); } - } - return modelProps; - } - function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { - if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { - mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); - } - if (object !== void 0 && object !== null) { - const payload = {}; - const modelProps = resolveModelProperties(serializer, mapper, objectName); - for (const key of Object.keys(modelProps)) { - const propertyMapper = modelProps[key]; - if (propertyMapper.readOnly) { - continue; + const acceptEncoding = request.headers.get("Accept-Encoding"); + const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); + let body = typeof request.body === "function" ? request.body() : request.body; + if (body && !request.headers.has("Content-Length")) { + const bodyLength = getBodyLength(body); + if (bodyLength !== null) { + request.headers.set("Content-Length", bodyLength); } - let propName; - let parentObject = payload; - if (serializer.isXML) { - if (propertyMapper.xmlIsWrapped) { - propName = propertyMapper.xmlName; + } + let responseStream; + try { + if (body && request.onUploadProgress) { + const onUploadProgress = request.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + uploadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in upload progress", e); + }); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); } else { - propName = propertyMapper.xmlElementName || propertyMapper.xmlName; + uploadReportStream.end(body); } + body = uploadReportStream; + } + const res = await this.makeRequest(request, abortController, body); + const headers = getResponseHeaders(res); + const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; + const response = { + status, + headers, + request + }; + if (request.method === "HEAD") { + res.resume(); + return response; + } + responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; + const onDownloadProgress = request.onDownloadProgress; + if (onDownloadProgress) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + downloadReportStream.on("error", (e) => { + log_js_1.logger.error("Error in download progress", e); + }); + responseStream.pipe(downloadReportStream); + responseStream = downloadReportStream; + } + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status)) + ) { + response.readableStreamBody = responseStream; } else { - const paths = splitSerializeName(propertyMapper.serializedName); - propName = paths.pop(); - for (const pathName of paths) { - const childObject = parentObject[pathName]; - if ((childObject === void 0 || childObject === null) && (object[key] !== void 0 && object[key] !== null || propertyMapper.defaultValue !== void 0)) { - parentObject[pathName] = {}; - } - parentObject = parentObject[pathName]; - } + response.bodyAsText = await streamToText(responseStream); } - if (parentObject !== void 0 && parentObject !== null) { - if (isXml && mapper.xmlNamespace) { - const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; - parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); + return response; + } finally { + if (request.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); } - const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName : objectName; - let toSerialize = object[key]; - const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); - if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && (toSerialize === void 0 || toSerialize === null)) { - toSerialize = mapper.serializedName; + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(responseStream)) { + downloadStreamDone = isStreamComplete(responseStream); } - const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); - if (serializedValue !== void 0 && propName !== void 0 && propName !== null) { - const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); - if (isXml && propertyMapper.xmlIsAttribute) { - parentObject[interfaces_js_1.XML_ATTRKEY] = parentObject[interfaces_js_1.XML_ATTRKEY] || {}; - parentObject[interfaces_js_1.XML_ATTRKEY][propName] = serializedValue; - } else if (isXml && propertyMapper.xmlIsWrapped) { - parentObject[propName] = { [propertyMapper.xmlElementName]: value }; - } else { - parentObject[propName] = value; + Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { + var _a2; + if (abortListener) { + (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener); } - } - } - } - const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); - if (additionalPropertiesMapper) { - const propNames = Object.keys(modelProps); - for (const clientPropName in object) { - const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); - if (isAdditionalProperty) { - payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); - } + }).catch((e) => { + log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); } } - return payload; - } - return object; - } - function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { - if (!isXml || !propertyMapper.xmlNamespace) { - return serializedValue; - } - const xmlnsKey = propertyMapper.xmlNamespacePrefix ? `xmlns:${propertyMapper.xmlNamespacePrefix}` : "xmlns"; - const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; - if (["Composite"].includes(propertyMapper.type.name)) { - if (serializedValue[interfaces_js_1.XML_ATTRKEY]) { - return serializedValue; - } else { - const result2 = Object.assign({}, serializedValue); - result2[interfaces_js_1.XML_ATTRKEY] = xmlNamespace; - return result2; - } - } - const result = {}; - result[options.xml.xmlCharKey] = serializedValue; - result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace; - return result; - } - function isSpecialXmlProperty(propertyName, options) { - return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName); - } - function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { - var _a, _b; - const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY; - if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { - mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } - const modelProps = resolveModelProperties(serializer, mapper, objectName); - let instance = {}; - const handledPropertyNames = []; - for (const key of Object.keys(modelProps)) { - const propertyMapper = modelProps[key]; - const paths = splitSerializeName(modelProps[key].serializedName); - handledPropertyNames.push(paths[0]); - const { serializedName, xmlName, xmlElementName } = propertyMapper; - let propertyObjectName = objectName; - if (serializedName !== "" && serializedName !== void 0) { - propertyObjectName = objectName + "." + serializedName; + makeRequest(request, abortController, body) { + var _a; + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); } - const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; - if (headerCollectionPrefix) { - const dictionary = {}; - for (const headerKey of Object.keys(responseBody)) { - if (headerKey.startsWith(headerCollectionPrefix)) { - dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); - } - handledPropertyNames.push(headerKey); - } - instance[key] = dictionary; - } else if (serializer.isXML) { - if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) { - instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options); - } else if (propertyMapper.xmlIsMsText) { - if (responseBody[xmlCharKey] !== void 0) { - instance[key] = responseBody[xmlCharKey]; - } else if (typeof responseBody === "string") { - instance[key] = responseBody; - } - } else { - const propertyName = xmlElementName || xmlName || serializedName; - if (propertyMapper.xmlIsWrapped) { - const wrapped = responseBody[xmlName]; - const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : []; - instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); - handledPropertyNames.push(xmlName); + const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); + const options = { + agent, + hostname: url.hostname, + path: `${url.pathname}${url.search}`, + port: url.port, + method: request.method, + headers: request.headers.toJSON({ preserveCase: true }) + }; + return new Promise((resolve2, reject) => { + const req = isInsecure ? http.request(options, resolve2) : https2.request(options, resolve2); + req.once("error", (err) => { + var _a2; + reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request })); + }); + abortController.signal.addEventListener("abort", () => { + const abortError = new abort_controller_1.AbortError("The operation was aborted."); + req.destroy(abortError); + reject(abortError); + }); + if (body && isReadableStream(body)) { + body.pipe(req); + } else if (body) { + if (typeof body === "string" || Buffer.isBuffer(body)) { + req.end(body); + } else if (isArrayBuffer(body)) { + req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); } else { - const property = responseBody[propertyName]; - instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); - handledPropertyNames.push(propertyName); + log_js_1.logger.error("Unrecognized body type", body); + reject(new restError_js_1.RestError("Unrecognized body type")); } + } else { + req.end(); } - } else { - let propertyInstance; - let res = responseBody; - let steps = 0; - for (const item of paths) { - if (!res) - break; - steps++; - res = res[item]; + }); + } + getOrCreateAgent(request, isInsecure) { + var _a; + const disableKeepAlive = request.disableKeepAlive; + if (isInsecure) { + if (disableKeepAlive) { + return http.globalAgent; } - if (res === null && steps < paths.length) { - res = void 0; + if (!this.cachedHttpAgent) { + this.cachedHttpAgent = new http.Agent({ keepAlive: true }); } - propertyInstance = res; - const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; - if (polymorphicDiscriminator && key === polymorphicDiscriminator.clientName && (propertyInstance === void 0 || propertyInstance === null)) { - propertyInstance = mapper.serializedName; + return this.cachedHttpAgent; + } else { + if (disableKeepAlive && !request.tlsSettings) { + return https2.globalAgent; } - let serializedValue; - if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { - propertyInstance = responseBody[key]; - const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); - for (const [k, v] of Object.entries(instance)) { - if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { - arrayInstance[k] = v; - } - } - instance = arrayInstance; - } else if (propertyInstance !== void 0 || propertyMapper.defaultValue !== void 0) { - serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); - instance[key] = serializedValue; + const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; + let agent = this.cachedHttpsAgents.get(tlsSettings); + if (agent && agent.options.keepAlive === !disableKeepAlive) { + return agent; } + log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent"); + agent = new https2.Agent(Object.assign({ + // keepAlive is true if disableKeepAlive is false. + keepAlive: !disableKeepAlive + }, tlsSettings)); + this.cachedHttpsAgents.set(tlsSettings, agent); + return agent; } } - const additionalPropertiesMapper = mapper.type.additionalProperties; - if (additionalPropertiesMapper) { - const isAdditionalProperty = (responsePropName) => { - for (const clientPropName in modelProps) { - const paths = splitSerializeName(modelProps[clientPropName].serializedName); - if (paths[0] === responsePropName) { - return false; - } - } - return true; - }; - for (const responsePropName in responseBody) { - if (isAdditionalProperty(responsePropName)) { - instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); - } - } - } else if (responseBody && !options.ignoreUnknownProperties) { - for (const key of Object.keys(responseBody)) { - if (instance[key] === void 0 && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) { - instance[key] = responseBody[key]; + }; + function getResponseHeaders(res) { + const headers = (0, httpHeaders_js_1.createHttpHeaders)(); + for (const header of Object.keys(res.headers)) { + const value = res.headers[header]; + if (Array.isArray(value)) { + if (value.length > 0) { + headers.set(header, value[0]); } + } else if (value) { + headers.set(header, value); } } - return instance; - } - function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { - const value = mapper.type.value; - if (!value || typeof value !== "object") { - throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}`); - } - if (responseBody) { - const tempDictionary = {}; - for (const key of Object.keys(responseBody)) { - tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); - } - return tempDictionary; - } - return responseBody; - } - function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { - var _a; - let element = mapper.type.element; - if (!element || typeof element !== "object") { - throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}`); - } - if (responseBody) { - if (!Array.isArray(responseBody)) { - responseBody = [responseBody]; - } - if (element.type.name === "Composite" && element.type.className) { - element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element; - } - const tempArray = []; - for (let i = 0; i < responseBody.length; i++) { - tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); - } - return tempArray; - } - return responseBody; + return headers; } - function getIndexDiscriminator(discriminators, discriminatorValue, typeName) { - const typeNamesToCheck = [typeName]; - while (typeNamesToCheck.length) { - const currentName = typeNamesToCheck.shift(); - const indexDiscriminator = discriminatorValue === currentName ? discriminatorValue : currentName + "." + discriminatorValue; - if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) { - return discriminators[indexDiscriminator]; - } else { - for (const [name, mapper] of Object.entries(discriminators)) { - if (name.startsWith(currentName + ".") && mapper.type.uberParent === currentName && mapper.type.className) { - typeNamesToCheck.push(mapper.type.className); - } - } - } + function getDecodedResponseStream(stream, headers) { + const contentEncoding = headers.get("Content-Encoding"); + if (contentEncoding === "gzip") { + const unzip = zlib.createGunzip(); + stream.pipe(unzip); + return unzip; + } else if (contentEncoding === "deflate") { + const inflate = zlib.createInflate(); + stream.pipe(inflate); + return inflate; } - return void 0; + return stream; } - function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { - var _a; - const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); - if (polymorphicDiscriminator) { - let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; - if (discriminatorName) { - if (polymorphicPropertyName === "serializedName") { - discriminatorName = discriminatorName.replace(/\\/gi, ""); + function streamToText(stream) { + return new Promise((resolve2, reject) => { + const buffer = []; + stream.on("data", (chunk) => { + if (Buffer.isBuffer(chunk)) { + buffer.push(chunk); + } else { + buffer.push(Buffer.from(chunk)); } - const discriminatorValue = object[discriminatorName]; - const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className; - if (typeof discriminatorValue === "string" && typeName) { - const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName); - if (polymorphicMapper) { - mapper = polymorphicMapper; - } + }); + stream.on("end", () => { + resolve2(Buffer.concat(buffer).toString("utf8")); + }); + stream.on("error", (e) => { + if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { + reject(e); + } else { + reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, { + code: restError_js_1.RestError.PARSE_ERROR + })); } - } + }); + }); + } + function getBodyLength(body) { + if (!body) { + return 0; + } else if (Buffer.isBuffer(body)) { + return body.length; + } else if (isReadableStream(body)) { + return null; + } else if (isArrayBuffer(body)) { + return body.byteLength; + } else if (typeof body === "string") { + return Buffer.from(body).length; + } else { + return null; } - return mapper; } - function getPolymorphicDiscriminatorRecursively(serializer, mapper) { - return mapper.type.polymorphicDiscriminator || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className); - } - function getPolymorphicDiscriminatorSafely(serializer, typeName) { - return typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator; + function createNodeHttpClient() { + return new NodeHttpClient(); } - exports2.MapperTypeNames = { - Base64Url: "Base64Url", - Boolean: "Boolean", - ByteArray: "ByteArray", - Composite: "Composite", - Date: "Date", - DateTime: "DateTime", - DateTimeRfc1123: "DateTimeRfc1123", - Dictionary: "Dictionary", - Enum: "Enum", - Number: "Number", - Object: "Object", - Sequence: "Sequence", - String: "String", - Stream: "Stream", - TimeSpan: "TimeSpan", - UnixTime: "UnixTime" - }; } }); -// node_modules/@azure/core-client/dist/commonjs/state.js -var require_state2 = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/state.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js +var require_defaultHttpClient = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.state = void 0; - exports2.state = { - operationRequestMap: /* @__PURE__ */ new WeakMap() - }; + exports2.createDefaultHttpClient = createDefaultHttpClient; + var nodeHttpClient_js_1 = require_nodeHttpClient(); + function createDefaultHttpClient() { + return (0, nodeHttpClient_js_1.createNodeHttpClient)(); + } } }); -// node_modules/@azure/core-client/dist/commonjs/operationHelpers.js -var require_operationHelpers = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/operationHelpers.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js +var require_pipelineRequest = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getOperationRequestInfo = exports2.getOperationArgumentValueFromParameter = void 0; - var state_js_1 = require_state2(); - function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) { - let parameterPath = parameter.parameterPath; - const parameterMapper = parameter.mapper; - let value; - if (typeof parameterPath === "string") { - parameterPath = [parameterPath]; - } - if (Array.isArray(parameterPath)) { - if (parameterPath.length > 0) { - if (parameterMapper.isConstant) { - value = parameterMapper.defaultValue; - } else { - let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); - if (!propertySearchResult.propertyFound && fallbackObject) { - propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath); - } - let useDefaultValue = false; - if (!propertySearchResult.propertyFound) { - useDefaultValue = parameterMapper.required || parameterPath[0] === "options" && parameterPath.length === 2; - } - value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; - } - } - } else { - if (parameterMapper.required) { - value = {}; - } - for (const propertyName in parameterPath) { - const propertyMapper = parameterMapper.type.modelProperties[propertyName]; - const propertyPath = parameterPath[propertyName]; - const propertyValue = getOperationArgumentValueFromParameter(operationArguments, { - parameterPath: propertyPath, - mapper: propertyMapper - }, fallbackObject); - if (propertyValue !== void 0) { - if (!value) { - value = {}; - } - value[propertyName] = propertyValue; - } - } - } - return value; - } - exports2.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter; - function getPropertyFromParameterPath(parent, parameterPath) { - const result = { propertyFound: false }; - let i = 0; - for (; i < parameterPath.length; ++i) { - const parameterPathPart = parameterPath[i]; - if (parent && parameterPathPart in parent) { - parent = parent[parameterPathPart]; - } else { - break; - } - } - if (i === parameterPath.length) { - result.propertyValue = parent; - result.propertyFound = true; + exports2.createPipelineRequest = createPipelineRequest; + var httpHeaders_js_1 = require_httpHeaders(); + var core_util_1 = require_commonjs4(); + var PipelineRequestImpl = class { + constructor(options) { + var _a, _b, _c, _d, _e, _f, _g; + this.url = options.url; + this.body = options.body; + this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)(); + this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; + this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; + this.multipartBody = options.multipartBody; + this.formData = options.formData; + this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; + this.proxySettings = options.proxySettings; + this.streamResponseStatusCodes = options.streamResponseStatusCodes; + this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; + this.abortSignal = options.abortSignal; + this.tracingOptions = options.tracingOptions; + this.onUploadProgress = options.onUploadProgress; + this.onDownloadProgress = options.onDownloadProgress; + this.requestId = options.requestId || (0, core_util_1.randomUUID)(); + this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; + this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; } - return result; - } - var originalRequestSymbol = Symbol.for("@azure/core-client original request"); - function hasOriginalRequest(request) { - return originalRequestSymbol in request; + }; + function createPipelineRequest(options) { + return new PipelineRequestImpl(options); } - function getOperationRequestInfo(request) { - if (hasOriginalRequest(request)) { - return getOperationRequestInfo(request[originalRequestSymbol]); - } - let info7 = state_js_1.state.operationRequestMap.get(request); - if (!info7) { - info7 = {}; - state_js_1.state.operationRequestMap.set(request, info7); - } - return info7; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js +var require_exponentialRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.exponentialRetryPolicyName = void 0; + exports2.exponentialRetryPolicy = exponentialRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants7(); + exports2.exponentialRetryPolicyName = "exponentialRetryPolicy"; + function exponentialRetryPolicy(options = {}) { + var _a; + return (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }); } - exports2.getOperationRequestInfo = getOperationRequestInfo; } }); -// node_modules/@azure/core-client/dist/commonjs/deserializationPolicy.js -var require_deserializationPolicy = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/deserializationPolicy.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js +var require_systemErrorRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.deserializationPolicy = exports2.deserializationPolicyName = void 0; - var interfaces_js_1 = require_interfaces(); - var core_rest_pipeline_1 = require_commonjs7(); - var serializer_js_1 = require_serializer(); - var operationHelpers_js_1 = require_operationHelpers(); - var defaultJsonContentTypes = ["application/json", "text/json"]; - var defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; - exports2.deserializationPolicyName = "deserializationPolicy"; - function deserializationPolicy(options = {}) { - var _a, _b, _c, _d, _e, _f, _g; - const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes; - const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes; - const parseXML = options.parseXML; - const serializerOptions = options.serializerOptions; - const updatedOptions = { - xml: { - rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "", - includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false, - xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY - } + exports2.systemErrorRetryPolicyName = void 0; + exports2.systemErrorRetryPolicy = systemErrorRetryPolicy; + var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants7(); + exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy"; + function systemErrorRetryPolicy(options = {}) { + var _a; + return { + name: exports2.systemErrorRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([ + (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })) + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest }; + } + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js +var require_throttlingRetryPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.throttlingRetryPolicyName = void 0; + exports2.throttlingRetryPolicy = throttlingRetryPolicy; + var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy(); + var retryPolicy_js_1 = require_retryPolicy(); + var constants_js_1 = require_constants7(); + exports2.throttlingRetryPolicyName = "throttlingRetryPolicy"; + function throttlingRetryPolicy(options = {}) { + var _a; return { - name: exports2.deserializationPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML); - } + name: exports2.throttlingRetryPolicyName, + sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT + }).sendRequest }; } - exports2.deserializationPolicy = deserializationPolicy; - function getOperationResponseMap(parsedResponse) { - let result; - const request = parsedResponse.request; - const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); - const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; - if (operationSpec) { - if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) { - result = operationSpec.responses[parsedResponse.status]; + } +}); + +// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js +var require_tokenCycler = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DEFAULT_CYCLER_OPTIONS = void 0; + exports2.createTokenCycler = createTokenCycler; + var helpers_js_1 = require_helpers(); + exports2.DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1e3, + // Force waiting for a refresh 1s before the token expires + retryIntervalInMs: 3e3, + // Allow refresh attempts every 3s + refreshWindowInMs: 1e3 * 60 * 2 + // Start refreshing 2m before expiry + }; + async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { + async function tryGetAccessToken() { + if (Date.now() < refreshTimeout) { + try { + return await getAccessToken(); + } catch (_a) { + return null; + } } else { - result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse); + const finalToken = await getAccessToken(); + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; } } - return result; - } - function shouldDeserializeResponse(parsedResponse) { - const request = parsedResponse.request; - const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); - const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize; - let result; - if (shouldDeserialize === void 0) { - result = true; - } else if (typeof shouldDeserialize === "boolean") { - result = shouldDeserialize; - } else { - result = shouldDeserialize(parsedResponse); + let token = await tryGetAccessToken(); + while (token === null) { + await (0, helpers_js_1.delay)(retryIntervalInMs); + token = await tryGetAccessToken(); } - return result; + return token; } - async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) { - const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML); - if (!shouldDeserializeResponse(parsedResponse)) { - return parsedResponse; - } - const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request); - const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; - if (!operationSpec || !operationSpec.responses) { - return parsedResponse; - } - const responseSpec = getOperationResponseMap(parsedResponse); - const { error: error4, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options); - if (error4) { - throw error4; - } else if (shouldReturnResponse) { - return parsedResponse; - } - if (responseSpec) { - if (responseSpec.bodyMapper) { - let valueToDeserialize = parsedResponse.parsedBody; - if (operationSpec.isXML && responseSpec.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) { - valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : []; + function createTokenCycler(credential, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + let tenantId; + const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + const cycler = { + /** + * Produces true if a refresh job is currently in progress. + */ + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) + */ + get shouldRefresh() { + var _a; + if (cycler.isRefreshing) { + return false; } - try { - parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); - } catch (deserializeError) { - const restError = new core_rest_pipeline_1.RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, { - statusCode: parsedResponse.status, - request: parsedResponse.request, - response: parsedResponse - }); - throw restError; + if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { + return true; } - } else if (operationSpec.httpMethod === "HEAD") { - parsedResponse.parsedBody = response.status >= 200 && response.status < 300; - } - if (responseSpec.headersMapper) { - parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true }); + return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); } - } - return parsedResponse; - } - function isOperationSpecEmpty(operationSpec) { - const expectedStatusCodes = Object.keys(operationSpec.responses); - return expectedStatusCodes.length === 0 || expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"; - } - function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) { - var _a; - const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; - const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus : !!responseSpec; - if (isExpectedStatusCode) { - if (responseSpec) { - if (!responseSpec.isError) { - return { error: null, shouldReturnResponse: false }; - } - } else { - return { error: null, shouldReturnResponse: false }; + }; + function refresh(scopes, getTokenOptions) { + var _a; + if (!cycler.isRefreshing) { + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); + refreshWorker = beginRefresh( + tryGetAccessToken, + options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now() + ).then((_token) => { + refreshWorker = null; + token = _token; + tenantId = getTokenOptions.tenantId; + return token; + }).catch((reason) => { + refreshWorker = null; + token = null; + tenantId = void 0; + throw reason; + }); } + return refreshWorker; } - const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; - const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) ? `Unexpected status code: ${parsedResponse.status}` : parsedResponse.bodyAsText; - const error4 = new core_rest_pipeline_1.RestError(initialErrorMessage, { - statusCode: parsedResponse.status, - request: parsedResponse.request, - response: parsedResponse - }); - if (!errorResponseSpec) { - throw error4; - } - const defaultBodyMapper = errorResponseSpec.bodyMapper; - const defaultHeadersMapper = errorResponseSpec.headersMapper; - try { - if (parsedResponse.parsedBody) { - const parsedBody = parsedResponse.parsedBody; - let deserializedError; - if (defaultBodyMapper) { - let valueToDeserialize = parsedBody; - if (operationSpec.isXML && defaultBodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) { - valueToDeserialize = []; - const elementName = defaultBodyMapper.xmlElementName; - if (typeof parsedBody === "object" && elementName) { - valueToDeserialize = parsedBody[elementName]; - } - } - deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options); - } - const internalError = parsedBody.error || deserializedError || parsedBody; - error4.code = internalError.code; - if (internalError.message) { - error4.message = internalError.message; - } - if (defaultBodyMapper) { - error4.response.parsedBody = deserializedError; - } + return async (scopes, tokenOptions) => { + const hasClaimChallenge = Boolean(tokenOptions.claims); + const tenantIdChanged = tenantId !== tokenOptions.tenantId; + if (hasClaimChallenge) { + token = null; } - if (parsedResponse.headers && defaultHeadersMapper) { - error4.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders"); + const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; + if (mustRefresh) { + return refresh(scopes, tokenOptions); } - } catch (defaultError) { - error4.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; - } - return { error: error4, shouldReturnResponse: false }; - } - async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) { - var _a; - if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) && operationResponse.bodyAsText) { - const text = operationResponse.bodyAsText; - const contentType = operationResponse.headers.get("Content-Type") || ""; - const contentComponents = !contentType ? [] : contentType.split(";").map((component) => component.toLowerCase()); - try { - if (contentComponents.length === 0 || contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { - operationResponse.parsedBody = JSON.parse(text); - return operationResponse; - } else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { - if (!parseXML) { - throw new Error("Parsing XML not supported."); - } - const body = await parseXML(text, opts.xml); - operationResponse.parsedBody = body; - return operationResponse; - } - } catch (err) { - const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; - const errCode = err.code || core_rest_pipeline_1.RestError.PARSE_ERROR; - const e = new core_rest_pipeline_1.RestError(msg, { - code: errCode, - statusCode: operationResponse.status, - request: operationResponse.request, - response: operationResponse - }); - throw e; + if (cycler.shouldRefresh) { + refresh(scopes, tokenOptions); } - } - return operationResponse; + return token; + }; } } }); -// node_modules/@azure/core-client/dist/commonjs/interfaceHelpers.js -var require_interfaceHelpers = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/interfaceHelpers.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js +var require_bearerTokenAuthenticationPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getPathStringFromParameter = exports2.getStreamingResponseStatusCodes = void 0; - var serializer_js_1 = require_serializer(); - function getStreamingResponseStatusCodes(operationSpec) { - const result = /* @__PURE__ */ new Set(); - for (const statusCode in operationSpec.responses) { - const operationResponse = operationSpec.responses[statusCode]; - if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) { - result.add(Number(statusCode)); - } - } - return result; - } - exports2.getStreamingResponseStatusCodes = getStreamingResponseStatusCodes; - function getPathStringFromParameter(parameter) { - const { parameterPath, mapper } = parameter; - let result; - if (typeof parameterPath === "string") { - result = parameterPath; - } else if (Array.isArray(parameterPath)) { - result = parameterPath.join("."); - } else { - result = mapper.serializedName; + exports2.bearerTokenAuthenticationPolicyName = void 0; + exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log(); + exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; + async function defaultAuthorizeRequest(options) { + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions + }; + const accessToken = await getAccessToken(scopes, getTokenOptions); + if (accessToken) { + options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); } - return result; } - exports2.getPathStringFromParameter = getPathStringFromParameter; - } -}); - -// node_modules/@azure/core-client/dist/commonjs/serializationPolicy.js -var require_serializationPolicy = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/serializationPolicy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.serializeRequestBody = exports2.serializeHeaders = exports2.serializationPolicy = exports2.serializationPolicyName = void 0; - var interfaces_js_1 = require_interfaces(); - var operationHelpers_js_1 = require_operationHelpers(); - var serializer_js_1 = require_serializer(); - var interfaceHelpers_js_1 = require_interfaceHelpers(); - exports2.serializationPolicyName = "serializationPolicy"; - function serializationPolicy(options = {}) { - const stringifyXML = options.stringifyXML; + function getChallenge(response) { + const challenge = response.headers.get("WWW-Authenticate"); + if (response.status === 401 && challenge) { + return challenge; + } + return; + } + function bearerTokenAuthenticationPolicy(options) { + var _a; + const { credential, scopes, challengeCallbacks } = options; + const logger = options.logger || log_js_1.logger; + const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); + const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)( + credential + /* , options */ + ) : () => Promise.resolve(null); return { - name: exports2.serializationPolicyName, + name: exports2.bearerTokenAuthenticationPolicyName, + /** + * If there's no challenge parameter: + * - It will try to retrieve the token using the cache, or the credential's getToken. + * - Then it will try the next policy with or without the retrieved token. + * + * It uses the challenge parameters to: + * - Skip a first attempt to get the token from the credential if there's no cached token, + * since it expects the token to be retrievable only after the challenge. + * - Prepare the outgoing request if the `prepareRequest` method has been provided. + * - Send an initial request to receive the challenge if it fails. + * - Process a challenge if the response contains it. + * - Retrieve a token with the challenge information, then re-send the request. + */ async sendRequest(request, next) { - const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); - const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; - const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments; - if (operationSpec && operationArguments) { - serializeHeaders(request, operationArguments, operationSpec); - serializeRequestBody(request, operationArguments, operationSpec, stringifyXML); + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); } - return next(request); - } - }; - } - exports2.serializationPolicy = serializationPolicy; - function serializeHeaders(request, operationArguments, operationSpec) { - var _a, _b; - if (operationSpec.headerParameters) { - for (const headerParameter of operationSpec.headerParameters) { - let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter); - if (headerValue !== null && headerValue !== void 0 || headerParameter.mapper.required) { - headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter)); - const headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix; - if (headerCollectionPrefix) { - for (const key of Object.keys(headerValue)) { - request.headers.set(headerCollectionPrefix + key, headerValue[key]); - } - } else { - request.headers.set(headerParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter), headerValue); - } + await callbacks.authorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + }); + let response; + let error4; + try { + response = await next(request); + } catch (err) { + error4 = err; + response = err.response; } - } - } - const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders; - if (customHeaders) { - for (const customHeaderName of Object.keys(customHeaders)) { - request.headers.set(customHeaderName, customHeaders[customHeaderName]); - } - } - } - exports2.serializeHeaders = serializeHeaders; - function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function() { - throw new Error("XML serialization unsupported!"); - }) { - var _a, _b, _c, _d, _e; - const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; - const updatedOptions = { - xml: { - rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "", - includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false, - xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY - } - }; - const xmlCharKey = updatedOptions.xml.xmlCharKey; - if (operationSpec.requestBody && operationSpec.requestBody.mapper) { - request.body = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, operationSpec.requestBody); - const bodyMapper = operationSpec.requestBody.mapper; - const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable } = bodyMapper; - const typeName = bodyMapper.type.name; - try { - if (request.body !== void 0 && request.body !== null || nullable && request.body === null || required) { - const requestBodyParameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(operationSpec.requestBody); - request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions); - const isStream = typeName === serializer_js_1.MapperTypeNames.Stream; - if (operationSpec.isXML) { - const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; - const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions); - if (typeName === serializer_js_1.MapperTypeNames.Sequence) { - request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey }); - } else if (!isStream) { - request.body = stringifyXML(value, { - rootName: xmlName || serializedName, - xmlCharKey - }); - } - } else if (typeName === serializer_js_1.MapperTypeNames.String && (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) { - return; - } else if (!isStream) { - request.body = JSON.stringify(request.body); + if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) { + const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + response, + getAccessToken, + logger + }); + if (shouldSendRequest) { + return next(request); } } - } catch (error4) { - throw new Error(`Error "${error4.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, void 0, " ")}.`); - } - } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { - request.formData = {}; - for (const formDataParameter of operationSpec.formDataParameters) { - const formDataParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, formDataParameter); - if (formDataParameterValue !== void 0 && formDataParameterValue !== null) { - const formDataParameterPropertyName = formDataParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter); - request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter), updatedOptions); + if (error4) { + throw error4; + } else { + return response; } } - } - } - exports2.serializeRequestBody = serializeRequestBody; - function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { - if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { - const result = {}; - result[options.xml.xmlCharKey] = serializedValue; - result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; - return result; - } - return serializedValue; - } - function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { - if (!Array.isArray(obj)) { - obj = [obj]; - } - if (!xmlNamespaceKey || !xmlNamespace) { - return { [elementName]: obj }; - } - const result = { [elementName]: obj }; - result[interfaces_js_1.XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; - return result; - } - } -}); - -// node_modules/@azure/core-client/dist/commonjs/pipeline.js -var require_pipeline2 = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/pipeline.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createClientPipeline = void 0; - var deserializationPolicy_js_1 = require_deserializationPolicy(); - var core_rest_pipeline_1 = require_commonjs7(); - var serializationPolicy_js_1 = require_serializationPolicy(); - function createClientPipeline(options = {}) { - const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {}); - if (options.credentialOptions) { - pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({ - credential: options.credentialOptions.credential, - scopes: options.credentialOptions.credentialScopes - })); - } - pipeline.addPolicy((0, serializationPolicy_js_1.serializationPolicy)(options.serializationOptions), { phase: "Serialize" }); - pipeline.addPolicy((0, deserializationPolicy_js_1.deserializationPolicy)(options.deserializationOptions), { - phase: "Deserialize" - }); - return pipeline; + }; } - exports2.createClientPipeline = createClientPipeline; } }); -// node_modules/@azure/core-client/dist/commonjs/httpClientCache.js -var require_httpClientCache = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/httpClientCache.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js +var require_ndJsonPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getCachedDefaultHttpClient = void 0; - var core_rest_pipeline_1 = require_commonjs7(); - var cachedHttpClient; - function getCachedDefaultHttpClient() { - if (!cachedHttpClient) { - cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)(); - } - return cachedHttpClient; + exports2.ndJsonPolicyName = void 0; + exports2.ndJsonPolicy = ndJsonPolicy; + exports2.ndJsonPolicyName = "ndJsonPolicy"; + function ndJsonPolicy() { + return { + name: exports2.ndJsonPolicyName, + async sendRequest(request, next) { + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } + return next(request); + } + }; } - exports2.getCachedDefaultHttpClient = getCachedDefaultHttpClient; } }); -// node_modules/@azure/core-client/dist/commonjs/urlHelpers.js -var require_urlHelpers = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/urlHelpers.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js +var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.appendQueryParams = exports2.getRequestUrl = void 0; - var operationHelpers_js_1 = require_operationHelpers(); - var interfaceHelpers_js_1 = require_interfaceHelpers(); - var CollectionFormatToDelimiterMap = { - CSV: ",", - SSV: " ", - Multi: "Multi", - TSV: " ", - Pipes: "|" - }; - function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) { - const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject); - let isAbsolutePath = false; - let requestUrl = replaceAll(baseUri, urlReplacements); - if (operationSpec.path) { - let path2 = replaceAll(operationSpec.path, urlReplacements); - if (operationSpec.path === "/{nextLink}" && path2.startsWith("/")) { - path2 = path2.substring(1); - } - if (isAbsoluteUrl(path2)) { - requestUrl = path2; - isAbsolutePath = true; - } else { - requestUrl = appendPath(requestUrl, path2); - } - } - const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject); - requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath); - return requestUrl; - } - exports2.getRequestUrl = getRequestUrl; - function replaceAll(input, replacements) { - let result = input; - for (const [searchValue, replaceValue] of replacements) { - result = result.split(searchValue).join(replaceValue); - } - return result; - } - function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) { - var _a; - const result = /* @__PURE__ */ new Map(); - if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) { - for (const urlParameter of operationSpec.urlParameters) { - let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject); - const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter); - urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString); - if (!urlParameter.skipEncoding) { - urlParameterValue = encodeURIComponent(urlParameterValue); - } - result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue); - } - } - return result; - } - function isAbsoluteUrl(url) { - return url.includes("://"); - } - function appendPath(url, pathToAppend) { - if (!pathToAppend) { - return url; - } - const parsedUrl = new URL(url); - let newPath = parsedUrl.pathname; - if (!newPath.endsWith("/")) { - newPath = `${newPath}/`; - } - if (pathToAppend.startsWith("/")) { - pathToAppend = pathToAppend.substring(1); - } - const searchStart = pathToAppend.indexOf("?"); - if (searchStart !== -1) { - const path2 = pathToAppend.substring(0, searchStart); - const search = pathToAppend.substring(searchStart + 1); - newPath = newPath + path2; - if (search) { - parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search; - } - } else { - newPath = newPath + pathToAppend; - } - parsedUrl.pathname = newPath; - return parsedUrl.toString(); - } - function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) { - var _a; - const result = /* @__PURE__ */ new Map(); - const sequenceParams = /* @__PURE__ */ new Set(); - if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) { - for (const queryParameter of operationSpec.queryParameters) { - if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) { - sequenceParams.add(queryParameter.mapper.serializedName); - } - let queryParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, queryParameter, fallbackObject); - if (queryParameterValue !== void 0 && queryParameterValue !== null || queryParameter.mapper.required) { - queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter)); - const delimiter = queryParameter.collectionFormat ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat] : ""; - if (Array.isArray(queryParameterValue)) { - queryParameterValue = queryParameterValue.map((item) => { - if (item === null || item === void 0) { - return ""; - } - return item; - }); - } - if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) { - continue; - } else if (Array.isArray(queryParameterValue) && (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) { - queryParameterValue = queryParameterValue.join(delimiter); - } - if (!queryParameter.skipEncoding) { - if (Array.isArray(queryParameterValue)) { - queryParameterValue = queryParameterValue.map((item) => { - return encodeURIComponent(item); - }); - } else { - queryParameterValue = encodeURIComponent(queryParameterValue); - } - } - if (Array.isArray(queryParameterValue) && (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) { - queryParameterValue = queryParameterValue.join(delimiter); - } - result.set(queryParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter), queryParameterValue); - } - } - } - return { - queryParams: result, - sequenceParams + exports2.auxiliaryAuthenticationHeaderPolicyName = void 0; + exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; + var tokenCycler_js_1 = require_tokenCycler(); + var log_js_1 = require_log(); + exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy"; + var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary"; + async function sendAuthorizeRequest(options) { + var _a, _b; + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions }; + return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : ""; } - function simpleParseQueryParams(queryString) { - const result = /* @__PURE__ */ new Map(); - if (!queryString || queryString[0] !== "?") { - return result; - } - queryString = queryString.slice(1); - const pairs2 = queryString.split("&"); - for (const pair of pairs2) { - const [name, value] = pair.split("=", 2); - const existingValue = result.get(name); - if (existingValue) { - if (Array.isArray(existingValue)) { - existingValue.push(value); - } else { - result.set(name, [existingValue, value]); - } - } else { - result.set(name, value); - } - } - return result; - } - function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) { - if (queryParams.size === 0) { - return url; - } - const parsedUrl = new URL(url); - const combinedParams = simpleParseQueryParams(parsedUrl.search); - for (const [name, value] of queryParams) { - const existingValue = combinedParams.get(name); - if (Array.isArray(existingValue)) { - if (Array.isArray(value)) { - existingValue.push(...value); - const valueSet = new Set(existingValue); - combinedParams.set(name, Array.from(valueSet)); - } else { - existingValue.push(value); + function auxiliaryAuthenticationHeaderPolicy(options) { + const { credentials, scopes } = options; + const logger = options.logger || log_js_1.logger; + const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); + return { + name: exports2.auxiliaryAuthenticationHeaderPolicyName, + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); } - } else if (existingValue) { - if (Array.isArray(value)) { - value.unshift(existingValue); - } else if (sequenceParams.has(name)) { - combinedParams.set(name, [existingValue, value]); + if (!credentials || credentials.length === 0) { + logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); + return next(request); } - if (!noOverwrite) { - combinedParams.set(name, value); + const tokenPromises = []; + for (const credential of credentials) { + let getAccessToken = tokenCyclerMap.get(credential); + if (!getAccessToken) { + getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential); + tokenCyclerMap.set(credential, getAccessToken); + } + tokenPromises.push(sendAuthorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger + })); } - } else { - combinedParams.set(name, value); - } - } - const searchPieces = []; - for (const [name, value] of combinedParams) { - if (typeof value === "string") { - searchPieces.push(`${name}=${value}`); - } else if (Array.isArray(value)) { - for (const subValue of value) { - searchPieces.push(`${name}=${subValue}`); + const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); + if (auxiliaryTokens.length === 0) { + logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); + return next(request); } - } else { - searchPieces.push(`${name}=${value}`); + request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); + return next(request); } - } - parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; - return parsedUrl.toString(); + }; } - exports2.appendQueryParams = appendQueryParams; } }); -// node_modules/@azure/core-client/dist/commonjs/log.js -var require_log2 = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/log.js"(exports2) { +// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js +var require_commonjs7 = __commonJS({ + "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.logger = void 0; - var logger_1 = require_dist(); - exports2.logger = (0, logger_1.createClientLogger)("core-client"); - } -}); - -// node_modules/@azure/core-client/dist/commonjs/serviceClient.js -var require_serviceClient = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/serviceClient.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ServiceClient = void 0; - var core_rest_pipeline_1 = require_commonjs7(); - var pipeline_js_1 = require_pipeline2(); - var utils_js_1 = require_utils5(); - var httpClientCache_js_1 = require_httpClientCache(); - var operationHelpers_js_1 = require_operationHelpers(); - var urlHelpers_js_1 = require_urlHelpers(); - var interfaceHelpers_js_1 = require_interfaceHelpers(); - var log_js_1 = require_log2(); - var ServiceClient = class { - /** - * The ServiceClient constructor - * @param credential - The credentials used for authentication with the service. - * @param options - The service client options that govern the behavior of the client. - */ - constructor(options = {}) { - var _a, _b; - this._requestContentType = options.requestContentType; - this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri; - if (options.baseUri) { - log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead."); - } - this._allowInsecureConnection = options.allowInsecureConnection; - this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)(); - this.pipeline = options.pipeline || createDefaultPipeline(options); - if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) { - for (const { policy, position } of options.additionalPolicies) { - const afterPhase = position === "perRetry" ? "Sign" : void 0; - this.pipeline.addPolicy(policy, { - afterPhase - }); - } - } - } - /** - * Send the provided httpRequest. - */ - async sendRequest(request) { - return this.pipeline.sendRequest(this._httpClient, request); - } - /** - * Send an HTTP request that is populated using the provided OperationSpec. - * @typeParam T - The typed result of the request, based on the OperationSpec. - * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. - * @param operationSpec - The OperationSpec to use to populate the httpRequest. - */ - async sendOperationRequest(operationArguments, operationSpec) { - const endpoint = operationSpec.baseUrl || this._endpoint; - if (!endpoint) { - throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use."); - } - const url = (0, urlHelpers_js_1.getRequestUrl)(endpoint, operationSpec, operationArguments, this); - const request = (0, core_rest_pipeline_1.createPipelineRequest)({ - url - }); - request.method = operationSpec.httpMethod; - const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); - operationInfo.operationSpec = operationSpec; - operationInfo.operationArguments = operationArguments; - const contentType = operationSpec.contentType || this._requestContentType; - if (contentType && operationSpec.requestBody) { - request.headers.set("Content-Type", contentType); - } - const options = operationArguments.options; - if (options) { - const requestOptions = options.requestOptions; - if (requestOptions) { - if (requestOptions.timeout) { - request.timeout = requestOptions.timeout; - } - if (requestOptions.onUploadProgress) { - request.onUploadProgress = requestOptions.onUploadProgress; - } - if (requestOptions.onDownloadProgress) { - request.onDownloadProgress = requestOptions.onDownloadProgress; - } - if (requestOptions.shouldDeserialize !== void 0) { - operationInfo.shouldDeserialize = requestOptions.shouldDeserialize; - } - if (requestOptions.allowInsecureConnection) { - request.allowInsecureConnection = true; - } - } - if (options.abortSignal) { - request.abortSignal = options.abortSignal; - } - if (options.tracingOptions) { - request.tracingOptions = options.tracingOptions; - } - } - if (this._allowInsecureConnection) { - request.allowInsecureConnection = true; - } - if (request.streamResponseStatusCodes === void 0) { - request.streamResponseStatusCodes = (0, interfaceHelpers_js_1.getStreamingResponseStatusCodes)(operationSpec); - } - try { - const rawResponse = await this.sendRequest(request); - const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]); - if (options === null || options === void 0 ? void 0 : options.onResponse) { - options.onResponse(rawResponse, flatResponse); - } - return flatResponse; - } catch (error4) { - if (typeof error4 === "object" && (error4 === null || error4 === void 0 ? void 0 : error4.response)) { - const rawResponse = error4.response; - const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error4.statusCode] || operationSpec.responses["default"]); - error4.details = flatResponse; - if (options === null || options === void 0 ? void 0 : options.onResponse) { - options.onResponse(rawResponse, flatResponse, error4); - } - } - throw error4; - } - } - }; - exports2.ServiceClient = ServiceClient; - function createDefaultPipeline(options) { - const credentialScopes = getCredentialScopes(options); - const credentialOptions = options.credential && credentialScopes ? { credentialScopes, credential: options.credential } : void 0; - return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions })); - } - function getCredentialScopes(options) { - if (options.credentialScopes) { - return options.credentialScopes; - } - if (options.endpoint) { - return `${options.endpoint}/.default`; - } - if (options.baseUri) { - return `${options.baseUri}/.default`; - } - if (options.credential && !options.credentialScopes) { - throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`); - } - return void 0; - } - } -}); - -// node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnClaimChallenge.js -var require_authorizeRequestOnClaimChallenge = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnClaimChallenge.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.authorizeRequestOnClaimChallenge = exports2.parseCAEChallenge = void 0; - var log_js_1 = require_log2(); - var base64_js_1 = require_base642(); - function parseCAEChallenge(challenges) { - const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x); - return bearerChallenges.map((challenge) => { - const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x); - const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="'))); - return keyValuePairs.reduce((a, b) => Object.assign(Object.assign({}, a), b), {}); - }); - } - exports2.parseCAEChallenge = parseCAEChallenge; - async function authorizeRequestOnClaimChallenge(onChallengeOptions) { - const { scopes, response } = onChallengeOptions; - const logger = onChallengeOptions.logger || log_js_1.logger; - const challenge = response.headers.get("WWW-Authenticate"); - if (!challenge) { - logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`); - return false; - } - const challenges = parseCAEChallenge(challenge) || []; - const parsedChallenge = challenges.find((x) => x.claims); - if (!parsedChallenge) { - logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`); - return false; - } - const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, { - claims: (0, base64_js_1.decodeStringToString)(parsedChallenge.claims) - }); - if (!accessToken) { - return false; - } - onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`); - return true; - } - exports2.authorizeRequestOnClaimChallenge = authorizeRequestOnClaimChallenge; - } -}); - -// node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnTenantChallenge.js -var require_authorizeRequestOnTenantChallenge = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnTenantChallenge.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.authorizeRequestOnTenantChallenge = void 0; - var Constants = { - DefaultScope: "/.default", - /** - * Defines constants for use with HTTP headers. - */ - HeaderConstants: { - /** - * The Authorization header. - */ - AUTHORIZATION: "authorization" - } - }; - function isUuid(text) { - return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text); - } - var authorizeRequestOnTenantChallenge = async (challengeOptions) => { - const requestOptions = requestToOptions(challengeOptions.request); - const challenge = getChallenge(challengeOptions.response); - if (challenge) { - const challengeInfo = parseChallenge(challenge); - const challengeScopes = buildScopes(challengeOptions, challengeInfo); - const tenantId = extractTenantId(challengeInfo); - if (!tenantId) { - return false; - } - const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId })); - if (!accessToken) { - return false; - } - challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`); - return true; - } - return false; - }; - exports2.authorizeRequestOnTenantChallenge = authorizeRequestOnTenantChallenge; - function extractTenantId(challengeInfo) { - const parsedAuthUri = new URL(challengeInfo.authorization_uri); - const pathSegments = parsedAuthUri.pathname.split("/"); - const tenantId = pathSegments[1]; - if (tenantId && isUuid(tenantId)) { - return tenantId; - } - return void 0; - } - function buildScopes(challengeOptions, challengeInfo) { - if (!challengeInfo.resource_id) { - return challengeOptions.scopes; - } - const challengeScopes = new URL(challengeInfo.resource_id); - challengeScopes.pathname = Constants.DefaultScope; - let scope = challengeScopes.toString(); - if (scope === "https://disk.azure.com/.default") { - scope = "https://disk.azure.com//.default"; - } - return [scope]; - } - function getChallenge(response) { - const challenge = response.headers.get("WWW-Authenticate"); - if (response.status === 401 && challenge) { - return challenge; - } - return; - } - function parseChallenge(challenge) { - const bearerChallenge = challenge.slice("Bearer ".length); - const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x); - const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("="))); - return keyValuePairs.reduce((a, b) => Object.assign(Object.assign({}, a), b), {}); - } - function requestToOptions(request) { - return { - abortSignal: request.abortSignal, - requestOptions: { - timeout: request.timeout - }, - tracingOptions: request.tracingOptions - }; - } - } -}); - -// node_modules/@azure/core-client/dist/commonjs/index.js -var require_commonjs9 = __commonJS({ - "node_modules/@azure/core-client/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.authorizeRequestOnTenantChallenge = exports2.authorizeRequestOnClaimChallenge = exports2.serializationPolicyName = exports2.serializationPolicy = exports2.deserializationPolicyName = exports2.deserializationPolicy = exports2.XML_CHARKEY = exports2.XML_ATTRKEY = exports2.createClientPipeline = exports2.ServiceClient = exports2.MapperTypeNames = exports2.createSerializer = void 0; - var serializer_js_1 = require_serializer(); - Object.defineProperty(exports2, "createSerializer", { enumerable: true, get: function() { - return serializer_js_1.createSerializer; + exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0; + var pipeline_js_1 = require_pipeline(); + Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() { + return pipeline_js_1.createEmptyPipeline; } }); - Object.defineProperty(exports2, "MapperTypeNames", { enumerable: true, get: function() { - return serializer_js_1.MapperTypeNames; + var createPipelineFromOptions_js_1 = require_createPipelineFromOptions(); + Object.defineProperty(exports2, "createPipelineFromOptions", { enumerable: true, get: function() { + return createPipelineFromOptions_js_1.createPipelineFromOptions; } }); - var serviceClient_js_1 = require_serviceClient(); - Object.defineProperty(exports2, "ServiceClient", { enumerable: true, get: function() { - return serviceClient_js_1.ServiceClient; + var defaultHttpClient_js_1 = require_defaultHttpClient(); + Object.defineProperty(exports2, "createDefaultHttpClient", { enumerable: true, get: function() { + return defaultHttpClient_js_1.createDefaultHttpClient; } }); - var pipeline_js_1 = require_pipeline2(); - Object.defineProperty(exports2, "createClientPipeline", { enumerable: true, get: function() { - return pipeline_js_1.createClientPipeline; + var httpHeaders_js_1 = require_httpHeaders(); + Object.defineProperty(exports2, "createHttpHeaders", { enumerable: true, get: function() { + return httpHeaders_js_1.createHttpHeaders; } }); - var interfaces_js_1 = require_interfaces(); - Object.defineProperty(exports2, "XML_ATTRKEY", { enumerable: true, get: function() { - return interfaces_js_1.XML_ATTRKEY; + var pipelineRequest_js_1 = require_pipelineRequest(); + Object.defineProperty(exports2, "createPipelineRequest", { enumerable: true, get: function() { + return pipelineRequest_js_1.createPipelineRequest; } }); - Object.defineProperty(exports2, "XML_CHARKEY", { enumerable: true, get: function() { - return interfaces_js_1.XML_CHARKEY; + var restError_js_1 = require_restError(); + Object.defineProperty(exports2, "RestError", { enumerable: true, get: function() { + return restError_js_1.RestError; } }); - var deserializationPolicy_js_1 = require_deserializationPolicy(); - Object.defineProperty(exports2, "deserializationPolicy", { enumerable: true, get: function() { - return deserializationPolicy_js_1.deserializationPolicy; + Object.defineProperty(exports2, "isRestError", { enumerable: true, get: function() { + return restError_js_1.isRestError; } }); - Object.defineProperty(exports2, "deserializationPolicyName", { enumerable: true, get: function() { - return deserializationPolicy_js_1.deserializationPolicyName; + var decompressResponsePolicy_js_1 = require_decompressResponsePolicy(); + Object.defineProperty(exports2, "decompressResponsePolicy", { enumerable: true, get: function() { + return decompressResponsePolicy_js_1.decompressResponsePolicy; } }); - var serializationPolicy_js_1 = require_serializationPolicy(); - Object.defineProperty(exports2, "serializationPolicy", { enumerable: true, get: function() { - return serializationPolicy_js_1.serializationPolicy; + Object.defineProperty(exports2, "decompressResponsePolicyName", { enumerable: true, get: function() { + return decompressResponsePolicy_js_1.decompressResponsePolicyName; } }); - Object.defineProperty(exports2, "serializationPolicyName", { enumerable: true, get: function() { - return serializationPolicy_js_1.serializationPolicyName; + var exponentialRetryPolicy_js_1 = require_exponentialRetryPolicy(); + Object.defineProperty(exports2, "exponentialRetryPolicy", { enumerable: true, get: function() { + return exponentialRetryPolicy_js_1.exponentialRetryPolicy; } }); - var authorizeRequestOnClaimChallenge_js_1 = require_authorizeRequestOnClaimChallenge(); - Object.defineProperty(exports2, "authorizeRequestOnClaimChallenge", { enumerable: true, get: function() { - return authorizeRequestOnClaimChallenge_js_1.authorizeRequestOnClaimChallenge; + Object.defineProperty(exports2, "exponentialRetryPolicyName", { enumerable: true, get: function() { + return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; } }); - var authorizeRequestOnTenantChallenge_js_1 = require_authorizeRequestOnTenantChallenge(); - Object.defineProperty(exports2, "authorizeRequestOnTenantChallenge", { enumerable: true, get: function() { - return authorizeRequestOnTenantChallenge_js_1.authorizeRequestOnTenantChallenge; + var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy(); + Object.defineProperty(exports2, "setClientRequestIdPolicy", { enumerable: true, get: function() { + return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; + } }); + Object.defineProperty(exports2, "setClientRequestIdPolicyName", { enumerable: true, get: function() { + return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; + } }); + var logPolicy_js_1 = require_logPolicy(); + Object.defineProperty(exports2, "logPolicy", { enumerable: true, get: function() { + return logPolicy_js_1.logPolicy; + } }); + Object.defineProperty(exports2, "logPolicyName", { enumerable: true, get: function() { + return logPolicy_js_1.logPolicyName; + } }); + var multipartPolicy_js_1 = require_multipartPolicy(); + Object.defineProperty(exports2, "multipartPolicy", { enumerable: true, get: function() { + return multipartPolicy_js_1.multipartPolicy; + } }); + Object.defineProperty(exports2, "multipartPolicyName", { enumerable: true, get: function() { + return multipartPolicy_js_1.multipartPolicyName; + } }); + var proxyPolicy_js_1 = require_proxyPolicy(); + Object.defineProperty(exports2, "proxyPolicy", { enumerable: true, get: function() { + return proxyPolicy_js_1.proxyPolicy; + } }); + Object.defineProperty(exports2, "proxyPolicyName", { enumerable: true, get: function() { + return proxyPolicy_js_1.proxyPolicyName; + } }); + Object.defineProperty(exports2, "getDefaultProxySettings", { enumerable: true, get: function() { + return proxyPolicy_js_1.getDefaultProxySettings; + } }); + var redirectPolicy_js_1 = require_redirectPolicy(); + Object.defineProperty(exports2, "redirectPolicy", { enumerable: true, get: function() { + return redirectPolicy_js_1.redirectPolicy; + } }); + Object.defineProperty(exports2, "redirectPolicyName", { enumerable: true, get: function() { + return redirectPolicy_js_1.redirectPolicyName; + } }); + var systemErrorRetryPolicy_js_1 = require_systemErrorRetryPolicy(); + Object.defineProperty(exports2, "systemErrorRetryPolicy", { enumerable: true, get: function() { + return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; + } }); + Object.defineProperty(exports2, "systemErrorRetryPolicyName", { enumerable: true, get: function() { + return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; + } }); + var throttlingRetryPolicy_js_1 = require_throttlingRetryPolicy(); + Object.defineProperty(exports2, "throttlingRetryPolicy", { enumerable: true, get: function() { + return throttlingRetryPolicy_js_1.throttlingRetryPolicy; + } }); + Object.defineProperty(exports2, "throttlingRetryPolicyName", { enumerable: true, get: function() { + return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; + } }); + var retryPolicy_js_1 = require_retryPolicy(); + Object.defineProperty(exports2, "retryPolicy", { enumerable: true, get: function() { + return retryPolicy_js_1.retryPolicy; + } }); + var tracingPolicy_js_1 = require_tracingPolicy(); + Object.defineProperty(exports2, "tracingPolicy", { enumerable: true, get: function() { + return tracingPolicy_js_1.tracingPolicy; + } }); + Object.defineProperty(exports2, "tracingPolicyName", { enumerable: true, get: function() { + return tracingPolicy_js_1.tracingPolicyName; + } }); + var defaultRetryPolicy_js_1 = require_defaultRetryPolicy(); + Object.defineProperty(exports2, "defaultRetryPolicy", { enumerable: true, get: function() { + return defaultRetryPolicy_js_1.defaultRetryPolicy; + } }); + var userAgentPolicy_js_1 = require_userAgentPolicy(); + Object.defineProperty(exports2, "userAgentPolicy", { enumerable: true, get: function() { + return userAgentPolicy_js_1.userAgentPolicy; + } }); + Object.defineProperty(exports2, "userAgentPolicyName", { enumerable: true, get: function() { + return userAgentPolicy_js_1.userAgentPolicyName; + } }); + var tlsPolicy_js_1 = require_tlsPolicy(); + Object.defineProperty(exports2, "tlsPolicy", { enumerable: true, get: function() { + return tlsPolicy_js_1.tlsPolicy; + } }); + Object.defineProperty(exports2, "tlsPolicyName", { enumerable: true, get: function() { + return tlsPolicy_js_1.tlsPolicyName; + } }); + var formDataPolicy_js_1 = require_formDataPolicy(); + Object.defineProperty(exports2, "formDataPolicy", { enumerable: true, get: function() { + return formDataPolicy_js_1.formDataPolicy; + } }); + Object.defineProperty(exports2, "formDataPolicyName", { enumerable: true, get: function() { + return formDataPolicy_js_1.formDataPolicyName; + } }); + var bearerTokenAuthenticationPolicy_js_1 = require_bearerTokenAuthenticationPolicy(); + Object.defineProperty(exports2, "bearerTokenAuthenticationPolicy", { enumerable: true, get: function() { + return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; + } }); + Object.defineProperty(exports2, "bearerTokenAuthenticationPolicyName", { enumerable: true, get: function() { + return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; + } }); + var ndJsonPolicy_js_1 = require_ndJsonPolicy(); + Object.defineProperty(exports2, "ndJsonPolicy", { enumerable: true, get: function() { + return ndJsonPolicy_js_1.ndJsonPolicy; + } }); + Object.defineProperty(exports2, "ndJsonPolicyName", { enumerable: true, get: function() { + return ndJsonPolicy_js_1.ndJsonPolicyName; + } }); + var auxiliaryAuthenticationHeaderPolicy_js_1 = require_auxiliaryAuthenticationHeaderPolicy(); + Object.defineProperty(exports2, "auxiliaryAuthenticationHeaderPolicy", { enumerable: true, get: function() { + return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; + } }); + Object.defineProperty(exports2, "auxiliaryAuthenticationHeaderPolicyName", { enumerable: true, get: function() { + return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; + } }); + var file_js_1 = require_file2(); + Object.defineProperty(exports2, "createFile", { enumerable: true, get: function() { + return file_js_1.createFile; + } }); + Object.defineProperty(exports2, "createFileFromStream", { enumerable: true, get: function() { + return file_js_1.createFileFromStream; } }); } }); -// node_modules/@azure/core-http-compat/dist/commonjs/util.js -var require_util9 = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/util.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HttpHeaders = exports2.toHttpHeadersLike = exports2.toWebResourceLike = exports2.toPipelineRequest = void 0; - var core_rest_pipeline_1 = require_commonjs7(); - var originalRequestSymbol = Symbol("Original PipelineRequest"); - var originalClientRequestSymbol = Symbol.for("@azure/core-client original request"); - function toPipelineRequest(webResource, options = {}) { - const compatWebResource = webResource; - const request = compatWebResource[originalRequestSymbol]; - const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true })); - if (request) { - request.headers = headers; - return request; - } else { - const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({ - url: webResource.url, - method: webResource.method, - headers, - withCredentials: webResource.withCredentials, - timeout: webResource.timeout, - requestId: webResource.requestId, - abortSignal: webResource.abortSignal, - body: webResource.body, - formData: webResource.formData, - disableKeepAlive: !!webResource.keepAlive, - onDownloadProgress: webResource.onDownloadProgress, - onUploadProgress: webResource.onUploadProgress, - proxySettings: webResource.proxySettings, - streamResponseStatusCodes: webResource.streamResponseStatusCodes - }); - if (options.originalRequest) { - newRequest[originalClientRequestSymbol] = options.originalRequest; - } - return newRequest; - } - } - exports2.toPipelineRequest = toPipelineRequest; - function toWebResourceLike(request, options) { - var _a; - const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request; - const webResource = { - url: request.url, - method: request.method, - headers: toHttpHeadersLike(request.headers), - withCredentials: request.withCredentials, - timeout: request.timeout, - requestId: request.headers.get("x-ms-client-request-id") || request.requestId, - abortSignal: request.abortSignal, - body: request.body, - formData: request.formData, - keepAlive: !!request.disableKeepAlive, - onDownloadProgress: request.onDownloadProgress, - onUploadProgress: request.onUploadProgress, - proxySettings: request.proxySettings, - streamResponseStatusCodes: request.streamResponseStatusCodes, - clone() { - throw new Error("Cannot clone a non-proxied WebResourceLike"); - }, - prepare() { - throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat"); - }, - validateRequestProperties() { - } - }; - if (options === null || options === void 0 ? void 0 : options.createProxy) { - return new Proxy(webResource, { - get(target, prop, receiver) { - if (prop === originalRequestSymbol) { - return request; - } else if (prop === "clone") { - return () => { - return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), { - createProxy: true, - originalRequest - }); - }; - } - return Reflect.get(target, prop, receiver); - }, - set(target, prop, value, receiver) { - if (prop === "keepAlive") { - request.disableKeepAlive = !value; - } - const passThroughProps = [ - "url", - "method", - "withCredentials", - "timeout", - "requestId", - "abortSignal", - "body", - "formData", - "onDownloadProgress", - "onUploadProgress", - "proxySettings", - "streamResponseStatusCodes" - ]; - if (typeof prop === "string" && passThroughProps.includes(prop)) { - request[prop] = value; - } - return Reflect.set(target, prop, value, receiver); - } - }); - } else { - return webResource; +// node_modules/@azure/storage-blob/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports2 = {}; +__export(tslib_es6_exports2, { + __addDisposableResource: () => __addDisposableResource2, + __assign: () => __assign2, + __asyncDelegator: () => __asyncDelegator2, + __asyncGenerator: () => __asyncGenerator2, + __asyncValues: () => __asyncValues2, + __await: () => __await2, + __awaiter: () => __awaiter2, + __classPrivateFieldGet: () => __classPrivateFieldGet2, + __classPrivateFieldIn: () => __classPrivateFieldIn2, + __classPrivateFieldSet: () => __classPrivateFieldSet2, + __createBinding: () => __createBinding2, + __decorate: () => __decorate2, + __disposeResources: () => __disposeResources2, + __esDecorate: () => __esDecorate2, + __exportStar: () => __exportStar2, + __extends: () => __extends2, + __generator: () => __generator2, + __importDefault: () => __importDefault2, + __importStar: () => __importStar2, + __makeTemplateObject: () => __makeTemplateObject2, + __metadata: () => __metadata2, + __param: () => __param2, + __propKey: () => __propKey2, + __read: () => __read2, + __rest: () => __rest2, + __runInitializers: () => __runInitializers2, + __setFunctionName: () => __setFunctionName2, + __spread: () => __spread2, + __spreadArray: () => __spreadArray2, + __spreadArrays: () => __spreadArrays2, + __values: () => __values3, + default: () => tslib_es6_default2 +}); +function __extends2(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics2(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest2(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} +function __decorate2(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param2(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate2(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _2, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context2 = {}; + for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; + context2.addInitializer = function(f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_2 = accept(result.get)) descriptor.get = _2; + if (_2 = accept(result.set)) descriptor.set = _2; + if (_2 = accept(result.init)) initializers.unshift(_2); + } else if (_2 = accept(result)) { + if (kind === "field") initializers.unshift(_2); + else descriptor[key] = _2; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers2(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey2(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName2(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata2(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter2(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - exports2.toWebResourceLike = toWebResourceLike; - function toHttpHeadersLike(headers) { - return new HttpHeaders(headers.toJSON({ preserveCase: true })); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - exports2.toHttpHeadersLike = toHttpHeadersLike; - function getHeaderKey(headerName) { - return headerName.toLowerCase(); + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); } - var HttpHeaders = class _HttpHeaders { - constructor(rawHeaders) { - this._headersMap = {}; - if (rawHeaders) { - for (const headerName in rawHeaders) { - this.set(headerName, rawHeaders[headerName]); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator2(thisArg, body) { + var _2 = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_2 = 0)), _2) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _2.label++; + return { value: op[1], done: false }; + case 5: + _2.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; + continue; } - } - } - /** - * Set a header in this collection with the provided name and value. The name is - * case-insensitive. - * @param headerName - The name of the header to set. This value is case-insensitive. - * @param headerValue - The value of the header to set. - */ - set(headerName, headerValue) { - this._headersMap[getHeaderKey(headerName)] = { - name: headerName, - value: headerValue.toString() - }; - } - /** - * Get the header value for the provided header name, or undefined if no header exists in this - * collection with the provided name. - * @param headerName - The name of the header. - */ - get(headerName) { - const header = this._headersMap[getHeaderKey(headerName)]; - return !header ? void 0 : header.value; - } - /** - * Get whether or not this header collection contains a header entry for the provided header name. - */ - contains(headerName) { - return !!this._headersMap[getHeaderKey(headerName)]; - } - /** - * Remove the header with the provided headerName. Return whether or not the header existed and - * was removed. - * @param headerName - The name of the header to remove. - */ - remove(headerName) { - const result = this.contains(headerName); - delete this._headersMap[getHeaderKey(headerName)]; - return result; - } - /** - * Get the headers that are contained this collection as an object. - */ - rawHeaders() { - return this.toJson({ preserveCase: true }); - } - /** - * Get the headers that are contained in this collection as an array. - */ - headersArray() { - const headers = []; - for (const headerKey in this._headersMap) { - headers.push(this._headersMap[headerKey]); - } - return headers; - } - /** - * Get the header names that are contained in this collection. - */ - headerNames() { - const headerNames = []; - const headers = this.headersArray(); - for (let i = 0; i < headers.length; ++i) { - headerNames.push(headers[i].name); - } - return headerNames; - } - /** - * Get the header values that are contained in this collection. - */ - headerValues() { - const headerValues = []; - const headers = this.headersArray(); - for (let i = 0; i < headers.length; ++i) { - headerValues.push(headers[i].value); - } - return headerValues; - } - /** - * Get the JSON object representation of this HTTP header collection. - */ - toJson(options = {}) { - const result = {}; - if (options.preserveCase) { - for (const headerKey in this._headersMap) { - const header = this._headersMap[headerKey]; - result[header.name] = header.value; + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _2.label = op[1]; + break; } - } else { - for (const headerKey in this._headersMap) { - const header = this._headersMap[headerKey]; - result[getHeaderKey(header.name)] = header.value; + if (op[0] === 6 && _2.label < t[1]) { + _2.label = t[1]; + t = op; + break; } - } - return result; - } - /** - * Get the string representation of this HTTP header collection. - */ - toString() { - return JSON.stringify(this.toJson({ preserveCase: true })); - } - /** - * Create a deep clone/copy of this HttpHeaders collection. - */ - clone() { - const resultPreservingCasing = {}; - for (const headerKey in this._headersMap) { - const header = this._headersMap[headerKey]; - resultPreservingCasing[header.name] = header.value; - } - return new _HttpHeaders(resultPreservingCasing); + if (t && _2.label < t[2]) { + _2.label = t[2]; + _2.ops.push(op); + break; + } + if (t[2]) _2.ops.pop(); + _2.trys.pop(); + continue; } + op = body.call(thisArg, _2); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } +} +function __exportStar2(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding2(o, m, p); +} +function __values3(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function() { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read2(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error4) { + e = { error: error4 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread2() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read2(arguments[i])); + return ar; +} +function __spreadArrays2() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} +function __spreadArray2(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await2(v) { + return this instanceof __await2 ? (this.v = v, this) : new __await2(v); +} +function __asyncGenerator2(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); }; - exports2.HttpHeaders = HttpHeaders; } -}); - -// node_modules/@azure/core-http-compat/dist/commonjs/response.js -var require_response2 = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/response.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.toPipelineResponse = exports2.toCompatResponse = void 0; - var core_rest_pipeline_1 = require_commonjs7(); - var util_js_1 = require_util9(); - var originalResponse = Symbol("Original FullOperationResponse"); - function toCompatResponse(response, options) { - let request = (0, util_js_1.toWebResourceLike)(response.request); - let headers = (0, util_js_1.toHttpHeadersLike)(response.headers); - if (options === null || options === void 0 ? void 0 : options.createProxy) { - return new Proxy(response, { - get(target, prop, receiver) { - if (prop === "headers") { - return headers; - } else if (prop === "request") { - return request; - } else if (prop === originalResponse) { - return response; - } - return Reflect.get(target, prop, receiver); - }, - set(target, prop, value, receiver) { - if (prop === "headers") { - headers = value; - } else if (prop === "request") { - request = value; - } - return Reflect.set(target, prop, value, receiver); - } - }); - } else { - return Object.assign(Object.assign({}, response), { - request, - headers + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); }); - } + }; + if (f) i[n] = f(i[n]); } - exports2.toCompatResponse = toCompatResponse; - function toPipelineResponse(compatResponse) { - const extendedCompatResponse = compatResponse; - const response = extendedCompatResponse[originalResponse]; - const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true })); - if (response) { - response.headers = headers; - return response; - } else { - return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) }); - } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); } - exports2.toPipelineResponse = toPipelineResponse; } -}); + function step(r) { + r.value instanceof __await2 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator2(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function(e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function() { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function(v) { + return (p = !p) ? { value: __await2(o[n](v)), done: false } : f ? f(v) : v; + } : f; + } +} +function __asyncValues2(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values3 === "function" ? __values3(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); + }); + }; + } + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject2(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar2(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k); + } + __setModuleDefault2(result, mod); + return result; +} +function __importDefault2(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet2(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet2(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn2(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +function __addDisposableResource2(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources2(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +var extendStatics2, __assign2, __createBinding2, __setModuleDefault2, _SuppressedError2, tslib_es6_default2; +var init_tslib_es62 = __esm({ + "node_modules/@azure/storage-blob/node_modules/tslib/tslib.es6.mjs"() { + extendStatics2 = function(d, b) { + extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics2(d, b); + }; + __assign2 = function() { + __assign2 = Object.assign || function __assign4(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign2.apply(this, arguments); + }; + __createBinding2 = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault2 = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + _SuppressedError2 = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; + }; + tslib_es6_default2 = { + __extends: __extends2, + __assign: __assign2, + __rest: __rest2, + __decorate: __decorate2, + __param: __param2, + __metadata: __metadata2, + __awaiter: __awaiter2, + __generator: __generator2, + __createBinding: __createBinding2, + __exportStar: __exportStar2, + __values: __values3, + __read: __read2, + __spread: __spread2, + __spreadArrays: __spreadArrays2, + __spreadArray: __spreadArray2, + __await: __await2, + __asyncGenerator: __asyncGenerator2, + __asyncDelegator: __asyncDelegator2, + __asyncValues: __asyncValues2, + __makeTemplateObject: __makeTemplateObject2, + __importStar: __importStar2, + __importDefault: __importDefault2, + __classPrivateFieldGet: __classPrivateFieldGet2, + __classPrivateFieldSet: __classPrivateFieldSet2, + __classPrivateFieldIn: __classPrivateFieldIn2, + __addDisposableResource: __addDisposableResource2, + __disposeResources: __disposeResources2 + }; + } +}); -// node_modules/@azure/core-http-compat/dist/commonjs/extendedClient.js -var require_extendedClient = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/extendedClient.js"(exports2) { +// node_modules/@azure/core-auth/dist/commonjs/azureKeyCredential.js +var require_azureKeyCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/azureKeyCredential.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ExtendedServiceClient = void 0; - var disableKeepAlivePolicy_js_1 = require_disableKeepAlivePolicy(); - var core_rest_pipeline_1 = require_commonjs7(); - var core_client_1 = require_commonjs9(); - var response_js_1 = require_response2(); - var ExtendedServiceClient = class extends core_client_1.ServiceClient { - constructor(options) { - var _a, _b; - super(options); - if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false && !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) { - this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)()); - } - if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) { - this.pipeline.removePolicy({ - name: core_rest_pipeline_1.redirectPolicyName - }); + exports2.AzureKeyCredential = void 0; + var AzureKeyCredential = class { + /** + * The value of the key to be used in authentication + */ + get key() { + return this._key; + } + /** + * Create an instance of an AzureKeyCredential for use + * with a service client. + * + * @param key - The initial value of the key to use in authentication + */ + constructor(key) { + if (!key) { + throw new Error("key must be a non-empty string"); } + this._key = key; } /** - * Compatible send operation request function. + * Change the value of the key. * - * @param operationArguments - Operation arguments - * @param operationSpec - Operation Spec - * @returns + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newKey - The new key value to be used */ - async sendOperationRequest(operationArguments, operationSpec) { - var _a; - const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse; - let lastResponse; - function onResponse(rawResponse, flatResponse, error4) { - lastResponse = rawResponse; - if (userProvidedCallBack) { - userProvidedCallBack(rawResponse, flatResponse, error4); - } + update(newKey) { + this._key = newKey; + } + }; + exports2.AzureKeyCredential = AzureKeyCredential; + } +}); + +// node_modules/@azure/core-auth/dist/commonjs/keyCredential.js +var require_keyCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/keyCredential.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isKeyCredential = isKeyCredential; + var core_util_1 = require_commonjs4(); + function isKeyCredential(credential) { + return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string"; + } + } +}); + +// node_modules/@azure/core-auth/dist/commonjs/azureNamedKeyCredential.js +var require_azureNamedKeyCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/azureNamedKeyCredential.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AzureNamedKeyCredential = void 0; + exports2.isNamedKeyCredential = isNamedKeyCredential; + var core_util_1 = require_commonjs4(); + var AzureNamedKeyCredential = class { + /** + * The value of the key to be used in authentication. + */ + get key() { + return this._key; + } + /** + * The value of the name to be used in authentication. + */ + get name() { + return this._name; + } + /** + * Create an instance of an AzureNamedKeyCredential for use + * with a service client. + * + * @param name - The initial value of the name to use in authentication. + * @param key - The initial value of the key to use in authentication. + */ + constructor(name, key) { + if (!name || !key) { + throw new TypeError("name and key must be non-empty strings"); } - operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse }); - const result = await super.sendOperationRequest(operationArguments, operationSpec); - if (lastResponse) { - Object.defineProperty(result, "_response", { - value: (0, response_js_1.toCompatResponse)(lastResponse) - }); + this._name = name; + this._key = key; + } + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newName - The new name value to be used. + * @param newKey - The new key value to be used. + */ + update(newName, newKey) { + if (!newName || !newKey) { + throw new TypeError("newName and newKey must be non-empty strings"); } - return result; + this._name = newName; + this._key = newKey; } }; - exports2.ExtendedServiceClient = ExtendedServiceClient; + exports2.AzureNamedKeyCredential = AzureNamedKeyCredential; + function isNamedKeyCredential(credential) { + return (0, core_util_1.isObjectWithProperties)(credential, ["name", "key"]) && typeof credential.key === "string" && typeof credential.name === "string"; + } } }); -// node_modules/@azure/core-http-compat/dist/commonjs/policies/requestPolicyFactoryPolicy.js -var require_requestPolicyFactoryPolicy = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/policies/requestPolicyFactoryPolicy.js"(exports2) { +// node_modules/@azure/core-auth/dist/commonjs/azureSASCredential.js +var require_azureSASCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/azureSASCredential.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createRequestPolicyFactoryPolicy = exports2.requestPolicyFactoryPolicyName = exports2.HttpPipelineLogLevel = void 0; - var util_js_1 = require_util9(); - var response_js_1 = require_response2(); - var HttpPipelineLogLevel; - (function(HttpPipelineLogLevel2) { - HttpPipelineLogLevel2[HttpPipelineLogLevel2["ERROR"] = 1] = "ERROR"; - HttpPipelineLogLevel2[HttpPipelineLogLevel2["INFO"] = 3] = "INFO"; - HttpPipelineLogLevel2[HttpPipelineLogLevel2["OFF"] = 0] = "OFF"; - HttpPipelineLogLevel2[HttpPipelineLogLevel2["WARNING"] = 2] = "WARNING"; - })(HttpPipelineLogLevel || (exports2.HttpPipelineLogLevel = HttpPipelineLogLevel = {})); - var mockRequestPolicyOptions = { - log(_logLevel, _message) { - }, - shouldLog(_logLevel) { - return false; + exports2.AzureSASCredential = void 0; + exports2.isSASCredential = isSASCredential; + var core_util_1 = require_commonjs4(); + var AzureSASCredential = class { + /** + * The value of the shared access signature to be used in authentication + */ + get signature() { + return this._signature; } - }; - exports2.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy"; - function createRequestPolicyFactoryPolicy(factories) { - const orderedFactories = factories.slice().reverse(); - return { - name: exports2.requestPolicyFactoryPolicyName, - async sendRequest(request, next) { - let httpPipeline = { - async sendRequest(httpRequest) { - const response2 = await next((0, util_js_1.toPipelineRequest)(httpRequest)); - return (0, response_js_1.toCompatResponse)(response2, { createProxy: true }); - } - }; - for (const factory of orderedFactories) { - httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions); - } - const webResourceLike = (0, util_js_1.toWebResourceLike)(request, { createProxy: true }); - const response = await httpPipeline.sendRequest(webResourceLike); - return (0, response_js_1.toPipelineResponse)(response); + /** + * Create an instance of an AzureSASCredential for use + * with a service client. + * + * @param signature - The initial value of the shared access signature to use in authentication + */ + constructor(signature) { + if (!signature) { + throw new Error("shared access signature must be a non-empty string"); } - }; + this._signature = signature; + } + /** + * Change the value of the signature. + * + * Updates will take effect upon the next request after + * updating the signature value. + * + * @param newSignature - The new shared access signature value to be used + */ + update(newSignature) { + if (!newSignature) { + throw new Error("shared access signature must be a non-empty string"); + } + this._signature = newSignature; + } + }; + exports2.AzureSASCredential = AzureSASCredential; + function isSASCredential(credential) { + return (0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string"; } - exports2.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy; } }); -// node_modules/@azure/core-http-compat/dist/commonjs/httpClientAdapter.js -var require_httpClientAdapter = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/httpClientAdapter.js"(exports2) { +// node_modules/@azure/core-auth/dist/commonjs/tokenCredential.js +var require_tokenCredential = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/tokenCredential.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.convertHttpClient = void 0; - var response_js_1 = require_response2(); - var util_js_1 = require_util9(); - function convertHttpClient(requestPolicyClient) { - return { - sendRequest: async (request) => { - const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request, { createProxy: true })); - return (0, response_js_1.toPipelineResponse)(response); - } - }; + exports2.isTokenCredential = isTokenCredential; + function isTokenCredential(credential) { + const castCredential = credential; + return castCredential && typeof castCredential.getToken === "function" && (castCredential.signRequest === void 0 || castCredential.getToken.length > 0); } - exports2.convertHttpClient = convertHttpClient; } }); -// node_modules/@azure/core-http-compat/dist/commonjs/index.js -var require_commonjs10 = __commonJS({ - "node_modules/@azure/core-http-compat/dist/commonjs/index.js"(exports2) { +// node_modules/@azure/core-auth/dist/commonjs/index.js +var require_commonjs8 = __commonJS({ + "node_modules/@azure/core-auth/dist/commonjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.toHttpHeadersLike = exports2.convertHttpClient = exports2.disableKeepAlivePolicyName = exports2.HttpPipelineLogLevel = exports2.createRequestPolicyFactoryPolicy = exports2.requestPolicyFactoryPolicyName = exports2.ExtendedServiceClient = void 0; - var extendedClient_js_1 = require_extendedClient(); - Object.defineProperty(exports2, "ExtendedServiceClient", { enumerable: true, get: function() { - return extendedClient_js_1.ExtendedServiceClient; + exports2.isTokenCredential = exports2.isSASCredential = exports2.AzureSASCredential = exports2.isNamedKeyCredential = exports2.AzureNamedKeyCredential = exports2.isKeyCredential = exports2.AzureKeyCredential = void 0; + var azureKeyCredential_js_1 = require_azureKeyCredential(); + Object.defineProperty(exports2, "AzureKeyCredential", { enumerable: true, get: function() { + return azureKeyCredential_js_1.AzureKeyCredential; } }); - var requestPolicyFactoryPolicy_js_1 = require_requestPolicyFactoryPolicy(); - Object.defineProperty(exports2, "requestPolicyFactoryPolicyName", { enumerable: true, get: function() { - return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; + var keyCredential_js_1 = require_keyCredential(); + Object.defineProperty(exports2, "isKeyCredential", { enumerable: true, get: function() { + return keyCredential_js_1.isKeyCredential; } }); - Object.defineProperty(exports2, "createRequestPolicyFactoryPolicy", { enumerable: true, get: function() { - return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; + var azureNamedKeyCredential_js_1 = require_azureNamedKeyCredential(); + Object.defineProperty(exports2, "AzureNamedKeyCredential", { enumerable: true, get: function() { + return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; } }); - Object.defineProperty(exports2, "HttpPipelineLogLevel", { enumerable: true, get: function() { - return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; + Object.defineProperty(exports2, "isNamedKeyCredential", { enumerable: true, get: function() { + return azureNamedKeyCredential_js_1.isNamedKeyCredential; } }); - var disableKeepAlivePolicy_js_1 = require_disableKeepAlivePolicy(); - Object.defineProperty(exports2, "disableKeepAlivePolicyName", { enumerable: true, get: function() { - return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; + var azureSASCredential_js_1 = require_azureSASCredential(); + Object.defineProperty(exports2, "AzureSASCredential", { enumerable: true, get: function() { + return azureSASCredential_js_1.AzureSASCredential; } }); - var httpClientAdapter_js_1 = require_httpClientAdapter(); - Object.defineProperty(exports2, "convertHttpClient", { enumerable: true, get: function() { - return httpClientAdapter_js_1.convertHttpClient; + Object.defineProperty(exports2, "isSASCredential", { enumerable: true, get: function() { + return azureSASCredential_js_1.isSASCredential; } }); - var util_js_1 = require_util9(); - Object.defineProperty(exports2, "toHttpHeadersLike", { enumerable: true, get: function() { - return util_js_1.toHttpHeadersLike; + var tokenCredential_js_1 = require_tokenCredential(); + Object.defineProperty(exports2, "isTokenCredential", { enumerable: true, get: function() { + return tokenCredential_js_1.isTokenCredential; } }); } }); -// node_modules/fast-xml-parser/src/util.js -var require_util10 = __commonJS({ - "node_modules/fast-xml-parser/src/util.js"(exports2) { +// node_modules/@azure/core-http-compat/dist/commonjs/policies/disableKeepAlivePolicy.js +var require_disableKeepAlivePolicy = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/policies/disableKeepAlivePolicy.js"(exports2) { "use strict"; - var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; - var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; - var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*"; - var regexName = new RegExp("^" + nameRegexp + "$"); - var getAllMatches = function(string, regex) { - const matches = []; - let match = regex.exec(string); - while (match) { - const allmatches = []; - allmatches.startIndex = regex.lastIndex - match[0].length; - const len = match.length; - for (let index = 0; index < len; index++) { - allmatches.push(match[index]); - } - matches.push(allmatches); - match = regex.exec(string); - } - return matches; - }; - var isName = function(string) { - const match = regexName.exec(string); - return !(match === null || typeof match === "undefined"); - }; - exports2.isExist = function(v) { - return typeof v !== "undefined"; - }; - exports2.isEmptyObject = function(obj) { - return Object.keys(obj).length === 0; - }; - exports2.merge = function(target, a, arrayMode) { - if (a) { - const keys = Object.keys(a); - const len = keys.length; - for (let i = 0; i < len; i++) { - if (arrayMode === "strict") { - target[keys[i]] = [a[keys[i]]]; - } else { - target[keys[i]] = a[keys[i]]; - } + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.pipelineContainsDisableKeepAlivePolicy = exports2.createDisableKeepAlivePolicy = exports2.disableKeepAlivePolicyName = void 0; + exports2.disableKeepAlivePolicyName = "DisableKeepAlivePolicy"; + function createDisableKeepAlivePolicy() { + return { + name: exports2.disableKeepAlivePolicyName, + async sendRequest(request, next) { + request.disableKeepAlive = true; + return next(request); } - } - }; - exports2.getValue = function(v) { - if (exports2.isExist(v)) { - return v; - } else { - return ""; - } - }; - exports2.isName = isName; - exports2.getAllMatches = getAllMatches; - exports2.nameRegexp = nameRegexp; + }; + } + exports2.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy; + function pipelineContainsDisableKeepAlivePolicy(pipeline) { + return pipeline.getOrderedPolicies().some((policy) => policy.name === exports2.disableKeepAlivePolicyName); + } + exports2.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy; } }); -// node_modules/fast-xml-parser/src/validator.js -var require_validator = __commonJS({ - "node_modules/fast-xml-parser/src/validator.js"(exports2) { - "use strict"; - var util = require_util10(); - var defaultOptions = { - allowBooleanAttributes: false, - //A tag can have attributes without any value - unpairedTags: [] +// node_modules/@azure/core-client/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports3 = {}; +__export(tslib_es6_exports3, { + __addDisposableResource: () => __addDisposableResource3, + __assign: () => __assign3, + __asyncDelegator: () => __asyncDelegator3, + __asyncGenerator: () => __asyncGenerator3, + __asyncValues: () => __asyncValues3, + __await: () => __await3, + __awaiter: () => __awaiter3, + __classPrivateFieldGet: () => __classPrivateFieldGet3, + __classPrivateFieldIn: () => __classPrivateFieldIn3, + __classPrivateFieldSet: () => __classPrivateFieldSet3, + __createBinding: () => __createBinding3, + __decorate: () => __decorate3, + __disposeResources: () => __disposeResources3, + __esDecorate: () => __esDecorate3, + __exportStar: () => __exportStar3, + __extends: () => __extends3, + __generator: () => __generator3, + __importDefault: () => __importDefault3, + __importStar: () => __importStar3, + __makeTemplateObject: () => __makeTemplateObject3, + __metadata: () => __metadata3, + __param: () => __param3, + __propKey: () => __propKey3, + __read: () => __read3, + __rest: () => __rest3, + __runInitializers: () => __runInitializers3, + __setFunctionName: () => __setFunctionName3, + __spread: () => __spread3, + __spreadArray: () => __spreadArray3, + __spreadArrays: () => __spreadArrays3, + __values: () => __values4, + default: () => tslib_es6_default3 +}); +function __extends3(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics3(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest3(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} +function __decorate3(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param3(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate3(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _2, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context2 = {}; + for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context2.access[p] = contextIn.access[p]; + context2.addInitializer = function(f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); }; - exports2.validate = function(xmlData, options) { - options = Object.assign({}, defaultOptions, options); - const tags = []; - let tagFound = false; - let reachedRoot = false; - if (xmlData[0] === "\uFEFF") { - xmlData = xmlData.substr(1); - } - for (let i = 0; i < xmlData.length; i++) { - if (xmlData[i] === "<" && xmlData[i + 1] === "?") { - i += 2; - i = readPI(xmlData, i); - if (i.err) return i; - } else if (xmlData[i] === "<") { - let tagStartPos = i; - i++; - if (xmlData[i] === "!") { - i = readCommentAndCDATA(xmlData, i); - continue; - } else { - let closingTag = false; - if (xmlData[i] === "/") { - closingTag = true; - i++; - } - let tagName = ""; - for (; i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== " " && xmlData[i] !== "\n" && xmlData[i] !== "\r"; i++) { - tagName += xmlData[i]; - } - tagName = tagName.trim(); - if (tagName[tagName.length - 1] === "/") { - tagName = tagName.substring(0, tagName.length - 1); - i--; - } - if (!validateTagName(tagName)) { - let msg; - if (tagName.trim().length === 0) { - msg = "Invalid space after '<'."; - } else { - msg = "Tag '" + tagName + "' is an invalid name."; - } - return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i)); - } - const result = readAttributeStr(xmlData, i); - if (result === false) { - return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i)); - } - let attrStr = result.value; - i = result.index; - if (attrStr[attrStr.length - 1] === "/") { - const attrStrStart = i - attrStr.length; - attrStr = attrStr.substring(0, attrStr.length - 1); - const isValid = validateAttributeString(attrStr, options); - if (isValid === true) { - tagFound = true; - } else { - return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); - } - } else if (closingTag) { - if (!result.tagClosed) { - return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); - } else if (attrStr.trim().length > 0) { - return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); - } else if (tags.length === 0) { - return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); - } else { - const otg = tags.pop(); - if (tagName !== otg.tagName) { - let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); - return getErrorObject( - "InvalidTag", - "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", - getLineNumberForPosition(xmlData, tagStartPos) - ); - } - if (tags.length == 0) { - reachedRoot = true; - } - } - } else { - const isValid = validateAttributeString(attrStr, options); - if (isValid !== true) { - return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); - } - if (reachedRoot === true) { - return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i)); - } else if (options.unpairedTags.indexOf(tagName) !== -1) { - } else { - tags.push({ tagName, tagStartPos }); - } - tagFound = true; - } - for (i++; i < xmlData.length; i++) { - if (xmlData[i] === "<") { - if (xmlData[i + 1] === "!") { - i++; - i = readCommentAndCDATA(xmlData, i); - continue; - } else if (xmlData[i + 1] === "?") { - i = readPI(xmlData, ++i); - if (i.err) return i; - } else { - break; - } - } else if (xmlData[i] === "&") { - const afterAmp = validateAmpersand(xmlData, i); - if (afterAmp == -1) - return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); - i = afterAmp; - } else { - if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { - return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i)); - } - } - } - if (xmlData[i] === "<") { - i--; - } - } - } else { - if (isWhiteSpace(xmlData[i])) { - continue; - } - return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i)); - } + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_2 = accept(result.get)) descriptor.get = _2; + if (_2 = accept(result.set)) descriptor.set = _2; + if (_2 = accept(result.init)) initializers.unshift(_2); + } else if (_2 = accept(result)) { + if (kind === "field") initializers.unshift(_2); + else descriptor[key] = _2; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers3(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey3(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName3(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata3(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter3(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve2) { + resolve2(value); + }); + } + return new (P || (P = Promise))(function(resolve2, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - if (!tagFound) { - return getErrorObject("InvalidXml", "Start tag expected.", 1); - } else if (tags.length == 1) { - return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); - } else if (tags.length > 0) { - return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - return true; - }; - function isWhiteSpace(char) { - return char === " " || char === " " || char === "\n" || char === "\r"; } - function readPI(xmlData, i) { - const start = i; - for (; i < xmlData.length; i++) { - if (xmlData[i] == "?" || xmlData[i] == " ") { - const tagname = xmlData.substr(start, i - start); - if (i > 5 && tagname === "xml") { - return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i)); - } else if (xmlData[i] == "?" && xmlData[i + 1] == ">") { - i++; - break; - } else { + function step(result) { + result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator3(thisArg, body) { + var _2 = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_2 = 0)), _2) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _2.label++; + return { value: op[1], done: false }; + case 5: + _2.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; continue; } - } - } - return i; - } - function readCommentAndCDATA(xmlData, i) { - if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") { - for (i += 3; i < xmlData.length; i++) { - if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") { - i += 2; + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _2.label = op[1]; break; } - } - } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") { - let angleBracketsCount = 1; - for (i += 8; i < xmlData.length; i++) { - if (xmlData[i] === "<") { - angleBracketsCount++; - } else if (xmlData[i] === ">") { - angleBracketsCount--; - if (angleBracketsCount === 0) { - break; - } - } - } - } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") { - for (i += 8; i < xmlData.length; i++) { - if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") { - i += 2; + if (op[0] === 6 && _2.label < t[1]) { + _2.label = t[1]; + t = op; break; } - } - } - return i; - } - var doubleQuote = '"'; - var singleQuote = "'"; - function readAttributeStr(xmlData, i) { - let attrStr = ""; - let startChar = ""; - let tagClosed = false; - for (; i < xmlData.length; i++) { - if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { - if (startChar === "") { - startChar = xmlData[i]; - } else if (startChar !== xmlData[i]) { - } else { - startChar = ""; - } - } else if (xmlData[i] === ">") { - if (startChar === "") { - tagClosed = true; + if (t && _2.label < t[2]) { + _2.label = t[2]; + _2.ops.push(op); break; } - } - attrStr += xmlData[i]; - } - if (startChar !== "") { - return false; - } - return { - value: attrStr, - index: i, - tagClosed - }; - } - var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); - function validateAttributeString(attrStr, options) { - const matches = util.getAllMatches(attrStr, validAttrStrRegxp); - const attrNames = {}; - for (let i = 0; i < matches.length; i++) { - if (matches[i][1].length === 0) { - return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i])); - } else if (matches[i][3] !== void 0 && matches[i][4] === void 0) { - return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i])); - } else if (matches[i][3] === void 0 && !options.allowBooleanAttributes) { - return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i])); - } - const attrName = matches[i][2]; - if (!validateAttrName(attrName)) { - return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i])); - } - if (!attrNames.hasOwnProperty(attrName)) { - attrNames[attrName] = 1; - } else { - return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i])); - } + if (t[2]) _2.ops.pop(); + _2.trys.pop(); + continue; } - return true; + op = body.call(thisArg, _2); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; } - function validateNumberAmpersand(xmlData, i) { - let re = /\d/; - if (xmlData[i] === "x") { - i++; - re = /[\da-fA-F]/; - } - for (; i < xmlData.length; i++) { - if (xmlData[i] === ";") - return i; - if (!xmlData[i].match(re)) - break; - } - return -1; + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } +} +function __exportStar3(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding3(o, m, p); +} +function __values4(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function() { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - function validateAmpersand(xmlData, i) { - i++; - if (xmlData[i] === ";") - return -1; - if (xmlData[i] === "#") { - i++; - return validateNumberAmpersand(xmlData, i); - } - let count = 0; - for (; i < xmlData.length; i++, count++) { - if (xmlData[i].match(/\w/) && count < 20) - continue; - if (xmlData[i] === ";") - break; - return -1; - } - return i; - } - function getErrorObject(code, message, lineNumber) { - return { - err: { - code, - msg: message, - line: lineNumber.line || lineNumber, - col: lineNumber.col - } - }; - } - function validateAttrName(attrName) { - return util.isName(attrName); + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read3(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error4) { + e = { error: error4 }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; } - function validateTagName(tagname) { - return util.isName(tagname); + } + return ar; +} +function __spread3() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read3(arguments[i])); + return ar; +} +function __spreadArrays3() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} +function __spreadArray3(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; } - function getLineNumberForPosition(xmlData, index) { - const lines = xmlData.substring(0, index).split(/\r?\n/); - return { - line: lines.length, - // column number is last line's length + 1, because column numbering starts at 1: - col: lines[lines.length - 1].length + 1 + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await3(v) { + return this instanceof __await3 ? (this.v = v, this) : new __await3(v); +} +function __asyncGenerator3(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); }; + if (f) i[n] = f(i[n]); } - function getPositionFromMatch(match) { - return match.startIndex + match[1].length; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); } } -}); - -// node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js -var require_OptionsBuilder = __commonJS({ - "node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports2) { - var defaultOptions = { - preserveOrder: false, - attributeNamePrefix: "@_", - attributesGroupName: false, - textNodeName: "#text", - ignoreAttributes: true, - removeNSPrefix: false, - // remove NS from tag name or attribute name if true - allowBooleanAttributes: false, - //a tag can have attributes without any value - //ignoreRootElement : false, - parseTagValue: true, - parseAttributeValue: false, - trimValues: true, - //Trim string values of tag and attributes - cdataPropName: false, - numberParseOptions: { - hex: true, - leadingZeros: true, - eNotation: true - }, - tagValueProcessor: function(tagName, val2) { - return val2; - }, - attributeValueProcessor: function(attrName, val2) { - return val2; - }, - stopNodes: [], - //nested tags will not be parsed even for errors - alwaysCreateTextNode: false, - isArray: () => false, - commentPropName: false, - unpairedTags: [], - processEntities: true, - htmlEntities: false, - ignoreDeclaration: false, - ignorePiTags: false, - transformTagName: false, - transformAttributeName: false, - updateTag: function(tagName, jPath, attrs) { - return tagName; - } - // skipEmptyListItem: false - }; - var buildOptions = function(options) { - return Object.assign({}, defaultOptions, options); + function step(r) { + r.value instanceof __await3 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator3(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function(e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function() { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function(v) { + return (p = !p) ? { value: __await3(o[n](v)), done: false } : f ? f(v) : v; + } : f; + } +} +function __asyncValues3(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values4 === "function" ? __values4(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve2, reject) { + v = o[n](v), settle(resolve2, reject, v.done, v.value); + }); }; - exports2.buildOptions = buildOptions; - exports2.defaultOptions = defaultOptions; } -}); - -// node_modules/fast-xml-parser/src/xmlparser/xmlNode.js -var require_xmlNode = __commonJS({ - "node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports2, module2) { - "use strict"; - var XmlNode = class { - constructor(tagname) { - this.tagname = tagname; - this.child = []; - this[":@"] = {}; + function settle(resolve2, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve2({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject3(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar3(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding3(result, mod, k); + } + __setModuleDefault3(result, mod); + return result; +} +function __importDefault3(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet3(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet3(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn3(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +function __addDisposableResource3(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); } - add(key, val2) { - if (key === "__proto__") key = "#__proto__"; - this.child.push({ [key]: val2 }); + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources3(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError3(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); } - addChild(node) { - if (node.tagname === "__proto__") node.tagname = "#__proto__"; - if (node[":@"] && Object.keys(node[":@"]).length > 0) { - this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); - } else { - this.child.push({ [node.tagname]: node.child }); + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +var extendStatics3, __assign3, __createBinding3, __setModuleDefault3, _SuppressedError3, tslib_es6_default3; +var init_tslib_es63 = __esm({ + "node_modules/@azure/core-client/node_modules/tslib/tslib.es6.mjs"() { + extendStatics3 = function(d, b) { + extendStatics3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics3(d, b); + }; + __assign3 = function() { + __assign3 = Object.assign || function __assign4(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } + return t; + }; + return __assign3.apply(this, arguments); + }; + __createBinding3 = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault3 = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + _SuppressedError3 = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e; + }; + tslib_es6_default3 = { + __extends: __extends3, + __assign: __assign3, + __rest: __rest3, + __decorate: __decorate3, + __param: __param3, + __metadata: __metadata3, + __awaiter: __awaiter3, + __generator: __generator3, + __createBinding: __createBinding3, + __exportStar: __exportStar3, + __values: __values4, + __read: __read3, + __spread: __spread3, + __spreadArrays: __spreadArrays3, + __spreadArray: __spreadArray3, + __await: __await3, + __asyncGenerator: __asyncGenerator3, + __asyncDelegator: __asyncDelegator3, + __asyncValues: __asyncValues3, + __makeTemplateObject: __makeTemplateObject3, + __importStar: __importStar3, + __importDefault: __importDefault3, + __classPrivateFieldGet: __classPrivateFieldGet3, + __classPrivateFieldSet: __classPrivateFieldSet3, + __classPrivateFieldIn: __classPrivateFieldIn3, + __addDisposableResource: __addDisposableResource3, + __disposeResources: __disposeResources3 }; - module2.exports = XmlNode; } }); -// node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js -var require_DocTypeReader = __commonJS({ - "node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports2, module2) { - var util = require_util10(); - function readDocType(xmlData, i) { - const entities = {}; - if (xmlData[i + 3] === "O" && xmlData[i + 4] === "C" && xmlData[i + 5] === "T" && xmlData[i + 6] === "Y" && xmlData[i + 7] === "P" && xmlData[i + 8] === "E") { - i = i + 9; - let angleBracketsCount = 1; - let hasBody = false, comment = false; - let exp = ""; - for (; i < xmlData.length; i++) { - if (xmlData[i] === "<" && !comment) { - if (hasBody && isEntity(xmlData, i)) { - i += 7; - [entityName, val, i] = readEntityExp(xmlData, i + 1); - if (val.indexOf("&") === -1) - entities[validateEntityName(entityName)] = { - regx: RegExp(`&${entityName};`, "g"), - val - }; - } else if (hasBody && isElement(xmlData, i)) i += 8; - else if (hasBody && isAttlist(xmlData, i)) i += 8; - else if (hasBody && isNotation(xmlData, i)) i += 9; - else if (isComment) comment = true; - else throw new Error("Invalid DOCTYPE"); - angleBracketsCount++; - exp = ""; - } else if (xmlData[i] === ">") { - if (comment) { - if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") { - comment = false; - angleBracketsCount--; - } - } else { - angleBracketsCount--; - } - if (angleBracketsCount === 0) { - break; - } - } else if (xmlData[i] === "[") { - hasBody = true; - } else { - exp += xmlData[i]; - } - } - if (angleBracketsCount !== 0) { - throw new Error(`Unclosed DOCTYPE`); - } - } else { - throw new Error(`Invalid Tag instead of DOCTYPE`); - } - return { entities, i }; - } - function readEntityExp(xmlData, i) { - let entityName2 = ""; - for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"'); i++) { - entityName2 += xmlData[i]; - } - entityName2 = entityName2.trim(); - if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported"); - const startChar = xmlData[i++]; - let val2 = ""; - for (; i < xmlData.length && xmlData[i] !== startChar; i++) { - val2 += xmlData[i]; - } - return [entityName2, val2, i]; - } - function isComment(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "-" && xmlData[i + 3] === "-") return true; - return false; - } - function isEntity(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "N" && xmlData[i + 4] === "T" && xmlData[i + 5] === "I" && xmlData[i + 6] === "T" && xmlData[i + 7] === "Y") return true; - return false; - } - function isElement(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "L" && xmlData[i + 4] === "E" && xmlData[i + 5] === "M" && xmlData[i + 6] === "E" && xmlData[i + 7] === "N" && xmlData[i + 8] === "T") return true; - return false; +// node_modules/@azure/core-client/dist/commonjs/base64.js +var require_base642 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/base64.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.decodeStringToString = exports2.decodeString = exports2.encodeByteArray = exports2.encodeString = void 0; + function encodeString(value) { + return Buffer.from(value).toString("base64"); } - function isAttlist(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "A" && xmlData[i + 3] === "T" && xmlData[i + 4] === "T" && xmlData[i + 5] === "L" && xmlData[i + 6] === "I" && xmlData[i + 7] === "S" && xmlData[i + 8] === "T") return true; - return false; + exports2.encodeString = encodeString; + function encodeByteArray(value) { + const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); + return bufferValue.toString("base64"); } - function isNotation(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "N" && xmlData[i + 3] === "O" && xmlData[i + 4] === "T" && xmlData[i + 5] === "A" && xmlData[i + 6] === "T" && xmlData[i + 7] === "I" && xmlData[i + 8] === "O" && xmlData[i + 9] === "N") return true; - return false; + exports2.encodeByteArray = encodeByteArray; + function decodeString(value) { + return Buffer.from(value, "base64"); } - function validateEntityName(name) { - if (util.isName(name)) - return name; - else - throw new Error(`Invalid entity name ${name}`); + exports2.decodeString = decodeString; + function decodeStringToString(value) { + return Buffer.from(value, "base64").toString(); } - module2.exports = readDocType; + exports2.decodeStringToString = decodeStringToString; } }); -// node_modules/strnum/strnum.js -var require_strnum = __commonJS({ - "node_modules/strnum/strnum.js"(exports2, module2) { - var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; - var numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/; - if (!Number.parseInt && window.parseInt) { - Number.parseInt = window.parseInt; - } - if (!Number.parseFloat && window.parseFloat) { - Number.parseFloat = window.parseFloat; - } - var consider = { - hex: true, - leadingZeros: true, - decimalPoint: ".", - eNotation: true - //skipLike: /regex/ - }; - function toNumber(str2, options = {}) { - options = Object.assign({}, consider, options); - if (!str2 || typeof str2 !== "string") return str2; - let trimmedStr = str2.trim(); - if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str2; - else if (options.hex && hexRegex.test(trimmedStr)) { - return Number.parseInt(trimmedStr, 16); +// node_modules/@azure/core-client/dist/commonjs/interfaces.js +var require_interfaces = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/interfaces.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.XML_CHARKEY = exports2.XML_ATTRKEY = void 0; + exports2.XML_ATTRKEY = "$"; + exports2.XML_CHARKEY = "_"; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/utils.js +var require_utils5 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/utils.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.flattenResponse = exports2.isValidUuid = exports2.isDuration = exports2.isPrimitiveBody = void 0; + function isPrimitiveBody(value, mapperTypeName) { + return mapperTypeName !== "Composite" && mapperTypeName !== "Dictionary" && (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !== null || value === void 0 || value === null); + } + exports2.isPrimitiveBody = isPrimitiveBody; + var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + function isDuration(value) { + return validateISODuration.test(value); + } + exports2.isDuration = isDuration; + var validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; + function isValidUuid(uuid) { + return validUuidRegex.test(uuid); + } + exports2.isValidUuid = isValidUuid; + function handleNullableResponseAndWrappableBody(responseObject) { + const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body); + if (responseObject.hasNullableType && Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) { + return responseObject.shouldWrapBody ? { body: null } : null; } else { - const match = numRegex.exec(trimmedStr); - if (match) { - const sign = match[1]; - const leadingZeros = match[2]; - let numTrimmedByZeros = trimZeros(match[3]); - const eNotation = match[4] || match[6]; - if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str2; - else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str2; - else { - const num = Number(trimmedStr); - const numStr = "" + num; - if (numStr.search(/[eE]/) !== -1) { - if (options.eNotation) return num; - else return str2; - } else if (eNotation) { - if (options.eNotation) return num; - else return str2; - } else if (trimmedStr.indexOf(".") !== -1) { - if (numStr === "0" && numTrimmedByZeros === "") return num; - else if (numStr === numTrimmedByZeros) return num; - else if (sign && numStr === "-" + numTrimmedByZeros) return num; - else return str2; - } - if (leadingZeros) { - if (numTrimmedByZeros === numStr) return num; - else if (sign + numTrimmedByZeros === numStr) return num; - else return str2; - } - if (trimmedStr === numStr) return num; - else if (trimmedStr === sign + numStr) return num; - return str2; - } - } else { - return str2; - } + return responseObject.shouldWrapBody ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody; } } - function trimZeros(numStr) { - if (numStr && numStr.indexOf(".") !== -1) { - numStr = numStr.replace(/0+$/, ""); - if (numStr === ".") numStr = "0"; - else if (numStr[0] === ".") numStr = "0" + numStr; - else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1); - return numStr; + function flattenResponse(fullResponse, responseSpec) { + var _a, _b; + const parsedHeaders = fullResponse.parsedHeaders; + if (fullResponse.request.method === "HEAD") { + return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody }); } - return numStr; - } - module2.exports = toNumber; - } -}); - -// node_modules/fast-xml-parser/src/ignoreAttributes.js -var require_ignoreAttributes = __commonJS({ - "node_modules/fast-xml-parser/src/ignoreAttributes.js"(exports2, module2) { - function getIgnoreAttributesFn(ignoreAttributes) { - if (typeof ignoreAttributes === "function") { - return ignoreAttributes; + const bodyMapper = responseSpec && responseSpec.bodyMapper; + const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable); + const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name; + if (expectedBodyTypeName === "Stream") { + return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody }); } - if (Array.isArray(ignoreAttributes)) { - return (attrName) => { - for (const pattern of ignoreAttributes) { - if (typeof pattern === "string" && attrName === pattern) { - return true; - } - if (pattern instanceof RegExp && pattern.test(attrName)) { - return true; - } + const modelProperties = expectedBodyTypeName === "Composite" && bodyMapper.type.modelProperties || {}; + const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); + if (expectedBodyTypeName === "Sequence" || isPageableResponse) { + const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : []; + for (const key of Object.keys(modelProperties)) { + if (modelProperties[key].serializedName) { + arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key]; } - }; + } + if (parsedHeaders) { + for (const key of Object.keys(parsedHeaders)) { + arrayResponse[key] = parsedHeaders[key]; + } + } + return isNullable && !fullResponse.parsedBody && !parsedHeaders && Object.getOwnPropertyNames(modelProperties).length === 0 ? null : arrayResponse; } - return () => false; + return handleNullableResponseAndWrappableBody({ + body: fullResponse.parsedBody, + headers: parsedHeaders, + hasNullableType: isNullable, + shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName) + }); } - module2.exports = getIgnoreAttributesFn; + exports2.flattenResponse = flattenResponse; } }); -// node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js -var require_OrderedObjParser = __commonJS({ - "node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports2, module2) { +// node_modules/@azure/core-client/dist/commonjs/serializer.js +var require_serializer = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/serializer.js"(exports2) { "use strict"; - var util = require_util10(); - var xmlNode = require_xmlNode(); - var readDocType = require_DocTypeReader(); - var toNumber = require_strnum(); - var getIgnoreAttributesFn = require_ignoreAttributes(); - var OrderedObjParser = class { - constructor(options) { - this.options = options; - this.currentNode = null; - this.tagsNodeStack = []; - this.docTypeEntities = {}; - this.lastEntities = { - "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, - "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, - "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, - "quot": { regex: /&(quot|#34|#x22);/g, val: '"' } - }; - this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; - this.htmlEntities = { - "space": { regex: /&(nbsp|#160);/g, val: " " }, - // "lt" : { regex: /&(lt|#60);/g, val: "<" }, - // "gt" : { regex: /&(gt|#62);/g, val: ">" }, - // "amp" : { regex: /&(amp|#38);/g, val: "&" }, - // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, - // "apos" : { regex: /&(apos|#39);/g, val: "'" }, - "cent": { regex: /&(cent|#162);/g, val: "\xA2" }, - "pound": { regex: /&(pound|#163);/g, val: "\xA3" }, - "yen": { regex: /&(yen|#165);/g, val: "\xA5" }, - "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" }, - "copyright": { regex: /&(copy|#169);/g, val: "\xA9" }, - "reg": { regex: /&(reg|#174);/g, val: "\xAE" }, - "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" }, - "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_2, str2) => String.fromCharCode(Number.parseInt(str2, 10)) }, - "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_2, str2) => String.fromCharCode(Number.parseInt(str2, 16)) } - }; - this.addExternalEntities = addExternalEntities; - this.parseXml = parseXml; - this.parseTextData = parseTextData; - this.resolveNameSpace = resolveNameSpace; - this.buildAttributesMap = buildAttributesMap; - this.isItStopNode = isItStopNode; - this.replaceEntitiesValue = replaceEntitiesValue; - this.readStopNodeData = readStopNodeData; - this.saveTextToParentTag = saveTextToParentTag; - this.addChild = addChild; - this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MapperTypeNames = exports2.createSerializer = void 0; + var tslib_1 = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3)); + var base64 = tslib_1.__importStar(require_base642()); + var interfaces_js_1 = require_interfaces(); + var utils_js_1 = require_utils5(); + var SerializerImpl = class { + constructor(modelMappers = {}, isXML = false) { + this.modelMappers = modelMappers; + this.isXML = isXML; } - }; - function addExternalEntities(externalEntities) { - const entKeys = Object.keys(externalEntities); - for (let i = 0; i < entKeys.length; i++) { - const ent = entKeys[i]; - this.lastEntities[ent] = { - regex: new RegExp("&" + ent + ";", "g"), - val: externalEntities[ent] + /** + * @deprecated Removing the constraints validation on client side. + */ + validateConstraints(mapper, value, objectName) { + const failValidation = (constraintName, constraintValue) => { + throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); }; - } - } - function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { - if (val2 !== void 0) { - if (this.options.trimValues && !dontTrim) { - val2 = val2.trim(); - } - if (val2.length > 0) { - if (!escapeEntities) val2 = this.replaceEntitiesValue(val2); - const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode); - if (newval === null || newval === void 0) { - return val2; - } else if (typeof newval !== typeof val2 || newval !== val2) { - return newval; - } else if (this.options.trimValues) { - return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); - } else { - const trimmedVal = val2.trim(); - if (trimmedVal === val2) { - return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); - } else { - return val2; + if (mapper.constraints && value !== void 0 && value !== null) { + const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems } = mapper.constraints; + if (ExclusiveMaximum !== void 0 && value >= ExclusiveMaximum) { + failValidation("ExclusiveMaximum", ExclusiveMaximum); + } + if (ExclusiveMinimum !== void 0 && value <= ExclusiveMinimum) { + failValidation("ExclusiveMinimum", ExclusiveMinimum); + } + if (InclusiveMaximum !== void 0 && value > InclusiveMaximum) { + failValidation("InclusiveMaximum", InclusiveMaximum); + } + if (InclusiveMinimum !== void 0 && value < InclusiveMinimum) { + failValidation("InclusiveMinimum", InclusiveMinimum); + } + if (MaxItems !== void 0 && value.length > MaxItems) { + failValidation("MaxItems", MaxItems); + } + if (MaxLength !== void 0 && value.length > MaxLength) { + failValidation("MaxLength", MaxLength); + } + if (MinItems !== void 0 && value.length < MinItems) { + failValidation("MinItems", MinItems); + } + if (MinLength !== void 0 && value.length < MinLength) { + failValidation("MinLength", MinLength); + } + if (MultipleOf !== void 0 && value % MultipleOf !== 0) { + failValidation("MultipleOf", MultipleOf); + } + if (Pattern) { + const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; + if (typeof value !== "string" || value.match(pattern) === null) { + failValidation("Pattern", Pattern); } } + if (UniqueItems && value.some((item, i, ar) => ar.indexOf(item) !== i)) { + failValidation("UniqueItems", UniqueItems); + } } } - } - function resolveNameSpace(tagname) { - if (this.options.removeNSPrefix) { - const tags = tagname.split(":"); - const prefix = tagname.charAt(0) === "/" ? "/" : ""; - if (tags[0] === "xmlns") { - return ""; + /** + * Serialize the given object based on its metadata defined in the mapper + * + * @param mapper - The mapper which defines the metadata of the serializable object + * + * @param object - A valid Javascript object to be serialized + * + * @param objectName - Name of the serialized object + * + * @param options - additional options to serialization + * + * @returns A valid serialized Javascript object + */ + serialize(mapper, object, objectName, options = { xml: {} }) { + var _a, _b, _c; + const updatedOptions = { + xml: { + rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY + } + }; + let payload = {}; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; } - if (tags.length === 2) { - tagname = prefix + tags[1]; + if (mapperType.match(/^Sequence$/i) !== null) { + payload = []; + } + if (mapper.isConstant) { + object = mapper.defaultValue; + } + const { required, nullable } = mapper; + if (required && nullable && object === void 0) { + throw new Error(`${objectName} cannot be undefined.`); + } + if (required && !nullable && (object === void 0 || object === null)) { + throw new Error(`${objectName} cannot be null or undefined.`); + } + if (!required && nullable === false && object === null) { + throw new Error(`${objectName} cannot be null.`); + } + if (object === void 0 || object === null) { + payload = object; + } else { + if (mapperType.match(/^any$/i) !== null) { + payload = object; + } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { + payload = serializeBasicTypes(mapperType, objectName, object); + } else if (mapperType.match(/^Enum$/i) !== null) { + const enumMapper = mapper; + payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); + } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { + payload = serializeDateTypes(mapperType, object, objectName); + } else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = serializeByteArrayType(objectName, object); + } else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = serializeBase64UrlType(objectName, object); + } else if (mapperType.match(/^Sequence$/i) !== null) { + payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } else if (mapperType.match(/^Composite$/i) !== null) { + payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } } + return payload; } - return tagname; - } - var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm"); - function buildAttributesMap(attrStr, jPath, tagName) { - if (this.options.ignoreAttributes !== true && typeof attrStr === "string") { - const matches = util.getAllMatches(attrStr, attrsRegx); - const len = matches.length; - const attrs = {}; - for (let i = 0; i < len; i++) { - const attrName = this.resolveNameSpace(matches[i][1]); - if (this.ignoreAttributesFn(attrName, jPath)) { - continue; + /** + * Deserialize the given object based on its metadata defined in the mapper + * + * @param mapper - The mapper which defines the metadata of the serializable object + * + * @param responseBody - A valid Javascript entity to be deserialized + * + * @param objectName - Name of the deserialized object + * + * @param options - Controls behavior of XML parser and builder. + * + * @returns A valid deserialized Javascript object + */ + deserialize(mapper, responseBody, objectName, options = { xml: {} }) { + var _a, _b, _c, _d; + const updatedOptions = { + xml: { + rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY + }, + ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false + }; + if (responseBody === void 0 || responseBody === null) { + if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { + responseBody = []; } - let oldVal = matches[i][4]; - let aName = this.options.attributeNamePrefix + attrName; - if (attrName.length) { - if (this.options.transformAttributeName) { - aName = this.options.transformAttributeName(aName); + if (mapper.defaultValue !== void 0) { + responseBody = mapper.defaultValue; + } + return responseBody; + } + let payload; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; + } + if (mapperType.match(/^Composite$/i) !== null) { + payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); + } else { + if (this.isXML) { + const xmlCharKey = updatedOptions.xml.xmlCharKey; + if (responseBody[interfaces_js_1.XML_ATTRKEY] !== void 0 && responseBody[xmlCharKey] !== void 0) { + responseBody = responseBody[xmlCharKey]; } - if (aName === "__proto__") aName = "#__proto__"; - if (oldVal !== void 0) { - if (this.options.trimValues) { - oldVal = oldVal.trim(); - } - oldVal = this.replaceEntitiesValue(oldVal); - const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); - if (newVal === null || newVal === void 0) { - attrs[aName] = oldVal; - } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) { - attrs[aName] = newVal; - } else { - attrs[aName] = parseValue( - oldVal, - this.options.parseAttributeValue, - this.options.numberParseOptions - ); - } - } else if (this.options.allowBooleanAttributes) { - attrs[aName] = true; + } + if (mapperType.match(/^Number$/i) !== null) { + payload = parseFloat(responseBody); + if (isNaN(payload)) { + payload = responseBody; + } + } else if (mapperType.match(/^Boolean$/i) !== null) { + if (responseBody === "true") { + payload = true; + } else if (responseBody === "false") { + payload = false; + } else { + payload = responseBody; } + } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) { + payload = responseBody; + } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) { + payload = new Date(responseBody); + } else if (mapperType.match(/^UnixTime$/i) !== null) { + payload = unixTimeToDate(responseBody); + } else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = base64.decodeString(responseBody); + } else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = base64UrlToByteArray(responseBody); + } else if (mapperType.match(/^Sequence$/i) !== null) { + payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); + } else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); } } - if (!Object.keys(attrs).length) { - return; + if (mapper.isConstant) { + payload = mapper.defaultValue; } - if (this.options.attributesGroupName) { - const attrCollection = {}; - attrCollection[this.options.attributesGroupName] = attrs; - return attrCollection; + return payload; + } + }; + function createSerializer(modelMappers = {}, isXML = false) { + return new SerializerImpl(modelMappers, isXML); + } + exports2.createSerializer = createSerializer; + function trimEnd(str2, ch) { + let len = str2.length; + while (len - 1 >= 0 && str2[len - 1] === ch) { + --len; + } + return str2.substr(0, len); + } + function bufferToBase64Url(buffer) { + if (!buffer) { + return void 0; + } + if (!(buffer instanceof Uint8Array)) { + throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); + } + const str2 = base64.encodeByteArray(buffer); + return trimEnd(str2, "=").replace(/\+/g, "-").replace(/\//g, "_"); + } + function base64UrlToByteArray(str2) { + if (!str2) { + return void 0; + } + if (str2 && typeof str2.valueOf() !== "string") { + throw new Error("Please provide an input of type string for converting to Uint8Array"); + } + str2 = str2.replace(/-/g, "+").replace(/_/g, "/"); + return base64.decodeString(str2); + } + function splitSerializeName(prop) { + const classes = []; + let partialclass = ""; + if (prop) { + const subwords = prop.split("."); + for (const item of subwords) { + if (item.charAt(item.length - 1) === "\\") { + partialclass += item.substr(0, item.length - 1) + "."; + } else { + partialclass += item; + classes.push(partialclass); + partialclass = ""; + } } - return attrs; } + return classes; } - var parseXml = function(xmlData) { - xmlData = xmlData.replace(/\r\n?/g, "\n"); - const xmlObj = new xmlNode("!xml"); - let currentNode = xmlObj; - let textData = ""; - let jPath = ""; - for (let i = 0; i < xmlData.length; i++) { - const ch = xmlData[i]; - if (ch === "<") { - if (xmlData[i + 1] === "/") { - const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed."); - let tagName = xmlData.substring(i + 2, closeIndex).trim(); - if (this.options.removeNSPrefix) { - const colonIndex = tagName.indexOf(":"); - if (colonIndex !== -1) { - tagName = tagName.substr(colonIndex + 1); - } - } - if (this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); - } - if (currentNode) { - textData = this.saveTextToParentTag(textData, currentNode, jPath); - } - const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1); - if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) { - throw new Error(`Unpaired tag can not be used as closing tag: `); - } - let propIndex = 0; - if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) { - propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1); - this.tagsNodeStack.pop(); - } else { - propIndex = jPath.lastIndexOf("."); - } - jPath = jPath.substring(0, propIndex); - currentNode = this.tagsNodeStack.pop(); - textData = ""; - i = closeIndex; - } else if (xmlData[i + 1] === "?") { - let tagData = readTagExp(xmlData, i, false, "?>"); - if (!tagData) throw new Error("Pi Tag is not closed."); - textData = this.saveTextToParentTag(textData, currentNode, jPath); - if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) { - } else { - const childNode = new xmlNode(tagData.tagName); - childNode.add(this.options.textNodeName, ""); - if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) { - childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); - } - this.addChild(currentNode, childNode, jPath); - } - i = tagData.closeIndex + 1; - } else if (xmlData.substr(i + 1, 3) === "!--") { - const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed."); - if (this.options.commentPropName) { - const comment = xmlData.substring(i + 4, endIndex - 2); - textData = this.saveTextToParentTag(textData, currentNode, jPath); - currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]); - } - i = endIndex; - } else if (xmlData.substr(i + 1, 2) === "!D") { - const result = readDocType(xmlData, i); - this.docTypeEntities = result.entities; - i = result.i; - } else if (xmlData.substr(i + 1, 2) === "![") { - const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; - const tagExp = xmlData.substring(i + 9, closeIndex); - textData = this.saveTextToParentTag(textData, currentNode, jPath); - let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); - if (val2 == void 0) val2 = ""; - if (this.options.cdataPropName) { - currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]); - } else { - currentNode.add(this.options.textNodeName, val2); - } - i = closeIndex + 2; - } else { - let result = readTagExp(xmlData, i, this.options.removeNSPrefix); - let tagName = result.tagName; - const rawTagName = result.rawTagName; - let tagExp = result.tagExp; - let attrExpPresent = result.attrExpPresent; - let closeIndex = result.closeIndex; - if (this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); - } - if (currentNode && textData) { - if (currentNode.tagname !== "!xml") { - textData = this.saveTextToParentTag(textData, currentNode, jPath, false); - } - } - const lastTag = currentNode; - if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) { - currentNode = this.tagsNodeStack.pop(); - jPath = jPath.substring(0, jPath.lastIndexOf(".")); - } - if (tagName !== xmlObj.tagname) { - jPath += jPath ? "." + tagName : tagName; - } - if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { - let tagContent = ""; - if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { - if (tagName[tagName.length - 1] === "/") { - tagName = tagName.substr(0, tagName.length - 1); - jPath = jPath.substr(0, jPath.length - 1); - tagExp = tagName; - } else { - tagExp = tagExp.substr(0, tagExp.length - 1); - } - i = result.closeIndex; - } else if (this.options.unpairedTags.indexOf(tagName) !== -1) { - i = result.closeIndex; - } else { - const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); - if (!result2) throw new Error(`Unexpected end of ${rawTagName}`); - i = result2.i; - tagContent = result2.tagContent; - } - const childNode = new xmlNode(tagName); - if (tagName !== tagExp && attrExpPresent) { - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); - } - if (tagContent) { - tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); - } - jPath = jPath.substr(0, jPath.lastIndexOf(".")); - childNode.add(this.options.textNodeName, tagContent); - this.addChild(currentNode, childNode, jPath); - } else { - if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { - if (tagName[tagName.length - 1] === "/") { - tagName = tagName.substr(0, tagName.length - 1); - jPath = jPath.substr(0, jPath.length - 1); - tagExp = tagName; - } else { - tagExp = tagExp.substr(0, tagExp.length - 1); - } - if (this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); - } - const childNode = new xmlNode(tagName); - if (tagName !== tagExp && attrExpPresent) { - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); - } - this.addChild(currentNode, childNode, jPath); - jPath = jPath.substr(0, jPath.lastIndexOf(".")); - } else { - const childNode = new xmlNode(tagName); - this.tagsNodeStack.push(currentNode); - if (tagName !== tagExp && attrExpPresent) { - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); - } - this.addChild(currentNode, childNode, jPath); - currentNode = childNode; - } - textData = ""; - i = closeIndex; - } - } - } else { - textData += xmlData[i]; - } - } - return xmlObj.child; - }; - function addChild(currentNode, childNode, jPath) { - const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]); - if (result === false) { - } else if (typeof result === "string") { - childNode.tagname = result; - currentNode.addChild(childNode); - } else { - currentNode.addChild(childNode); - } - } - var replaceEntitiesValue = function(val2) { - if (this.options.processEntities) { - for (let entityName2 in this.docTypeEntities) { - const entity = this.docTypeEntities[entityName2]; - val2 = val2.replace(entity.regx, entity.val); - } - for (let entityName2 in this.lastEntities) { - const entity = this.lastEntities[entityName2]; - val2 = val2.replace(entity.regex, entity.val); - } - if (this.options.htmlEntities) { - for (let entityName2 in this.htmlEntities) { - const entity = this.htmlEntities[entityName2]; - val2 = val2.replace(entity.regex, entity.val); - } - } - val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val); + function dateToUnixTime(d) { + if (!d) { + return void 0; } - return val2; - }; - function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { - if (textData) { - if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0; - textData = this.parseTextData( - textData, - currentNode.tagname, - jPath, - false, - currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, - isLeafNode - ); - if (textData !== void 0 && textData !== "") - currentNode.add(this.options.textNodeName, textData); - textData = ""; + if (typeof d.valueOf() === "string") { + d = new Date(d); } - return textData; + return Math.floor(d.getTime() / 1e3); } - function isItStopNode(stopNodes, jPath, currentTagName) { - const allNodesExp = "*." + currentTagName; - for (const stopNodePath in stopNodes) { - const stopNodeExp = stopNodes[stopNodePath]; - if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true; + function unixTimeToDate(n) { + if (!n) { + return void 0; } - return false; + return new Date(n * 1e3); } - function tagExpWithClosingIndex(xmlData, i, closingChar = ">") { - let attrBoundary; - let tagExp = ""; - for (let index = i; index < xmlData.length; index++) { - let ch = xmlData[index]; - if (attrBoundary) { - if (ch === attrBoundary) attrBoundary = ""; - } else if (ch === '"' || ch === "'") { - attrBoundary = ch; - } else if (ch === closingChar[0]) { - if (closingChar[1]) { - if (xmlData[index + 1] === closingChar[1]) { - return { - data: tagExp, - index - }; - } - } else { - return { - data: tagExp, - index - }; + function serializeBasicTypes(typeName, objectName, value) { + if (value !== null && value !== void 0) { + if (typeName.match(/^Number$/i) !== null) { + if (typeof value !== "number") { + throw new Error(`${objectName} with value ${value} must be of type number.`); + } + } else if (typeName.match(/^String$/i) !== null) { + if (typeof value.valueOf() !== "string") { + throw new Error(`${objectName} with value "${value}" must be of type string.`); + } + } else if (typeName.match(/^Uuid$/i) !== null) { + if (!(typeof value.valueOf() === "string" && (0, utils_js_1.isValidUuid)(value))) { + throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); + } + } else if (typeName.match(/^Boolean$/i) !== null) { + if (typeof value !== "boolean") { + throw new Error(`${objectName} with value ${value} must be of type boolean.`); + } + } else if (typeName.match(/^Stream$/i) !== null) { + const objectType = typeof value; + if (objectType !== "string" && typeof value.pipe !== "function" && // NodeJS.ReadableStream + typeof value.tee !== "function" && // browser ReadableStream + !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && // File objects count as a type of Blob, so we want to use instanceof explicitly + !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) && objectType !== "function") { + throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`); } - } else if (ch === " ") { - ch = " "; } - tagExp += ch; - } - } - function findClosingIndex(xmlData, str2, i, errMsg) { - const closingIndex = xmlData.indexOf(str2, i); - if (closingIndex === -1) { - throw new Error(errMsg); - } else { - return closingIndex + str2.length - 1; } + return value; } - function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") { - const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar); - if (!result) return; - let tagExp = result.data; - const closeIndex = result.index; - const separatorIndex = tagExp.search(/\s/); - let tagName = tagExp; - let attrExpPresent = true; - if (separatorIndex !== -1) { - tagName = tagExp.substring(0, separatorIndex); - tagExp = tagExp.substring(separatorIndex + 1).trimStart(); + function serializeEnumType(objectName, allowedValues, value) { + if (!allowedValues) { + throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); } - const rawTagName = tagName; - if (removeNSPrefix) { - const colonIndex = tagName.indexOf(":"); - if (colonIndex !== -1) { - tagName = tagName.substr(colonIndex + 1); - attrExpPresent = tagName !== result.data.substr(colonIndex + 1); + const isPresent = allowedValues.some((item) => { + if (typeof item.valueOf() === "string") { + return item.toLowerCase() === value.toLowerCase(); } + return item === value; + }); + if (!isPresent) { + throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); } - return { - tagName, - tagExp, - closeIndex, - attrExpPresent, - rawTagName - }; + return value; } - function readStopNodeData(xmlData, tagName, i) { - const startIndex = i; - let openTagCount = 1; - for (; i < xmlData.length; i++) { - if (xmlData[i] === "<") { - if (xmlData[i + 1] === "/") { - const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); - let closeTagName = xmlData.substring(i + 2, closeIndex).trim(); - if (closeTagName === tagName) { - openTagCount--; - if (openTagCount === 0) { - return { - tagContent: xmlData.substring(startIndex, i), - i: closeIndex - }; - } - } - i = closeIndex; - } else if (xmlData[i + 1] === "?") { - const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed."); - i = closeIndex; - } else if (xmlData.substr(i + 1, 3) === "!--") { - const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed."); - i = closeIndex; - } else if (xmlData.substr(i + 1, 2) === "![") { - const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; - i = closeIndex; - } else { - const tagData = readTagExp(xmlData, i, ">"); - if (tagData) { - const openTagName = tagData && tagData.tagName; - if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") { - openTagCount++; - } - i = tagData.closeIndex; - } - } + function serializeByteArrayType(objectName, value) { + if (value !== void 0 && value !== null) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); } + value = base64.encodeByteArray(value); } + return value; } - function parseValue(val2, shouldParse, options) { - if (shouldParse && typeof val2 === "string") { - const newval = val2.trim(); - if (newval === "true") return true; - else if (newval === "false") return false; - else return toNumber(val2, options); - } else { - if (util.isExist(val2)) { - return val2; - } else { - return ""; + function serializeBase64UrlType(objectName, value) { + if (value !== void 0 && value !== null) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); } + value = bufferToBase64Url(value); } + return value; } - module2.exports = OrderedObjParser; - } -}); - -// node_modules/fast-xml-parser/src/xmlparser/node2json.js -var require_node2json = __commonJS({ - "node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports2) { - "use strict"; - function prettify(node, options) { - return compress(node, options); - } - function compress(arr, options, jPath) { - let text; - const compressedObj = {}; - for (let i = 0; i < arr.length; i++) { - const tagObj = arr[i]; - const property = propName(tagObj); - let newJpath = ""; - if (jPath === void 0) newJpath = property; - else newJpath = jPath + "." + property; - if (property === options.textNodeName) { - if (text === void 0) text = tagObj[property]; - else text += "" + tagObj[property]; - } else if (property === void 0) { - continue; - } else if (tagObj[property]) { - let val2 = compress(tagObj[property], options, newJpath); - const isLeaf = isLeafTag(val2, options); - if (tagObj[":@"]) { - assignAttributes(val2, tagObj[":@"], newJpath, options); - } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) { - val2 = val2[options.textNodeName]; - } else if (Object.keys(val2).length === 0) { - if (options.alwaysCreateTextNode) val2[options.textNodeName] = ""; - else val2 = ""; + function serializeDateTypes(typeName, value, objectName) { + if (value !== void 0 && value !== null) { + if (typeName.match(/^Date$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); } - if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) { - if (!Array.isArray(compressedObj[property])) { - compressedObj[property] = [compressedObj[property]]; - } - compressedObj[property].push(val2); - } else { - if (options.isArray(property, newJpath, isLeaf)) { - compressedObj[property] = [val2]; - } else { - compressedObj[property] = val2; - } + value = value instanceof Date ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10); + } else if (typeName.match(/^DateTime$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); + } + value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + } else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); + } + value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); + } else if (typeName.match(/^UnixTime$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format for it to be serialized in UnixTime/Epoch format.`); + } + value = dateToUnixTime(value); + } else if (typeName.match(/^TimeSpan$/i) !== null) { + if (!(0, utils_js_1.isDuration)(value)) { + throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); } } } - if (typeof text === "string") { - if (text.length > 0) compressedObj[options.textNodeName] = text; - } else if (text !== void 0) compressedObj[options.textNodeName] = text; - return compressedObj; + return value; } - function propName(obj) { - const keys = Object.keys(obj); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if (key !== ":@") return key; + function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { + var _a; + if (!Array.isArray(object)) { + throw new Error(`${objectName} must be of type Array.`); } - } - function assignAttributes(obj, attrMap, jpath, options) { - if (attrMap) { - const keys = Object.keys(attrMap); - const len = keys.length; - for (let i = 0; i < len; i++) { - const atrrName = keys[i]; - if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { - obj[atrrName] = [attrMap[atrrName]]; + let elementType = mapper.type.element; + if (!elementType || typeof elementType !== "object") { + throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}.`); + } + if (elementType.type.name === "Composite" && elementType.type.className) { + elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType; + } + const tempArray = []; + for (let i = 0; i < object.length; i++) { + const serializedValue = serializer.serialize(elementType, object[i], objectName, options); + if (isXml && elementType.xmlNamespace) { + const xmlnsKey = elementType.xmlNamespacePrefix ? `xmlns:${elementType.xmlNamespacePrefix}` : "xmlns"; + if (elementType.type.name === "Composite") { + tempArray[i] = Object.assign({}, serializedValue); + tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; } else { - obj[atrrName] = attrMap[atrrName]; + tempArray[i] = {}; + tempArray[i][options.xml.xmlCharKey] = serializedValue; + tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; } + } else { + tempArray[i] = serializedValue; } } + return tempArray; } - function isLeafTag(obj, options) { - const { textNodeName } = options; - const propCount = Object.keys(obj).length; - if (propCount === 0) { - return true; + function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { + if (typeof object !== "object") { + throw new Error(`${objectName} must be of type object.`); } - if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) { - return true; + const valueType = mapper.type.value; + if (!valueType || typeof valueType !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}.`); } - return false; - } - exports2.prettify = prettify; - } -}); - -// node_modules/fast-xml-parser/src/xmlparser/XMLParser.js -var require_XMLParser = __commonJS({ - "node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports2, module2) { - var { buildOptions } = require_OptionsBuilder(); - var OrderedObjParser = require_OrderedObjParser(); - var { prettify } = require_node2json(); - var validator = require_validator(); - var XMLParser = class { - constructor(options) { - this.externalEntities = {}; - this.options = buildOptions(options); + const tempDictionary = {}; + for (const key of Object.keys(object)) { + const serializedValue = serializer.serialize(valueType, object[key], objectName, options); + tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); } - /** - * Parse XML dats to JS object - * @param {string|Buffer} xmlData - * @param {boolean|Object} validationOption - */ - parse(xmlData, validationOption) { - if (typeof xmlData === "string") { - } else if (xmlData.toString) { - xmlData = xmlData.toString(); - } else { - throw new Error("XML data is accepted in String or Bytes[] form."); - } - if (validationOption) { - if (validationOption === true) validationOption = {}; - const result = validator.validate(xmlData, validationOption); - if (result !== true) { - throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`); - } - } - const orderedObjParser = new OrderedObjParser(this.options); - orderedObjParser.addExternalEntities(this.externalEntities); - const orderedResult = orderedObjParser.parseXml(xmlData); - if (this.options.preserveOrder || orderedResult === void 0) return orderedResult; - else return prettify(orderedResult, this.options); + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + const result = tempDictionary; + result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; + return result; } - /** - * Add Entity which is not by default supported by this library - * @param {string} key - * @param {string} value - */ - addEntity(key, value) { - if (value.indexOf("&") !== -1) { - throw new Error("Entity value can't have '&'"); - } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { - throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '"); - } else if (value === "&") { - throw new Error("An entity with value '&' is not permitted"); - } else { - this.externalEntities[key] = value; - } + return tempDictionary; + } + function resolveAdditionalProperties(serializer, mapper, objectName) { + const additionalProperties = mapper.type.additionalProperties; + if (!additionalProperties && mapper.type.className) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; } - }; - module2.exports = XMLParser; - } -}); - -// node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js -var require_orderedJs2Xml = __commonJS({ - "node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports2, module2) { - var EOL = "\n"; - function toXml(jArray, options) { - let indentation = ""; - if (options.format && options.indentBy.length > 0) { - indentation = EOL; + return additionalProperties; + } + function resolveReferencedMapper(serializer, mapper, objectName) { + const className = mapper.type.className; + if (!className) { + throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, void 0, 2)}".`); } - return arrToStr(jArray, options, "", indentation); + return serializer.modelMappers[className]; } - function arrToStr(arr, options, jPath, indentation) { - let xmlStr = ""; - let isPreviousElementTag = false; - for (let i = 0; i < arr.length; i++) { - const tagObj = arr[i]; - const tagName = propName(tagObj); - if (tagName === void 0) continue; - let newJPath = ""; - if (jPath.length === 0) newJPath = tagName; - else newJPath = `${jPath}.${tagName}`; - if (tagName === options.textNodeName) { - let tagText = tagObj[tagName]; - if (!isStopNode(newJPath, options)) { - tagText = options.tagValueProcessor(tagName, tagText); - tagText = replaceEntitiesValue(tagText, options); - } - if (isPreviousElementTag) { - xmlStr += indentation; - } - xmlStr += tagText; - isPreviousElementTag = false; - continue; - } else if (tagName === options.cdataPropName) { - if (isPreviousElementTag) { - xmlStr += indentation; - } - xmlStr += ``; - isPreviousElementTag = false; - continue; - } else if (tagName === options.commentPropName) { - xmlStr += indentation + ``; - isPreviousElementTag = true; - continue; - } else if (tagName[0] === "?") { - const attStr2 = attr_to_str(tagObj[":@"], options); - const tempInd = tagName === "?xml" ? "" : indentation; - let piTextNodeName = tagObj[tagName][0][options.textNodeName]; - piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; - xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`; - isPreviousElementTag = true; - continue; - } - let newIdentation = indentation; - if (newIdentation !== "") { - newIdentation += options.indentBy; + function resolveModelProperties(serializer, mapper, objectName) { + let modelProps = mapper.type.modelProperties; + if (!modelProps) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + if (!modelMapper) { + throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); } - const attStr = attr_to_str(tagObj[":@"], options); - const tagStart = indentation + `<${tagName}${attStr}`; - const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); - if (options.unpairedTags.indexOf(tagName) !== -1) { - if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; - else xmlStr += tagStart + "/>"; - } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { - xmlStr += tagStart + "/>"; - } else if (tagValue && tagValue.endsWith(">")) { - xmlStr += tagStart + `>${tagValue}${indentation}`; - } else { - xmlStr += tagStart + ">"; - if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; + modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; + if (!modelProps) { + throw new Error(`modelProperties cannot be null or undefined in the mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); } - isPreviousElementTag = true; } - return xmlStr; + return modelProps; } - function propName(obj) { - const keys = Object.keys(obj); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if (!obj.hasOwnProperty(key)) continue; - if (key !== ":@") return key; + function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); } - } - function attr_to_str(attrMap, options) { - let attrStr = ""; - if (attrMap && !options.ignoreAttributes) { - for (let attr in attrMap) { - if (!attrMap.hasOwnProperty(attr)) continue; - let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); - attrVal = replaceEntitiesValue(attrVal, options); - if (attrVal === true && options.suppressBooleanAttributes) { - attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; + if (object !== void 0 && object !== null) { + const payload = {}; + const modelProps = resolveModelProperties(serializer, mapper, objectName); + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + if (propertyMapper.readOnly) { + continue; + } + let propName; + let parentObject = payload; + if (serializer.isXML) { + if (propertyMapper.xmlIsWrapped) { + propName = propertyMapper.xmlName; + } else { + propName = propertyMapper.xmlElementName || propertyMapper.xmlName; + } } else { - attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + const paths = splitSerializeName(propertyMapper.serializedName); + propName = paths.pop(); + for (const pathName of paths) { + const childObject = parentObject[pathName]; + if ((childObject === void 0 || childObject === null) && (object[key] !== void 0 && object[key] !== null || propertyMapper.defaultValue !== void 0)) { + parentObject[pathName] = {}; + } + parentObject = parentObject[pathName]; + } + } + if (parentObject !== void 0 && parentObject !== null) { + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); + } + const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName : objectName; + let toSerialize = object[key]; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && (toSerialize === void 0 || toSerialize === null)) { + toSerialize = mapper.serializedName; + } + const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); + if (serializedValue !== void 0 && propName !== void 0 && propName !== null) { + const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); + if (isXml && propertyMapper.xmlIsAttribute) { + parentObject[interfaces_js_1.XML_ATTRKEY] = parentObject[interfaces_js_1.XML_ATTRKEY] || {}; + parentObject[interfaces_js_1.XML_ATTRKEY][propName] = serializedValue; + } else if (isXml && propertyMapper.xmlIsWrapped) { + parentObject[propName] = { [propertyMapper.xmlElementName]: value }; + } else { + parentObject[propName] = value; + } + } + } + } + const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); + if (additionalPropertiesMapper) { + const propNames = Object.keys(modelProps); + for (const clientPropName in object) { + const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); + if (isAdditionalProperty) { + payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); + } } } + return payload; } - return attrStr; + return object; } - function isStopNode(jPath, options) { - jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); - let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); - for (let index in options.stopNodes) { - if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; + function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { + if (!isXml || !propertyMapper.xmlNamespace) { + return serializedValue; } - return false; - } - function replaceEntitiesValue(textValue, options) { - if (textValue && textValue.length > 0 && options.processEntities) { - for (let i = 0; i < options.entities.length; i++) { - const entity = options.entities[i]; - textValue = textValue.replace(entity.regex, entity.val); + const xmlnsKey = propertyMapper.xmlNamespacePrefix ? `xmlns:${propertyMapper.xmlNamespacePrefix}` : "xmlns"; + const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; + if (["Composite"].includes(propertyMapper.type.name)) { + if (serializedValue[interfaces_js_1.XML_ATTRKEY]) { + return serializedValue; + } else { + const result2 = Object.assign({}, serializedValue); + result2[interfaces_js_1.XML_ATTRKEY] = xmlNamespace; + return result2; } } - return textValue; + const result = {}; + result[options.xml.xmlCharKey] = serializedValue; + result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace; + return result; } - module2.exports = toXml; - } -}); - -// node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js -var require_json2xml = __commonJS({ - "node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports2, module2) { - "use strict"; - var buildFromOrderedJs = require_orderedJs2Xml(); - var getIgnoreAttributesFn = require_ignoreAttributes(); - var defaultOptions = { - attributeNamePrefix: "@_", - attributesGroupName: false, - textNodeName: "#text", - ignoreAttributes: true, - cdataPropName: false, - format: false, - indentBy: " ", - suppressEmptyNode: false, - suppressUnpairedNode: true, - suppressBooleanAttributes: true, - tagValueProcessor: function(key, a) { - return a; - }, - attributeValueProcessor: function(attrName, a) { - return a; - }, - preserveOrder: false, - commentPropName: false, - unpairedTags: [], - entities: [ - { regex: new RegExp("&", "g"), val: "&" }, - //it must be on top - { regex: new RegExp(">", "g"), val: ">" }, - { regex: new RegExp("<", "g"), val: "<" }, - { regex: new RegExp("'", "g"), val: "'" }, - { regex: new RegExp('"', "g"), val: """ } - ], - processEntities: true, - stopNodes: [], - // transformTagName: false, - // transformAttributeName: false, - oneListGroup: false - }; - function Builder(options) { - this.options = Object.assign({}, defaultOptions, options); - if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { - this.isAttribute = function() { - return false; - }; - } else { - this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); - this.attrPrefixLen = this.options.attributeNamePrefix.length; - this.isAttribute = isAttribute; - } - this.processTextOrObjNode = processTextOrObjNode; - if (this.options.format) { - this.indentate = indentate; - this.tagEndChar = ">\n"; - this.newLine = "\n"; - } else { - this.indentate = function() { - return ""; - }; - this.tagEndChar = ">"; - this.newLine = ""; - } + function isSpecialXmlProperty(propertyName, options) { + return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName); } - Builder.prototype.build = function(jObj) { - if (this.options.preserveOrder) { - return buildFromOrderedJs(jObj, this.options); - } else { - if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) { - jObj = { - [this.options.arrayNodeName]: jObj - }; - } - return this.j2x(jObj, 0, []).val; + function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { + var _a, _b; + const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY; + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } - }; - Builder.prototype.j2x = function(jObj, level, ajPath) { - let attrStr = ""; - let val2 = ""; - const jPath = ajPath.join("."); - for (let key in jObj) { - if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue; - if (typeof jObj[key] === "undefined") { - if (this.isAttribute(key)) { - val2 += ""; + const modelProps = resolveModelProperties(serializer, mapper, objectName); + let instance = {}; + const handledPropertyNames = []; + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + const paths = splitSerializeName(modelProps[key].serializedName); + handledPropertyNames.push(paths[0]); + const { serializedName, xmlName, xmlElementName } = propertyMapper; + let propertyObjectName = objectName; + if (serializedName !== "" && serializedName !== void 0) { + propertyObjectName = objectName + "." + serializedName; + } + const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; + if (headerCollectionPrefix) { + const dictionary = {}; + for (const headerKey of Object.keys(responseBody)) { + if (headerKey.startsWith(headerCollectionPrefix)) { + dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); + } + handledPropertyNames.push(headerKey); } - } else if (jObj[key] === null) { - if (this.isAttribute(key)) { - val2 += ""; - } else if (key[0] === "?") { - val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; + instance[key] = dictionary; + } else if (serializer.isXML) { + if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) { + instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options); + } else if (propertyMapper.xmlIsMsText) { + if (responseBody[xmlCharKey] !== void 0) { + instance[key] = responseBody[xmlCharKey]; + } else if (typeof responseBody === "string") { + instance[key] = responseBody; + } } else { - val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; - } - } else if (jObj[key] instanceof Date) { - val2 += this.buildTextValNode(jObj[key], key, "", level); - } else if (typeof jObj[key] !== "object") { - const attr = this.isAttribute(key); - if (attr && !this.ignoreAttributesFn(attr, jPath)) { - attrStr += this.buildAttrPairStr(attr, "" + jObj[key]); - } else if (!attr) { - if (key === this.options.textNodeName) { - let newval = this.options.tagValueProcessor(key, "" + jObj[key]); - val2 += this.replaceEntitiesValue(newval); + const propertyName = xmlElementName || xmlName || serializedName; + if (propertyMapper.xmlIsWrapped) { + const wrapped = responseBody[xmlName]; + const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : []; + instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); + handledPropertyNames.push(xmlName); } else { - val2 += this.buildTextValNode(jObj[key], key, "", level); + const property = responseBody[propertyName]; + instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); + handledPropertyNames.push(propertyName); } } - } else if (Array.isArray(jObj[key])) { - const arrLen = jObj[key].length; - let listTagVal = ""; - let listTagAttr = ""; - for (let j = 0; j < arrLen; j++) { - const item = jObj[key][j]; - if (typeof item === "undefined") { - } else if (item === null) { - if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; - else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; - } else if (typeof item === "object") { - if (this.options.oneListGroup) { - const result = this.j2x(item, level + 1, ajPath.concat(key)); - listTagVal += result.val; - if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { - listTagAttr += result.attrStr; - } - } else { - listTagVal += this.processTextOrObjNode(item, key, level, ajPath); - } - } else { - if (this.options.oneListGroup) { - let textValue = this.options.tagValueProcessor(key, item); - textValue = this.replaceEntitiesValue(textValue); - listTagVal += textValue; - } else { - listTagVal += this.buildTextValNode(item, key, "", level); + } else { + let propertyInstance; + let res = responseBody; + let steps = 0; + for (const item of paths) { + if (!res) + break; + steps++; + res = res[item]; + } + if (res === null && steps < paths.length) { + res = void 0; + } + propertyInstance = res; + const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; + if (polymorphicDiscriminator && key === polymorphicDiscriminator.clientName && (propertyInstance === void 0 || propertyInstance === null)) { + propertyInstance = mapper.serializedName; + } + let serializedValue; + if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { + propertyInstance = responseBody[key]; + const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + for (const [k, v] of Object.entries(instance)) { + if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { + arrayInstance[k] = v; } } + instance = arrayInstance; + } else if (propertyInstance !== void 0 || propertyMapper.defaultValue !== void 0) { + serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + instance[key] = serializedValue; } - if (this.options.oneListGroup) { - listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); - } - val2 += listTagVal; - } else { - if (this.options.attributesGroupName && key === this.options.attributesGroupName) { - const Ks = Object.keys(jObj[key]); - const L = Ks.length; - for (let j = 0; j < L; j++) { - attrStr += this.buildAttrPairStr(Ks[j], "" + jObj[key][Ks[j]]); + } + } + const additionalPropertiesMapper = mapper.type.additionalProperties; + if (additionalPropertiesMapper) { + const isAdditionalProperty = (responsePropName) => { + for (const clientPropName in modelProps) { + const paths = splitSerializeName(modelProps[clientPropName].serializedName); + if (paths[0] === responsePropName) { + return false; } - } else { - val2 += this.processTextOrObjNode(jObj[key], key, level, ajPath); + } + return true; + }; + for (const responsePropName in responseBody) { + if (isAdditionalProperty(responsePropName)) { + instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); + } + } + } else if (responseBody && !options.ignoreUnknownProperties) { + for (const key of Object.keys(responseBody)) { + if (instance[key] === void 0 && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) { + instance[key] = responseBody[key]; } } } - return { attrStr, val: val2 }; - }; - Builder.prototype.buildAttrPairStr = function(attrName, val2) { - val2 = this.options.attributeValueProcessor(attrName, "" + val2); - val2 = this.replaceEntitiesValue(val2); - if (this.options.suppressBooleanAttributes && val2 === "true") { - return " " + attrName; - } else return " " + attrName + '="' + val2 + '"'; - }; - function processTextOrObjNode(object, key, level, ajPath) { - const result = this.j2x(object, level + 1, ajPath.concat(key)); - if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) { - return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); - } else { - return this.buildObjectNode(result.val, key, result.attrStr, level); + return instance; + } + function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { + const value = mapper.type.value; + if (!value || typeof value !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}`); + } + if (responseBody) { + const tempDictionary = {}; + for (const key of Object.keys(responseBody)) { + tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); + } + return tempDictionary; } + return responseBody; } - Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) { - if (val2 === "") { - if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; - else { - return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; + function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { + var _a; + let element = mapper.type.element; + if (!element || typeof element !== "object") { + throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${objectName}`); + } + if (responseBody) { + if (!Array.isArray(responseBody)) { + responseBody = [responseBody]; } - } else { - let tagEndExp = "" + val2 + tagEndExp; - } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { - return this.indentate(level) + `` + this.newLine; - } else { - return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp; + const tempArray = []; + for (let i = 0; i < responseBody.length; i++) { + tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); } + return tempArray; } - }; - Builder.prototype.closeTag = function(key) { - let closeTag = ""; - if (this.options.unpairedTags.indexOf(key) !== -1) { - if (!this.options.suppressUnpairedNode) closeTag = "/"; - } else if (this.options.suppressEmptyNode) { - closeTag = "/"; - } else { - closeTag = `>` + this.newLine; - } else if (this.options.commentPropName !== false && key === this.options.commentPropName) { - return this.indentate(level) + `` + this.newLine; - } else if (key[0] === "?") { - return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; - } else { - let textValue = this.options.tagValueProcessor(key, val2); - textValue = this.replaceEntitiesValue(textValue); - if (textValue === "") { - return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; + return responseBody; + } + function getIndexDiscriminator(discriminators, discriminatorValue, typeName) { + const typeNamesToCheck = [typeName]; + while (typeNamesToCheck.length) { + const currentName = typeNamesToCheck.shift(); + const indexDiscriminator = discriminatorValue === currentName ? discriminatorValue : currentName + "." + discriminatorValue; + if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) { + return discriminators[indexDiscriminator]; } else { - return this.indentate(level) + "<" + key + attrStr + ">" + textValue + " 0 && this.options.processEntities) { - for (let i = 0; i < this.options.entities.length; i++) { - const entity = this.options.entities[i]; - textValue = textValue.replace(entity.regex, entity.val); + return void 0; + } + function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { + var _a; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator) { + let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; + if (discriminatorName) { + if (polymorphicPropertyName === "serializedName") { + discriminatorName = discriminatorName.replace(/\\/gi, ""); + } + const discriminatorValue = object[discriminatorName]; + const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className; + if (typeof discriminatorValue === "string" && typeName) { + const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName); + if (polymorphicMapper) { + mapper = polymorphicMapper; + } + } } } - return textValue; - }; - function indentate(level) { - return this.options.indentBy.repeat(level); + return mapper; } - function isAttribute(name) { - if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) { - return name.substr(this.attrPrefixLen); - } else { - return false; - } + function getPolymorphicDiscriminatorRecursively(serializer, mapper) { + return mapper.type.polymorphicDiscriminator || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className); } - module2.exports = Builder; + function getPolymorphicDiscriminatorSafely(serializer, typeName) { + return typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator; + } + exports2.MapperTypeNames = { + Base64Url: "Base64Url", + Boolean: "Boolean", + ByteArray: "ByteArray", + Composite: "Composite", + Date: "Date", + DateTime: "DateTime", + DateTimeRfc1123: "DateTimeRfc1123", + Dictionary: "Dictionary", + Enum: "Enum", + Number: "Number", + Object: "Object", + Sequence: "Sequence", + String: "String", + Stream: "Stream", + TimeSpan: "TimeSpan", + UnixTime: "UnixTime" + }; } }); -// node_modules/fast-xml-parser/src/fxp.js -var require_fxp = __commonJS({ - "node_modules/fast-xml-parser/src/fxp.js"(exports2, module2) { +// node_modules/@azure/core-client/dist/commonjs/state.js +var require_state2 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/state.js"(exports2) { "use strict"; - var validator = require_validator(); - var XMLParser = require_XMLParser(); - var XMLBuilder = require_json2xml(); - module2.exports = { - XMLParser, - XMLValidator: validator, - XMLBuilder + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.state = void 0; + exports2.state = { + operationRequestMap: /* @__PURE__ */ new WeakMap() }; } }); -// node_modules/@azure/core-xml/dist/commonjs/xml.common.js -var require_xml_common = __commonJS({ - "node_modules/@azure/core-xml/dist/commonjs/xml.common.js"(exports2) { +// node_modules/@azure/core-client/dist/commonjs/operationHelpers.js +var require_operationHelpers = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/operationHelpers.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.XML_CHARKEY = exports2.XML_ATTRKEY = void 0; - exports2.XML_ATTRKEY = "$"; - exports2.XML_CHARKEY = "_"; + exports2.getOperationRequestInfo = exports2.getOperationArgumentValueFromParameter = void 0; + var state_js_1 = require_state2(); + function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) { + let parameterPath = parameter.parameterPath; + const parameterMapper = parameter.mapper; + let value; + if (typeof parameterPath === "string") { + parameterPath = [parameterPath]; + } + if (Array.isArray(parameterPath)) { + if (parameterPath.length > 0) { + if (parameterMapper.isConstant) { + value = parameterMapper.defaultValue; + } else { + let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); + if (!propertySearchResult.propertyFound && fallbackObject) { + propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath); + } + let useDefaultValue = false; + if (!propertySearchResult.propertyFound) { + useDefaultValue = parameterMapper.required || parameterPath[0] === "options" && parameterPath.length === 2; + } + value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; + } + } + } else { + if (parameterMapper.required) { + value = {}; + } + for (const propertyName in parameterPath) { + const propertyMapper = parameterMapper.type.modelProperties[propertyName]; + const propertyPath = parameterPath[propertyName]; + const propertyValue = getOperationArgumentValueFromParameter(operationArguments, { + parameterPath: propertyPath, + mapper: propertyMapper + }, fallbackObject); + if (propertyValue !== void 0) { + if (!value) { + value = {}; + } + value[propertyName] = propertyValue; + } + } + } + return value; + } + exports2.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter; + function getPropertyFromParameterPath(parent, parameterPath) { + const result = { propertyFound: false }; + let i = 0; + for (; i < parameterPath.length; ++i) { + const parameterPathPart = parameterPath[i]; + if (parent && parameterPathPart in parent) { + parent = parent[parameterPathPart]; + } else { + break; + } + } + if (i === parameterPath.length) { + result.propertyValue = parent; + result.propertyFound = true; + } + return result; + } + var originalRequestSymbol = Symbol.for("@azure/core-client original request"); + function hasOriginalRequest(request) { + return originalRequestSymbol in request; + } + function getOperationRequestInfo(request) { + if (hasOriginalRequest(request)) { + return getOperationRequestInfo(request[originalRequestSymbol]); + } + let info7 = state_js_1.state.operationRequestMap.get(request); + if (!info7) { + info7 = {}; + state_js_1.state.operationRequestMap.set(request, info7); + } + return info7; + } + exports2.getOperationRequestInfo = getOperationRequestInfo; } }); -// node_modules/@azure/core-xml/dist/commonjs/xml.js -var require_xml = __commonJS({ - "node_modules/@azure/core-xml/dist/commonjs/xml.js"(exports2) { +// node_modules/@azure/core-client/dist/commonjs/deserializationPolicy.js +var require_deserializationPolicy = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/deserializationPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringifyXML = stringifyXML; - exports2.parseXML = parseXML; - var fast_xml_parser_1 = require_fxp(); - var xml_common_js_1 = require_xml_common(); - function getCommonOptions(options) { - var _a; + exports2.deserializationPolicy = exports2.deserializationPolicyName = void 0; + var interfaces_js_1 = require_interfaces(); + var core_rest_pipeline_1 = require_commonjs7(); + var serializer_js_1 = require_serializer(); + var operationHelpers_js_1 = require_operationHelpers(); + var defaultJsonContentTypes = ["application/json", "text/json"]; + var defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; + exports2.deserializationPolicyName = "deserializationPolicy"; + function deserializationPolicy(options = {}) { + var _a, _b, _c, _d, _e, _f, _g; + const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes; + const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes; + const parseXML = options.parseXML; + const serializerOptions = options.serializerOptions; + const updatedOptions = { + xml: { + rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "", + includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false, + xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY + } + }; return { - attributesGroupName: xml_common_js_1.XML_ATTRKEY, - textNodeName: (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : xml_common_js_1.XML_CHARKEY, - ignoreAttributes: false, - suppressBooleanAttributes: false + name: exports2.deserializationPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML); + } }; } - function getSerializerOptions(options = {}) { - var _a, _b; - return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" }); + exports2.deserializationPolicy = deserializationPolicy; + function getOperationResponseMap(parsedResponse) { + let result; + const request = parsedResponse.request; + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + if (operationSpec) { + if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) { + result = operationSpec.responses[parsedResponse.status]; + } else { + result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse); + } + } + return result; } - function getParserOptions(options = {}) { - return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true }); + function shouldDeserializeResponse(parsedResponse) { + const request = parsedResponse.request; + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); + const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize; + let result; + if (shouldDeserialize === void 0) { + result = true; + } else if (typeof shouldDeserialize === "boolean") { + result = shouldDeserialize; + } else { + result = shouldDeserialize(parsedResponse); + } + return result; } - function stringifyXML(obj, opts = {}) { - const parserOptions = getSerializerOptions(opts); - const j2x = new fast_xml_parser_1.XMLBuilder(parserOptions); - const node = { [parserOptions.rootNodeName]: obj }; - const xmlData = j2x.build(node); - return `${xmlData}`.replace(/\n/g, ""); + async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) { + const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML); + if (!shouldDeserializeResponse(parsedResponse)) { + return parsedResponse; + } + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request); + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + if (!operationSpec || !operationSpec.responses) { + return parsedResponse; + } + const responseSpec = getOperationResponseMap(parsedResponse); + const { error: error4, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options); + if (error4) { + throw error4; + } else if (shouldReturnResponse) { + return parsedResponse; + } + if (responseSpec) { + if (responseSpec.bodyMapper) { + let valueToDeserialize = parsedResponse.parsedBody; + if (operationSpec.isXML && responseSpec.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) { + valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : []; + } + try { + parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); + } catch (deserializeError) { + const restError = new core_rest_pipeline_1.RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, { + statusCode: parsedResponse.status, + request: parsedResponse.request, + response: parsedResponse + }); + throw restError; + } + } else if (operationSpec.httpMethod === "HEAD") { + parsedResponse.parsedBody = response.status >= 200 && response.status < 300; + } + if (responseSpec.headersMapper) { + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true }); + } + } + return parsedResponse; } - async function parseXML(str2, opts = {}) { - if (!str2) { - throw new Error("Document is empty"); + function isOperationSpecEmpty(operationSpec) { + const expectedStatusCodes = Object.keys(operationSpec.responses); + return expectedStatusCodes.length === 0 || expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"; + } + function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) { + var _a; + const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; + const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus : !!responseSpec; + if (isExpectedStatusCode) { + if (responseSpec) { + if (!responseSpec.isError) { + return { error: null, shouldReturnResponse: false }; + } + } else { + return { error: null, shouldReturnResponse: false }; + } } - const validation = fast_xml_parser_1.XMLValidator.validate(str2); - if (validation !== true) { - throw validation; + const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; + const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) ? `Unexpected status code: ${parsedResponse.status}` : parsedResponse.bodyAsText; + const error4 = new core_rest_pipeline_1.RestError(initialErrorMessage, { + statusCode: parsedResponse.status, + request: parsedResponse.request, + response: parsedResponse + }); + if (!errorResponseSpec) { + throw error4; } - const parser = new fast_xml_parser_1.XMLParser(getParserOptions(opts)); - const parsedXml = parser.parse(str2); - if (parsedXml["?xml"]) { - delete parsedXml["?xml"]; + const defaultBodyMapper = errorResponseSpec.bodyMapper; + const defaultHeadersMapper = errorResponseSpec.headersMapper; + try { + if (parsedResponse.parsedBody) { + const parsedBody = parsedResponse.parsedBody; + let deserializedError; + if (defaultBodyMapper) { + let valueToDeserialize = parsedBody; + if (operationSpec.isXML && defaultBodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) { + valueToDeserialize = []; + const elementName = defaultBodyMapper.xmlElementName; + if (typeof parsedBody === "object" && elementName) { + valueToDeserialize = parsedBody[elementName]; + } + } + deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options); + } + const internalError = parsedBody.error || deserializedError || parsedBody; + error4.code = internalError.code; + if (internalError.message) { + error4.message = internalError.message; + } + if (defaultBodyMapper) { + error4.response.parsedBody = deserializedError; + } + } + if (parsedResponse.headers && defaultHeadersMapper) { + error4.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders"); + } + } catch (defaultError) { + error4.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; } - if (!opts.includeRoot) { - for (const key of Object.keys(parsedXml)) { - const value = parsedXml[key]; - return typeof value === "object" ? Object.assign({}, value) : value; + return { error: error4, shouldReturnResponse: false }; + } + async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) { + var _a; + if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) && operationResponse.bodyAsText) { + const text = operationResponse.bodyAsText; + const contentType = operationResponse.headers.get("Content-Type") || ""; + const contentComponents = !contentType ? [] : contentType.split(";").map((component) => component.toLowerCase()); + try { + if (contentComponents.length === 0 || contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { + operationResponse.parsedBody = JSON.parse(text); + return operationResponse; + } else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { + if (!parseXML) { + throw new Error("Parsing XML not supported."); + } + const body = await parseXML(text, opts.xml); + operationResponse.parsedBody = body; + return operationResponse; + } + } catch (err) { + const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; + const errCode = err.code || core_rest_pipeline_1.RestError.PARSE_ERROR; + const e = new core_rest_pipeline_1.RestError(msg, { + code: errCode, + statusCode: operationResponse.status, + request: operationResponse.request, + response: operationResponse + }); + throw e; } } - return parsedXml; + return operationResponse; } } }); -// node_modules/@azure/core-xml/dist/commonjs/index.js -var require_commonjs11 = __commonJS({ - "node_modules/@azure/core-xml/dist/commonjs/index.js"(exports2) { +// node_modules/@azure/core-client/dist/commonjs/interfaceHelpers.js +var require_interfaceHelpers = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/interfaceHelpers.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.XML_CHARKEY = exports2.XML_ATTRKEY = exports2.parseXML = exports2.stringifyXML = void 0; - var xml_js_1 = require_xml(); - Object.defineProperty(exports2, "stringifyXML", { enumerable: true, get: function() { - return xml_js_1.stringifyXML; - } }); - Object.defineProperty(exports2, "parseXML", { enumerable: true, get: function() { - return xml_js_1.parseXML; - } }); - var xml_common_js_1 = require_xml_common(); - Object.defineProperty(exports2, "XML_ATTRKEY", { enumerable: true, get: function() { - return xml_common_js_1.XML_ATTRKEY; - } }); - Object.defineProperty(exports2, "XML_CHARKEY", { enumerable: true, get: function() { - return xml_common_js_1.XML_CHARKEY; - } }); - } -}); - -// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js -var require_AbortError3 = __commonJS({ - "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + exports2.getPathStringFromParameter = exports2.getStreamingResponseStatusCodes = void 0; + var serializer_js_1 = require_serializer(); + function getStreamingResponseStatusCodes(operationSpec) { + const result = /* @__PURE__ */ new Set(); + for (const statusCode in operationSpec.responses) { + const operationResponse = operationSpec.responses[statusCode]; + if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) { + result.add(Number(statusCode)); + } } - }; - exports2.AbortError = AbortError; - } -}); - -// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js -var require_commonjs12 = __commonJS({ - "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbortError = void 0; - var AbortError_js_1 = require_AbortError3(); - Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { - return AbortError_js_1.AbortError; - } }); + return result; + } + exports2.getStreamingResponseStatusCodes = getStreamingResponseStatusCodes; + function getPathStringFromParameter(parameter) { + const { parameterPath, mapper } = parameter; + let result; + if (typeof parameterPath === "string") { + result = parameterPath; + } else if (Array.isArray(parameterPath)) { + result = parameterPath.join("."); + } else { + result = mapper.serializedName; + } + return result; + } + exports2.getPathStringFromParameter = getPathStringFromParameter; } }); -// node_modules/@azure/abort-controller/dist/index.js -var require_dist5 = __commonJS({ - "node_modules/@azure/abort-controller/dist/index.js"(exports2) { +// node_modules/@azure/core-client/dist/commonjs/serializationPolicy.js +var require_serializationPolicy = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/serializationPolicy.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var listenersMap = /* @__PURE__ */ new WeakMap(); - var abortedMap = /* @__PURE__ */ new WeakMap(); - var AbortSignal2 = class _AbortSignal { - constructor() { - this.onabort = null; - listenersMap.set(this, []); - abortedMap.set(this, false); - } - /** - * Status of whether aborted or not. - * - * @readonly - */ - get aborted() { - if (!abortedMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); + exports2.serializeRequestBody = exports2.serializeHeaders = exports2.serializationPolicy = exports2.serializationPolicyName = void 0; + var interfaces_js_1 = require_interfaces(); + var operationHelpers_js_1 = require_operationHelpers(); + var serializer_js_1 = require_serializer(); + var interfaceHelpers_js_1 = require_interfaceHelpers(); + exports2.serializationPolicyName = "serializationPolicy"; + function serializationPolicy(options = {}) { + const stringifyXML = options.stringifyXML; + return { + name: exports2.serializationPolicyName, + async sendRequest(request, next) { + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); + const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; + const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments; + if (operationSpec && operationArguments) { + serializeHeaders(request, operationArguments, operationSpec); + serializeRequestBody(request, operationArguments, operationSpec, stringifyXML); + } + return next(request); } - return abortedMap.get(this); - } - /** - * Creates a new AbortSignal instance that will never be aborted. - * - * @readonly - */ - static get none() { - return new _AbortSignal(); - } - /** - * Added new "abort" event listener, only support "abort" event. - * - * @param _type - Only support "abort" event - * @param listener - The listener to be added - */ - addEventListener(_type, listener) { - if (!listenersMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); + }; + } + exports2.serializationPolicy = serializationPolicy; + function serializeHeaders(request, operationArguments, operationSpec) { + var _a, _b; + if (operationSpec.headerParameters) { + for (const headerParameter of operationSpec.headerParameters) { + let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter); + if (headerValue !== null && headerValue !== void 0 || headerParameter.mapper.required) { + headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter)); + const headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix; + if (headerCollectionPrefix) { + for (const key of Object.keys(headerValue)) { + request.headers.set(headerCollectionPrefix + key, headerValue[key]); + } + } else { + request.headers.set(headerParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter), headerValue); + } + } } - const listeners = listenersMap.get(this); - listeners.push(listener); } - /** - * Remove "abort" event listener, only support "abort" event. - * - * @param _type - Only support "abort" event - * @param listener - The listener to be removed - */ - removeEventListener(_type, listener) { - if (!listenersMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - const listeners = listenersMap.get(this); - const index = listeners.indexOf(listener); - if (index > -1) { - listeners.splice(index, 1); + const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders; + if (customHeaders) { + for (const customHeaderName of Object.keys(customHeaders)) { + request.headers.set(customHeaderName, customHeaders[customHeaderName]); } } - /** - * Dispatches a synthetic event to the AbortSignal. - */ - dispatchEvent(_event) { - throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); - } - }; - function abortSignal(signal) { - if (signal.aborted) { - return; - } - if (signal.onabort) { - signal.onabort.call(signal); - } - const listeners = listenersMap.get(signal); - if (listeners) { - listeners.slice().forEach((listener) => { - listener.call(signal, { type: "abort" }); - }); - } - abortedMap.set(signal, true); } - var AbortError = class extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; - } - }; - var AbortController2 = class { - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - constructor(parentSignals) { - this._signal = new AbortSignal2(); - if (!parentSignals) { - return; + exports2.serializeHeaders = serializeHeaders; + function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function() { + throw new Error("XML serialization unsupported!"); + }) { + var _a, _b, _c, _d, _e; + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; + const updatedOptions = { + xml: { + rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "", + includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false, + xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY } - if (!Array.isArray(parentSignals)) { - parentSignals = arguments; + }; + const xmlCharKey = updatedOptions.xml.xmlCharKey; + if (operationSpec.requestBody && operationSpec.requestBody.mapper) { + request.body = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, operationSpec.requestBody); + const bodyMapper = operationSpec.requestBody.mapper; + const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable } = bodyMapper; + const typeName = bodyMapper.type.name; + try { + if (request.body !== void 0 && request.body !== null || nullable && request.body === null || required) { + const requestBodyParameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(operationSpec.requestBody); + request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions); + const isStream = typeName === serializer_js_1.MapperTypeNames.Stream; + if (operationSpec.isXML) { + const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; + const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions); + if (typeName === serializer_js_1.MapperTypeNames.Sequence) { + request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey }); + } else if (!isStream) { + request.body = stringifyXML(value, { + rootName: xmlName || serializedName, + xmlCharKey + }); + } + } else if (typeName === serializer_js_1.MapperTypeNames.String && (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) { + return; + } else if (!isStream) { + request.body = JSON.stringify(request.body); + } + } + } catch (error4) { + throw new Error(`Error "${error4.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, void 0, " ")}.`); } - for (const parentSignal of parentSignals) { - if (parentSignal.aborted) { - this.abort(); - } else { - parentSignal.addEventListener("abort", () => { - this.abort(); - }); + } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { + request.formData = {}; + for (const formDataParameter of operationSpec.formDataParameters) { + const formDataParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, formDataParameter); + if (formDataParameterValue !== void 0 && formDataParameterValue !== null) { + const formDataParameterPropertyName = formDataParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter); + request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter), updatedOptions); } } } - /** - * The AbortSignal associated with this controller that will signal aborted - * when the abort method is called on this controller. - * - * @readonly - */ - get signal() { - return this._signal; + } + exports2.serializeRequestBody = serializeRequestBody; + function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { + if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { + const result = {}; + result[options.xml.xmlCharKey] = serializedValue; + result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; + return result; } - /** - * Signal that any operations passed this controller's associated abort signal - * to cancel any remaining work and throw an `AbortError`. - */ - abort() { - abortSignal(this._signal); + return serializedValue; + } + function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { + if (!Array.isArray(obj)) { + obj = [obj]; } - /** - * Creates a new AbortSignal instance that will abort after the provided ms. - * @param ms - Elapsed time in milliseconds to trigger an abort. - */ - static timeout(ms) { - const signal = new AbortSignal2(); - const timer = setTimeout(abortSignal, ms, signal); - if (typeof timer.unref === "function") { - timer.unref(); - } - return signal; + if (!xmlNamespaceKey || !xmlNamespace) { + return { [elementName]: obj }; } - }; - exports2.AbortController = AbortController2; - exports2.AbortError = AbortError; - exports2.AbortSignal = AbortSignal2; + const result = { [elementName]: obj }; + result[interfaces_js_1.XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; + return result; + } } }); -// node_modules/@azure/core-lro/dist/index.js -var require_dist6 = __commonJS({ - "node_modules/@azure/core-lro/dist/index.js"(exports2) { +// node_modules/@azure/core-client/dist/commonjs/pipeline.js +var require_pipeline2 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/pipeline.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var logger$1 = require_dist(); - var abortController = require_dist5(); - var coreUtil = require_commonjs4(); - var logger = logger$1.createClientLogger("core-lro"); - var POLL_INTERVAL_IN_MS = 2e3; - var terminalStates = ["succeeded", "canceled", "failed"]; - function deserializeState(serializedState) { - try { - return JSON.parse(serializedState).state; - } catch (e) { - throw new Error(`Unable to deserialize input state: ${serializedState}`); + exports2.createClientPipeline = void 0; + var deserializationPolicy_js_1 = require_deserializationPolicy(); + var core_rest_pipeline_1 = require_commonjs7(); + var serializationPolicy_js_1 = require_serializationPolicy(); + function createClientPipeline(options = {}) { + const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {}); + if (options.credentialOptions) { + pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({ + credential: options.credentialOptions.credential, + scopes: options.credentialOptions.credentialScopes + })); } + pipeline.addPolicy((0, serializationPolicy_js_1.serializationPolicy)(options.serializationOptions), { phase: "Serialize" }); + pipeline.addPolicy((0, deserializationPolicy_js_1.deserializationPolicy)(options.deserializationOptions), { + phase: "Deserialize" + }); + return pipeline; } - function setStateError(inputs) { - const { state, stateProxy, isOperationError: isOperationError2 } = inputs; - return (error4) => { - if (isOperationError2(error4)) { - stateProxy.setError(state, error4); - stateProxy.setFailed(state); - } - throw error4; - }; + exports2.createClientPipeline = createClientPipeline; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/httpClientCache.js +var require_httpClientCache = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/httpClientCache.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getCachedDefaultHttpClient = void 0; + var core_rest_pipeline_1 = require_commonjs7(); + var cachedHttpClient; + function getCachedDefaultHttpClient() { + if (!cachedHttpClient) { + cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)(); + } + return cachedHttpClient; } - function appendReadableErrorMessage(currentMessage, innerMessage) { - let message = currentMessage; - if (message.slice(-1) !== ".") { - message = message + "."; + exports2.getCachedDefaultHttpClient = getCachedDefaultHttpClient; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/urlHelpers.js +var require_urlHelpers = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/urlHelpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.appendQueryParams = exports2.getRequestUrl = void 0; + var operationHelpers_js_1 = require_operationHelpers(); + var interfaceHelpers_js_1 = require_interfaceHelpers(); + var CollectionFormatToDelimiterMap = { + CSV: ",", + SSV: " ", + Multi: "Multi", + TSV: " ", + Pipes: "|" + }; + function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) { + const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject); + let isAbsolutePath = false; + let requestUrl = replaceAll(baseUri, urlReplacements); + if (operationSpec.path) { + let path2 = replaceAll(operationSpec.path, urlReplacements); + if (operationSpec.path === "/{nextLink}" && path2.startsWith("/")) { + path2 = path2.substring(1); + } + if (isAbsoluteUrl(path2)) { + requestUrl = path2; + isAbsolutePath = true; + } else { + requestUrl = appendPath(requestUrl, path2); + } } - return message + " " + innerMessage; + const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject); + requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath); + return requestUrl; } - function simplifyError(err) { - let message = err.message; - let code = err.code; - let curErr = err; - while (curErr.innererror) { - curErr = curErr.innererror; - code = curErr.code; - message = appendReadableErrorMessage(message, curErr.message); + exports2.getRequestUrl = getRequestUrl; + function replaceAll(input, replacements) { + let result = input; + for (const [searchValue, replaceValue] of replacements) { + result = result.split(searchValue).join(replaceValue); } - return { - code, - message - }; + return result; } - function processOperationStatus(result) { - const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result; - switch (status) { - case "succeeded": { - stateProxy.setSucceeded(state); - break; - } - case "failed": { - const err = getError === null || getError === void 0 ? void 0 : getError(response); - let postfix = ""; - if (err) { - const { code, message } = simplifyError(err); - postfix = `. ${code}. ${message}`; + function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) { + var _a; + const result = /* @__PURE__ */ new Map(); + if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) { + for (const urlParameter of operationSpec.urlParameters) { + let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject); + const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter); + urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString); + if (!urlParameter.skipEncoding) { + urlParameterValue = encodeURIComponent(urlParameterValue); } - const errStr = `The long-running operation has failed${postfix}`; - stateProxy.setError(state, new Error(errStr)); - stateProxy.setFailed(state); - logger.warning(errStr); - break; - } - case "canceled": { - stateProxy.setCanceled(state); - break; + result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue); } } - if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) || isDone === void 0 && ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status)) { - stateProxy.setResult(state, buildResult({ - response, - state, - processResult - })); - } - } - function buildResult(inputs) { - const { processResult, response, state } = inputs; - return processResult ? processResult(response, state) : response; + return result; } - async function initOperation(inputs) { - const { init, stateProxy, processResult, getOperationStatus: getOperationStatus2, withOperationLocation, setErrorAsResult } = inputs; - const { operationLocation, resourceLocation, metadata, response } = await init(); - if (operationLocation) - withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); - const config = { - metadata, - operationLocation, - resourceLocation - }; - logger.verbose(`LRO: Operation description:`, config); - const state = stateProxy.initState(config); - const status = getOperationStatus2({ response, state, operationLocation }); - processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult }); - return state; + function isAbsoluteUrl(url) { + return url.includes("://"); } - async function pollOperationHelper(inputs) { - const { poll, state, stateProxy, operationLocation, getOperationStatus: getOperationStatus2, getResourceLocation: getResourceLocation2, isOperationError: isOperationError2, options } = inputs; - const response = await poll(operationLocation, options).catch(setStateError({ - state, - stateProxy, - isOperationError: isOperationError2 - })); - const status = getOperationStatus2(response, state); - logger.verbose(`LRO: Status: - Polling from: ${state.config.operationLocation} - Operation status: ${status} - Polling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`); - if (status === "succeeded") { - const resourceLocation = getResourceLocation2(response, state); - if (resourceLocation !== void 0) { - return { - response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError: isOperationError2 })), - status - }; + function appendPath(url, pathToAppend) { + if (!pathToAppend) { + return url; + } + const parsedUrl = new URL(url); + let newPath = parsedUrl.pathname; + if (!newPath.endsWith("/")) { + newPath = `${newPath}/`; + } + if (pathToAppend.startsWith("/")) { + pathToAppend = pathToAppend.substring(1); + } + const searchStart = pathToAppend.indexOf("?"); + if (searchStart !== -1) { + const path2 = pathToAppend.substring(0, searchStart); + const search = pathToAppend.substring(searchStart + 1); + newPath = newPath + path2; + if (search) { + parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search; } + } else { + newPath = newPath + pathToAppend; } - return { response, status }; + parsedUrl.pathname = newPath; + return parsedUrl.toString(); } - async function pollOperation(inputs) { - const { poll, state, stateProxy, options, getOperationStatus: getOperationStatus2, getResourceLocation: getResourceLocation2, getOperationLocation: getOperationLocation2, isOperationError: isOperationError2, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult } = inputs; - const { operationLocation } = state.config; - if (operationLocation !== void 0) { - const { response, status } = await pollOperationHelper({ - poll, - getOperationStatus: getOperationStatus2, - state, - stateProxy, - operationLocation, - getResourceLocation: getResourceLocation2, - isOperationError: isOperationError2, - options - }); - processOperationStatus({ - status, - response, - state, - stateProxy, - isDone, - processResult, - getError, - setErrorAsResult - }); - if (!terminalStates.includes(status)) { - const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response); - if (intervalInMs) - setDelay(intervalInMs); - const location = getOperationLocation2 === null || getOperationLocation2 === void 0 ? void 0 : getOperationLocation2(response, state); - if (location !== void 0) { - const isUpdated = operationLocation !== location; - state.config.operationLocation = location; - withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated); - } else - withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); + function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) { + var _a; + const result = /* @__PURE__ */ new Map(); + const sequenceParams = /* @__PURE__ */ new Set(); + if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) { + for (const queryParameter of operationSpec.queryParameters) { + if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) { + sequenceParams.add(queryParameter.mapper.serializedName); + } + let queryParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, queryParameter, fallbackObject); + if (queryParameterValue !== void 0 && queryParameterValue !== null || queryParameter.mapper.required) { + queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter)); + const delimiter = queryParameter.collectionFormat ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat] : ""; + if (Array.isArray(queryParameterValue)) { + queryParameterValue = queryParameterValue.map((item) => { + if (item === null || item === void 0) { + return ""; + } + return item; + }); + } + if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) { + continue; + } else if (Array.isArray(queryParameterValue) && (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) { + queryParameterValue = queryParameterValue.join(delimiter); + } + if (!queryParameter.skipEncoding) { + if (Array.isArray(queryParameterValue)) { + queryParameterValue = queryParameterValue.map((item) => { + return encodeURIComponent(item); + }); + } else { + queryParameterValue = encodeURIComponent(queryParameterValue); + } + } + if (Array.isArray(queryParameterValue) && (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) { + queryParameterValue = queryParameterValue.join(delimiter); + } + result.set(queryParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter), queryParameterValue); + } } - updateState === null || updateState === void 0 ? void 0 : updateState(state, response); } + return { + queryParams: result, + sequenceParams + }; } - function getOperationLocationPollingUrl(inputs) { - const { azureAsyncOperation, operationLocation } = inputs; - return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation; - } - function getLocationHeader(rawResponse) { - return rawResponse.headers["location"]; - } - function getOperationLocationHeader(rawResponse) { - return rawResponse.headers["operation-location"]; + function simpleParseQueryParams(queryString) { + const result = /* @__PURE__ */ new Map(); + if (!queryString || queryString[0] !== "?") { + return result; + } + queryString = queryString.slice(1); + const pairs2 = queryString.split("&"); + for (const pair of pairs2) { + const [name, value] = pair.split("=", 2); + const existingValue = result.get(name); + if (existingValue) { + if (Array.isArray(existingValue)) { + existingValue.push(value); + } else { + result.set(name, [existingValue, value]); + } + } else { + result.set(name, value); + } + } + return result; } - function getAzureAsyncOperationHeader(rawResponse) { - return rawResponse.headers["azure-asyncoperation"]; + function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) { + if (queryParams.size === 0) { + return url; + } + const parsedUrl = new URL(url); + const combinedParams = simpleParseQueryParams(parsedUrl.search); + for (const [name, value] of queryParams) { + const existingValue = combinedParams.get(name); + if (Array.isArray(existingValue)) { + if (Array.isArray(value)) { + existingValue.push(...value); + const valueSet = new Set(existingValue); + combinedParams.set(name, Array.from(valueSet)); + } else { + existingValue.push(value); + } + } else if (existingValue) { + if (Array.isArray(value)) { + value.unshift(existingValue); + } else if (sequenceParams.has(name)) { + combinedParams.set(name, [existingValue, value]); + } + if (!noOverwrite) { + combinedParams.set(name, value); + } + } else { + combinedParams.set(name, value); + } + } + const searchPieces = []; + for (const [name, value] of combinedParams) { + if (typeof value === "string") { + searchPieces.push(`${name}=${value}`); + } else if (Array.isArray(value)) { + for (const subValue of value) { + searchPieces.push(`${name}=${subValue}`); + } + } else { + searchPieces.push(`${name}=${value}`); + } + } + parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; + return parsedUrl.toString(); } - function findResourceLocation(inputs) { - const { location, requestMethod, requestPath, resourceLocationConfig } = inputs; - switch (requestMethod) { - case "PUT": { - return requestPath; + exports2.appendQueryParams = appendQueryParams; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/log.js +var require_log2 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/log.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.logger = void 0; + var logger_1 = require_dist(); + exports2.logger = (0, logger_1.createClientLogger)("core-client"); + } +}); + +// node_modules/@azure/core-client/dist/commonjs/serviceClient.js +var require_serviceClient = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/serviceClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ServiceClient = void 0; + var core_rest_pipeline_1 = require_commonjs7(); + var pipeline_js_1 = require_pipeline2(); + var utils_js_1 = require_utils5(); + var httpClientCache_js_1 = require_httpClientCache(); + var operationHelpers_js_1 = require_operationHelpers(); + var urlHelpers_js_1 = require_urlHelpers(); + var interfaceHelpers_js_1 = require_interfaceHelpers(); + var log_js_1 = require_log2(); + var ServiceClient = class { + /** + * The ServiceClient constructor + * @param credential - The credentials used for authentication with the service. + * @param options - The service client options that govern the behavior of the client. + */ + constructor(options = {}) { + var _a, _b; + this._requestContentType = options.requestContentType; + this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri; + if (options.baseUri) { + log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead."); } - case "DELETE": { - return void 0; + this._allowInsecureConnection = options.allowInsecureConnection; + this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)(); + this.pipeline = options.pipeline || createDefaultPipeline(options); + if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) { + for (const { policy, position } of options.additionalPolicies) { + const afterPhase = position === "perRetry" ? "Sign" : void 0; + this.pipeline.addPolicy(policy, { + afterPhase + }); + } } - default: { - switch (resourceLocationConfig) { - case "azure-async-operation": { - return void 0; + } + /** + * Send the provided httpRequest. + */ + async sendRequest(request) { + return this.pipeline.sendRequest(this._httpClient, request); + } + /** + * Send an HTTP request that is populated using the provided OperationSpec. + * @typeParam T - The typed result of the request, based on the OperationSpec. + * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. + * @param operationSpec - The OperationSpec to use to populate the httpRequest. + */ + async sendOperationRequest(operationArguments, operationSpec) { + const endpoint = operationSpec.baseUrl || this._endpoint; + if (!endpoint) { + throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use."); + } + const url = (0, urlHelpers_js_1.getRequestUrl)(endpoint, operationSpec, operationArguments, this); + const request = (0, core_rest_pipeline_1.createPipelineRequest)({ + url + }); + request.method = operationSpec.httpMethod; + const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request); + operationInfo.operationSpec = operationSpec; + operationInfo.operationArguments = operationArguments; + const contentType = operationSpec.contentType || this._requestContentType; + if (contentType && operationSpec.requestBody) { + request.headers.set("Content-Type", contentType); + } + const options = operationArguments.options; + if (options) { + const requestOptions = options.requestOptions; + if (requestOptions) { + if (requestOptions.timeout) { + request.timeout = requestOptions.timeout; } - case "original-uri": { - return requestPath; + if (requestOptions.onUploadProgress) { + request.onUploadProgress = requestOptions.onUploadProgress; } - case "location": - default: { - return location; + if (requestOptions.onDownloadProgress) { + request.onDownloadProgress = requestOptions.onDownloadProgress; + } + if (requestOptions.shouldDeserialize !== void 0) { + operationInfo.shouldDeserialize = requestOptions.shouldDeserialize; + } + if (requestOptions.allowInsecureConnection) { + request.allowInsecureConnection = true; + } + } + if (options.abortSignal) { + request.abortSignal = options.abortSignal; + } + if (options.tracingOptions) { + request.tracingOptions = options.tracingOptions; + } + } + if (this._allowInsecureConnection) { + request.allowInsecureConnection = true; + } + if (request.streamResponseStatusCodes === void 0) { + request.streamResponseStatusCodes = (0, interfaceHelpers_js_1.getStreamingResponseStatusCodes)(operationSpec); + } + try { + const rawResponse = await this.sendRequest(request); + const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]); + if (options === null || options === void 0 ? void 0 : options.onResponse) { + options.onResponse(rawResponse, flatResponse); + } + return flatResponse; + } catch (error4) { + if (typeof error4 === "object" && (error4 === null || error4 === void 0 ? void 0 : error4.response)) { + const rawResponse = error4.response; + const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error4.statusCode] || operationSpec.responses["default"]); + error4.details = flatResponse; + if (options === null || options === void 0 ? void 0 : options.onResponse) { + options.onResponse(rawResponse, flatResponse, error4); } } + throw error4; } } + }; + exports2.ServiceClient = ServiceClient; + function createDefaultPipeline(options) { + const credentialScopes = getCredentialScopes(options); + const credentialOptions = options.credential && credentialScopes ? { credentialScopes, credential: options.credential } : void 0; + return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions })); } - function inferLroMode(inputs) { - const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs; - const operationLocation = getOperationLocationHeader(rawResponse); - const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse); - const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation }); - const location = getLocationHeader(rawResponse); - const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase(); - if (pollingUrl !== void 0) { - return { - mode: "OperationLocation", - operationLocation: pollingUrl, - resourceLocation: findResourceLocation({ - requestMethod: normalizedRequestMethod, - location, - requestPath, - resourceLocationConfig - }) - }; - } else if (location !== void 0) { - return { - mode: "ResourceLocation", - operationLocation: location - }; - } else if (normalizedRequestMethod === "PUT" && requestPath) { - return { - mode: "Body", - operationLocation: requestPath - }; - } else { - return void 0; + function getCredentialScopes(options) { + if (options.credentialScopes) { + return options.credentialScopes; } - } - function transformStatus(inputs) { - const { status, statusCode } = inputs; - if (typeof status !== "string" && status !== void 0) { - throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`); + if (options.endpoint) { + return `${options.endpoint}/.default`; } - switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) { - case void 0: - return toOperationStatus(statusCode); - case "succeeded": - return "succeeded"; - case "failed": - return "failed"; - case "running": - case "accepted": - case "started": - case "canceling": - case "cancelling": - return "running"; - case "canceled": - case "cancelled": - return "canceled"; - default: { - logger.verbose(`LRO: unrecognized operation status: ${status}`); - return status; - } + if (options.baseUri) { + return `${options.baseUri}/.default`; } + if (options.credential && !options.credentialScopes) { + throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`); + } + return void 0; } - function getStatus(rawResponse) { - var _a; - const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - return transformStatus({ status, statusCode: rawResponse.statusCode }); + } +}); + +// node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnClaimChallenge.js +var require_authorizeRequestOnClaimChallenge = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnClaimChallenge.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.authorizeRequestOnClaimChallenge = exports2.parseCAEChallenge = void 0; + var log_js_1 = require_log2(); + var base64_js_1 = require_base642(); + function parseCAEChallenge(challenges) { + const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x); + return bearerChallenges.map((challenge) => { + const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x); + const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="'))); + return keyValuePairs.reduce((a, b) => Object.assign(Object.assign({}, a), b), {}); + }); } - function getProvisioningState(rawResponse) { - var _a, _b; - const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; - return transformStatus({ status, statusCode: rawResponse.statusCode }); + exports2.parseCAEChallenge = parseCAEChallenge; + async function authorizeRequestOnClaimChallenge(onChallengeOptions) { + const { scopes, response } = onChallengeOptions; + const logger = onChallengeOptions.logger || log_js_1.logger; + const challenge = response.headers.get("WWW-Authenticate"); + if (!challenge) { + logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`); + return false; + } + const challenges = parseCAEChallenge(challenge) || []; + const parsedChallenge = challenges.find((x) => x.claims); + if (!parsedChallenge) { + logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`); + return false; + } + const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, { + claims: (0, base64_js_1.decodeStringToString)(parsedChallenge.claims) + }); + if (!accessToken) { + return false; + } + onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`); + return true; } - function toOperationStatus(statusCode) { - if (statusCode === 202) { - return "running"; - } else if (statusCode < 300) { - return "succeeded"; - } else { - return "failed"; + exports2.authorizeRequestOnClaimChallenge = authorizeRequestOnClaimChallenge; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnTenantChallenge.js +var require_authorizeRequestOnTenantChallenge = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/authorizeRequestOnTenantChallenge.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.authorizeRequestOnTenantChallenge = void 0; + var Constants = { + DefaultScope: "/.default", + /** + * Defines constants for use with HTTP headers. + */ + HeaderConstants: { + /** + * The Authorization header. + */ + AUTHORIZATION: "authorization" } + }; + function isUuid(text) { + return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text); } - function parseRetryAfter({ rawResponse }) { - const retryAfter = rawResponse.headers["retry-after"]; - if (retryAfter !== void 0) { - const retryAfterInSeconds = parseInt(retryAfter); - return isNaN(retryAfterInSeconds) ? calculatePollingIntervalFromDate(new Date(retryAfter)) : retryAfterInSeconds * 1e3; + var authorizeRequestOnTenantChallenge = async (challengeOptions) => { + const requestOptions = requestToOptions(challengeOptions.request); + const challenge = getChallenge(challengeOptions.response); + if (challenge) { + const challengeInfo = parseChallenge(challenge); + const challengeScopes = buildScopes(challengeOptions, challengeInfo); + const tenantId = extractTenantId(challengeInfo); + if (!tenantId) { + return false; + } + const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId })); + if (!accessToken) { + return false; + } + challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`); + return true; + } + return false; + }; + exports2.authorizeRequestOnTenantChallenge = authorizeRequestOnTenantChallenge; + function extractTenantId(challengeInfo) { + const parsedAuthUri = new URL(challengeInfo.authorization_uri); + const pathSegments = parsedAuthUri.pathname.split("/"); + const tenantId = pathSegments[1]; + if (tenantId && isUuid(tenantId)) { + return tenantId; } return void 0; } - function getErrorFromResponse(response) { - const error4 = response.flatResponse.error; - if (!error4) { - logger.warning(`The long-running operation failed but there is no error property in the response's body`); - return; + function buildScopes(challengeOptions, challengeInfo) { + if (!challengeInfo.resource_id) { + return challengeOptions.scopes; } - if (!error4.code || !error4.message) { - logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`); - return; + const challengeScopes = new URL(challengeInfo.resource_id); + challengeScopes.pathname = Constants.DefaultScope; + let scope = challengeScopes.toString(); + if (scope === "https://disk.azure.com/.default") { + scope = "https://disk.azure.com//.default"; } - return error4; + return [scope]; } - function calculatePollingIntervalFromDate(retryAfterDate) { - const timeNow = Math.floor((/* @__PURE__ */ new Date()).getTime()); - const retryAfterTime = retryAfterDate.getTime(); - if (timeNow < retryAfterTime) { - return retryAfterTime - timeNow; + function getChallenge(response) { + const challenge = response.headers.get("WWW-Authenticate"); + if (response.status === 401 && challenge) { + return challenge; } - return void 0; + return; } - function getStatusFromInitialResponse(inputs) { - const { response, state, operationLocation } = inputs; - function helper() { - var _a; - const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; - switch (mode) { - case void 0: - return toOperationStatus(response.rawResponse.statusCode); - case "Body": - return getOperationStatus(response, state); - default: - return "running"; - } - } - const status = helper(); - return status === "running" && operationLocation === void 0 ? "succeeded" : status; + function parseChallenge(challenge) { + const bearerChallenge = challenge.slice("Bearer ".length); + const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x); + const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("="))); + return keyValuePairs.reduce((a, b) => Object.assign(Object.assign({}, a), b), {}); } - async function initHttpOperation(inputs) { - const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs; - return initOperation({ - init: async () => { - const response = await lro.sendInitialRequest(); - const config = inferLroMode({ - rawResponse: response.rawResponse, - requestPath: lro.requestPath, - requestMethod: lro.requestMethod, - resourceLocationConfig - }); - return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, (config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}); + function requestToOptions(request) { + return { + abortSignal: request.abortSignal, + requestOptions: { + timeout: request.timeout }, - stateProxy, - processResult: processResult ? ({ flatResponse }, state) => processResult(flatResponse, state) : ({ flatResponse }) => flatResponse, - getOperationStatus: getStatusFromInitialResponse, - setErrorAsResult - }); + tracingOptions: request.tracingOptions + }; } - function getOperationLocation({ rawResponse }, state) { - var _a; - const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; - switch (mode) { - case "OperationLocation": { - return getOperationLocationPollingUrl({ - operationLocation: getOperationLocationHeader(rawResponse), - azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse) - }); - } - case "ResourceLocation": { - return getLocationHeader(rawResponse); - } - case "Body": - default: { - return void 0; + } +}); + +// node_modules/@azure/core-client/dist/commonjs/index.js +var require_commonjs9 = __commonJS({ + "node_modules/@azure/core-client/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.authorizeRequestOnTenantChallenge = exports2.authorizeRequestOnClaimChallenge = exports2.serializationPolicyName = exports2.serializationPolicy = exports2.deserializationPolicyName = exports2.deserializationPolicy = exports2.XML_CHARKEY = exports2.XML_ATTRKEY = exports2.createClientPipeline = exports2.ServiceClient = exports2.MapperTypeNames = exports2.createSerializer = void 0; + var serializer_js_1 = require_serializer(); + Object.defineProperty(exports2, "createSerializer", { enumerable: true, get: function() { + return serializer_js_1.createSerializer; + } }); + Object.defineProperty(exports2, "MapperTypeNames", { enumerable: true, get: function() { + return serializer_js_1.MapperTypeNames; + } }); + var serviceClient_js_1 = require_serviceClient(); + Object.defineProperty(exports2, "ServiceClient", { enumerable: true, get: function() { + return serviceClient_js_1.ServiceClient; + } }); + var pipeline_js_1 = require_pipeline2(); + Object.defineProperty(exports2, "createClientPipeline", { enumerable: true, get: function() { + return pipeline_js_1.createClientPipeline; + } }); + var interfaces_js_1 = require_interfaces(); + Object.defineProperty(exports2, "XML_ATTRKEY", { enumerable: true, get: function() { + return interfaces_js_1.XML_ATTRKEY; + } }); + Object.defineProperty(exports2, "XML_CHARKEY", { enumerable: true, get: function() { + return interfaces_js_1.XML_CHARKEY; + } }); + var deserializationPolicy_js_1 = require_deserializationPolicy(); + Object.defineProperty(exports2, "deserializationPolicy", { enumerable: true, get: function() { + return deserializationPolicy_js_1.deserializationPolicy; + } }); + Object.defineProperty(exports2, "deserializationPolicyName", { enumerable: true, get: function() { + return deserializationPolicy_js_1.deserializationPolicyName; + } }); + var serializationPolicy_js_1 = require_serializationPolicy(); + Object.defineProperty(exports2, "serializationPolicy", { enumerable: true, get: function() { + return serializationPolicy_js_1.serializationPolicy; + } }); + Object.defineProperty(exports2, "serializationPolicyName", { enumerable: true, get: function() { + return serializationPolicy_js_1.serializationPolicyName; + } }); + var authorizeRequestOnClaimChallenge_js_1 = require_authorizeRequestOnClaimChallenge(); + Object.defineProperty(exports2, "authorizeRequestOnClaimChallenge", { enumerable: true, get: function() { + return authorizeRequestOnClaimChallenge_js_1.authorizeRequestOnClaimChallenge; + } }); + var authorizeRequestOnTenantChallenge_js_1 = require_authorizeRequestOnTenantChallenge(); + Object.defineProperty(exports2, "authorizeRequestOnTenantChallenge", { enumerable: true, get: function() { + return authorizeRequestOnTenantChallenge_js_1.authorizeRequestOnTenantChallenge; + } }); + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/util.js +var require_util9 = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/util.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpHeaders = exports2.toHttpHeadersLike = exports2.toWebResourceLike = exports2.toPipelineRequest = void 0; + var core_rest_pipeline_1 = require_commonjs7(); + var originalRequestSymbol = Symbol("Original PipelineRequest"); + var originalClientRequestSymbol = Symbol.for("@azure/core-client original request"); + function toPipelineRequest(webResource, options = {}) { + const compatWebResource = webResource; + const request = compatWebResource[originalRequestSymbol]; + const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true })); + if (request) { + request.headers = headers; + return request; + } else { + const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({ + url: webResource.url, + method: webResource.method, + headers, + withCredentials: webResource.withCredentials, + timeout: webResource.timeout, + requestId: webResource.requestId, + abortSignal: webResource.abortSignal, + body: webResource.body, + formData: webResource.formData, + disableKeepAlive: !!webResource.keepAlive, + onDownloadProgress: webResource.onDownloadProgress, + onUploadProgress: webResource.onUploadProgress, + proxySettings: webResource.proxySettings, + streamResponseStatusCodes: webResource.streamResponseStatusCodes + }); + if (options.originalRequest) { + newRequest[originalClientRequestSymbol] = options.originalRequest; } + return newRequest; } } - function getOperationStatus({ rawResponse }, state) { + exports2.toPipelineRequest = toPipelineRequest; + function toWebResourceLike(request, options) { var _a; - const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; - switch (mode) { - case "OperationLocation": { - return getStatus(rawResponse); - } - case "ResourceLocation": { - return toOperationStatus(rawResponse.statusCode); - } - case "Body": { - return getProvisioningState(rawResponse); - } - default: - throw new Error(`Internal error: Unexpected operation mode: ${mode}`); - } - } - function getResourceLocation({ flatResponse }, state) { - if (typeof flatResponse === "object") { - const resourceLocation = flatResponse.resourceLocation; - if (resourceLocation !== void 0) { - state.config.resourceLocation = resourceLocation; + const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request; + const webResource = { + url: request.url, + method: request.method, + headers: toHttpHeadersLike(request.headers), + withCredentials: request.withCredentials, + timeout: request.timeout, + requestId: request.headers.get("x-ms-client-request-id") || request.requestId, + abortSignal: request.abortSignal, + body: request.body, + formData: request.formData, + keepAlive: !!request.disableKeepAlive, + onDownloadProgress: request.onDownloadProgress, + onUploadProgress: request.onUploadProgress, + proxySettings: request.proxySettings, + streamResponseStatusCodes: request.streamResponseStatusCodes, + clone() { + throw new Error("Cannot clone a non-proxied WebResourceLike"); + }, + prepare() { + throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat"); + }, + validateRequestProperties() { } - } - return state.config.resourceLocation; - } - function isOperationError(e) { - return e.name === "RestError"; - } - async function pollHttpOperation(inputs) { - const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult } = inputs; - return pollOperation({ - state, - stateProxy, - setDelay, - processResult: processResult ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState) : ({ flatResponse }) => flatResponse, - getError: getErrorFromResponse, - updateState, - getPollingInterval: parseRetryAfter, - getOperationLocation, - getOperationStatus, - isOperationError, - getResourceLocation, - options, - /** - * The expansion here is intentional because `lro` could be an object that - * references an inner this, so we need to preserve a reference to it. - */ - poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions), - setErrorAsResult - }); - } - var createStateProxy$1 = () => ({ - /** - * The state at this point is created to be of type OperationState. - * It will be updated later to be of type TState when the - * customer-provided callback, `updateState`, is called during polling. - */ - initState: (config) => ({ status: "running", config }), - setCanceled: (state) => state.status = "canceled", - setError: (state, error4) => state.error = error4, - setResult: (state, result) => state.result = result, - setRunning: (state) => state.status = "running", - setSucceeded: (state) => state.status = "succeeded", - setFailed: (state) => state.status = "failed", - getError: (state) => state.error, - getResult: (state) => state.result, - isCanceled: (state) => state.status === "canceled", - isFailed: (state) => state.status === "failed", - isRunning: (state) => state.status === "running", - isSucceeded: (state) => state.status === "succeeded" - }); - function buildCreatePoller(inputs) { - const { getOperationLocation: getOperationLocation2, getStatusFromInitialResponse: getStatusFromInitialResponse2, getStatusFromPollResponse, isOperationError: isOperationError2, getResourceLocation: getResourceLocation2, getPollingInterval, getError, resolveOnUnsuccessful } = inputs; - return async ({ init, poll }, options) => { - const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom } = options || {}; - const stateProxy = createStateProxy$1(); - const withOperationLocation = withOperationLocationCallback ? /* @__PURE__ */ (() => { - let called = false; - return (operationLocation, isUpdated) => { - if (isUpdated) - withOperationLocationCallback(operationLocation); - else if (!called) - withOperationLocationCallback(operationLocation); - called = true; - }; - })() : void 0; - const state = restoreFrom ? deserializeState(restoreFrom) : await initOperation({ - init, - stateProxy, - processResult, - getOperationStatus: getStatusFromInitialResponse2, - withOperationLocation, - setErrorAsResult: !resolveOnUnsuccessful - }); - let resultPromise; - const abortController$1 = new abortController.AbortController(); - const handlers = /* @__PURE__ */ new Map(); - const handleProgressEvents = async () => handlers.forEach((h) => h(state)); - const cancelErrMsg = "Operation was canceled"; - let currentPollIntervalInMs = intervalInMs; - const poller = { - getOperationState: () => state, - getResult: () => state.result, - isDone: () => ["succeeded", "failed", "canceled"].includes(state.status), - isStopped: () => resultPromise === void 0, - stopPolling: () => { - abortController$1.abort(); - }, - toString: () => JSON.stringify({ - state - }), - onProgress: (callback) => { - const s = Symbol(); - handlers.set(s, callback); - return () => handlers.delete(s); - }, - pollUntilDone: (pollOptions) => resultPromise !== null && resultPromise !== void 0 ? resultPromise : resultPromise = (async () => { - const { abortSignal: inputAbortSignal } = pollOptions || {}; - const { signal: abortSignal } = inputAbortSignal ? new abortController.AbortController([inputAbortSignal, abortController$1.signal]) : abortController$1; - if (!poller.isDone()) { - await poller.poll({ abortSignal }); - while (!poller.isDone()) { - await coreUtil.delay(currentPollIntervalInMs, { abortSignal }); - await poller.poll({ abortSignal }); - } - } - if (resolveOnUnsuccessful) { - return poller.getResult(); - } else { - switch (state.status) { - case "succeeded": - return poller.getResult(); - case "canceled": - throw new Error(cancelErrMsg); - case "failed": - throw state.error; - case "notStarted": - case "running": - throw new Error(`Polling completed without succeeding or failing`); - } + }; + if (options === null || options === void 0 ? void 0 : options.createProxy) { + return new Proxy(webResource, { + get(target, prop, receiver) { + if (prop === originalRequestSymbol) { + return request; + } else if (prop === "clone") { + return () => { + return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), { + createProxy: true, + originalRequest + }); + }; } - })().finally(() => { - resultPromise = void 0; - }), - async poll(pollOptions) { - if (resolveOnUnsuccessful) { - if (poller.isDone()) - return; - } else { - switch (state.status) { - case "succeeded": - return; - case "canceled": - throw new Error(cancelErrMsg); - case "failed": - throw state.error; - } + return Reflect.get(target, prop, receiver); + }, + set(target, prop, value, receiver) { + if (prop === "keepAlive") { + request.disableKeepAlive = !value; } - await pollOperation({ - poll, - state, - stateProxy, - getOperationLocation: getOperationLocation2, - isOperationError: isOperationError2, - withOperationLocation, - getPollingInterval, - getOperationStatus: getStatusFromPollResponse, - getResourceLocation: getResourceLocation2, - processResult, - getError, - updateState, - options: pollOptions, - setDelay: (pollIntervalInMs) => { - currentPollIntervalInMs = pollIntervalInMs; - }, - setErrorAsResult: !resolveOnUnsuccessful - }); - await handleProgressEvents(); - if (!resolveOnUnsuccessful) { - switch (state.status) { - case "canceled": - throw new Error(cancelErrMsg); - case "failed": - throw state.error; - } + const passThroughProps = [ + "url", + "method", + "withCredentials", + "timeout", + "requestId", + "abortSignal", + "body", + "formData", + "onDownloadProgress", + "onUploadProgress", + "proxySettings", + "streamResponseStatusCodes" + ]; + if (typeof prop === "string" && passThroughProps.includes(prop)) { + request[prop] = value; } + return Reflect.set(target, prop, value, receiver); } - }; - return poller; - }; + }); + } else { + return webResource; + } } - async function createHttpPoller(lro, options) { - const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false } = options || {}; - return buildCreatePoller({ - getStatusFromInitialResponse, - getStatusFromPollResponse: getOperationStatus, - isOperationError, - getOperationLocation, - getResourceLocation, - getPollingInterval: parseRetryAfter, - getError: getErrorFromResponse, - resolveOnUnsuccessful - })({ - init: async () => { - const response = await lro.sendInitialRequest(); - const config = inferLroMode({ - rawResponse: response.rawResponse, - requestPath: lro.requestPath, - requestMethod: lro.requestMethod, - resourceLocationConfig - }); - return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, (config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}); - }, - poll: lro.sendPollRequest - }, { - intervalInMs, - withOperationLocation, - restoreFrom, - updateState, - processResult: processResult ? ({ flatResponse }, state) => processResult(flatResponse, state) : ({ flatResponse }) => flatResponse - }); + exports2.toWebResourceLike = toWebResourceLike; + function toHttpHeadersLike(headers) { + return new HttpHeaders(headers.toJSON({ preserveCase: true })); } - var createStateProxy = () => ({ - initState: (config) => ({ config, isStarted: true }), - setCanceled: (state) => state.isCancelled = true, - setError: (state, error4) => state.error = error4, - setResult: (state, result) => state.result = result, - setRunning: (state) => state.isStarted = true, - setSucceeded: (state) => state.isCompleted = true, - setFailed: () => { - }, - getError: (state) => state.error, - getResult: (state) => state.result, - isCanceled: (state) => !!state.isCancelled, - isFailed: (state) => !!state.error, - isRunning: (state) => !!state.isStarted, - isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error) - }); - var GenericPollOperation = class { - constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) { - this.state = state; - this.lro = lro; - this.setErrorAsResult = setErrorAsResult; - this.lroResourceLocationConfig = lroResourceLocationConfig; - this.processResult = processResult; - this.updateState = updateState; - this.isDone = isDone; - } - setPollerConfig(pollerConfig) { - this.pollerConfig = pollerConfig; - } - async update(options) { - var _a; - const stateProxy = createStateProxy(); - if (!this.state.isStarted) { - this.state = Object.assign(Object.assign({}, this.state), await initHttpOperation({ - lro: this.lro, - stateProxy, - resourceLocationConfig: this.lroResourceLocationConfig, - processResult: this.processResult, - setErrorAsResult: this.setErrorAsResult - })); - } - const updateState = this.updateState; - const isDone = this.isDone; - if (!this.state.isCompleted && this.state.error === void 0) { - await pollHttpOperation({ - lro: this.lro, - state: this.state, - stateProxy, - processResult: this.processResult, - updateState: updateState ? (state, { rawResponse }) => updateState(state, rawResponse) : void 0, - isDone: isDone ? ({ flatResponse }, state) => isDone(flatResponse, state) : void 0, - options, - setDelay: (intervalInMs) => { - this.pollerConfig.intervalInMs = intervalInMs; - }, - setErrorAsResult: this.setErrorAsResult - }); + exports2.toHttpHeadersLike = toHttpHeadersLike; + function getHeaderKey(headerName) { + return headerName.toLowerCase(); + } + var HttpHeaders = class _HttpHeaders { + constructor(rawHeaders) { + this._headersMap = {}; + if (rawHeaders) { + for (const headerName in rawHeaders) { + this.set(headerName, rawHeaders[headerName]); + } } - (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state); - return this; - } - async cancel() { - logger.error("`cancelOperation` is deprecated because it wasn't implemented"); - return this; } /** - * Serializes the Poller operation. + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param headerName - The name of the header to set. This value is case-insensitive. + * @param headerValue - The value of the header to set. */ - toString() { - return JSON.stringify({ - state: this.state - }); - } - }; - var PollerStoppedError = class _PollerStoppedError extends Error { - constructor(message) { - super(message); - this.name = "PollerStoppedError"; - Object.setPrototypeOf(this, _PollerStoppedError.prototype); - } - }; - var PollerCancelledError = class _PollerCancelledError extends Error { - constructor(message) { - super(message); - this.name = "PollerCancelledError"; - Object.setPrototypeOf(this, _PollerCancelledError.prototype); - } - }; - var Poller = class { - /** - * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`. - * - * When writing an implementation of a Poller, this implementation needs to deal with the initialization - * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's - * operation has already been defined, at least its basic properties. The code below shows how to approach - * the definition of the constructor of a new custom poller. - * - * ```ts - * export class MyPoller extends Poller { - * constructor({ - * // Anything you might need outside of the basics - * }) { - * let state: MyOperationState = { - * privateProperty: private, - * publicProperty: public, - * }; - * - * const operation = { - * state, - * update, - * cancel, - * toString - * } - * - * // Sending the operation to the parent's constructor. - * super(operation); - * - * // You can assign more local properties here. - * } - * } - * ``` - * - * Inside of this constructor, a new promise is created. This will be used to - * tell the user when the poller finishes (see `pollUntilDone()`). The promise's - * resolve and reject methods are also used internally to control when to resolve - * or reject anyone waiting for the poller to finish. - * - * The constructor of a custom implementation of a poller is where any serialized version of - * a previous poller's operation should be deserialized into the operation sent to the - * base constructor. For example: - * - * ```ts - * export class MyPoller extends Poller { - * constructor( - * baseOperation: string | undefined - * ) { - * let state: MyOperationState = {}; - * if (baseOperation) { - * state = { - * ...JSON.parse(baseOperation).state, - * ...state - * }; - * } - * const operation = { - * state, - * // ... - * } - * super(operation); - * } - * } - * ``` - * - * @param operation - Must contain the basic properties of `PollOperation`. - */ - constructor(operation) { - this.resolveOnUnsuccessful = false; - this.stopped = true; - this.pollProgressCallbacks = []; - this.operation = operation; - this.promise = new Promise((resolve2, reject) => { - this.resolve = resolve2; - this.reject = reject; - }); - this.promise.catch(() => { - }); + set(headerName, headerValue) { + this._headersMap[getHeaderKey(headerName)] = { + name: headerName, + value: headerValue.toString() + }; } /** - * Starts a loop that will break only if the poller is done - * or if the poller is stopped. + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param headerName - The name of the header. */ - async startPolling(pollOptions = {}) { - if (this.stopped) { - this.stopped = false; - } - while (!this.isStopped() && !this.isDone()) { - await this.poll(pollOptions); - await this.delay(); - } + get(headerName) { + const header = this._headersMap[getHeaderKey(headerName)]; + return !header ? void 0 : header.value; } /** - * pollOnce does one polling, by calling to the update method of the underlying - * poll operation to make any relevant change effective. - * - * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. - * - * @param options - Optional properties passed to the operation's update method. + * Get whether or not this header collection contains a header entry for the provided header name. */ - async pollOnce(options = {}) { - if (!this.isDone()) { - this.operation = await this.operation.update({ - abortSignal: options.abortSignal, - fireProgress: this.fireProgress.bind(this) - }); - } - this.processUpdatedState(); + contains(headerName) { + return !!this._headersMap[getHeaderKey(headerName)]; } /** - * fireProgress calls the functions passed in via onProgress the method of the poller. - * - * It loops over all of the callbacks received from onProgress, and executes them, sending them - * the current operation state. - * - * @param state - The current operation state. + * Remove the header with the provided headerName. Return whether or not the header existed and + * was removed. + * @param headerName - The name of the header to remove. */ - fireProgress(state) { - for (const callback of this.pollProgressCallbacks) { - callback(state); - } + remove(headerName) { + const result = this.contains(headerName); + delete this._headersMap[getHeaderKey(headerName)]; + return result; } /** - * Invokes the underlying operation's cancel method. + * Get the headers that are contained this collection as an object. */ - async cancelOnce(options = {}) { - this.operation = await this.operation.cancel(options); + rawHeaders() { + return this.toJson({ preserveCase: true }); } /** - * Returns a promise that will resolve once a single polling request finishes. - * It does this by calling the update method of the Poller's operation. - * - * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. - * - * @param options - Optional properties passed to the operation's update method. + * Get the headers that are contained in this collection as an array. */ - poll(options = {}) { - if (!this.pollOncePromise) { - this.pollOncePromise = this.pollOnce(options); - const clearPollOncePromise = () => { - this.pollOncePromise = void 0; - }; - this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject); - } - return this.pollOncePromise; - } - processUpdatedState() { - if (this.operation.state.error) { - this.stopped = true; - if (!this.resolveOnUnsuccessful) { - this.reject(this.operation.state.error); - throw this.operation.state.error; - } - } - if (this.operation.state.isCancelled) { - this.stopped = true; - if (!this.resolveOnUnsuccessful) { - const error4 = new PollerCancelledError("Operation was canceled"); - this.reject(error4); - throw error4; - } - } - if (this.isDone() && this.resolve) { - this.resolve(this.getResult()); + headersArray() { + const headers = []; + for (const headerKey in this._headersMap) { + headers.push(this._headersMap[headerKey]); } + return headers; } /** - * Returns a promise that will resolve once the underlying operation is completed. + * Get the header names that are contained in this collection. */ - async pollUntilDone(pollOptions = {}) { - if (this.stopped) { - this.startPolling(pollOptions).catch(this.reject); + headerNames() { + const headerNames = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { + headerNames.push(headers[i].name); } - this.processUpdatedState(); - return this.promise; - } - /** - * Invokes the provided callback after each polling is completed, - * sending the current state of the poller's operation. - * - * It returns a method that can be used to stop receiving updates on the given callback function. - */ - onProgress(callback) { - this.pollProgressCallbacks.push(callback); - return () => { - this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback); - }; - } - /** - * Returns true if the poller has finished polling. - */ - isDone() { - const state = this.operation.state; - return Boolean(state.isCompleted || state.isCancelled || state.error); + return headerNames; } /** - * Stops the poller from continuing to poll. + * Get the header values that are contained in this collection. */ - stopPolling() { - if (!this.stopped) { - this.stopped = true; - if (this.reject) { - this.reject(new PollerStoppedError("This poller is already stopped")); - } + headerValues() { + const headerValues = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { + headerValues.push(headers[i].value); } + return headerValues; } /** - * Returns true if the poller is stopped. - */ - isStopped() { - return this.stopped; - } - /** - * Attempts to cancel the underlying operation. - * - * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. - * - * If it's called again before it finishes, it will throw an error. - * - * @param options - Optional properties passed to the operation's update method. + * Get the JSON object representation of this HTTP header collection. */ - cancelOperation(options = {}) { - if (!this.cancelPromise) { - this.cancelPromise = this.cancelOnce(options); - } else if (options.abortSignal) { - throw new Error("A cancel request is currently pending"); + toJson(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[header.name] = header.value; + } + } else { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[getHeaderKey(header.name)] = header.value; + } } - return this.cancelPromise; - } - /** - * Returns the state of the operation. - * - * Even though TState will be the same type inside any of the methods of any extension of the Poller class, - * implementations of the pollers can customize what's shared with the public by writing their own - * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller - * and a public type representing a safe to share subset of the properties of the internal state. - * Their definition of getOperationState can then return their public type. - * - * Example: - * - * ```ts - * // Let's say we have our poller's operation state defined as: - * interface MyOperationState extends PollOperationState { - * privateProperty?: string; - * publicProperty?: string; - * } - * - * // To allow us to have a true separation of public and private state, we have to define another interface: - * interface PublicState extends PollOperationState { - * publicProperty?: string; - * } - * - * // Then, we define our Poller as follows: - * export class MyPoller extends Poller { - * // ... More content is needed here ... - * - * public getOperationState(): PublicState { - * const state: PublicState = this.operation.state; - * return { - * // Properties from PollOperationState - * isStarted: state.isStarted, - * isCompleted: state.isCompleted, - * isCancelled: state.isCancelled, - * error: state.error, - * result: state.result, - * - * // The only other property needed by PublicState. - * publicProperty: state.publicProperty - * } - * } - * } - * ``` - * - * You can see this in the tests of this repository, go to the file: - * `../test/utils/testPoller.ts` - * and look for the getOperationState implementation. - */ - getOperationState() { - return this.operation.state; - } - /** - * Returns the result value of the operation, - * regardless of the state of the poller. - * It can return undefined or an incomplete form of the final TResult value - * depending on the implementation. - */ - getResult() { - const state = this.operation.state; - return state.result; + return result; } /** - * Returns a serialized version of the poller's operation - * by invoking the operation's toString method. + * Get the string representation of this HTTP header collection. */ toString() { - return this.operation.toString(); - } - }; - var LroEngine = class extends Poller { - constructor(lro, options) { - const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState } = options || {}; - const state = resumeFrom ? deserializeState(resumeFrom) : {}; - const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone); - super(operation); - this.resolveOnUnsuccessful = resolveOnUnsuccessful; - this.config = { intervalInMs }; - operation.setPollerConfig(this.config); + return JSON.stringify(this.toJson({ preserveCase: true })); } /** - * The method used by the poller to wait before attempting to update its operation. + * Create a deep clone/copy of this HttpHeaders collection. */ - delay() { - return new Promise((resolve2) => setTimeout(() => resolve2(), this.config.intervalInMs)); + clone() { + const resultPreservingCasing = {}; + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + resultPreservingCasing[header.name] = header.value; + } + return new _HttpHeaders(resultPreservingCasing); } }; - exports2.LroEngine = LroEngine; - exports2.Poller = Poller; - exports2.PollerCancelledError = PollerCancelledError; - exports2.PollerStoppedError = PollerStoppedError; - exports2.createHttpPoller = createHttpPoller; + exports2.HttpHeaders = HttpHeaders; } }); -// node_modules/@azure/storage-blob/dist/index.js -var require_dist7 = __commonJS({ - "node_modules/@azure/storage-blob/dist/index.js"(exports2) { +// node_modules/@azure/core-http-compat/dist/commonjs/response.js +var require_response2 = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/response.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); - var coreRestPipeline = require_commonjs7(); - var tslib = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); - var coreAuth = require_commonjs8(); - var coreUtil = require_commonjs4(); - var coreHttpCompat = require_commonjs10(); - var coreClient = require_commonjs9(); - var coreXml = require_commonjs11(); - var logger$1 = require_dist(); - var abortController = require_commonjs12(); - var crypto = require("crypto"); - var coreTracing = require_commonjs6(); - var stream = require("stream"); - var coreLro = require_dist6(); - var events = require("events"); - var fs2 = require("fs"); - var util = require("util"); - var buffer = require("buffer"); - function _interopNamespaceDefault(e) { - var n = /* @__PURE__ */ Object.create(null); - if (e) { - Object.keys(e).forEach(function(k) { - if (k !== "default") { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function() { - return e[k]; - } - }); + exports2.toPipelineResponse = exports2.toCompatResponse = void 0; + var core_rest_pipeline_1 = require_commonjs7(); + var util_js_1 = require_util9(); + var originalResponse = Symbol("Original FullOperationResponse"); + function toCompatResponse(response, options) { + let request = (0, util_js_1.toWebResourceLike)(response.request); + let headers = (0, util_js_1.toHttpHeadersLike)(response.headers); + if (options === null || options === void 0 ? void 0 : options.createProxy) { + return new Proxy(response, { + get(target, prop, receiver) { + if (prop === "headers") { + return headers; + } else if (prop === "request") { + return request; + } else if (prop === originalResponse) { + return response; + } + return Reflect.get(target, prop, receiver); + }, + set(target, prop, value, receiver) { + if (prop === "headers") { + headers = value; + } else if (prop === "request") { + request = value; + } + return Reflect.set(target, prop, value, receiver); } }); + } else { + return Object.assign(Object.assign({}, response), { + request, + headers + }); } - n.default = e; - return Object.freeze(n); } - var coreHttpCompat__namespace = /* @__PURE__ */ _interopNamespaceDefault(coreHttpCompat); - var coreClient__namespace = /* @__PURE__ */ _interopNamespaceDefault(coreClient); - var fs__namespace = /* @__PURE__ */ _interopNamespaceDefault(fs2); - var util__namespace = /* @__PURE__ */ _interopNamespaceDefault(util); - var logger = logger$1.createClientLogger("storage-blob"); - var BaseRequestPolicy = class { - /** - * The main method to implement that manipulates a request/response. - */ - constructor(_nextPolicy, _options) { - this._nextPolicy = _nextPolicy; - this._options = _options; + exports2.toCompatResponse = toCompatResponse; + function toPipelineResponse(compatResponse) { + const extendedCompatResponse = compatResponse; + const response = extendedCompatResponse[originalResponse]; + const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true })); + if (response) { + response.headers = headers; + return response; + } else { + return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) }); } - /** - * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. - * @returns Whether or not a log with the provided log level should be logged. - */ - shouldLog(logLevel) { - return this._options.shouldLog(logLevel); + } + exports2.toPipelineResponse = toPipelineResponse; + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/extendedClient.js +var require_extendedClient = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/extendedClient.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ExtendedServiceClient = void 0; + var disableKeepAlivePolicy_js_1 = require_disableKeepAlivePolicy(); + var core_rest_pipeline_1 = require_commonjs7(); + var core_client_1 = require_commonjs9(); + var response_js_1 = require_response2(); + var ExtendedServiceClient = class extends core_client_1.ServiceClient { + constructor(options) { + var _a, _b; + super(options); + if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false && !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) { + this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)()); + } + if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) { + this.pipeline.removePolicy({ + name: core_rest_pipeline_1.redirectPolicyName + }); + } } /** - * Attempt to log the provided message to the provided logger. If no logger was provided or if - * the log level does not meat the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. + * Compatible send operation request function. + * + * @param operationArguments - Operation arguments + * @param operationSpec - Operation Spec + * @returns */ - log(logLevel, message) { - this._options.log(logLevel, message); - } - }; - var SDK_VERSION = "12.25.0"; - var SERVICE_VERSION = "2024-11-04"; - var BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; - var BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4e3 * 1024 * 1024; - var BLOCK_BLOB_MAX_BLOCKS = 5e4; - var DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; - var DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; - var DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; - var REQUEST_TIMEOUT = 100 * 1e3; - var StorageOAuthScopes = "https://storage.azure.com/.default"; - var URLConstants = { - Parameters: { - FORCE_BROWSER_NO_CACHE: "_", - SIGNATURE: "sig", - SNAPSHOT: "snapshot", - VERSIONID: "versionid", - TIMEOUT: "timeout" - } - }; - var HTTPURLConnection = { - HTTP_ACCEPTED: 202, - HTTP_CONFLICT: 409, - HTTP_NOT_FOUND: 404, - HTTP_PRECON_FAILED: 412, - HTTP_RANGE_NOT_SATISFIABLE: 416 - }; - var HeaderConstants = { - AUTHORIZATION: "Authorization", - AUTHORIZATION_SCHEME: "Bearer", - CONTENT_ENCODING: "Content-Encoding", - CONTENT_ID: "Content-ID", - CONTENT_LANGUAGE: "Content-Language", - CONTENT_LENGTH: "Content-Length", - CONTENT_MD5: "Content-Md5", - CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", - CONTENT_TYPE: "Content-Type", - COOKIE: "Cookie", - DATE: "date", - IF_MATCH: "if-match", - IF_MODIFIED_SINCE: "if-modified-since", - IF_NONE_MATCH: "if-none-match", - IF_UNMODIFIED_SINCE: "if-unmodified-since", - PREFIX_FOR_STORAGE: "x-ms-", - RANGE: "Range", - USER_AGENT: "User-Agent", - X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", - X_MS_COPY_SOURCE: "x-ms-copy-source", - X_MS_DATE: "x-ms-date", - X_MS_ERROR_CODE: "x-ms-error-code", - X_MS_VERSION: "x-ms-version", - X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code" - }; - var ETagNone = ""; - var ETagAny = "*"; - var SIZE_1_MB = 1 * 1024 * 1024; - var BATCH_MAX_REQUEST = 256; - var BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; - var HTTP_LINE_ENDING = "\r\n"; - var HTTP_VERSION_1_1 = "HTTP/1.1"; - var EncryptionAlgorithmAES25 = "AES256"; - var DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; - var StorageBlobLoggingAllowedHeaderNames = [ - "Access-Control-Allow-Origin", - "Cache-Control", - "Content-Length", - "Content-Type", - "Date", - "Request-Id", - "traceparent", - "Transfer-Encoding", - "User-Agent", - "x-ms-client-request-id", - "x-ms-date", - "x-ms-error-code", - "x-ms-request-id", - "x-ms-return-client-request-id", - "x-ms-version", - "Accept-Ranges", - "Content-Disposition", - "Content-Encoding", - "Content-Language", - "Content-MD5", - "Content-Range", - "ETag", - "Last-Modified", - "Server", - "Vary", - "x-ms-content-crc64", - "x-ms-copy-action", - "x-ms-copy-completion-time", - "x-ms-copy-id", - "x-ms-copy-progress", - "x-ms-copy-status", - "x-ms-has-immutability-policy", - "x-ms-has-legal-hold", - "x-ms-lease-state", - "x-ms-lease-status", - "x-ms-range", - "x-ms-request-server-encrypted", - "x-ms-server-encrypted", - "x-ms-snapshot", - "x-ms-source-range", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "x-ms-access-tier", - "x-ms-access-tier-change-time", - "x-ms-access-tier-inferred", - "x-ms-account-kind", - "x-ms-archive-status", - "x-ms-blob-append-offset", - "x-ms-blob-cache-control", - "x-ms-blob-committed-block-count", - "x-ms-blob-condition-appendpos", - "x-ms-blob-condition-maxsize", - "x-ms-blob-content-disposition", - "x-ms-blob-content-encoding", - "x-ms-blob-content-language", - "x-ms-blob-content-length", - "x-ms-blob-content-md5", - "x-ms-blob-content-type", - "x-ms-blob-public-access", - "x-ms-blob-sequence-number", - "x-ms-blob-type", - "x-ms-copy-destination-snapshot", - "x-ms-creation-time", - "x-ms-default-encryption-scope", - "x-ms-delete-snapshots", - "x-ms-delete-type-permanent", - "x-ms-deny-encryption-scope-override", - "x-ms-encryption-algorithm", - "x-ms-if-sequence-number-eq", - "x-ms-if-sequence-number-le", - "x-ms-if-sequence-number-lt", - "x-ms-incremental-copy", - "x-ms-lease-action", - "x-ms-lease-break-period", - "x-ms-lease-duration", - "x-ms-lease-id", - "x-ms-lease-time", - "x-ms-page-write", - "x-ms-proposed-lease-id", - "x-ms-range-get-content-md5", - "x-ms-rehydrate-priority", - "x-ms-sequence-number-action", - "x-ms-sku-name", - "x-ms-source-content-md5", - "x-ms-source-if-match", - "x-ms-source-if-modified-since", - "x-ms-source-if-none-match", - "x-ms-source-if-unmodified-since", - "x-ms-tag-count", - "x-ms-encryption-key-sha256", - "x-ms-copy-source-error-code", - "x-ms-copy-source-status-code", - "x-ms-if-tags", - "x-ms-source-if-tags" - ]; - var StorageBlobLoggingAllowedQueryParameters = [ - "comp", - "maxresults", - "rscc", - "rscd", - "rsce", - "rscl", - "rsct", - "se", - "si", - "sip", - "sp", - "spr", - "sr", - "srt", - "ss", - "st", - "sv", - "include", - "marker", - "prefix", - "copyid", - "restype", - "blockid", - "blocklisttype", - "delimiter", - "prevsnapshot", - "ske", - "skoid", - "sks", - "skt", - "sktid", - "skv", - "snapshot" - ]; - var BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption"; - var BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption"; - var PathStylePorts = [ - "10000", - "10001", - "10002", - "10003", - "10004", - "10100", - "10101", - "10102", - "10103", - "10104", - "11000", - "11001", - "11002", - "11003", - "11004", - "11100", - "11101", - "11102", - "11103", - "11104" - ]; - function escapeURLPath(url2) { - const urlParsed = new URL(url2); - let path2 = urlParsed.pathname; - path2 = path2 || "/"; - path2 = escape(path2); - urlParsed.pathname = path2; - return urlParsed.toString(); - } - function getProxyUriFromDevConnString(connectionString) { - let proxyUri = ""; - if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { - const matchCredentials = connectionString.split(";"); - for (const element of matchCredentials) { - if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { - proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; + async sendOperationRequest(operationArguments, operationSpec) { + var _a; + const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse; + let lastResponse; + function onResponse(rawResponse, flatResponse, error4) { + lastResponse = rawResponse; + if (userProvidedCallBack) { + userProvidedCallBack(rawResponse, flatResponse, error4); } } - } - return proxyUri; - } - function getValueInConnString(connectionString, argument) { - const elements = connectionString.split(";"); - for (const element of elements) { - if (element.trim().startsWith(argument)) { - return element.trim().match(argument + "=(.*)")[1]; + operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse }); + const result = await super.sendOperationRequest(operationArguments, operationSpec); + if (lastResponse) { + Object.defineProperty(result, "_response", { + value: (0, response_js_1.toCompatResponse)(lastResponse) + }); } + return result; } - return ""; - } - function extractConnectionStringParts(connectionString) { - let proxyUri = ""; - if (connectionString.startsWith("UseDevelopmentStorage=true")) { - proxyUri = getProxyUriFromDevConnString(connectionString); - connectionString = DevelopmentConnectionString; + }; + exports2.ExtendedServiceClient = ExtendedServiceClient; + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/policies/requestPolicyFactoryPolicy.js +var require_requestPolicyFactoryPolicy = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/policies/requestPolicyFactoryPolicy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createRequestPolicyFactoryPolicy = exports2.requestPolicyFactoryPolicyName = exports2.HttpPipelineLogLevel = void 0; + var util_js_1 = require_util9(); + var response_js_1 = require_response2(); + var HttpPipelineLogLevel; + (function(HttpPipelineLogLevel2) { + HttpPipelineLogLevel2[HttpPipelineLogLevel2["ERROR"] = 1] = "ERROR"; + HttpPipelineLogLevel2[HttpPipelineLogLevel2["INFO"] = 3] = "INFO"; + HttpPipelineLogLevel2[HttpPipelineLogLevel2["OFF"] = 0] = "OFF"; + HttpPipelineLogLevel2[HttpPipelineLogLevel2["WARNING"] = 2] = "WARNING"; + })(HttpPipelineLogLevel || (exports2.HttpPipelineLogLevel = HttpPipelineLogLevel = {})); + var mockRequestPolicyOptions = { + log(_logLevel, _message) { + }, + shouldLog(_logLevel) { + return false; } - let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); - blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; - if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { - let defaultEndpointsProtocol = ""; - let accountName = ""; - let accountKey = Buffer.from("accountKey", "base64"); - let endpointSuffix = ""; - accountName = getValueInConnString(connectionString, "AccountName"); - accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); - if (!blobEndpoint) { - defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); - const protocol = defaultEndpointsProtocol.toLowerCase(); - if (protocol !== "https" && protocol !== "http") { - throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); - } - endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); - if (!endpointSuffix) { - throw new Error("Invalid EndpointSuffix in the provided Connection String"); + }; + exports2.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy"; + function createRequestPolicyFactoryPolicy(factories) { + const orderedFactories = factories.slice().reverse(); + return { + name: exports2.requestPolicyFactoryPolicyName, + async sendRequest(request, next) { + let httpPipeline = { + async sendRequest(httpRequest) { + const response2 = await next((0, util_js_1.toPipelineRequest)(httpRequest)); + return (0, response_js_1.toCompatResponse)(response2, { createProxy: true }); + } + }; + for (const factory of orderedFactories) { + httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions); } - blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; - } - if (!accountName) { - throw new Error("Invalid AccountName in the provided Connection String"); - } else if (accountKey.length === 0) { - throw new Error("Invalid AccountKey in the provided Connection String"); - } - return { - kind: "AccountConnString", - url: blobEndpoint, - accountName, - accountKey, - proxyUri - }; - } else { - let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); - let accountName = getValueInConnString(connectionString, "AccountName"); - if (!accountName) { - accountName = getAccountNameFromUrl(blobEndpoint); + const webResourceLike = (0, util_js_1.toWebResourceLike)(request, { createProxy: true }); + const response = await httpPipeline.sendRequest(webResourceLike); + return (0, response_js_1.toPipelineResponse)(response); } - if (!blobEndpoint) { - throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); - } else if (!accountSas) { - throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); + }; + } + exports2.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy; + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/httpClientAdapter.js +var require_httpClientAdapter = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/httpClientAdapter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.convertHttpClient = void 0; + var response_js_1 = require_response2(); + var util_js_1 = require_util9(); + function convertHttpClient(requestPolicyClient) { + return { + sendRequest: async (request) => { + const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request, { createProxy: true })); + return (0, response_js_1.toPipelineResponse)(response); } - if (accountSas.startsWith("?")) { - accountSas = accountSas.substring(1); + }; + } + exports2.convertHttpClient = convertHttpClient; + } +}); + +// node_modules/@azure/core-http-compat/dist/commonjs/index.js +var require_commonjs10 = __commonJS({ + "node_modules/@azure/core-http-compat/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.toHttpHeadersLike = exports2.convertHttpClient = exports2.disableKeepAlivePolicyName = exports2.HttpPipelineLogLevel = exports2.createRequestPolicyFactoryPolicy = exports2.requestPolicyFactoryPolicyName = exports2.ExtendedServiceClient = void 0; + var extendedClient_js_1 = require_extendedClient(); + Object.defineProperty(exports2, "ExtendedServiceClient", { enumerable: true, get: function() { + return extendedClient_js_1.ExtendedServiceClient; + } }); + var requestPolicyFactoryPolicy_js_1 = require_requestPolicyFactoryPolicy(); + Object.defineProperty(exports2, "requestPolicyFactoryPolicyName", { enumerable: true, get: function() { + return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; + } }); + Object.defineProperty(exports2, "createRequestPolicyFactoryPolicy", { enumerable: true, get: function() { + return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; + } }); + Object.defineProperty(exports2, "HttpPipelineLogLevel", { enumerable: true, get: function() { + return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; + } }); + var disableKeepAlivePolicy_js_1 = require_disableKeepAlivePolicy(); + Object.defineProperty(exports2, "disableKeepAlivePolicyName", { enumerable: true, get: function() { + return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; + } }); + var httpClientAdapter_js_1 = require_httpClientAdapter(); + Object.defineProperty(exports2, "convertHttpClient", { enumerable: true, get: function() { + return httpClientAdapter_js_1.convertHttpClient; + } }); + var util_js_1 = require_util9(); + Object.defineProperty(exports2, "toHttpHeadersLike", { enumerable: true, get: function() { + return util_js_1.toHttpHeadersLike; + } }); + } +}); + +// node_modules/fast-xml-parser/src/util.js +var require_util10 = __commonJS({ + "node_modules/fast-xml-parser/src/util.js"(exports2) { + "use strict"; + var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; + var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; + var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*"; + var regexName = new RegExp("^" + nameRegexp + "$"); + var getAllMatches = function(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); } - return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; + matches.push(allmatches); + match = regex.exec(string); } - } - function escape(text) { - return encodeURIComponent(text).replace(/%2F/g, "/").replace(/'/g, "%27").replace(/\+/g, "%20").replace(/%25/g, "%"); - } - function appendToURLPath(url2, name) { - const urlParsed = new URL(url2); - let path2 = urlParsed.pathname; - path2 = path2 ? path2.endsWith("/") ? `${path2}${name}` : `${path2}/${name}` : name; - urlParsed.pathname = path2; - return urlParsed.toString(); - } - function setURLParameter(url2, name, value) { - const urlParsed = new URL(url2); - const encodedName = encodeURIComponent(name); - const encodedValue = value ? encodeURIComponent(value) : void 0; - const searchString = urlParsed.search === "" ? "?" : urlParsed.search; - const searchPieces = []; - for (const pair of searchString.slice(1).split("&")) { - if (pair) { - const [key] = pair.split("=", 2); - if (key !== encodedName) { - searchPieces.push(pair); + return matches; + }; + var isName = function(string) { + const match = regexName.exec(string); + return !(match === null || typeof match === "undefined"); + }; + exports2.isExist = function(v) { + return typeof v !== "undefined"; + }; + exports2.isEmptyObject = function(obj) { + return Object.keys(obj).length === 0; + }; + exports2.merge = function(target, a, arrayMode) { + if (a) { + const keys = Object.keys(a); + const len = keys.length; + for (let i = 0; i < len; i++) { + if (arrayMode === "strict") { + target[keys[i]] = [a[keys[i]]]; + } else { + target[keys[i]] = a[keys[i]]; } } } - if (encodedValue) { - searchPieces.push(`${encodedName}=${encodedValue}`); - } - urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; - return urlParsed.toString(); - } - function getURLParameter(url2, name) { - var _a; - const urlParsed = new URL(url2); - return (_a = urlParsed.searchParams.get(name)) !== null && _a !== void 0 ? _a : void 0; - } - function setURLHost(url2, host) { - const urlParsed = new URL(url2); - urlParsed.hostname = host; - return urlParsed.toString(); - } - function getURLPath(url2) { - try { - const urlParsed = new URL(url2); - return urlParsed.pathname; - } catch (e) { - return void 0; - } - } - function getURLScheme(url2) { - try { - const urlParsed = new URL(url2); - return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; - } catch (e) { - return void 0; - } - } - function getURLPathAndQuery(url2) { - const urlParsed = new URL(url2); - const pathString = urlParsed.pathname; - if (!pathString) { - throw new RangeError("Invalid url without valid path."); + }; + exports2.getValue = function(v) { + if (exports2.isExist(v)) { + return v; + } else { + return ""; } - let queryString = urlParsed.search || ""; - queryString = queryString.trim(); - if (queryString !== "") { - queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; - } - return `${pathString}${queryString}`; - } - function getURLQueries(url2) { - let queryString = new URL(url2).search; - if (!queryString) { - return {}; + }; + exports2.isName = isName; + exports2.getAllMatches = getAllMatches; + exports2.nameRegexp = nameRegexp; + } +}); + +// node_modules/fast-xml-parser/src/validator.js +var require_validator = __commonJS({ + "node_modules/fast-xml-parser/src/validator.js"(exports2) { + "use strict"; + var util = require_util10(); + var defaultOptions = { + allowBooleanAttributes: false, + //A tag can have attributes without any value + unpairedTags: [] + }; + exports2.validate = function(xmlData, options) { + options = Object.assign({}, defaultOptions, options); + const tags = []; + let tagFound = false; + let reachedRoot = false; + if (xmlData[0] === "\uFEFF") { + xmlData = xmlData.substr(1); } - queryString = queryString.trim(); - queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; - let querySubStrings = queryString.split("&"); - querySubStrings = querySubStrings.filter((value) => { - const indexOfEqual = value.indexOf("="); - const lastIndexOfEqual = value.lastIndexOf("="); - return indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1; - }); - const queries = {}; - for (const querySubString of querySubStrings) { - const splitResults = querySubString.split("="); - const key = splitResults[0]; - const value = splitResults[1]; - queries[key] = value; + for (let i = 0; i < xmlData.length; i++) { + if (xmlData[i] === "<" && xmlData[i + 1] === "?") { + i += 2; + i = readPI(xmlData, i); + if (i.err) return i; + } else if (xmlData[i] === "<") { + let tagStartPos = i; + i++; + if (xmlData[i] === "!") { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === "/") { + closingTag = true; + i++; + } + let tagName = ""; + for (; i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== " " && xmlData[i] !== "\n" && xmlData[i] !== "\r"; i++) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substring(0, tagName.length - 1); + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '" + tagName + "' is an invalid name."; + } + return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i)); + } + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; + if (attrStr[attrStr.length - 1] === "/") { + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + } else { + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags.length === 0) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject( + "InvalidTag", + "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", + getLineNumberForPosition(xmlData, tagStartPos) + ); + } + if (tags.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + if (reachedRoot === true) { + return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i)); + } else if (options.unpairedTags.indexOf(tagName) !== -1) { + } else { + tags.push({ tagName, tagStartPos }); + } + tagFound = true; + } + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + if (xmlData[i + 1] === "!") { + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i + 1] === "?") { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else { + break; + } + } else if (xmlData[i] === "&") { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + } else { + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } + if (xmlData[i] === "<") { + i--; + } + } + } else { + if (isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i)); + } } - return queries; - } - function appendToURLQuery(url2, queryParts) { - const urlParsed = new URL(url2); - let query = urlParsed.search; - if (query) { - query += "&" + queryParts; - } else { - query = queryParts; + if (!tagFound) { + return getErrorObject("InvalidXml", "Start tag expected.", 1); + } else if (tags.length == 1) { + return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); + } else if (tags.length > 0) { + return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }); } - urlParsed.search = query; - return urlParsed.toString(); - } - function truncatedISO8061Date(date, withMilliseconds = true) { - const dateString = date.toISOString(); - return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000Z" : dateString.substring(0, dateString.length - 5) + "Z"; - } - function base64encode(content) { - return !coreUtil.isNode ? btoa(content) : Buffer.from(content).toString("base64"); + return true; + }; + function isWhiteSpace(char) { + return char === " " || char === " " || char === "\n" || char === "\r"; } - function generateBlockID(blockIDPrefix, blockIndex) { - const maxSourceStringLength = 48; - const maxBlockIndexLength = 6; - const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; - if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { - blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); + function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == "?" || xmlData[i] == " ") { + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === "xml") { + return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == "?" && xmlData[i + 1] == ">") { + i++; + break; + } else { + continue; + } + } } - const res = blockIDPrefix + padStart2(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); - return base64encode(res); + return i; } - async function delay(timeInMs, aborter, abortError) { - return new Promise((resolve2, reject) => { - let timeout; - const abortHandler = () => { - if (timeout !== void 0) { - clearTimeout(timeout); - } - reject(abortError); - }; - const resolveHandler = () => { - if (aborter !== void 0) { - aborter.removeEventListener("abort", abortHandler); + function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") { + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") { + i += 2; + break; } - resolve2(); - }; - timeout = setTimeout(resolveHandler, timeInMs); - if (aborter !== void 0) { - aborter.addEventListener("abort", abortHandler); } - }); - } - function padStart2(currentString, targetLength, padString = " ") { - if (String.prototype.padStart) { - return currentString.padStart(targetLength, padString); - } - padString = padString || " "; - if (currentString.length > targetLength) { - return currentString; - } else { - targetLength = targetLength - currentString.length; - if (targetLength > padString.length) { - padString += padString.repeat(targetLength / padString.length); + } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + angleBracketsCount++; + } else if (xmlData[i] === ">") { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } } - return padString.slice(0, targetLength) + currentString; - } - } - function iEqual(str1, str2) { - return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); - } - function getAccountNameFromUrl(url2) { - const parsedUrl = new URL(url2); - let accountName; - try { - if (parsedUrl.hostname.split(".")[1] === "blob") { - accountName = parsedUrl.hostname.split(".")[0]; - } else if (isIpEndpointStyle(parsedUrl)) { - accountName = parsedUrl.pathname.split("/")[1]; - } else { - accountName = ""; + } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") { + i += 2; + break; + } } - return accountName; - } catch (error4) { - throw new Error("Unable to extract accountName with provided information."); } + return i; } - function isIpEndpointStyle(parsedUrl) { - const host = parsedUrl.host; - return /^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) || Boolean(parsedUrl.port) && PathStylePorts.includes(parsedUrl.port); - } - function toBlobTagsString(tags2) { - if (tags2 === void 0) { - return void 0; - } - const tagPairs = []; - for (const key in tags2) { - if (Object.prototype.hasOwnProperty.call(tags2, key)) { - const value = tags2[key]; - tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); + var doubleQuote = '"'; + var singleQuote = "'"; + function readAttributeStr(xmlData, i) { + let attrStr = ""; + let startChar = ""; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === "") { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) { + } else { + startChar = ""; + } + } else if (xmlData[i] === ">") { + if (startChar === "") { + tagClosed = true; + break; + } } + attrStr += xmlData[i]; } - return tagPairs.join("&"); - } - function toBlobTags(tags2) { - if (tags2 === void 0) { - return void 0; + if (startChar !== "") { + return false; } - const res = { - blobTagSet: [] + return { + value: attrStr, + index: i, + tagClosed }; - for (const key in tags2) { - if (Object.prototype.hasOwnProperty.call(tags2, key)) { - const value = tags2[key]; - res.blobTagSet.push({ - key, - value - }); + } + var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); + function validateAttributeString(attrStr, options) { + const matches = util.getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] !== void 0 && matches[i][4] === void 0) { + return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === void 0 && !options.allowBooleanAttributes) { + return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i])); + } + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!attrNames.hasOwnProperty(attrName)) { + attrNames[attrName] = 1; + } else { + return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i])); } } - return res; + return true; } - function toTags(tags2) { - if (tags2 === void 0) { - return void 0; + function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === "x") { + i++; + re = /[\da-fA-F]/; } - const res = {}; - for (const blobTag of tags2.blobTagSet) { - res[blobTag.key] = blobTag.value; + for (; i < xmlData.length; i++) { + if (xmlData[i] === ";") + return i; + if (!xmlData[i].match(re)) + break; } - return res; + return -1; } - function toQuerySerialization(textConfiguration) { - if (textConfiguration === void 0) { - return void 0; + function validateAmpersand(xmlData, i) { + i++; + if (xmlData[i] === ";") + return -1; + if (xmlData[i] === "#") { + i++; + return validateNumberAmpersand(xmlData, i); } - switch (textConfiguration.kind) { - case "csv": - return { - format: { - type: "delimited", - delimitedTextConfiguration: { - columnSeparator: textConfiguration.columnSeparator || ",", - fieldQuote: textConfiguration.fieldQuote || "", - recordSeparator: textConfiguration.recordSeparator, - escapeChar: textConfiguration.escapeCharacter || "", - headersPresent: textConfiguration.hasHeaders || false - } - } - }; - case "json": - return { - format: { - type: "json", - jsonTextConfiguration: { - recordSeparator: textConfiguration.recordSeparator - } - } - }; - case "arrow": - return { - format: { - type: "arrow", - arrowConfiguration: { - schema: textConfiguration.schema - } - } - }; - case "parquet": - return { - format: { - type: "parquet" - } - }; - default: - throw Error("Invalid BlobQueryTextConfiguration."); + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ";") + break; + return -1; } + return i; } - function parseObjectReplicationRecord(objectReplicationRecord) { - if (!objectReplicationRecord) { - return void 0; - } - if ("policy-id" in objectReplicationRecord) { - return void 0; - } - const orProperties = []; - for (const key in objectReplicationRecord) { - const ids = key.split("_"); - const policyPrefix = "or-"; - if (ids[0].startsWith(policyPrefix)) { - ids[0] = ids[0].substring(policyPrefix.length); - } - const rule = { - ruleId: ids[1], - replicationStatus: objectReplicationRecord[key] - }; - const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); - if (policyIndex > -1) { - orProperties[policyIndex].rules.push(rule); - } else { - orProperties.push({ - policyId: ids[0], - rules: [rule] - }); + function getErrorObject(code, message, lineNumber) { + return { + err: { + code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col } - } - return orProperties; + }; } - function httpAuthorizationToString(httpAuthorization) { - return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : void 0; + function validateAttrName(attrName) { + return util.isName(attrName); } - function BlobNameToString(name) { - if (name.encoded) { - return decodeURIComponent(name.content); - } else { - return name.content; - } + function validateTagName(tagname) { + return util.isName(tagname); } - function ConvertInternalResponseOfListBlobFlat(internalResponse) { - return Object.assign(Object.assign({}, internalResponse), { segment: { - blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { - const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); - return blobItem; - }) - } }); + function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; } - function ConvertInternalResponseOfListBlobHierarchy(internalResponse) { - var _a; - return Object.assign(Object.assign({}, internalResponse), { segment: { - blobPrefixes: (_a = internalResponse.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { - const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); - return blobPrefix; - }), - blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { - const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); - return blobItem; - }) - } }); + function getPositionFromMatch(match) { + return match.startIndex + match[1].length; } - function* ExtractPageRangeInfoItems(getPageRangesSegment) { - let pageRange = []; - let clearRange = []; - if (getPageRangesSegment.pageRange) - pageRange = getPageRangesSegment.pageRange; - if (getPageRangesSegment.clearRange) - clearRange = getPageRangesSegment.clearRange; - let pageRangeIndex = 0; - let clearRangeIndex = 0; - while (pageRangeIndex < pageRange.length && clearRangeIndex < clearRange.length) { - if (pageRange[pageRangeIndex].start < clearRange[clearRangeIndex].start) { - yield { - start: pageRange[pageRangeIndex].start, - end: pageRange[pageRangeIndex].end, - isClear: false - }; - ++pageRangeIndex; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js +var require_OptionsBuilder = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports2) { + var defaultOptions = { + preserveOrder: false, + attributeNamePrefix: "@_", + attributesGroupName: false, + textNodeName: "#text", + ignoreAttributes: true, + removeNSPrefix: false, + // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, + //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, + //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true + }, + tagValueProcessor: function(tagName, val2) { + return val2; + }, + attributeValueProcessor: function(attrName, val2) { + return val2; + }, + stopNodes: [], + //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: () => false, + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: function(tagName, jPath, attrs) { + return tagName; + } + // skipEmptyListItem: false + }; + var buildOptions = function(options) { + return Object.assign({}, defaultOptions, options); + }; + exports2.buildOptions = buildOptions; + exports2.defaultOptions = defaultOptions; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/xmlNode.js +var require_xmlNode = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports2, module2) { + "use strict"; + var XmlNode = class { + constructor(tagname) { + this.tagname = tagname; + this.child = []; + this[":@"] = {}; + } + add(key, val2) { + if (key === "__proto__") key = "#__proto__"; + this.child.push({ [key]: val2 }); + } + addChild(node) { + if (node.tagname === "__proto__") node.tagname = "#__proto__"; + if (node[":@"] && Object.keys(node[":@"]).length > 0) { + this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); } else { - yield { - start: clearRange[clearRangeIndex].start, - end: clearRange[clearRangeIndex].end, - isClear: true - }; - ++clearRangeIndex; + this.child.push({ [node.tagname]: node.child }); } } - for (; pageRangeIndex < pageRange.length; ++pageRangeIndex) { - yield { - start: pageRange[pageRangeIndex].start, - end: pageRange[pageRangeIndex].end, - isClear: false - }; + }; + module2.exports = XmlNode; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js +var require_DocTypeReader = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports2, module2) { + var util = require_util10(); + function readDocType(xmlData, i) { + const entities = {}; + if (xmlData[i + 3] === "O" && xmlData[i + 4] === "C" && xmlData[i + 5] === "T" && xmlData[i + 6] === "Y" && xmlData[i + 7] === "P" && xmlData[i + 8] === "E") { + i = i + 9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + for (; i < xmlData.length; i++) { + if (xmlData[i] === "<" && !comment) { + if (hasBody && isEntity(xmlData, i)) { + i += 7; + [entityName, val, i] = readEntityExp(xmlData, i + 1); + if (val.indexOf("&") === -1) + entities[validateEntityName(entityName)] = { + regx: RegExp(`&${entityName};`, "g"), + val + }; + } else if (hasBody && isElement(xmlData, i)) i += 8; + else if (hasBody && isAttlist(xmlData, i)) i += 8; + else if (hasBody && isNotation(xmlData, i)) i += 9; + else if (isComment) comment = true; + else throw new Error("Invalid DOCTYPE"); + angleBracketsCount++; + exp = ""; + } else if (xmlData[i] === ">") { + if (comment) { + if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") { + comment = false; + angleBracketsCount--; + } + } else { + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + } else if (xmlData[i] === "[") { + hasBody = true; + } else { + exp += xmlData[i]; + } + } + if (angleBracketsCount !== 0) { + throw new Error(`Unclosed DOCTYPE`); + } + } else { + throw new Error(`Invalid Tag instead of DOCTYPE`); } - for (; clearRangeIndex < clearRange.length; ++clearRangeIndex) { - yield { - start: clearRange[clearRangeIndex].start, - end: clearRange[clearRangeIndex].end, - isClear: true - }; + return { entities, i }; + } + function readEntityExp(xmlData, i) { + let entityName2 = ""; + for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"'); i++) { + entityName2 += xmlData[i]; + } + entityName2 = entityName2.trim(); + if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported"); + const startChar = xmlData[i++]; + let val2 = ""; + for (; i < xmlData.length && xmlData[i] !== startChar; i++) { + val2 += xmlData[i]; } + return [entityName2, val2, i]; } - function EscapePath(blobName) { - const split = blobName.split("/"); - for (let i = 0; i < split.length; i++) { - split[i] = encodeURIComponent(split[i]); + function isComment(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "-" && xmlData[i + 3] === "-") return true; + return false; + } + function isEntity(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "N" && xmlData[i + 4] === "T" && xmlData[i + 5] === "I" && xmlData[i + 6] === "T" && xmlData[i + 7] === "Y") return true; + return false; + } + function isElement(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "L" && xmlData[i + 4] === "E" && xmlData[i + 5] === "M" && xmlData[i + 6] === "E" && xmlData[i + 7] === "N" && xmlData[i + 8] === "T") return true; + return false; + } + function isAttlist(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "A" && xmlData[i + 3] === "T" && xmlData[i + 4] === "T" && xmlData[i + 5] === "L" && xmlData[i + 6] === "I" && xmlData[i + 7] === "S" && xmlData[i + 8] === "T") return true; + return false; + } + function isNotation(xmlData, i) { + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "N" && xmlData[i + 3] === "O" && xmlData[i + 4] === "T" && xmlData[i + 5] === "A" && xmlData[i + 6] === "T" && xmlData[i + 7] === "I" && xmlData[i + 8] === "O" && xmlData[i + 9] === "N") return true; + return false; + } + function validateEntityName(name) { + if (util.isName(name)) + return name; + else + throw new Error(`Invalid entity name ${name}`); + } + module2.exports = readDocType; + } +}); + +// node_modules/strnum/strnum.js +var require_strnum = __commonJS({ + "node_modules/strnum/strnum.js"(exports2, module2) { + var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; + var numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/; + if (!Number.parseInt && window.parseInt) { + Number.parseInt = window.parseInt; + } + if (!Number.parseFloat && window.parseFloat) { + Number.parseFloat = window.parseFloat; + } + var consider = { + hex: true, + leadingZeros: true, + decimalPoint: ".", + eNotation: true + //skipLike: /regex/ + }; + function toNumber(str2, options = {}) { + options = Object.assign({}, consider, options); + if (!str2 || typeof str2 !== "string") return str2; + let trimmedStr = str2.trim(); + if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str2; + else if (options.hex && hexRegex.test(trimmedStr)) { + return Number.parseInt(trimmedStr, 16); + } else { + const match = numRegex.exec(trimmedStr); + if (match) { + const sign = match[1]; + const leadingZeros = match[2]; + let numTrimmedByZeros = trimZeros(match[3]); + const eNotation = match[4] || match[6]; + if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str2; + else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str2; + else { + const num = Number(trimmedStr); + const numStr = "" + num; + if (numStr.search(/[eE]/) !== -1) { + if (options.eNotation) return num; + else return str2; + } else if (eNotation) { + if (options.eNotation) return num; + else return str2; + } else if (trimmedStr.indexOf(".") !== -1) { + if (numStr === "0" && numTrimmedByZeros === "") return num; + else if (numStr === numTrimmedByZeros) return num; + else if (sign && numStr === "-" + numTrimmedByZeros) return num; + else return str2; + } + if (leadingZeros) { + if (numTrimmedByZeros === numStr) return num; + else if (sign + numTrimmedByZeros === numStr) return num; + else return str2; + } + if (trimmedStr === numStr) return num; + else if (trimmedStr === sign + numStr) return num; + return str2; + } + } else { + return str2; + } } - return split.join("/"); } - function assertResponse(response) { - if (`_response` in response) { - return response; + function trimZeros(numStr) { + if (numStr && numStr.indexOf(".") !== -1) { + numStr = numStr.replace(/0+$/, ""); + if (numStr === ".") numStr = "0"; + else if (numStr[0] === ".") numStr = "0" + numStr; + else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1); + return numStr; } - throw new TypeError(`Unexpected response object ${response}`); + return numStr; } - exports2.StorageRetryPolicyType = void 0; - (function(StorageRetryPolicyType2) { - StorageRetryPolicyType2[StorageRetryPolicyType2["EXPONENTIAL"] = 0] = "EXPONENTIAL"; - StorageRetryPolicyType2[StorageRetryPolicyType2["FIXED"] = 1] = "FIXED"; - })(exports2.StorageRetryPolicyType || (exports2.StorageRetryPolicyType = {})); - var DEFAULT_RETRY_OPTIONS$1 = { - maxRetryDelayInMs: 120 * 1e3, - maxTries: 4, - retryDelayInMs: 4 * 1e3, - retryPolicyType: exports2.StorageRetryPolicyType.EXPONENTIAL, - secondaryHost: "", - tryTimeoutInMs: void 0 - // Use server side default timeout strategy - }; - var RETRY_ABORT_ERROR$1 = new abortController.AbortError("The operation was aborted."); - var StorageRetryPolicy = class extends BaseRequestPolicy { - /** - * Creates an instance of RetryPolicy. - * - * @param nextPolicy - - * @param options - - * @param retryOptions - - */ - constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS$1) { - super(nextPolicy, options); - this.retryOptions = { - retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS$1.retryPolicyType, - maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 ? Math.floor(retryOptions.maxTries) : DEFAULT_RETRY_OPTIONS$1.maxTries, - tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 ? retryOptions.tryTimeoutInMs : DEFAULT_RETRY_OPTIONS$1.tryTimeoutInMs, - retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs) : DEFAULT_RETRY_OPTIONS$1.retryDelayInMs, - maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs, - secondaryHost: retryOptions.secondaryHost ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS$1.secondaryHost + module2.exports = toNumber; + } +}); + +// node_modules/fast-xml-parser/src/ignoreAttributes.js +var require_ignoreAttributes = __commonJS({ + "node_modules/fast-xml-parser/src/ignoreAttributes.js"(exports2, module2) { + function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === "function") { + return ignoreAttributes; + } + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === "string" && attrName === pattern) { + return true; + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true; + } + } }; } - /** - * Sends request. - * - * @param request - - */ - async sendRequest(request) { - return this.attemptSendRequest(request, false, 1); + return () => false; + } + module2.exports = getIgnoreAttributesFn; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js +var require_OrderedObjParser = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports2, module2) { + "use strict"; + var util = require_util10(); + var xmlNode = require_xmlNode(); + var readDocType = require_DocTypeReader(); + var toNumber = require_strnum(); + var getIgnoreAttributesFn = require_ignoreAttributes(); + var OrderedObjParser = class { + constructor(options) { + this.options = options; + this.currentNode = null; + this.tagsNodeStack = []; + this.docTypeEntities = {}; + this.lastEntities = { + "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, + "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, + "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, + "quot": { regex: /&(quot|#34|#x22);/g, val: '"' } + }; + this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; + this.htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent": { regex: /&(cent|#162);/g, val: "\xA2" }, + "pound": { regex: /&(pound|#163);/g, val: "\xA3" }, + "yen": { regex: /&(yen|#165);/g, val: "\xA5" }, + "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" }, + "copyright": { regex: /&(copy|#169);/g, val: "\xA9" }, + "reg": { regex: /&(reg|#174);/g, val: "\xAE" }, + "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_2, str2) => String.fromCharCode(Number.parseInt(str2, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_2, str2) => String.fromCharCode(Number.parseInt(str2, 16)) } + }; + this.addExternalEntities = addExternalEntities; + this.parseXml = parseXml; + this.parseTextData = parseTextData; + this.resolveNameSpace = resolveNameSpace; + this.buildAttributesMap = buildAttributesMap; + this.isItStopNode = isItStopNode; + this.replaceEntitiesValue = replaceEntitiesValue; + this.readStopNodeData = readStopNodeData; + this.saveTextToParentTag = saveTextToParentTag; + this.addChild = addChild; + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); } - /** - * Decide and perform next retry. Won't mutate request parameter. - * - * @param request - - * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then - * the resource was not found. This may be due to replication delay. So, in this - * case, we'll never try the secondary again for this operation. - * @param attempt - How many retries has been attempted to performed, starting from 1, which includes - * the attempt will be performed by this method call. - */ - async attemptSendRequest(request, secondaryHas404, attempt) { - const newRequest = request.clone(); - const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || attempt % 2 === 1; - if (!isPrimaryRetry) { - newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); - } - if (this.retryOptions.tryTimeoutInMs) { - newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1e3).toString()); + }; + function addExternalEntities(externalEntities) { + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.lastEntities[ent] = { + regex: new RegExp("&" + ent + ";", "g"), + val: externalEntities[ent] + }; + } + } + function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { + if (val2 !== void 0) { + if (this.options.trimValues && !dontTrim) { + val2 = val2.trim(); } - let response; - try { - logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); - response = await this._nextPolicy.sendRequest(newRequest); - if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { - return response; - } - secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; - } catch (err) { - logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); - if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { - throw err; + if (val2.length > 0) { + if (!escapeEntities) val2 = this.replaceEntitiesValue(val2); + const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode); + if (newval === null || newval === void 0) { + return val2; + } else if (typeof newval !== typeof val2 || newval !== val2) { + return newval; + } else if (this.options.trimValues) { + return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); + } else { + const trimmedVal = val2.trim(); + if (trimmedVal === val2) { + return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); + } else { + return val2; + } } } - await this.delay(isPrimaryRetry, attempt, request.abortSignal); - return this.attemptSendRequest(request, secondaryHas404, ++attempt); } - /** - * Decide whether to retry according to last HTTP response and retry counters. - * - * @param isPrimaryRetry - - * @param attempt - - * @param response - - * @param err - - */ - shouldRetry(isPrimaryRetry, attempt, response, err) { - if (attempt >= this.retryOptions.maxTries) { - logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions.maxTries}, no further try.`); - return false; + } + function resolveNameSpace(tagname) { + if (this.options.removeNSPrefix) { + const tags = tagname.split(":"); + const prefix = tagname.charAt(0) === "/" ? "/" : ""; + if (tags[0] === "xmlns") { + return ""; } - const retriableErrors2 = [ - "ETIMEDOUT", - "ESOCKETTIMEDOUT", - "ECONNREFUSED", - "ECONNRESET", - "ENOENT", - "ENOTFOUND", - "TIMEOUT", - "EPIPE", - "REQUEST_SEND_ERROR" - // For default xhr based http client provided in ms-rest-js - ]; - if (err) { - for (const retriableError of retriableErrors2) { - if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || err.code && err.code.toString().toUpperCase() === retriableError) { - logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); - return true; - } - } + if (tags.length === 2) { + tagname = prefix + tags[1]; } - if (response || err) { - const statusCode = response ? response.status : err ? err.statusCode : 0; - if (!isPrimaryRetry && statusCode === 404) { - logger.info(`RetryPolicy: Secondary access with 404, will retry.`); - return true; + } + return tagname; + } + var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm"); + function buildAttributesMap(attrStr, jPath, tagName) { + if (this.options.ignoreAttributes !== true && typeof attrStr === "string") { + const matches = util.getAllMatches(attrStr, attrsRegx); + const len = matches.length; + const attrs = {}; + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + if (this.ignoreAttributesFn(attrName, jPath)) { + continue; } - if (statusCode === 503 || statusCode === 500) { - logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); - return true; + let oldVal = matches[i][4]; + let aName = this.options.attributeNamePrefix + attrName; + if (attrName.length) { + if (this.options.transformAttributeName) { + aName = this.options.transformAttributeName(aName); + } + if (aName === "__proto__") aName = "#__proto__"; + if (oldVal !== void 0) { + if (this.options.trimValues) { + oldVal = oldVal.trim(); + } + oldVal = this.replaceEntitiesValue(oldVal); + const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); + if (newVal === null || newVal === void 0) { + attrs[aName] = oldVal; + } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) { + attrs[aName] = newVal; + } else { + attrs[aName] = parseValue( + oldVal, + this.options.parseAttributeValue, + this.options.numberParseOptions + ); + } + } else if (this.options.allowBooleanAttributes) { + attrs[aName] = true; + } } } - if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith(`Error "Error: Unclosed root tag`))) { - logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; + if (!Object.keys(attrs).length) { + return; } - return false; + if (this.options.attributesGroupName) { + const attrCollection = {}; + attrCollection[this.options.attributesGroupName] = attrs; + return attrCollection; + } + return attrs; } - /** - * Delay a calculated time between retries. - * - * @param isPrimaryRetry - - * @param attempt - - * @param abortSignal - - */ - async delay(isPrimaryRetry, attempt, abortSignal) { - let delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (this.retryOptions.retryPolicyType) { - case exports2.StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); - break; - case exports2.StorageRetryPolicyType.FIXED: - delayTimeInMs = this.retryOptions.retryDelayInMs; - break; + } + var parseXml = function(xmlData) { + xmlData = xmlData.replace(/\r\n?/g, "\n"); + const xmlObj = new xmlNode("!xml"); + let currentNode = xmlObj; + let textData = ""; + let jPath = ""; + for (let i = 0; i < xmlData.length; i++) { + const ch = xmlData[i]; + if (ch === "<") { + if (xmlData[i + 1] === "/") { + const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed."); + let tagName = xmlData.substring(i + 2, closeIndex).trim(); + if (this.options.removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + } + } + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + if (currentNode) { + textData = this.saveTextToParentTag(textData, currentNode, jPath); + } + const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1); + if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) { + throw new Error(`Unpaired tag can not be used as closing tag: `); + } + let propIndex = 0; + if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) { + propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1); + this.tagsNodeStack.pop(); + } else { + propIndex = jPath.lastIndexOf("."); + } + jPath = jPath.substring(0, propIndex); + currentNode = this.tagsNodeStack.pop(); + textData = ""; + i = closeIndex; + } else if (xmlData[i + 1] === "?") { + let tagData = readTagExp(xmlData, i, false, "?>"); + if (!tagData) throw new Error("Pi Tag is not closed."); + textData = this.saveTextToParentTag(textData, currentNode, jPath); + if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) { + } else { + const childNode = new xmlNode(tagData.tagName); + childNode.add(this.options.textNodeName, ""); + if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); + } + this.addChild(currentNode, childNode, jPath); + } + i = tagData.closeIndex + 1; + } else if (xmlData.substr(i + 1, 3) === "!--") { + const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed."); + if (this.options.commentPropName) { + const comment = xmlData.substring(i + 4, endIndex - 2); + textData = this.saveTextToParentTag(textData, currentNode, jPath); + currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]); + } + i = endIndex; + } else if (xmlData.substr(i + 1, 2) === "!D") { + const result = readDocType(xmlData, i); + this.docTypeEntities = result.entities; + i = result.i; + } else if (xmlData.substr(i + 1, 2) === "![") { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; + const tagExp = xmlData.substring(i + 9, closeIndex); + textData = this.saveTextToParentTag(textData, currentNode, jPath); + let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); + if (val2 == void 0) val2 = ""; + if (this.options.cdataPropName) { + currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]); + } else { + currentNode.add(this.options.textNodeName, val2); + } + i = closeIndex + 2; + } else { + let result = readTagExp(xmlData, i, this.options.removeNSPrefix); + let tagName = result.tagName; + const rawTagName = result.rawTagName; + let tagExp = result.tagExp; + let attrExpPresent = result.attrExpPresent; + let closeIndex = result.closeIndex; + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + if (currentNode && textData) { + if (currentNode.tagname !== "!xml") { + textData = this.saveTextToParentTag(textData, currentNode, jPath, false); + } + } + const lastTag = currentNode; + if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) { + currentNode = this.tagsNodeStack.pop(); + jPath = jPath.substring(0, jPath.lastIndexOf(".")); + } + if (tagName !== xmlObj.tagname) { + jPath += jPath ? "." + tagName : tagName; + } + if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { + let tagContent = ""; + if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + } else { + tagExp = tagExp.substr(0, tagExp.length - 1); + } + i = result.closeIndex; + } else if (this.options.unpairedTags.indexOf(tagName) !== -1) { + i = result.closeIndex; + } else { + const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); + if (!result2) throw new Error(`Unexpected end of ${rawTagName}`); + i = result2.i; + tagContent = result2.tagContent; + } + const childNode = new xmlNode(tagName); + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + if (tagContent) { + tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); + } + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + childNode.add(this.options.textNodeName, tagContent); + this.addChild(currentNode, childNode, jPath); + } else { + if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + } else { + tagExp = tagExp.substr(0, tagExp.length - 1); + } + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + const childNode = new xmlNode(tagName); + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath); + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + } else { + const childNode = new xmlNode(tagName); + this.tagsNodeStack.push(currentNode); + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath); + currentNode = childNode; + } + textData = ""; + i = closeIndex; + } } } else { - delayTimeInMs = Math.random() * 1e3; + textData += xmlData[i]; } - logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); - return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR$1); } + return xmlObj.child; }; - var StorageRetryPolicyFactory = class { - /** - * Creates an instance of StorageRetryPolicyFactory. - * @param retryOptions - - */ - constructor(retryOptions) { - this.retryOptions = retryOptions; + function addChild(currentNode, childNode, jPath) { + const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]); + if (result === false) { + } else if (typeof result === "string") { + childNode.tagname = result; + currentNode.addChild(childNode); + } else { + currentNode.addChild(childNode); } - /** - * Creates a StorageRetryPolicy object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); + } + var replaceEntitiesValue = function(val2) { + if (this.options.processEntities) { + for (let entityName2 in this.docTypeEntities) { + const entity = this.docTypeEntities[entityName2]; + val2 = val2.replace(entity.regx, entity.val); + } + for (let entityName2 in this.lastEntities) { + const entity = this.lastEntities[entityName2]; + val2 = val2.replace(entity.regex, entity.val); + } + if (this.options.htmlEntities) { + for (let entityName2 in this.htmlEntities) { + const entity = this.htmlEntities[entityName2]; + val2 = val2.replace(entity.regex, entity.val); + } + } + val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val); } + return val2; }; - var CredentialPolicy = class extends BaseRequestPolicy { - /** - * Sends out request. - * - * @param request - - */ - sendRequest(request) { - return this._nextPolicy.sendRequest(this.signRequest(request)); + function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { + if (textData) { + if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0; + textData = this.parseTextData( + textData, + currentNode.tagname, + jPath, + false, + currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, + isLeafNode + ); + if (textData !== void 0 && textData !== "") + currentNode.add(this.options.textNodeName, textData); + textData = ""; } - /** - * Child classes must implement this method with request signing. This method - * will be executed in {@link sendRequest}. - * - * @param request - - */ - signRequest(request) { - return request; + return textData; + } + function isItStopNode(stopNodes, jPath, currentTagName) { + const allNodesExp = "*." + currentTagName; + for (const stopNodePath in stopNodes) { + const stopNodeExp = stopNodes[stopNodePath]; + if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true; } - }; - var table_lv0 = new Uint32Array([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1820, - 0, - 1823, - 1825, - 1827, - 1829, - 0, - 0, - 0, - 1837, - 2051, - 0, - 0, - 1843, - 0, - 3331, - 3354, - 3356, - 3358, - 3360, - 3362, - 3364, - 3366, - 3368, - 3370, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 3586, - 3593, - 3594, - 3610, - 3617, - 3619, - 3621, - 3628, - 3634, - 3637, - 3638, - 3656, - 3665, - 3696, - 3708, - 3710, - 3721, - 3722, - 3729, - 3737, - 3743, - 3746, - 3748, - 3750, - 3751, - 3753, - 0, - 0, - 0, - 1859, - 1860, - 1864, - 3586, - 3593, - 3594, - 3610, - 3617, - 3619, - 3621, - 3628, - 3634, - 3637, - 3638, - 3656, - 3665, - 3696, - 3708, - 3710, - 3721, - 3722, - 3729, - 3737, - 3743, - 3746, - 3748, - 3750, - 3751, - 3753, - 0, - 1868, - 0, - 1872, - 0 - ]); - var table_lv2 = new Uint32Array([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 18, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]); - var table_lv4 = new Uint32Array([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 32786, - 0, - 0, - 0, - 0, - 0, - 33298, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]); - function compareHeader(lhs, rhs) { - if (isLessThan(lhs, rhs)) - return -1; - return 1; + return false; } - function isLessThan(lhs, rhs) { - const tables = [table_lv0, table_lv2, table_lv4]; - let curr_level = 0; - let i = 0; - let j = 0; - while (curr_level < tables.length) { - if (curr_level === tables.length - 1 && i !== j) { - return i > j; - } - const weight1 = i < lhs.length ? tables[curr_level][lhs[i].charCodeAt(0)] : 1; - const weight2 = j < rhs.length ? tables[curr_level][rhs[j].charCodeAt(0)] : 1; - if (weight1 === 1 && weight2 === 1) { - i = 0; - j = 0; - ++curr_level; - } else if (weight1 === weight2) { - ++i; - ++j; - } else if (weight1 === 0) { - ++i; - } else if (weight2 === 0) { - ++j; - } else { - return weight1 < weight2; + function tagExpWithClosingIndex(xmlData, i, closingChar = ">") { + let attrBoundary; + let tagExp = ""; + for (let index = i; index < xmlData.length; index++) { + let ch = xmlData[index]; + if (attrBoundary) { + if (ch === attrBoundary) attrBoundary = ""; + } else if (ch === '"' || ch === "'") { + attrBoundary = ch; + } else if (ch === closingChar[0]) { + if (closingChar[1]) { + if (xmlData[index + 1] === closingChar[1]) { + return { + data: tagExp, + index + }; + } + } else { + return { + data: tagExp, + index + }; + } + } else if (ch === " ") { + ch = " "; } + tagExp += ch; } - return false; } - var StorageSharedKeyCredentialPolicy = class extends CredentialPolicy { - /** - * Creates an instance of StorageSharedKeyCredentialPolicy. - * @param nextPolicy - - * @param options - - * @param factory - - */ - constructor(nextPolicy, options, factory) { - super(nextPolicy, options); - this.factory = factory; + function findClosingIndex(xmlData, str2, i, errMsg) { + const closingIndex = xmlData.indexOf(str2, i); + if (closingIndex === -1) { + throw new Error(errMsg); + } else { + return closingIndex + str2.length - 1; } - /** - * Signs request. - * - * @param request - - */ - signRequest(request) { - request.headers.set(HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); - if (request.body && (typeof request.body === "string" || request.body !== void 0) && request.body.length > 0) { - request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") { + const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar); + if (!result) return; + let tagExp = result.data; + const closeIndex = result.index; + const separatorIndex = tagExp.search(/\s/); + let tagName = tagExp; + let attrExpPresent = true; + if (separatorIndex !== -1) { + tagName = tagExp.substring(0, separatorIndex); + tagExp = tagExp.substring(separatorIndex + 1).trimStart(); + } + const rawTagName = tagName; + if (removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + attrExpPresent = tagName !== result.data.substr(colonIndex + 1); } - const stringToSign = [ - request.method.toUpperCase(), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), - this.getHeaderValueToSign(request, HeaderConstants.DATE), - this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), - this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH), - this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), - this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), - this.getHeaderValueToSign(request, HeaderConstants.RANGE) - ].join("\n") + "\n" + this.getCanonicalizedHeadersString(request) + this.getCanonicalizedResourceString(request); - const signature = this.factory.computeHMACSHA256(stringToSign); - request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); - return request; } - /** - * Retrieve header value according to shared key sign rules. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key - * - * @param request - - * @param headerName - - */ - getHeaderValueToSign(request, headerName) { - const value = request.headers.get(headerName); - if (!value) { - return ""; + return { + tagName, + tagExp, + closeIndex, + attrExpPresent, + rawTagName + }; + } + function readStopNodeData(xmlData, tagName, i) { + const startIndex = i; + let openTagCount = 1; + for (; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + if (xmlData[i + 1] === "/") { + const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); + let closeTagName = xmlData.substring(i + 2, closeIndex).trim(); + if (closeTagName === tagName) { + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlData.substring(startIndex, i), + i: closeIndex + }; + } + } + i = closeIndex; + } else if (xmlData[i + 1] === "?") { + const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed."); + i = closeIndex; + } else if (xmlData.substr(i + 1, 3) === "!--") { + const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed."); + i = closeIndex; + } else if (xmlData.substr(i + 1, 2) === "![") { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; + i = closeIndex; + } else { + const tagData = readTagExp(xmlData, i, ">"); + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") { + openTagCount++; + } + i = tagData.closeIndex; + } + } } - if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { + } + } + function parseValue(val2, shouldParse, options) { + if (shouldParse && typeof val2 === "string") { + const newval = val2.trim(); + if (newval === "true") return true; + else if (newval === "false") return false; + else return toNumber(val2, options); + } else { + if (util.isExist(val2)) { + return val2; + } else { return ""; } - return value; } - /** - * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: - * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. - * 2. Convert each HTTP header name to lowercase. - * 3. Sort the headers lexicographically by header name, in ascending order. - * Each header may appear only once in the string. - * 4. Replace any linear whitespace in the header value with a single space. - * 5. Trim any whitespace around the colon in the header. - * 6. Finally, append a new-line character to each canonicalized header in the resulting list. - * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. - * - * @param request - - */ - getCanonicalizedHeadersString(request) { - let headersArray = request.headers.headersArray().filter((value) => { - return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); - }); - headersArray.sort((a, b) => { - return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); - }); - headersArray = headersArray.filter((value, index, array) => { - if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { - return false; + } + module2.exports = OrderedObjParser; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/node2json.js +var require_node2json = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports2) { + "use strict"; + function prettify(node, options) { + return compress(node, options); + } + function compress(arr, options, jPath) { + let text; + const compressedObj = {}; + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const property = propName(tagObj); + let newJpath = ""; + if (jPath === void 0) newJpath = property; + else newJpath = jPath + "." + property; + if (property === options.textNodeName) { + if (text === void 0) text = tagObj[property]; + else text += "" + tagObj[property]; + } else if (property === void 0) { + continue; + } else if (tagObj[property]) { + let val2 = compress(tagObj[property], options, newJpath); + const isLeaf = isLeafTag(val2, options); + if (tagObj[":@"]) { + assignAttributes(val2, tagObj[":@"], newJpath, options); + } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) { + val2 = val2[options.textNodeName]; + } else if (Object.keys(val2).length === 0) { + if (options.alwaysCreateTextNode) val2[options.textNodeName] = ""; + else val2 = ""; } - return true; - }); - let canonicalizedHeadersStringToSign = ""; - headersArray.forEach((header) => { - canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} -`; - }); - return canonicalizedHeadersStringToSign; - } - /** - * Retrieves the webResource canonicalized resource string. - * - * @param request - - */ - getCanonicalizedResourceString(request) { - const path2 = getURLPath(request.url) || "/"; - let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${this.factory.accountName}${path2}`; - const queries = getURLQueries(request.url); - const lowercaseQueries = {}; - if (queries) { - const queryKeys = []; - for (const key in queries) { - if (Object.prototype.hasOwnProperty.call(queries, key)) { - const lowercaseKey = key.toLowerCase(); - lowercaseQueries[lowercaseKey] = queries[key]; - queryKeys.push(lowercaseKey); + if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) { + if (!Array.isArray(compressedObj[property])) { + compressedObj[property] = [compressedObj[property]]; + } + compressedObj[property].push(val2); + } else { + if (options.isArray(property, newJpath, isLeaf)) { + compressedObj[property] = [val2]; + } else { + compressedObj[property] = val2; } - } - queryKeys.sort(); - for (const key of queryKeys) { - canonicalizedResourceString += ` -${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } - return canonicalizedResourceString; } - }; - var Credential = class { - /** - * Creates a RequestPolicy object. - * - * @param _nextPolicy - - * @param _options - - */ - create(_nextPolicy, _options) { - throw new Error("Method should be implemented in children classes."); + if (typeof text === "string") { + if (text.length > 0) compressedObj[options.textNodeName] = text; + } else if (text !== void 0) compressedObj[options.textNodeName] = text; + return compressedObj; + } + function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key !== ":@") return key; } - }; - var StorageSharedKeyCredential = class extends Credential { - /** - * Creates an instance of StorageSharedKeyCredential. - * @param accountName - - * @param accountKey - - */ - constructor(accountName, accountKey) { - super(); - this.accountName = accountName; - this.accountKey = Buffer.from(accountKey, "base64"); + } + function assignAttributes(obj, attrMap, jpath, options) { + if (attrMap) { + const keys = Object.keys(attrMap); + const len = keys.length; + for (let i = 0; i < len; i++) { + const atrrName = keys[i]; + if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { + obj[atrrName] = [attrMap[atrrName]]; + } else { + obj[atrrName] = attrMap[atrrName]; + } + } } - /** - * Creates a StorageSharedKeyCredentialPolicy object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); + } + function isLeafTag(obj, options) { + const { textNodeName } = options; + const propCount = Object.keys(obj).length; + if (propCount === 0) { + return true; } - /** - * Generates a hash signature for an HTTP request or for a SAS. - * - * @param stringToSign - - */ - computeHMACSHA256(stringToSign) { - return crypto.createHmac("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); + if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) { + return true; + } + return false; + } + exports2.prettify = prettify; + } +}); + +// node_modules/fast-xml-parser/src/xmlparser/XMLParser.js +var require_XMLParser = __commonJS({ + "node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports2, module2) { + var { buildOptions } = require_OptionsBuilder(); + var OrderedObjParser = require_OrderedObjParser(); + var { prettify } = require_node2json(); + var validator = require_validator(); + var XMLParser = class { + constructor(options) { + this.externalEntities = {}; + this.options = buildOptions(options); } - }; - var AnonymousCredentialPolicy = class extends CredentialPolicy { /** - * Creates an instance of AnonymousCredentialPolicy. - * @param nextPolicy - - * @param options - + * Parse XML dats to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption */ - // The base class has a protected constructor. Adding a public one to enable constructing of this class. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ - constructor(nextPolicy, options) { - super(nextPolicy, options); + parse(xmlData, validationOption) { + if (typeof xmlData === "string") { + } else if (xmlData.toString) { + xmlData = xmlData.toString(); + } else { + throw new Error("XML data is accepted in String or Bytes[] form."); + } + if (validationOption) { + if (validationOption === true) validationOption = {}; + const result = validator.validate(xmlData, validationOption); + if (result !== true) { + throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`); + } + } + const orderedObjParser = new OrderedObjParser(this.options); + orderedObjParser.addExternalEntities(this.externalEntities); + const orderedResult = orderedObjParser.parseXml(xmlData); + if (this.options.preserveOrder || orderedResult === void 0) return orderedResult; + else return prettify(orderedResult, this.options); } - }; - var AnonymousCredential = class extends Credential { /** - * Creates an {@link AnonymousCredentialPolicy} object. - * - * @param nextPolicy - - * @param options - + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value */ - create(nextPolicy, options) { - return new AnonymousCredentialPolicy(nextPolicy, options); + addEntity(key, value) { + if (value.indexOf("&") !== -1) { + throw new Error("Entity value can't have '&'"); + } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '"); + } else if (value === "&") { + throw new Error("An entity with value '&' is not permitted"); + } else { + this.externalEntities[key] = value; + } } }; - var _defaultHttpClient; - function getCachedDefaultHttpClient() { - if (!_defaultHttpClient) { - _defaultHttpClient = coreRestPipeline.createDefaultHttpClient(); + module2.exports = XMLParser; + } +}); + +// node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js +var require_orderedJs2Xml = __commonJS({ + "node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports2, module2) { + var EOL = "\n"; + function toXml(jArray, options) { + let indentation = ""; + if (options.format && options.indentBy.length > 0) { + indentation = EOL; } - return _defaultHttpClient; + return arrToStr(jArray, options, "", indentation); } - var storageBrowserPolicyName = "storageBrowserPolicy"; - function storageBrowserPolicy() { - return { - name: storageBrowserPolicyName, - async sendRequest(request, next) { - if (coreUtil.isNode) { - return next(request); - } - if (request.method === "GET" || request.method === "HEAD") { - request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); + function arrToStr(arr, options, jPath, indentation) { + let xmlStr = ""; + let isPreviousElementTag = false; + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const tagName = propName(tagObj); + if (tagName === void 0) continue; + let newJPath = ""; + if (jPath.length === 0) newJPath = tagName; + else newJPath = `${jPath}.${tagName}`; + if (tagName === options.textNodeName) { + let tagText = tagObj[tagName]; + if (!isStopNode(newJPath, options)) { + tagText = options.tagValueProcessor(tagName, tagText); + tagText = replaceEntitiesValue(tagText, options); } - request.headers.delete(HeaderConstants.COOKIE); - request.headers.delete(HeaderConstants.CONTENT_LENGTH); - return next(request); - } - }; - } - var storageRetryPolicyName = "storageRetryPolicy"; - var StorageRetryPolicyType; - (function(StorageRetryPolicyType2) { - StorageRetryPolicyType2[StorageRetryPolicyType2["EXPONENTIAL"] = 0] = "EXPONENTIAL"; - StorageRetryPolicyType2[StorageRetryPolicyType2["FIXED"] = 1] = "FIXED"; - })(StorageRetryPolicyType || (StorageRetryPolicyType = {})); - var DEFAULT_RETRY_OPTIONS = { - maxRetryDelayInMs: 120 * 1e3, - maxTries: 4, - retryDelayInMs: 4 * 1e3, - retryPolicyType: StorageRetryPolicyType.EXPONENTIAL, - secondaryHost: "", - tryTimeoutInMs: void 0 - // Use server side default timeout strategy - }; - var retriableErrors = [ - "ETIMEDOUT", - "ESOCKETTIMEDOUT", - "ECONNREFUSED", - "ECONNRESET", - "ENOENT", - "ENOTFOUND", - "TIMEOUT", - "EPIPE", - "REQUEST_SEND_ERROR" - ]; - var RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); - function storageRetryPolicy(options = {}) { - var _a, _b, _c, _d, _e, _f; - const retryPolicyType = (_a = options.retryPolicyType) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_OPTIONS.retryPolicyType; - const maxTries = (_b = options.maxTries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_OPTIONS.maxTries; - const retryDelayInMs = (_c = options.retryDelayInMs) !== null && _c !== void 0 ? _c : DEFAULT_RETRY_OPTIONS.retryDelayInMs; - const maxRetryDelayInMs = (_d = options.maxRetryDelayInMs) !== null && _d !== void 0 ? _d : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs; - const secondaryHost = (_e = options.secondaryHost) !== null && _e !== void 0 ? _e : DEFAULT_RETRY_OPTIONS.secondaryHost; - const tryTimeoutInMs = (_f = options.tryTimeoutInMs) !== null && _f !== void 0 ? _f : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs; - function shouldRetry({ isPrimaryRetry, attempt, response, error: error4 }) { - var _a2, _b2; - if (attempt >= maxTries) { - logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`); - return false; - } - if (error4) { - for (const retriableError of retriableErrors) { - if (error4.name.toUpperCase().includes(retriableError) || error4.message.toUpperCase().includes(retriableError) || error4.code && error4.code.toString().toUpperCase() === retriableError) { - logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); - return true; - } + if (isPreviousElementTag) { + xmlStr += indentation; } - if ((error4 === null || error4 === void 0 ? void 0 : error4.code) === "PARSE_ERROR" && (error4 === null || error4 === void 0 ? void 0 : error4.message.startsWith(`Error "Error: Unclosed root tag`))) { - logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; + xmlStr += tagText; + isPreviousElementTag = false; + continue; + } else if (tagName === options.cdataPropName) { + if (isPreviousElementTag) { + xmlStr += indentation; } + xmlStr += ``; + isPreviousElementTag = false; + continue; + } else if (tagName === options.commentPropName) { + xmlStr += indentation + ``; + isPreviousElementTag = true; + continue; + } else if (tagName[0] === "?") { + const attStr2 = attr_to_str(tagObj[":@"], options); + const tempInd = tagName === "?xml" ? "" : indentation; + let piTextNodeName = tagObj[tagName][0][options.textNodeName]; + piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; + xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`; + isPreviousElementTag = true; + continue; } - if (response || error4) { - const statusCode = (_b2 = (_a2 = response === null || response === void 0 ? void 0 : response.status) !== null && _a2 !== void 0 ? _a2 : error4 === null || error4 === void 0 ? void 0 : error4.statusCode) !== null && _b2 !== void 0 ? _b2 : 0; - if (!isPrimaryRetry && statusCode === 404) { - logger.info(`RetryPolicy: Secondary access with 404, will retry.`); - return true; - } - if (statusCode === 503 || statusCode === 500) { - logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); - return true; - } + let newIdentation = indentation; + if (newIdentation !== "") { + newIdentation += options.indentBy; } - return false; - } - function calculateDelay(isPrimaryRetry, attempt) { - let delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (retryPolicyType) { - case StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs); - break; - case StorageRetryPolicyType.FIXED: - delayTimeInMs = retryDelayInMs; - break; - } + const attStr = attr_to_str(tagObj[":@"], options); + const tagStart = indentation + `<${tagName}${attStr}`; + const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); + if (options.unpairedTags.indexOf(tagName) !== -1) { + if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; + else xmlStr += tagStart + "/>"; + } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { + xmlStr += tagStart + "/>"; + } else if (tagValue && tagValue.endsWith(">")) { + xmlStr += tagStart + `>${tagValue}${indentation}`; } else { - delayTimeInMs = Math.random() * 1e3; - } - logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); - return delayTimeInMs; - } - return { - name: storageRetryPolicyName, - async sendRequest(request, next) { - if (tryTimeoutInMs) { - request.url = setURLParameter(request.url, URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1e3))); - } - const primaryUrl = request.url; - const secondaryUrl = secondaryHost ? setURLHost(request.url, secondaryHost) : void 0; - let secondaryHas404 = false; - let attempt = 1; - let retryAgain = true; - let response; - let error4; - while (retryAgain) { - const isPrimaryRetry = secondaryHas404 || !secondaryUrl || !["GET", "HEAD", "OPTIONS"].includes(request.method) || attempt % 2 === 1; - request.url = isPrimaryRetry ? primaryUrl : secondaryUrl; - response = void 0; - error4 = void 0; - try { - logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); - response = await next(request); - secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; - } catch (e) { - if (coreRestPipeline.isRestError(e)) { - logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`); - error4 = e; - } else { - logger.error(`RetryPolicy: Caught error, message: ${coreUtil.getErrorMessage(e)}`); - throw e; - } - } - retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error: error4 }); - if (retryAgain) { - await delay(calculateDelay(isPrimaryRetry, attempt), request.abortSignal, RETRY_ABORT_ERROR); - } - attempt++; - } - if (response) { - return response; + xmlStr += tagStart + ">"; + if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes(" 0) { - request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); - } - const stringToSign = [ - request.method.toUpperCase(), - getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), - getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), - getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), - getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), - getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), - getHeaderValueToSign(request, HeaderConstants.DATE), - getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), - getHeaderValueToSign(request, HeaderConstants.IF_MATCH), - getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), - getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), - getHeaderValueToSign(request, HeaderConstants.RANGE) - ].join("\n") + "\n" + getCanonicalizedHeadersString(request) + getCanonicalizedResourceString(request); - const signature = crypto.createHmac("sha256", options.accountKey).update(stringToSign, "utf8").digest("base64"); - request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`); - } - function getHeaderValueToSign(request, headerName) { - const value = request.headers.get(headerName); - if (!value) { - return ""; - } - if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { - return ""; + xmlStr += ``; } - return value; + isPreviousElementTag = true; } - function getCanonicalizedHeadersString(request) { - let headersArray = []; - for (const [name, value] of request.headers) { - if (name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE)) { - headersArray.push({ name, value }); - } - } - headersArray.sort((a, b) => { - return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); - }); - headersArray = headersArray.filter((value, index, array) => { - if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { - return false; - } - return true; - }); - let canonicalizedHeadersStringToSign = ""; - headersArray.forEach((header) => { - canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} -`; - }); - return canonicalizedHeadersStringToSign; + return xmlStr; + } + function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (!obj.hasOwnProperty(key)) continue; + if (key !== ":@") return key; } - function getCanonicalizedResourceString(request) { - const path2 = getURLPath(request.url) || "/"; - let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${options.accountName}${path2}`; - const queries = getURLQueries(request.url); - const lowercaseQueries = {}; - if (queries) { - const queryKeys = []; - for (const key in queries) { - if (Object.prototype.hasOwnProperty.call(queries, key)) { - const lowercaseKey = key.toLowerCase(); - lowercaseQueries[lowercaseKey] = queries[key]; - queryKeys.push(lowercaseKey); - } - } - queryKeys.sort(); - for (const key of queryKeys) { - canonicalizedResourceString += ` -${key}:${decodeURIComponent(lowercaseQueries[key])}`; + } + function attr_to_str(attrMap, options) { + let attrStr = ""; + if (attrMap && !options.ignoreAttributes) { + for (let attr in attrMap) { + if (!attrMap.hasOwnProperty(attr)) continue; + let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); + attrVal = replaceEntitiesValue(attrVal, options); + if (attrVal === true && options.suppressBooleanAttributes) { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; + } else { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; } } - return canonicalizedResourceString; } - return { - name: storageSharedKeyCredentialPolicyName, - async sendRequest(request, next) { - signRequest(request); - return next(request); - } - }; + return attrStr; } - var StorageBrowserPolicy = class extends BaseRequestPolicy { - /** - * Creates an instance of StorageBrowserPolicy. - * @param nextPolicy - - * @param options - - */ - // The base class has a protected constructor. Adding a public one to enable constructing of this class. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ - constructor(nextPolicy, options) { - super(nextPolicy, options); - } - /** - * Sends out request. - * - * @param request - - */ - async sendRequest(request) { - if (coreUtil.isNode) { - return this._nextPolicy.sendRequest(request); - } - if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { - request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); - } - request.headers.remove(HeaderConstants.COOKIE); - request.headers.remove(HeaderConstants.CONTENT_LENGTH); - return this._nextPolicy.sendRequest(request); - } - }; - var StorageBrowserPolicyFactory = class { - /** - * Creates a StorageBrowserPolicyFactory object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageBrowserPolicy(nextPolicy, options); - } - }; - var storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy"; - function storageCorrectContentLengthPolicy() { - function correctContentLength(request) { - if (request.body && (typeof request.body === "string" || Buffer.isBuffer(request.body)) && request.body.length > 0) { - request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); - } + function isStopNode(jPath, options) { + jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); + let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); + for (let index in options.stopNodes) { + if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; } - return { - name: storageCorrectContentLengthPolicyName, - async sendRequest(request, next) { - correctContentLength(request); - return next(request); - } - }; + return false; } - function isPipelineLike(pipeline) { - if (!pipeline || typeof pipeline !== "object") { - return false; + function replaceEntitiesValue(textValue, options) { + if (textValue && textValue.length > 0 && options.processEntities) { + for (let i = 0; i < options.entities.length; i++) { + const entity = options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } } - const castPipeline = pipeline; - return Array.isArray(castPipeline.factories) && typeof castPipeline.options === "object" && typeof castPipeline.toServiceClientOptions === "function"; + return textValue; } - var Pipeline = class { - /** - * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. - * - * @param factories - - * @param options - - */ - constructor(factories, options = {}) { - this.factories = factories; - this.options = options; - } - /** - * Transfer Pipeline object to ServiceClientOptions object which is required by - * ServiceClient constructor. - * - * @returns The ServiceClientOptions object from this Pipeline. - */ - toServiceClientOptions() { - return { - httpClient: this.options.httpClient, - requestPolicyFactories: this.factories + module2.exports = toXml; + } +}); + +// node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js +var require_json2xml = __commonJS({ + "node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports2, module2) { + "use strict"; + var buildFromOrderedJs = require_orderedJs2Xml(); + var getIgnoreAttributesFn = require_ignoreAttributes(); + var defaultOptions = { + attributeNamePrefix: "@_", + attributesGroupName: false, + textNodeName: "#text", + ignoreAttributes: true, + cdataPropName: false, + format: false, + indentBy: " ", + suppressEmptyNode: false, + suppressUnpairedNode: true, + suppressBooleanAttributes: true, + tagValueProcessor: function(key, a) { + return a; + }, + attributeValueProcessor: function(attrName, a) { + return a; + }, + preserveOrder: false, + commentPropName: false, + unpairedTags: [], + entities: [ + { regex: new RegExp("&", "g"), val: "&" }, + //it must be on top + { regex: new RegExp(">", "g"), val: ">" }, + { regex: new RegExp("<", "g"), val: "<" }, + { regex: new RegExp("'", "g"), val: "'" }, + { regex: new RegExp('"', "g"), val: """ } + ], + processEntities: true, + stopNodes: [], + // transformTagName: false, + // transformAttributeName: false, + oneListGroup: false + }; + function Builder(options) { + this.options = Object.assign({}, defaultOptions, options); + if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { + this.isAttribute = function() { + return false; }; + } else { + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); + this.attrPrefixLen = this.options.attributeNamePrefix.length; + this.isAttribute = isAttribute; } - }; - function newPipeline(credential, pipelineOptions = {}) { - if (!credential) { - credential = new AnonymousCredential(); + this.processTextOrObjNode = processTextOrObjNode; + if (this.options.format) { + this.indentate = indentate; + this.tagEndChar = ">\n"; + this.newLine = "\n"; + } else { + this.indentate = function() { + return ""; + }; + this.tagEndChar = ">"; + this.newLine = ""; } - const pipeline = new Pipeline([], pipelineOptions); - pipeline._credential = credential; - return pipeline; } - function processDownlevelPipeline(pipeline) { - const knownFactoryFunctions = [ - isAnonymousCredential, - isStorageSharedKeyCredential, - isCoreHttpBearerTokenFactory, - isStorageBrowserPolicyFactory, - isStorageRetryPolicyFactory, - isStorageTelemetryPolicyFactory, - isCoreHttpPolicyFactory - ]; - if (pipeline.factories.length) { - const novelFactories = pipeline.factories.filter((factory) => { - return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory)); - }); - if (novelFactories.length) { - const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory)); - return { - wrappedPolicies: coreHttpCompat.createRequestPolicyFactoryPolicy(novelFactories), - afterRetry: hasInjector + Builder.prototype.build = function(jObj) { + if (this.options.preserveOrder) { + return buildFromOrderedJs(jObj, this.options); + } else { + if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) { + jObj = { + [this.options.arrayNodeName]: jObj }; } + return this.j2x(jObj, 0, []).val; } - return void 0; - } - function getCoreClientOptions(pipeline) { - var _a; - const _b = pipeline.options, { httpClient: v1Client } = _b, restOptions = tslib.__rest(_b, ["httpClient"]); - let httpClient = pipeline._coreHttpClient; - if (!httpClient) { - httpClient = v1Client ? coreHttpCompat.convertHttpClient(v1Client) : getCachedDefaultHttpClient(); - pipeline._coreHttpClient = httpClient; - } - let corePipeline = pipeline._corePipeline; - if (!corePipeline) { - const packageDetails = `azsdk-js-azure-storage-blob/${SDK_VERSION}`; - const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; - corePipeline = coreClient.createClientPipeline(Object.assign(Object.assign({}, restOptions), { loggingOptions: { - additionalAllowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, - additionalAllowedQueryParameters: StorageBlobLoggingAllowedQueryParameters, - logger: logger.info - }, userAgentOptions: { - userAgentPrefix - }, serializationOptions: { - stringifyXML: coreXml.stringifyXML, - serializerOptions: { - xml: { - // Use customized XML char key of "#" so we can deserialize metadata - // with "_" key - xmlCharKey: "#" + }; + Builder.prototype.j2x = function(jObj, level, ajPath) { + let attrStr = ""; + let val2 = ""; + const jPath = ajPath.join("."); + for (let key in jObj) { + if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue; + if (typeof jObj[key] === "undefined") { + if (this.isAttribute(key)) { + val2 += ""; + } + } else if (jObj[key] === null) { + if (this.isAttribute(key)) { + val2 += ""; + } else if (key[0] === "?") { + val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; + } else { + val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; + } + } else if (jObj[key] instanceof Date) { + val2 += this.buildTextValNode(jObj[key], key, "", level); + } else if (typeof jObj[key] !== "object") { + const attr = this.isAttribute(key); + if (attr && !this.ignoreAttributesFn(attr, jPath)) { + attrStr += this.buildAttrPairStr(attr, "" + jObj[key]); + } else if (!attr) { + if (key === this.options.textNodeName) { + let newval = this.options.tagValueProcessor(key, "" + jObj[key]); + val2 += this.replaceEntitiesValue(newval); + } else { + val2 += this.buildTextValNode(jObj[key], key, "", level); } } - }, deserializationOptions: { - parseXML: coreXml.parseXML, - serializerOptions: { - xml: { - // Use customized XML char key of "#" so we can deserialize metadata - // with "_" key - xmlCharKey: "#" + } else if (Array.isArray(jObj[key])) { + const arrLen = jObj[key].length; + let listTagVal = ""; + let listTagAttr = ""; + for (let j = 0; j < arrLen; j++) { + const item = jObj[key][j]; + if (typeof item === "undefined") { + } else if (item === null) { + if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; + else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; + } else if (typeof item === "object") { + if (this.options.oneListGroup) { + const result = this.j2x(item, level + 1, ajPath.concat(key)); + listTagVal += result.val; + if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { + listTagAttr += result.attrStr; + } + } else { + listTagVal += this.processTextOrObjNode(item, key, level, ajPath); + } + } else { + if (this.options.oneListGroup) { + let textValue = this.options.tagValueProcessor(key, item); + textValue = this.replaceEntitiesValue(textValue); + listTagVal += textValue; + } else { + listTagVal += this.buildTextValNode(item, key, "", level); + } } } - } })); - corePipeline.removePolicy({ phase: "Retry" }); - corePipeline.removePolicy({ name: coreRestPipeline.decompressResponsePolicyName }); - corePipeline.addPolicy(storageCorrectContentLengthPolicy()); - corePipeline.addPolicy(storageRetryPolicy(restOptions.retryOptions), { phase: "Retry" }); - corePipeline.addPolicy(storageBrowserPolicy()); - const downlevelResults = processDownlevelPipeline(pipeline); - if (downlevelResults) { - corePipeline.addPolicy(downlevelResults.wrappedPolicies, downlevelResults.afterRetry ? { afterPhase: "Retry" } : void 0); - } - const credential = getCredentialFromPipeline(pipeline); - if (coreAuth.isTokenCredential(credential)) { - corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ - credential, - scopes: (_a = restOptions.audience) !== null && _a !== void 0 ? _a : StorageOAuthScopes, - challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge } - }), { phase: "Sign" }); - } else if (credential instanceof StorageSharedKeyCredential) { - corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ - accountName: credential.accountName, - accountKey: credential.accountKey - }), { phase: "Sign" }); + if (this.options.oneListGroup) { + listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); + } + val2 += listTagVal; + } else { + if (this.options.attributesGroupName && key === this.options.attributesGroupName) { + const Ks = Object.keys(jObj[key]); + const L = Ks.length; + for (let j = 0; j < L; j++) { + attrStr += this.buildAttrPairStr(Ks[j], "" + jObj[key][Ks[j]]); + } + } else { + val2 += this.processTextOrObjNode(jObj[key], key, level, ajPath); + } } - pipeline._corePipeline = corePipeline; } - return Object.assign(Object.assign({}, restOptions), { allowInsecureConnection: true, httpClient, pipeline: corePipeline }); + return { attrStr, val: val2 }; + }; + Builder.prototype.buildAttrPairStr = function(attrName, val2) { + val2 = this.options.attributeValueProcessor(attrName, "" + val2); + val2 = this.replaceEntitiesValue(val2); + if (this.options.suppressBooleanAttributes && val2 === "true") { + return " " + attrName; + } else return " " + attrName + '="' + val2 + '"'; + }; + function processTextOrObjNode(object, key, level, ajPath) { + const result = this.j2x(object, level + 1, ajPath.concat(key)); + if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) { + return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); + } else { + return this.buildObjectNode(result.val, key, result.attrStr, level); + } } - function getCredentialFromPipeline(pipeline) { - if (pipeline._credential) { - return pipeline._credential; + Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) { + if (val2 === "") { + if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; + else { + return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; + } + } else { + let tagEndExp = "" + val2 + tagEndExp; + } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { + return this.indentate(level) + `` + this.newLine; + } else { + return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp; + } } - let credential = new AnonymousCredential(); - for (const factory of pipeline.factories) { - if (coreAuth.isTokenCredential(factory.credential)) { - credential = factory.credential; - } else if (isStorageSharedKeyCredential(factory)) { - return factory; + }; + Builder.prototype.closeTag = function(key) { + let closeTag = ""; + if (this.options.unpairedTags.indexOf(key) !== -1) { + if (!this.options.suppressUnpairedNode) closeTag = "/"; + } else if (this.options.suppressEmptyNode) { + closeTag = "/"; + } else { + closeTag = `>` + this.newLine; + } else if (this.options.commentPropName !== false && key === this.options.commentPropName) { + return this.indentate(level) + `` + this.newLine; + } else if (key[0] === "?") { + return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; + } else { + let textValue = this.options.tagValueProcessor(key, val2); + textValue = this.replaceEntitiesValue(textValue); + if (textValue === "") { + return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; + } else { + return this.indentate(level) + "<" + key + attrStr + ">" + textValue + " 0 && this.options.processEntities) { + for (let i = 0; i < this.options.entities.length; i++) { + const entity = this.options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } } - return factory.constructor.name === "StorageSharedKeyCredential"; + return textValue; + }; + function indentate(level) { + return this.options.indentBy.repeat(level); } - function isAnonymousCredential(factory) { - if (factory instanceof AnonymousCredential) { - return true; + function isAttribute(name) { + if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) { + return name.substr(this.attrPrefixLen); + } else { + return false; } - return factory.constructor.name === "AnonymousCredential"; - } - function isCoreHttpBearerTokenFactory(factory) { - return coreAuth.isTokenCredential(factory.credential); } - function isStorageBrowserPolicyFactory(factory) { - if (factory instanceof StorageBrowserPolicyFactory) { - return true; - } - return factory.constructor.name === "StorageBrowserPolicyFactory"; + module2.exports = Builder; + } +}); + +// node_modules/fast-xml-parser/src/fxp.js +var require_fxp = __commonJS({ + "node_modules/fast-xml-parser/src/fxp.js"(exports2, module2) { + "use strict"; + var validator = require_validator(); + var XMLParser = require_XMLParser(); + var XMLBuilder = require_json2xml(); + module2.exports = { + XMLParser, + XMLValidator: validator, + XMLBuilder + }; + } +}); + +// node_modules/@azure/core-xml/dist/commonjs/xml.common.js +var require_xml_common = __commonJS({ + "node_modules/@azure/core-xml/dist/commonjs/xml.common.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.XML_CHARKEY = exports2.XML_ATTRKEY = void 0; + exports2.XML_ATTRKEY = "$"; + exports2.XML_CHARKEY = "_"; + } +}); + +// node_modules/@azure/core-xml/dist/commonjs/xml.js +var require_xml = __commonJS({ + "node_modules/@azure/core-xml/dist/commonjs/xml.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stringifyXML = stringifyXML; + exports2.parseXML = parseXML; + var fast_xml_parser_1 = require_fxp(); + var xml_common_js_1 = require_xml_common(); + function getCommonOptions(options) { + var _a; + return { + attributesGroupName: xml_common_js_1.XML_ATTRKEY, + textNodeName: (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : xml_common_js_1.XML_CHARKEY, + ignoreAttributes: false, + suppressBooleanAttributes: false + }; } - function isStorageRetryPolicyFactory(factory) { - if (factory instanceof StorageRetryPolicyFactory) { - return true; - } - return factory.constructor.name === "StorageRetryPolicyFactory"; + function getSerializerOptions(options = {}) { + var _a, _b; + return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" }); } - function isStorageTelemetryPolicyFactory(factory) { - return factory.constructor.name === "TelemetryPolicyFactory"; + function getParserOptions(options = {}) { + return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true }); } - function isInjectorPolicyFactory(factory) { - return factory.constructor.name === "InjectorPolicyFactory"; + function stringifyXML(obj, opts = {}) { + const parserOptions = getSerializerOptions(opts); + const j2x = new fast_xml_parser_1.XMLBuilder(parserOptions); + const node = { [parserOptions.rootNodeName]: obj }; + const xmlData = j2x.build(node); + return `${xmlData}`.replace(/\n/g, ""); } - function isCoreHttpPolicyFactory(factory) { - const knownPolicies = [ - "GenerateClientRequestIdPolicy", - "TracingPolicy", - "LogPolicy", - "ProxyPolicy", - "DisableResponseDecompressionPolicy", - "KeepAlivePolicy", - "DeserializationPolicy" - ]; - const mockHttpClient = { - sendRequest: async (request) => { - return { - request, - headers: request.headers.clone(), - status: 500 - }; - } - }; - const mockRequestPolicyOptions = { - log(_logLevel, _message) { - }, - shouldLog(_logLevel) { - return false; + async function parseXML(str2, opts = {}) { + if (!str2) { + throw new Error("Document is empty"); + } + const validation = fast_xml_parser_1.XMLValidator.validate(str2); + if (validation !== true) { + throw validation; + } + const parser = new fast_xml_parser_1.XMLParser(getParserOptions(opts)); + const parsedXml = parser.parse(str2); + if (parsedXml["?xml"]) { + delete parsedXml["?xml"]; + } + if (!opts.includeRoot) { + for (const key of Object.keys(parsedXml)) { + const value = parsedXml[key]; + return typeof value === "object" ? Object.assign({}, value) : value; } - }; - const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions); - const policyName = policyInstance.constructor.name; - return knownPolicies.some((knownPolicyName) => { - return policyName.startsWith(knownPolicyName); - }); + } + return parsedXml; } - var BlobServiceProperties = { - serializedName: "BlobServiceProperties", - xmlName: "StorageServiceProperties", - type: { - name: "Composite", - className: "BlobServiceProperties", - modelProperties: { - blobAnalyticsLogging: { - serializedName: "Logging", - xmlName: "Logging", - type: { - name: "Composite", - className: "Logging" - } - }, - hourMetrics: { - serializedName: "HourMetrics", - xmlName: "HourMetrics", - type: { - name: "Composite", - className: "Metrics" - } - }, - minuteMetrics: { - serializedName: "MinuteMetrics", - xmlName: "MinuteMetrics", - type: { - name: "Composite", - className: "Metrics" - } - }, - cors: { - serializedName: "Cors", - xmlName: "Cors", - xmlIsWrapped: true, - xmlElementName: "CorsRule", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "CorsRule" - } - } - } - }, - defaultServiceVersion: { - serializedName: "DefaultServiceVersion", - xmlName: "DefaultServiceVersion", - type: { - name: "String" - } - }, - deleteRetentionPolicy: { - serializedName: "DeleteRetentionPolicy", - xmlName: "DeleteRetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy" - } - }, - staticWebsite: { - serializedName: "StaticWebsite", - xmlName: "StaticWebsite", - type: { - name: "Composite", - className: "StaticWebsite" - } - } - } + } +}); + +// node_modules/@azure/core-xml/dist/commonjs/index.js +var require_commonjs11 = __commonJS({ + "node_modules/@azure/core-xml/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.XML_CHARKEY = exports2.XML_ATTRKEY = exports2.parseXML = exports2.stringifyXML = void 0; + var xml_js_1 = require_xml(); + Object.defineProperty(exports2, "stringifyXML", { enumerable: true, get: function() { + return xml_js_1.stringifyXML; + } }); + Object.defineProperty(exports2, "parseXML", { enumerable: true, get: function() { + return xml_js_1.parseXML; + } }); + var xml_common_js_1 = require_xml_common(); + Object.defineProperty(exports2, "XML_ATTRKEY", { enumerable: true, get: function() { + return xml_common_js_1.XML_ATTRKEY; + } }); + Object.defineProperty(exports2, "XML_CHARKEY", { enumerable: true, get: function() { + return xml_common_js_1.XML_CHARKEY; + } }); + } +}); + +// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js +var require_AbortError3 = __commonJS({ + "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } }; - var Logging = { - serializedName: "Logging", - type: { - name: "Composite", - className: "Logging", - modelProperties: { - version: { - serializedName: "Version", - required: true, - xmlName: "Version", - type: { - name: "String" - } - }, - deleteProperty: { - serializedName: "Delete", - required: true, - xmlName: "Delete", - type: { - name: "Boolean" - } - }, - read: { - serializedName: "Read", - required: true, - xmlName: "Read", - type: { - name: "Boolean" - } - }, - write: { - serializedName: "Write", - required: true, - xmlName: "Write", - type: { - name: "Boolean" - } - }, - retentionPolicy: { - serializedName: "RetentionPolicy", - xmlName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy" - } - } - } + exports2.AbortError = AbortError; + } +}); + +// node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js +var require_commonjs12 = __commonJS({ + "node_modules/@azure/storage-blob/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbortError = void 0; + var AbortError_js_1 = require_AbortError3(); + Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() { + return AbortError_js_1.AbortError; + } }); + } +}); + +// node_modules/@azure/abort-controller/dist/index.js +var require_dist5 = __commonJS({ + "node_modules/@azure/abort-controller/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var listenersMap = /* @__PURE__ */ new WeakMap(); + var abortedMap = /* @__PURE__ */ new WeakMap(); + var AbortSignal2 = class _AbortSignal { + constructor() { + this.onabort = null; + listenersMap.set(this, []); + abortedMap.set(this, false); } - }; - var RetentionPolicy = { - serializedName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy", - modelProperties: { - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", - type: { - name: "Boolean" - } - }, - days: { - constraints: { - InclusiveMinimum: 1 - }, - serializedName: "Days", - xmlName: "Days", - type: { - name: "Number" - } - } + /** + * Status of whether aborted or not. + * + * @readonly + */ + get aborted() { + if (!abortedMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); } + return abortedMap.get(this); } - }; - var Metrics = { - serializedName: "Metrics", - type: { - name: "Composite", - className: "Metrics", - modelProperties: { - version: { - serializedName: "Version", - xmlName: "Version", - type: { - name: "String" - } - }, - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", - type: { - name: "Boolean" - } - }, - includeAPIs: { - serializedName: "IncludeAPIs", - xmlName: "IncludeAPIs", - type: { - name: "Boolean" - } - }, - retentionPolicy: { - serializedName: "RetentionPolicy", - xmlName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy" - } - } + /** + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly + */ + static get none() { + return new _AbortSignal(); + } + /** + * Added new "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be added + */ + addEventListener(_type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); } + const listeners = listenersMap.get(this); + listeners.push(listener); } - }; - var CorsRule = { - serializedName: "CorsRule", - type: { - name: "Composite", - className: "CorsRule", - modelProperties: { - allowedOrigins: { - serializedName: "AllowedOrigins", - required: true, - xmlName: "AllowedOrigins", - type: { - name: "String" - } - }, - allowedMethods: { - serializedName: "AllowedMethods", - required: true, - xmlName: "AllowedMethods", - type: { - name: "String" - } - }, - allowedHeaders: { - serializedName: "AllowedHeaders", - required: true, - xmlName: "AllowedHeaders", - type: { - name: "String" - } - }, - exposedHeaders: { - serializedName: "ExposedHeaders", - required: true, - xmlName: "ExposedHeaders", - type: { - name: "String" - } - }, - maxAgeInSeconds: { - constraints: { - InclusiveMinimum: 0 - }, - serializedName: "MaxAgeInSeconds", - required: true, - xmlName: "MaxAgeInSeconds", - type: { - name: "Number" - } - } + /** + * Remove "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be removed + */ + removeEventListener(_type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + const listeners = listenersMap.get(this); + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); } } + /** + * Dispatches a synthetic event to the AbortSignal. + */ + dispatchEvent(_event) { + throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); + } }; - var StaticWebsite = { - serializedName: "StaticWebsite", - type: { - name: "Composite", - className: "StaticWebsite", - modelProperties: { - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", - type: { - name: "Boolean" - } - }, - indexDocument: { - serializedName: "IndexDocument", - xmlName: "IndexDocument", - type: { - name: "String" - } - }, - errorDocument404Path: { - serializedName: "ErrorDocument404Path", - xmlName: "ErrorDocument404Path", - type: { - name: "String" - } - }, - defaultIndexDocumentPath: { - serializedName: "DefaultIndexDocumentPath", - xmlName: "DefaultIndexDocumentPath", - type: { - name: "String" - } - } - } + function abortSignal(signal) { + if (signal.aborted) { + return; + } + if (signal.onabort) { + signal.onabort.call(signal); + } + const listeners = listenersMap.get(signal); + if (listeners) { + listeners.slice().forEach((listener) => { + listener.call(signal, { type: "abort" }); + }); + } + abortedMap.set(signal, true); + } + var AbortError = class extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } }; - var StorageError = { - serializedName: "StorageError", - type: { - name: "Composite", - className: "StorageError", - modelProperties: { - message: { - serializedName: "Message", - xmlName: "Message", - type: { - name: "String" - } - }, - code: { - serializedName: "Code", - xmlName: "Code", - type: { - name: "String" - } - }, - authenticationErrorDetail: { - serializedName: "AuthenticationErrorDetail", - xmlName: "AuthenticationErrorDetail", - type: { - name: "String" - } + var AbortController2 = class { + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + constructor(parentSignals) { + this._signal = new AbortSignal2(); + if (!parentSignals) { + return; + } + if (!Array.isArray(parentSignals)) { + parentSignals = arguments; + } + for (const parentSignal of parentSignals) { + if (parentSignal.aborted) { + this.abort(); + } else { + parentSignal.addEventListener("abort", () => { + this.abort(); + }); } } } - }; - var BlobServiceStatistics = { - serializedName: "BlobServiceStatistics", - xmlName: "StorageServiceStats", - type: { - name: "Composite", - className: "BlobServiceStatistics", - modelProperties: { - geoReplication: { - serializedName: "GeoReplication", - xmlName: "GeoReplication", - type: { - name: "Composite", - className: "GeoReplication" - } - } + /** + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + */ + get signal() { + return this._signal; + } + /** + * Signal that any operations passed this controller's associated abort signal + * to cancel any remaining work and throw an `AbortError`. + */ + abort() { + abortSignal(this._signal); + } + /** + * Creates a new AbortSignal instance that will abort after the provided ms. + * @param ms - Elapsed time in milliseconds to trigger an abort. + */ + static timeout(ms) { + const signal = new AbortSignal2(); + const timer = setTimeout(abortSignal, ms, signal); + if (typeof timer.unref === "function") { + timer.unref(); } + return signal; } }; - var GeoReplication = { - serializedName: "GeoReplication", - type: { - name: "Composite", - className: "GeoReplication", - modelProperties: { - status: { - serializedName: "Status", - required: true, - xmlName: "Status", - type: { - name: "Enum", - allowedValues: ["live", "bootstrap", "unavailable"] - } - }, - lastSyncOn: { - serializedName: "LastSyncTime", - required: true, - xmlName: "LastSyncTime", - type: { - name: "DateTimeRfc1123" - } - } + exports2.AbortController = AbortController2; + exports2.AbortError = AbortError; + exports2.AbortSignal = AbortSignal2; + } +}); + +// node_modules/@azure/core-lro/dist/index.js +var require_dist6 = __commonJS({ + "node_modules/@azure/core-lro/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var logger$1 = require_dist(); + var abortController = require_dist5(); + var coreUtil = require_commonjs4(); + var logger = logger$1.createClientLogger("core-lro"); + var POLL_INTERVAL_IN_MS = 2e3; + var terminalStates = ["succeeded", "canceled", "failed"]; + function deserializeState(serializedState) { + try { + return JSON.parse(serializedState).state; + } catch (e) { + throw new Error(`Unable to deserialize input state: ${serializedState}`); + } + } + function setStateError(inputs) { + const { state, stateProxy, isOperationError: isOperationError2 } = inputs; + return (error4) => { + if (isOperationError2(error4)) { + stateProxy.setError(state, error4); + stateProxy.setFailed(state); } + throw error4; + }; + } + function appendReadableErrorMessage(currentMessage, innerMessage) { + let message = currentMessage; + if (message.slice(-1) !== ".") { + message = message + "."; } - }; - var ListContainersSegmentResponse = { - serializedName: "ListContainersSegmentResponse", - xmlName: "EnumerationResults", - type: { - name: "Composite", - className: "ListContainersSegmentResponse", - modelProperties: { - serviceEndpoint: { - serializedName: "ServiceEndpoint", - required: true, - xmlName: "ServiceEndpoint", - xmlIsAttribute: true, - type: { - name: "String" - } - }, - prefix: { - serializedName: "Prefix", - xmlName: "Prefix", - type: { - name: "String" - } - }, - marker: { - serializedName: "Marker", - xmlName: "Marker", - type: { - name: "String" - } - }, - maxPageSize: { - serializedName: "MaxResults", - xmlName: "MaxResults", - type: { - name: "Number" - } - }, - containerItems: { - serializedName: "ContainerItems", - required: true, - xmlName: "Containers", - xmlIsWrapped: true, - xmlElementName: "Container", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "ContainerItem" - } - } - } - }, - continuationToken: { - serializedName: "NextMarker", - xmlName: "NextMarker", - type: { - name: "String" - } - } - } + return message + " " + innerMessage; + } + function simplifyError(err) { + let message = err.message; + let code = err.code; + let curErr = err; + while (curErr.innererror) { + curErr = curErr.innererror; + code = curErr.code; + message = appendReadableErrorMessage(message, curErr.message); } - }; - var ContainerItem = { - serializedName: "ContainerItem", - xmlName: "Container", - type: { - name: "Composite", - className: "ContainerItem", - modelProperties: { - name: { - serializedName: "Name", - required: true, - xmlName: "Name", - type: { - name: "String" - } - }, - deleted: { - serializedName: "Deleted", - xmlName: "Deleted", - type: { - name: "Boolean" - } - }, - version: { - serializedName: "Version", - xmlName: "Version", - type: { - name: "String" - } - }, - properties: { - serializedName: "Properties", - xmlName: "Properties", - type: { - name: "Composite", - className: "ContainerProperties" - } - }, - metadata: { - serializedName: "Metadata", - xmlName: "Metadata", - type: { - name: "Dictionary", - value: { type: { name: "String" } } - } - } + return { + code, + message + }; + } + function processOperationStatus(result) { + const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result; + switch (status) { + case "succeeded": { + stateProxy.setSucceeded(state); + break; } - } - }; - var ContainerProperties = { - serializedName: "ContainerProperties", - type: { - name: "Composite", - className: "ContainerProperties", - modelProperties: { - lastModified: { - serializedName: "Last-Modified", - required: true, - xmlName: "Last-Modified", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "Etag", - required: true, - xmlName: "Etag", - type: { - name: "String" - } - }, - leaseStatus: { - serializedName: "LeaseStatus", - xmlName: "LeaseStatus", - type: { - name: "Enum", - allowedValues: ["locked", "unlocked"] - } - }, - leaseState: { - serializedName: "LeaseState", - xmlName: "LeaseState", - type: { - name: "Enum", - allowedValues: [ - "available", - "leased", - "expired", - "breaking", - "broken" - ] - } - }, - leaseDuration: { - serializedName: "LeaseDuration", - xmlName: "LeaseDuration", - type: { - name: "Enum", - allowedValues: ["infinite", "fixed"] - } - }, - publicAccess: { - serializedName: "PublicAccess", - xmlName: "PublicAccess", - type: { - name: "Enum", - allowedValues: ["container", "blob"] - } - }, - hasImmutabilityPolicy: { - serializedName: "HasImmutabilityPolicy", - xmlName: "HasImmutabilityPolicy", - type: { - name: "Boolean" - } - }, - hasLegalHold: { - serializedName: "HasLegalHold", - xmlName: "HasLegalHold", - type: { - name: "Boolean" - } - }, - defaultEncryptionScope: { - serializedName: "DefaultEncryptionScope", - xmlName: "DefaultEncryptionScope", - type: { - name: "String" - } - }, - preventEncryptionScopeOverride: { - serializedName: "DenyEncryptionScopeOverride", - xmlName: "DenyEncryptionScopeOverride", - type: { - name: "Boolean" - } - }, - deletedOn: { - serializedName: "DeletedTime", - xmlName: "DeletedTime", - type: { - name: "DateTimeRfc1123" - } - }, - remainingRetentionDays: { - serializedName: "RemainingRetentionDays", - xmlName: "RemainingRetentionDays", - type: { - name: "Number" - } - }, - isImmutableStorageWithVersioningEnabled: { - serializedName: "ImmutableStorageWithVersioningEnabled", - xmlName: "ImmutableStorageWithVersioningEnabled", - type: { - name: "Boolean" - } + case "failed": { + const err = getError === null || getError === void 0 ? void 0 : getError(response); + let postfix = ""; + if (err) { + const { code, message } = simplifyError(err); + postfix = `. ${code}. ${message}`; } + const errStr = `The long-running operation has failed${postfix}`; + stateProxy.setError(state, new Error(errStr)); + stateProxy.setFailed(state); + logger.warning(errStr); + break; } - } - }; - var KeyInfo = { - serializedName: "KeyInfo", - type: { - name: "Composite", - className: "KeyInfo", - modelProperties: { - startsOn: { - serializedName: "Start", - required: true, - xmlName: "Start", - type: { - name: "String" - } - }, - expiresOn: { - serializedName: "Expiry", - required: true, - xmlName: "Expiry", - type: { - name: "String" - } - } + case "canceled": { + stateProxy.setCanceled(state); + break; } } - }; - var UserDelegationKey = { - serializedName: "UserDelegationKey", - type: { - name: "Composite", - className: "UserDelegationKey", - modelProperties: { - signedObjectId: { - serializedName: "SignedOid", - required: true, - xmlName: "SignedOid", - type: { - name: "String" - } - }, - signedTenantId: { - serializedName: "SignedTid", - required: true, - xmlName: "SignedTid", - type: { - name: "String" - } - }, - signedStartsOn: { - serializedName: "SignedStart", - required: true, - xmlName: "SignedStart", - type: { - name: "String" - } - }, - signedExpiresOn: { - serializedName: "SignedExpiry", - required: true, - xmlName: "SignedExpiry", - type: { - name: "String" - } - }, - signedService: { - serializedName: "SignedService", - required: true, - xmlName: "SignedService", - type: { - name: "String" - } - }, - signedVersion: { - serializedName: "SignedVersion", - required: true, - xmlName: "SignedVersion", - type: { - name: "String" - } - }, - value: { - serializedName: "Value", - required: true, - xmlName: "Value", - type: { - name: "String" - } - } + if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) || isDone === void 0 && ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status)) { + stateProxy.setResult(state, buildResult({ + response, + state, + processResult + })); + } + } + function buildResult(inputs) { + const { processResult, response, state } = inputs; + return processResult ? processResult(response, state) : response; + } + async function initOperation(inputs) { + const { init, stateProxy, processResult, getOperationStatus: getOperationStatus2, withOperationLocation, setErrorAsResult } = inputs; + const { operationLocation, resourceLocation, metadata, response } = await init(); + if (operationLocation) + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); + const config = { + metadata, + operationLocation, + resourceLocation + }; + logger.verbose(`LRO: Operation description:`, config); + const state = stateProxy.initState(config); + const status = getOperationStatus2({ response, state, operationLocation }); + processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult }); + return state; + } + async function pollOperationHelper(inputs) { + const { poll, state, stateProxy, operationLocation, getOperationStatus: getOperationStatus2, getResourceLocation: getResourceLocation2, isOperationError: isOperationError2, options } = inputs; + const response = await poll(operationLocation, options).catch(setStateError({ + state, + stateProxy, + isOperationError: isOperationError2 + })); + const status = getOperationStatus2(response, state); + logger.verbose(`LRO: Status: + Polling from: ${state.config.operationLocation} + Operation status: ${status} + Polling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`); + if (status === "succeeded") { + const resourceLocation = getResourceLocation2(response, state); + if (resourceLocation !== void 0) { + return { + response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError: isOperationError2 })), + status + }; } } - }; - var FilterBlobSegment = { - serializedName: "FilterBlobSegment", - xmlName: "EnumerationResults", - type: { - name: "Composite", - className: "FilterBlobSegment", - modelProperties: { - serviceEndpoint: { - serializedName: "ServiceEndpoint", - required: true, - xmlName: "ServiceEndpoint", - xmlIsAttribute: true, - type: { - name: "String" - } - }, - where: { - serializedName: "Where", - required: true, - xmlName: "Where", - type: { - name: "String" - } - }, - blobs: { - serializedName: "Blobs", - required: true, - xmlName: "Blobs", - xmlIsWrapped: true, - xmlElementName: "Blob", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "FilterBlobItem" - } - } - } - }, - continuationToken: { - serializedName: "NextMarker", - xmlName: "NextMarker", - type: { - name: "String" - } - } + return { response, status }; + } + async function pollOperation(inputs) { + const { poll, state, stateProxy, options, getOperationStatus: getOperationStatus2, getResourceLocation: getResourceLocation2, getOperationLocation: getOperationLocation2, isOperationError: isOperationError2, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult } = inputs; + const { operationLocation } = state.config; + if (operationLocation !== void 0) { + const { response, status } = await pollOperationHelper({ + poll, + getOperationStatus: getOperationStatus2, + state, + stateProxy, + operationLocation, + getResourceLocation: getResourceLocation2, + isOperationError: isOperationError2, + options + }); + processOperationStatus({ + status, + response, + state, + stateProxy, + isDone, + processResult, + getError, + setErrorAsResult + }); + if (!terminalStates.includes(status)) { + const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response); + if (intervalInMs) + setDelay(intervalInMs); + const location = getOperationLocation2 === null || getOperationLocation2 === void 0 ? void 0 : getOperationLocation2(response, state); + if (location !== void 0) { + const isUpdated = operationLocation !== location; + state.config.operationLocation = location; + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated); + } else + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); } + updateState === null || updateState === void 0 ? void 0 : updateState(state, response); } - }; - var FilterBlobItem = { - serializedName: "FilterBlobItem", - xmlName: "Blob", - type: { - name: "Composite", - className: "FilterBlobItem", - modelProperties: { - name: { - serializedName: "Name", - required: true, - xmlName: "Name", - type: { - name: "String" + } + function getOperationLocationPollingUrl(inputs) { + const { azureAsyncOperation, operationLocation } = inputs; + return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation; + } + function getLocationHeader(rawResponse) { + return rawResponse.headers["location"]; + } + function getOperationLocationHeader(rawResponse) { + return rawResponse.headers["operation-location"]; + } + function getAzureAsyncOperationHeader(rawResponse) { + return rawResponse.headers["azure-asyncoperation"]; + } + function findResourceLocation(inputs) { + const { location, requestMethod, requestPath, resourceLocationConfig } = inputs; + switch (requestMethod) { + case "PUT": { + return requestPath; + } + case "DELETE": { + return void 0; + } + default: { + switch (resourceLocationConfig) { + case "azure-async-operation": { + return void 0; } - }, - containerName: { - serializedName: "ContainerName", - required: true, - xmlName: "ContainerName", - type: { - name: "String" + case "original-uri": { + return requestPath; } - }, - tags: { - serializedName: "Tags", - xmlName: "Tags", - type: { - name: "Composite", - className: "BlobTags" + case "location": + default: { + return location; } } } } - }; - var BlobTags = { - serializedName: "BlobTags", - xmlName: "Tags", - type: { - name: "Composite", - className: "BlobTags", - modelProperties: { - blobTagSet: { - serializedName: "BlobTagSet", - required: true, - xmlName: "TagSet", - xmlIsWrapped: true, - xmlElementName: "Tag", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "BlobTag" - } - } - } - } + } + function inferLroMode(inputs) { + const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs; + const operationLocation = getOperationLocationHeader(rawResponse); + const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse); + const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation }); + const location = getLocationHeader(rawResponse); + const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase(); + if (pollingUrl !== void 0) { + return { + mode: "OperationLocation", + operationLocation: pollingUrl, + resourceLocation: findResourceLocation({ + requestMethod: normalizedRequestMethod, + location, + requestPath, + resourceLocationConfig + }) + }; + } else if (location !== void 0) { + return { + mode: "ResourceLocation", + operationLocation: location + }; + } else if (normalizedRequestMethod === "PUT" && requestPath) { + return { + mode: "Body", + operationLocation: requestPath + }; + } else { + return void 0; + } + } + function transformStatus(inputs) { + const { status, statusCode } = inputs; + if (typeof status !== "string" && status !== void 0) { + throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`); + } + switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) { + case void 0: + return toOperationStatus(statusCode); + case "succeeded": + return "succeeded"; + case "failed": + return "failed"; + case "running": + case "accepted": + case "started": + case "canceling": + case "cancelling": + return "running"; + case "canceled": + case "cancelled": + return "canceled"; + default: { + logger.verbose(`LRO: unrecognized operation status: ${status}`); + return status; } } - }; - var BlobTag = { - serializedName: "BlobTag", - xmlName: "Tag", - type: { - name: "Composite", - className: "BlobTag", - modelProperties: { - key: { - serializedName: "Key", - required: true, - xmlName: "Key", - type: { - name: "String" - } - }, - value: { - serializedName: "Value", - required: true, - xmlName: "Value", - type: { - name: "String" - } - } + } + function getStatus(rawResponse) { + var _a; + const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + return transformStatus({ status, statusCode: rawResponse.statusCode }); + } + function getProvisioningState(rawResponse) { + var _a, _b; + const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + return transformStatus({ status, statusCode: rawResponse.statusCode }); + } + function toOperationStatus(statusCode) { + if (statusCode === 202) { + return "running"; + } else if (statusCode < 300) { + return "succeeded"; + } else { + return "failed"; + } + } + function parseRetryAfter({ rawResponse }) { + const retryAfter = rawResponse.headers["retry-after"]; + if (retryAfter !== void 0) { + const retryAfterInSeconds = parseInt(retryAfter); + return isNaN(retryAfterInSeconds) ? calculatePollingIntervalFromDate(new Date(retryAfter)) : retryAfterInSeconds * 1e3; + } + return void 0; + } + function getErrorFromResponse(response) { + const error4 = response.flatResponse.error; + if (!error4) { + logger.warning(`The long-running operation failed but there is no error property in the response's body`); + return; + } + if (!error4.code || !error4.message) { + logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`); + return; + } + return error4; + } + function calculatePollingIntervalFromDate(retryAfterDate) { + const timeNow = Math.floor((/* @__PURE__ */ new Date()).getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return void 0; + } + function getStatusFromInitialResponse(inputs) { + const { response, state, operationLocation } = inputs; + function helper() { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case void 0: + return toOperationStatus(response.rawResponse.statusCode); + case "Body": + return getOperationStatus(response, state); + default: + return "running"; } } - }; - var SignedIdentifier = { - serializedName: "SignedIdentifier", - xmlName: "SignedIdentifier", - type: { - name: "Composite", - className: "SignedIdentifier", - modelProperties: { - id: { - serializedName: "Id", - required: true, - xmlName: "Id", - type: { - name: "String" - } - }, - accessPolicy: { - serializedName: "AccessPolicy", - xmlName: "AccessPolicy", - type: { - name: "Composite", - className: "AccessPolicy" - } - } + const status = helper(); + return status === "running" && operationLocation === void 0 ? "succeeded" : status; + } + async function initHttpOperation(inputs) { + const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs; + return initOperation({ + init: async () => { + const response = await lro.sendInitialRequest(); + const config = inferLroMode({ + rawResponse: response.rawResponse, + requestPath: lro.requestPath, + requestMethod: lro.requestMethod, + resourceLocationConfig + }); + return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, (config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}); + }, + stateProxy, + processResult: processResult ? ({ flatResponse }, state) => processResult(flatResponse, state) : ({ flatResponse }) => flatResponse, + getOperationStatus: getStatusFromInitialResponse, + setErrorAsResult + }); + } + function getOperationLocation({ rawResponse }, state) { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case "OperationLocation": { + return getOperationLocationPollingUrl({ + operationLocation: getOperationLocationHeader(rawResponse), + azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse) + }); + } + case "ResourceLocation": { + return getLocationHeader(rawResponse); + } + case "Body": + default: { + return void 0; } } - }; - var AccessPolicy = { - serializedName: "AccessPolicy", - type: { - name: "Composite", - className: "AccessPolicy", - modelProperties: { - startsOn: { - serializedName: "Start", - xmlName: "Start", - type: { - name: "String" - } - }, - expiresOn: { - serializedName: "Expiry", - xmlName: "Expiry", - type: { - name: "String" - } - }, - permissions: { - serializedName: "Permission", - xmlName: "Permission", - type: { - name: "String" - } - } + } + function getOperationStatus({ rawResponse }, state) { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case "OperationLocation": { + return getStatus(rawResponse); + } + case "ResourceLocation": { + return toOperationStatus(rawResponse.statusCode); + } + case "Body": { + return getProvisioningState(rawResponse); } + default: + throw new Error(`Internal error: Unexpected operation mode: ${mode}`); } - }; - var ListBlobsFlatSegmentResponse = { - serializedName: "ListBlobsFlatSegmentResponse", - xmlName: "EnumerationResults", - type: { - name: "Composite", - className: "ListBlobsFlatSegmentResponse", - modelProperties: { - serviceEndpoint: { - serializedName: "ServiceEndpoint", - required: true, - xmlName: "ServiceEndpoint", - xmlIsAttribute: true, - type: { - name: "String" - } - }, - containerName: { - serializedName: "ContainerName", - required: true, - xmlName: "ContainerName", - xmlIsAttribute: true, - type: { - name: "String" - } - }, - prefix: { - serializedName: "Prefix", - xmlName: "Prefix", - type: { - name: "String" - } + } + function getResourceLocation({ flatResponse }, state) { + if (typeof flatResponse === "object") { + const resourceLocation = flatResponse.resourceLocation; + if (resourceLocation !== void 0) { + state.config.resourceLocation = resourceLocation; + } + } + return state.config.resourceLocation; + } + function isOperationError(e) { + return e.name === "RestError"; + } + async function pollHttpOperation(inputs) { + const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult } = inputs; + return pollOperation({ + state, + stateProxy, + setDelay, + processResult: processResult ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState) : ({ flatResponse }) => flatResponse, + getError: getErrorFromResponse, + updateState, + getPollingInterval: parseRetryAfter, + getOperationLocation, + getOperationStatus, + isOperationError, + getResourceLocation, + options, + /** + * The expansion here is intentional because `lro` could be an object that + * references an inner this, so we need to preserve a reference to it. + */ + poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions), + setErrorAsResult + }); + } + var createStateProxy$1 = () => ({ + /** + * The state at this point is created to be of type OperationState. + * It will be updated later to be of type TState when the + * customer-provided callback, `updateState`, is called during polling. + */ + initState: (config) => ({ status: "running", config }), + setCanceled: (state) => state.status = "canceled", + setError: (state, error4) => state.error = error4, + setResult: (state, result) => state.result = result, + setRunning: (state) => state.status = "running", + setSucceeded: (state) => state.status = "succeeded", + setFailed: (state) => state.status = "failed", + getError: (state) => state.error, + getResult: (state) => state.result, + isCanceled: (state) => state.status === "canceled", + isFailed: (state) => state.status === "failed", + isRunning: (state) => state.status === "running", + isSucceeded: (state) => state.status === "succeeded" + }); + function buildCreatePoller(inputs) { + const { getOperationLocation: getOperationLocation2, getStatusFromInitialResponse: getStatusFromInitialResponse2, getStatusFromPollResponse, isOperationError: isOperationError2, getResourceLocation: getResourceLocation2, getPollingInterval, getError, resolveOnUnsuccessful } = inputs; + return async ({ init, poll }, options) => { + const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom } = options || {}; + const stateProxy = createStateProxy$1(); + const withOperationLocation = withOperationLocationCallback ? /* @__PURE__ */ (() => { + let called = false; + return (operationLocation, isUpdated) => { + if (isUpdated) + withOperationLocationCallback(operationLocation); + else if (!called) + withOperationLocationCallback(operationLocation); + called = true; + }; + })() : void 0; + const state = restoreFrom ? deserializeState(restoreFrom) : await initOperation({ + init, + stateProxy, + processResult, + getOperationStatus: getStatusFromInitialResponse2, + withOperationLocation, + setErrorAsResult: !resolveOnUnsuccessful + }); + let resultPromise; + const abortController$1 = new abortController.AbortController(); + const handlers = /* @__PURE__ */ new Map(); + const handleProgressEvents = async () => handlers.forEach((h) => h(state)); + const cancelErrMsg = "Operation was canceled"; + let currentPollIntervalInMs = intervalInMs; + const poller = { + getOperationState: () => state, + getResult: () => state.result, + isDone: () => ["succeeded", "failed", "canceled"].includes(state.status), + isStopped: () => resultPromise === void 0, + stopPolling: () => { + abortController$1.abort(); }, - marker: { - serializedName: "Marker", - xmlName: "Marker", - type: { - name: "String" - } + toString: () => JSON.stringify({ + state + }), + onProgress: (callback) => { + const s = Symbol(); + handlers.set(s, callback); + return () => handlers.delete(s); }, - maxPageSize: { - serializedName: "MaxResults", - xmlName: "MaxResults", - type: { - name: "Number" + pollUntilDone: (pollOptions) => resultPromise !== null && resultPromise !== void 0 ? resultPromise : resultPromise = (async () => { + const { abortSignal: inputAbortSignal } = pollOptions || {}; + const { signal: abortSignal } = inputAbortSignal ? new abortController.AbortController([inputAbortSignal, abortController$1.signal]) : abortController$1; + if (!poller.isDone()) { + await poller.poll({ abortSignal }); + while (!poller.isDone()) { + await coreUtil.delay(currentPollIntervalInMs, { abortSignal }); + await poller.poll({ abortSignal }); + } } - }, - segment: { - serializedName: "Segment", - xmlName: "Blobs", - type: { - name: "Composite", - className: "BlobFlatListSegment" + if (resolveOnUnsuccessful) { + return poller.getResult(); + } else { + switch (state.status) { + case "succeeded": + return poller.getResult(); + case "canceled": + throw new Error(cancelErrMsg); + case "failed": + throw state.error; + case "notStarted": + case "running": + throw new Error(`Polling completed without succeeding or failing`); + } } - }, - continuationToken: { - serializedName: "NextMarker", - xmlName: "NextMarker", - type: { - name: "String" + })().finally(() => { + resultPromise = void 0; + }), + async poll(pollOptions) { + if (resolveOnUnsuccessful) { + if (poller.isDone()) + return; + } else { + switch (state.status) { + case "succeeded": + return; + case "canceled": + throw new Error(cancelErrMsg); + case "failed": + throw state.error; + } } - } - } - } - }; - var BlobFlatListSegment = { - serializedName: "BlobFlatListSegment", - xmlName: "Blobs", - type: { - name: "Composite", - className: "BlobFlatListSegment", - modelProperties: { - blobItems: { - serializedName: "BlobItems", - required: true, - xmlName: "BlobItems", - xmlElementName: "Blob", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "BlobItemInternal" - } + await pollOperation({ + poll, + state, + stateProxy, + getOperationLocation: getOperationLocation2, + isOperationError: isOperationError2, + withOperationLocation, + getPollingInterval, + getOperationStatus: getStatusFromPollResponse, + getResourceLocation: getResourceLocation2, + processResult, + getError, + updateState, + options: pollOptions, + setDelay: (pollIntervalInMs) => { + currentPollIntervalInMs = pollIntervalInMs; + }, + setErrorAsResult: !resolveOnUnsuccessful + }); + await handleProgressEvents(); + if (!resolveOnUnsuccessful) { + switch (state.status) { + case "canceled": + throw new Error(cancelErrMsg); + case "failed": + throw state.error; } } } - } + }; + return poller; + }; + } + async function createHttpPoller(lro, options) { + const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false } = options || {}; + return buildCreatePoller({ + getStatusFromInitialResponse, + getStatusFromPollResponse: getOperationStatus, + isOperationError, + getOperationLocation, + getResourceLocation, + getPollingInterval: parseRetryAfter, + getError: getErrorFromResponse, + resolveOnUnsuccessful + })({ + init: async () => { + const response = await lro.sendInitialRequest(); + const config = inferLroMode({ + rawResponse: response.rawResponse, + requestPath: lro.requestPath, + requestMethod: lro.requestMethod, + resourceLocationConfig + }); + return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, (config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}); + }, + poll: lro.sendPollRequest + }, { + intervalInMs, + withOperationLocation, + restoreFrom, + updateState, + processResult: processResult ? ({ flatResponse }, state) => processResult(flatResponse, state) : ({ flatResponse }) => flatResponse + }); + } + var createStateProxy = () => ({ + initState: (config) => ({ config, isStarted: true }), + setCanceled: (state) => state.isCancelled = true, + setError: (state, error4) => state.error = error4, + setResult: (state, result) => state.result = result, + setRunning: (state) => state.isStarted = true, + setSucceeded: (state) => state.isCompleted = true, + setFailed: () => { + }, + getError: (state) => state.error, + getResult: (state) => state.result, + isCanceled: (state) => !!state.isCancelled, + isFailed: (state) => !!state.error, + isRunning: (state) => !!state.isStarted, + isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error) + }); + var GenericPollOperation = class { + constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) { + this.state = state; + this.lro = lro; + this.setErrorAsResult = setErrorAsResult; + this.lroResourceLocationConfig = lroResourceLocationConfig; + this.processResult = processResult; + this.updateState = updateState; + this.isDone = isDone; + } + setPollerConfig(pollerConfig) { + this.pollerConfig = pollerConfig; + } + async update(options) { + var _a; + const stateProxy = createStateProxy(); + if (!this.state.isStarted) { + this.state = Object.assign(Object.assign({}, this.state), await initHttpOperation({ + lro: this.lro, + stateProxy, + resourceLocationConfig: this.lroResourceLocationConfig, + processResult: this.processResult, + setErrorAsResult: this.setErrorAsResult + })); + } + const updateState = this.updateState; + const isDone = this.isDone; + if (!this.state.isCompleted && this.state.error === void 0) { + await pollHttpOperation({ + lro: this.lro, + state: this.state, + stateProxy, + processResult: this.processResult, + updateState: updateState ? (state, { rawResponse }) => updateState(state, rawResponse) : void 0, + isDone: isDone ? ({ flatResponse }, state) => isDone(flatResponse, state) : void 0, + options, + setDelay: (intervalInMs) => { + this.pollerConfig.intervalInMs = intervalInMs; + }, + setErrorAsResult: this.setErrorAsResult + }); + } + (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state); + return this; + } + async cancel() { + logger.error("`cancelOperation` is deprecated because it wasn't implemented"); + return this; + } + /** + * Serializes the Poller operation. + */ + toString() { + return JSON.stringify({ + state: this.state + }); + } + }; + var PollerStoppedError = class _PollerStoppedError extends Error { + constructor(message) { + super(message); + this.name = "PollerStoppedError"; + Object.setPrototypeOf(this, _PollerStoppedError.prototype); + } + }; + var PollerCancelledError = class _PollerCancelledError extends Error { + constructor(message) { + super(message); + this.name = "PollerCancelledError"; + Object.setPrototypeOf(this, _PollerCancelledError.prototype); + } + }; + var Poller = class { + /** + * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`. + * + * When writing an implementation of a Poller, this implementation needs to deal with the initialization + * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's + * operation has already been defined, at least its basic properties. The code below shows how to approach + * the definition of the constructor of a new custom poller. + * + * ```ts + * export class MyPoller extends Poller { + * constructor({ + * // Anything you might need outside of the basics + * }) { + * let state: MyOperationState = { + * privateProperty: private, + * publicProperty: public, + * }; + * + * const operation = { + * state, + * update, + * cancel, + * toString + * } + * + * // Sending the operation to the parent's constructor. + * super(operation); + * + * // You can assign more local properties here. + * } + * } + * ``` + * + * Inside of this constructor, a new promise is created. This will be used to + * tell the user when the poller finishes (see `pollUntilDone()`). The promise's + * resolve and reject methods are also used internally to control when to resolve + * or reject anyone waiting for the poller to finish. + * + * The constructor of a custom implementation of a poller is where any serialized version of + * a previous poller's operation should be deserialized into the operation sent to the + * base constructor. For example: + * + * ```ts + * export class MyPoller extends Poller { + * constructor( + * baseOperation: string | undefined + * ) { + * let state: MyOperationState = {}; + * if (baseOperation) { + * state = { + * ...JSON.parse(baseOperation).state, + * ...state + * }; + * } + * const operation = { + * state, + * // ... + * } + * super(operation); + * } + * } + * ``` + * + * @param operation - Must contain the basic properties of `PollOperation`. + */ + constructor(operation) { + this.resolveOnUnsuccessful = false; + this.stopped = true; + this.pollProgressCallbacks = []; + this.operation = operation; + this.promise = new Promise((resolve2, reject) => { + this.resolve = resolve2; + this.reject = reject; + }); + this.promise.catch(() => { + }); + } + /** + * Starts a loop that will break only if the poller is done + * or if the poller is stopped. + */ + async startPolling(pollOptions = {}) { + if (this.stopped) { + this.stopped = false; + } + while (!this.isStopped() && !this.isDone()) { + await this.poll(pollOptions); + await this.delay(); + } + } + /** + * pollOnce does one polling, by calling to the update method of the underlying + * poll operation to make any relevant change effective. + * + * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. + * + * @param options - Optional properties passed to the operation's update method. + */ + async pollOnce(options = {}) { + if (!this.isDone()) { + this.operation = await this.operation.update({ + abortSignal: options.abortSignal, + fireProgress: this.fireProgress.bind(this) + }); + } + this.processUpdatedState(); + } + /** + * fireProgress calls the functions passed in via onProgress the method of the poller. + * + * It loops over all of the callbacks received from onProgress, and executes them, sending them + * the current operation state. + * + * @param state - The current operation state. + */ + fireProgress(state) { + for (const callback of this.pollProgressCallbacks) { + callback(state); + } + } + /** + * Invokes the underlying operation's cancel method. + */ + async cancelOnce(options = {}) { + this.operation = await this.operation.cancel(options); + } + /** + * Returns a promise that will resolve once a single polling request finishes. + * It does this by calling the update method of the Poller's operation. + * + * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. + * + * @param options - Optional properties passed to the operation's update method. + */ + poll(options = {}) { + if (!this.pollOncePromise) { + this.pollOncePromise = this.pollOnce(options); + const clearPollOncePromise = () => { + this.pollOncePromise = void 0; + }; + this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject); + } + return this.pollOncePromise; + } + processUpdatedState() { + if (this.operation.state.error) { + this.stopped = true; + if (!this.resolveOnUnsuccessful) { + this.reject(this.operation.state.error); + throw this.operation.state.error; + } + } + if (this.operation.state.isCancelled) { + this.stopped = true; + if (!this.resolveOnUnsuccessful) { + const error4 = new PollerCancelledError("Operation was canceled"); + this.reject(error4); + throw error4; + } + } + if (this.isDone() && this.resolve) { + this.resolve(this.getResult()); + } + } + /** + * Returns a promise that will resolve once the underlying operation is completed. + */ + async pollUntilDone(pollOptions = {}) { + if (this.stopped) { + this.startPolling(pollOptions).catch(this.reject); + } + this.processUpdatedState(); + return this.promise; + } + /** + * Invokes the provided callback after each polling is completed, + * sending the current state of the poller's operation. + * + * It returns a method that can be used to stop receiving updates on the given callback function. + */ + onProgress(callback) { + this.pollProgressCallbacks.push(callback); + return () => { + this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback); + }; + } + /** + * Returns true if the poller has finished polling. + */ + isDone() { + const state = this.operation.state; + return Boolean(state.isCompleted || state.isCancelled || state.error); + } + /** + * Stops the poller from continuing to poll. + */ + stopPolling() { + if (!this.stopped) { + this.stopped = true; + if (this.reject) { + this.reject(new PollerStoppedError("This poller is already stopped")); + } + } + } + /** + * Returns true if the poller is stopped. + */ + isStopped() { + return this.stopped; + } + /** + * Attempts to cancel the underlying operation. + * + * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. + * + * If it's called again before it finishes, it will throw an error. + * + * @param options - Optional properties passed to the operation's update method. + */ + cancelOperation(options = {}) { + if (!this.cancelPromise) { + this.cancelPromise = this.cancelOnce(options); + } else if (options.abortSignal) { + throw new Error("A cancel request is currently pending"); + } + return this.cancelPromise; + } + /** + * Returns the state of the operation. + * + * Even though TState will be the same type inside any of the methods of any extension of the Poller class, + * implementations of the pollers can customize what's shared with the public by writing their own + * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller + * and a public type representing a safe to share subset of the properties of the internal state. + * Their definition of getOperationState can then return their public type. + * + * Example: + * + * ```ts + * // Let's say we have our poller's operation state defined as: + * interface MyOperationState extends PollOperationState { + * privateProperty?: string; + * publicProperty?: string; + * } + * + * // To allow us to have a true separation of public and private state, we have to define another interface: + * interface PublicState extends PollOperationState { + * publicProperty?: string; + * } + * + * // Then, we define our Poller as follows: + * export class MyPoller extends Poller { + * // ... More content is needed here ... + * + * public getOperationState(): PublicState { + * const state: PublicState = this.operation.state; + * return { + * // Properties from PollOperationState + * isStarted: state.isStarted, + * isCompleted: state.isCompleted, + * isCancelled: state.isCancelled, + * error: state.error, + * result: state.result, + * + * // The only other property needed by PublicState. + * publicProperty: state.publicProperty + * } + * } + * } + * ``` + * + * You can see this in the tests of this repository, go to the file: + * `../test/utils/testPoller.ts` + * and look for the getOperationState implementation. + */ + getOperationState() { + return this.operation.state; + } + /** + * Returns the result value of the operation, + * regardless of the state of the poller. + * It can return undefined or an incomplete form of the final TResult value + * depending on the implementation. + */ + getResult() { + const state = this.operation.state; + return state.result; + } + /** + * Returns a serialized version of the poller's operation + * by invoking the operation's toString method. + */ + toString() { + return this.operation.toString(); + } + }; + var LroEngine = class extends Poller { + constructor(lro, options) { + const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState } = options || {}; + const state = resumeFrom ? deserializeState(resumeFrom) : {}; + const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone); + super(operation); + this.resolveOnUnsuccessful = resolveOnUnsuccessful; + this.config = { intervalInMs }; + operation.setPollerConfig(this.config); + } + /** + * The method used by the poller to wait before attempting to update its operation. + */ + delay() { + return new Promise((resolve2) => setTimeout(() => resolve2(), this.config.intervalInMs)); + } + }; + exports2.LroEngine = LroEngine; + exports2.Poller = Poller; + exports2.PollerCancelledError = PollerCancelledError; + exports2.PollerStoppedError = PollerStoppedError; + exports2.createHttpPoller = createHttpPoller; + } +}); + +// node_modules/@azure/storage-blob/dist/index.js +var require_dist7 = __commonJS({ + "node_modules/@azure/storage-blob/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var coreRestPipeline = require_commonjs7(); + var tslib = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); + var coreAuth = require_commonjs8(); + var coreUtil = require_commonjs4(); + var coreHttpCompat = require_commonjs10(); + var coreClient = require_commonjs9(); + var coreXml = require_commonjs11(); + var logger$1 = require_dist(); + var abortController = require_commonjs12(); + var crypto = require("crypto"); + var coreTracing = require_commonjs6(); + var stream = require("stream"); + var coreLro = require_dist6(); + var events = require("events"); + var fs2 = require("fs"); + var util = require("util"); + var buffer = require("buffer"); + function _interopNamespaceDefault(e) { + var n = /* @__PURE__ */ Object.create(null); + if (e) { + Object.keys(e).forEach(function(k) { + if (k !== "default") { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function() { + return e[k]; + } + }); + } + }); + } + n.default = e; + return Object.freeze(n); + } + var coreHttpCompat__namespace = /* @__PURE__ */ _interopNamespaceDefault(coreHttpCompat); + var coreClient__namespace = /* @__PURE__ */ _interopNamespaceDefault(coreClient); + var fs__namespace = /* @__PURE__ */ _interopNamespaceDefault(fs2); + var util__namespace = /* @__PURE__ */ _interopNamespaceDefault(util); + var logger = logger$1.createClientLogger("storage-blob"); + var BaseRequestPolicy = class { + /** + * The main method to implement that manipulates a request/response. + */ + constructor(_nextPolicy, _options) { + this._nextPolicy = _nextPolicy; + this._options = _options; + } + /** + * Get whether or not a log with the provided log level should be logged. + * @param logLevel - The log level of the log that will be logged. + * @returns Whether or not a log with the provided log level should be logged. + */ + shouldLog(logLevel) { + return this._options.shouldLog(logLevel); + } + /** + * Attempt to log the provided message to the provided logger. If no logger was provided or if + * the log level does not meat the logger's threshold, then nothing will be logged. + * @param logLevel - The log level of this log. + * @param message - The message of this log. + */ + log(logLevel, message) { + this._options.log(logLevel, message); + } + }; + var SDK_VERSION = "12.25.0"; + var SERVICE_VERSION = "2024-11-04"; + var BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; + var BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4e3 * 1024 * 1024; + var BLOCK_BLOB_MAX_BLOCKS = 5e4; + var DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; + var DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; + var DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; + var REQUEST_TIMEOUT = 100 * 1e3; + var StorageOAuthScopes = "https://storage.azure.com/.default"; + var URLConstants = { + Parameters: { + FORCE_BROWSER_NO_CACHE: "_", + SIGNATURE: "sig", + SNAPSHOT: "snapshot", + VERSIONID: "versionid", + TIMEOUT: "timeout" + } + }; + var HTTPURLConnection = { + HTTP_ACCEPTED: 202, + HTTP_CONFLICT: 409, + HTTP_NOT_FOUND: 404, + HTTP_PRECON_FAILED: 412, + HTTP_RANGE_NOT_SATISFIABLE: 416 + }; + var HeaderConstants = { + AUTHORIZATION: "Authorization", + AUTHORIZATION_SCHEME: "Bearer", + CONTENT_ENCODING: "Content-Encoding", + CONTENT_ID: "Content-ID", + CONTENT_LANGUAGE: "Content-Language", + CONTENT_LENGTH: "Content-Length", + CONTENT_MD5: "Content-Md5", + CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", + CONTENT_TYPE: "Content-Type", + COOKIE: "Cookie", + DATE: "date", + IF_MATCH: "if-match", + IF_MODIFIED_SINCE: "if-modified-since", + IF_NONE_MATCH: "if-none-match", + IF_UNMODIFIED_SINCE: "if-unmodified-since", + PREFIX_FOR_STORAGE: "x-ms-", + RANGE: "Range", + USER_AGENT: "User-Agent", + X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", + X_MS_COPY_SOURCE: "x-ms-copy-source", + X_MS_DATE: "x-ms-date", + X_MS_ERROR_CODE: "x-ms-error-code", + X_MS_VERSION: "x-ms-version", + X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code" + }; + var ETagNone = ""; + var ETagAny = "*"; + var SIZE_1_MB = 1 * 1024 * 1024; + var BATCH_MAX_REQUEST = 256; + var BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; + var HTTP_LINE_ENDING = "\r\n"; + var HTTP_VERSION_1_1 = "HTTP/1.1"; + var EncryptionAlgorithmAES25 = "AES256"; + var DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; + var StorageBlobLoggingAllowedHeaderNames = [ + "Access-Control-Allow-Origin", + "Cache-Control", + "Content-Length", + "Content-Type", + "Date", + "Request-Id", + "traceparent", + "Transfer-Encoding", + "User-Agent", + "x-ms-client-request-id", + "x-ms-date", + "x-ms-error-code", + "x-ms-request-id", + "x-ms-return-client-request-id", + "x-ms-version", + "Accept-Ranges", + "Content-Disposition", + "Content-Encoding", + "Content-Language", + "Content-MD5", + "Content-Range", + "ETag", + "Last-Modified", + "Server", + "Vary", + "x-ms-content-crc64", + "x-ms-copy-action", + "x-ms-copy-completion-time", + "x-ms-copy-id", + "x-ms-copy-progress", + "x-ms-copy-status", + "x-ms-has-immutability-policy", + "x-ms-has-legal-hold", + "x-ms-lease-state", + "x-ms-lease-status", + "x-ms-range", + "x-ms-request-server-encrypted", + "x-ms-server-encrypted", + "x-ms-snapshot", + "x-ms-source-range", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "x-ms-access-tier", + "x-ms-access-tier-change-time", + "x-ms-access-tier-inferred", + "x-ms-account-kind", + "x-ms-archive-status", + "x-ms-blob-append-offset", + "x-ms-blob-cache-control", + "x-ms-blob-committed-block-count", + "x-ms-blob-condition-appendpos", + "x-ms-blob-condition-maxsize", + "x-ms-blob-content-disposition", + "x-ms-blob-content-encoding", + "x-ms-blob-content-language", + "x-ms-blob-content-length", + "x-ms-blob-content-md5", + "x-ms-blob-content-type", + "x-ms-blob-public-access", + "x-ms-blob-sequence-number", + "x-ms-blob-type", + "x-ms-copy-destination-snapshot", + "x-ms-creation-time", + "x-ms-default-encryption-scope", + "x-ms-delete-snapshots", + "x-ms-delete-type-permanent", + "x-ms-deny-encryption-scope-override", + "x-ms-encryption-algorithm", + "x-ms-if-sequence-number-eq", + "x-ms-if-sequence-number-le", + "x-ms-if-sequence-number-lt", + "x-ms-incremental-copy", + "x-ms-lease-action", + "x-ms-lease-break-period", + "x-ms-lease-duration", + "x-ms-lease-id", + "x-ms-lease-time", + "x-ms-page-write", + "x-ms-proposed-lease-id", + "x-ms-range-get-content-md5", + "x-ms-rehydrate-priority", + "x-ms-sequence-number-action", + "x-ms-sku-name", + "x-ms-source-content-md5", + "x-ms-source-if-match", + "x-ms-source-if-modified-since", + "x-ms-source-if-none-match", + "x-ms-source-if-unmodified-since", + "x-ms-tag-count", + "x-ms-encryption-key-sha256", + "x-ms-copy-source-error-code", + "x-ms-copy-source-status-code", + "x-ms-if-tags", + "x-ms-source-if-tags" + ]; + var StorageBlobLoggingAllowedQueryParameters = [ + "comp", + "maxresults", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct", + "se", + "si", + "sip", + "sp", + "spr", + "sr", + "srt", + "ss", + "st", + "sv", + "include", + "marker", + "prefix", + "copyid", + "restype", + "blockid", + "blocklisttype", + "delimiter", + "prevsnapshot", + "ske", + "skoid", + "sks", + "skt", + "sktid", + "skv", + "snapshot" + ]; + var BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption"; + var BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption"; + var PathStylePorts = [ + "10000", + "10001", + "10002", + "10003", + "10004", + "10100", + "10101", + "10102", + "10103", + "10104", + "11000", + "11001", + "11002", + "11003", + "11004", + "11100", + "11101", + "11102", + "11103", + "11104" + ]; + function escapeURLPath(url2) { + const urlParsed = new URL(url2); + let path2 = urlParsed.pathname; + path2 = path2 || "/"; + path2 = escape(path2); + urlParsed.pathname = path2; + return urlParsed.toString(); + } + function getProxyUriFromDevConnString(connectionString) { + let proxyUri = ""; + if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { + const matchCredentials = connectionString.split(";"); + for (const element of matchCredentials) { + if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { + proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; + } + } + } + return proxyUri; + } + function getValueInConnString(connectionString, argument) { + const elements = connectionString.split(";"); + for (const element of elements) { + if (element.trim().startsWith(argument)) { + return element.trim().match(argument + "=(.*)")[1]; + } + } + return ""; + } + function extractConnectionStringParts(connectionString) { + let proxyUri = ""; + if (connectionString.startsWith("UseDevelopmentStorage=true")) { + proxyUri = getProxyUriFromDevConnString(connectionString); + connectionString = DevelopmentConnectionString; + } + let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); + blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; + if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { + let defaultEndpointsProtocol = ""; + let accountName = ""; + let accountKey = Buffer.from("accountKey", "base64"); + let endpointSuffix = ""; + accountName = getValueInConnString(connectionString, "AccountName"); + accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); + if (!blobEndpoint) { + defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); + const protocol = defaultEndpointsProtocol.toLowerCase(); + if (protocol !== "https" && protocol !== "http") { + throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); + } + endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); + if (!endpointSuffix) { + throw new Error("Invalid EndpointSuffix in the provided Connection String"); + } + blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; + } + if (!accountName) { + throw new Error("Invalid AccountName in the provided Connection String"); + } else if (accountKey.length === 0) { + throw new Error("Invalid AccountKey in the provided Connection String"); + } + return { + kind: "AccountConnString", + url: blobEndpoint, + accountName, + accountKey, + proxyUri + }; + } else { + let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); + let accountName = getValueInConnString(connectionString, "AccountName"); + if (!accountName) { + accountName = getAccountNameFromUrl(blobEndpoint); + } + if (!blobEndpoint) { + throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); + } else if (!accountSas) { + throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); + } + if (accountSas.startsWith("?")) { + accountSas = accountSas.substring(1); + } + return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; + } + } + function escape(text) { + return encodeURIComponent(text).replace(/%2F/g, "/").replace(/'/g, "%27").replace(/\+/g, "%20").replace(/%25/g, "%"); + } + function appendToURLPath(url2, name) { + const urlParsed = new URL(url2); + let path2 = urlParsed.pathname; + path2 = path2 ? path2.endsWith("/") ? `${path2}${name}` : `${path2}/${name}` : name; + urlParsed.pathname = path2; + return urlParsed.toString(); + } + function setURLParameter(url2, name, value) { + const urlParsed = new URL(url2); + const encodedName = encodeURIComponent(name); + const encodedValue = value ? encodeURIComponent(value) : void 0; + const searchString = urlParsed.search === "" ? "?" : urlParsed.search; + const searchPieces = []; + for (const pair of searchString.slice(1).split("&")) { + if (pair) { + const [key] = pair.split("=", 2); + if (key !== encodedName) { + searchPieces.push(pair); + } + } + } + if (encodedValue) { + searchPieces.push(`${encodedName}=${encodedValue}`); + } + urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; + return urlParsed.toString(); + } + function getURLParameter(url2, name) { + var _a; + const urlParsed = new URL(url2); + return (_a = urlParsed.searchParams.get(name)) !== null && _a !== void 0 ? _a : void 0; + } + function setURLHost(url2, host) { + const urlParsed = new URL(url2); + urlParsed.hostname = host; + return urlParsed.toString(); + } + function getURLPath(url2) { + try { + const urlParsed = new URL(url2); + return urlParsed.pathname; + } catch (e) { + return void 0; + } + } + function getURLScheme(url2) { + try { + const urlParsed = new URL(url2); + return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; + } catch (e) { + return void 0; + } + } + function getURLPathAndQuery(url2) { + const urlParsed = new URL(url2); + const pathString = urlParsed.pathname; + if (!pathString) { + throw new RangeError("Invalid url without valid path."); + } + let queryString = urlParsed.search || ""; + queryString = queryString.trim(); + if (queryString !== "") { + queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; + } + return `${pathString}${queryString}`; + } + function getURLQueries(url2) { + let queryString = new URL(url2).search; + if (!queryString) { + return {}; + } + queryString = queryString.trim(); + queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; + let querySubStrings = queryString.split("&"); + querySubStrings = querySubStrings.filter((value) => { + const indexOfEqual = value.indexOf("="); + const lastIndexOfEqual = value.lastIndexOf("="); + return indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1; + }); + const queries = {}; + for (const querySubString of querySubStrings) { + const splitResults = querySubString.split("="); + const key = splitResults[0]; + const value = splitResults[1]; + queries[key] = value; + } + return queries; + } + function appendToURLQuery(url2, queryParts) { + const urlParsed = new URL(url2); + let query = urlParsed.search; + if (query) { + query += "&" + queryParts; + } else { + query = queryParts; + } + urlParsed.search = query; + return urlParsed.toString(); + } + function truncatedISO8061Date(date, withMilliseconds = true) { + const dateString = date.toISOString(); + return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000Z" : dateString.substring(0, dateString.length - 5) + "Z"; + } + function base64encode(content) { + return !coreUtil.isNode ? btoa(content) : Buffer.from(content).toString("base64"); + } + function generateBlockID(blockIDPrefix, blockIndex) { + const maxSourceStringLength = 48; + const maxBlockIndexLength = 6; + const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; + if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { + blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); + } + const res = blockIDPrefix + padStart2(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); + return base64encode(res); + } + async function delay(timeInMs, aborter, abortError) { + return new Promise((resolve2, reject) => { + let timeout; + const abortHandler = () => { + if (timeout !== void 0) { + clearTimeout(timeout); + } + reject(abortError); + }; + const resolveHandler = () => { + if (aborter !== void 0) { + aborter.removeEventListener("abort", abortHandler); + } + resolve2(); + }; + timeout = setTimeout(resolveHandler, timeInMs); + if (aborter !== void 0) { + aborter.addEventListener("abort", abortHandler); + } + }); + } + function padStart2(currentString, targetLength, padString = " ") { + if (String.prototype.padStart) { + return currentString.padStart(targetLength, padString); + } + padString = padString || " "; + if (currentString.length > targetLength) { + return currentString; + } else { + targetLength = targetLength - currentString.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength / padString.length); + } + return padString.slice(0, targetLength) + currentString; + } + } + function iEqual(str1, str2) { + return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); + } + function getAccountNameFromUrl(url2) { + const parsedUrl = new URL(url2); + let accountName; + try { + if (parsedUrl.hostname.split(".")[1] === "blob") { + accountName = parsedUrl.hostname.split(".")[0]; + } else if (isIpEndpointStyle(parsedUrl)) { + accountName = parsedUrl.pathname.split("/")[1]; + } else { + accountName = ""; + } + return accountName; + } catch (error4) { + throw new Error("Unable to extract accountName with provided information."); + } + } + function isIpEndpointStyle(parsedUrl) { + const host = parsedUrl.host; + return /^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) || Boolean(parsedUrl.port) && PathStylePorts.includes(parsedUrl.port); + } + function toBlobTagsString(tags2) { + if (tags2 === void 0) { + return void 0; + } + const tagPairs = []; + for (const key in tags2) { + if (Object.prototype.hasOwnProperty.call(tags2, key)) { + const value = tags2[key]; + tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); + } + } + return tagPairs.join("&"); + } + function toBlobTags(tags2) { + if (tags2 === void 0) { + return void 0; + } + const res = { + blobTagSet: [] + }; + for (const key in tags2) { + if (Object.prototype.hasOwnProperty.call(tags2, key)) { + const value = tags2[key]; + res.blobTagSet.push({ + key, + value + }); + } + } + return res; + } + function toTags(tags2) { + if (tags2 === void 0) { + return void 0; + } + const res = {}; + for (const blobTag of tags2.blobTagSet) { + res[blobTag.key] = blobTag.value; + } + return res; + } + function toQuerySerialization(textConfiguration) { + if (textConfiguration === void 0) { + return void 0; + } + switch (textConfiguration.kind) { + case "csv": + return { + format: { + type: "delimited", + delimitedTextConfiguration: { + columnSeparator: textConfiguration.columnSeparator || ",", + fieldQuote: textConfiguration.fieldQuote || "", + recordSeparator: textConfiguration.recordSeparator, + escapeChar: textConfiguration.escapeCharacter || "", + headersPresent: textConfiguration.hasHeaders || false + } + } + }; + case "json": + return { + format: { + type: "json", + jsonTextConfiguration: { + recordSeparator: textConfiguration.recordSeparator + } + } + }; + case "arrow": + return { + format: { + type: "arrow", + arrowConfiguration: { + schema: textConfiguration.schema + } + } + }; + case "parquet": + return { + format: { + type: "parquet" + } + }; + default: + throw Error("Invalid BlobQueryTextConfiguration."); + } + } + function parseObjectReplicationRecord(objectReplicationRecord) { + if (!objectReplicationRecord) { + return void 0; + } + if ("policy-id" in objectReplicationRecord) { + return void 0; + } + const orProperties = []; + for (const key in objectReplicationRecord) { + const ids = key.split("_"); + const policyPrefix = "or-"; + if (ids[0].startsWith(policyPrefix)) { + ids[0] = ids[0].substring(policyPrefix.length); + } + const rule = { + ruleId: ids[1], + replicationStatus: objectReplicationRecord[key] + }; + const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); + if (policyIndex > -1) { + orProperties[policyIndex].rules.push(rule); + } else { + orProperties.push({ + policyId: ids[0], + rules: [rule] + }); + } + } + return orProperties; + } + function httpAuthorizationToString(httpAuthorization) { + return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : void 0; + } + function BlobNameToString(name) { + if (name.encoded) { + return decodeURIComponent(name.content); + } else { + return name.content; + } + } + function ConvertInternalResponseOfListBlobFlat(internalResponse) { + return Object.assign(Object.assign({}, internalResponse), { segment: { + blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); + return blobItem; + }) + } }); + } + function ConvertInternalResponseOfListBlobHierarchy(internalResponse) { + var _a; + return Object.assign(Object.assign({}, internalResponse), { segment: { + blobPrefixes: (_a = internalResponse.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { + const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); + return blobPrefix; + }), + blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); + return blobItem; + }) + } }); + } + function* ExtractPageRangeInfoItems(getPageRangesSegment) { + let pageRange = []; + let clearRange = []; + if (getPageRangesSegment.pageRange) + pageRange = getPageRangesSegment.pageRange; + if (getPageRangesSegment.clearRange) + clearRange = getPageRangesSegment.clearRange; + let pageRangeIndex = 0; + let clearRangeIndex = 0; + while (pageRangeIndex < pageRange.length && clearRangeIndex < clearRange.length) { + if (pageRange[pageRangeIndex].start < clearRange[clearRangeIndex].start) { + yield { + start: pageRange[pageRangeIndex].start, + end: pageRange[pageRangeIndex].end, + isClear: false + }; + ++pageRangeIndex; + } else { + yield { + start: clearRange[clearRangeIndex].start, + end: clearRange[clearRangeIndex].end, + isClear: true + }; + ++clearRangeIndex; + } + } + for (; pageRangeIndex < pageRange.length; ++pageRangeIndex) { + yield { + start: pageRange[pageRangeIndex].start, + end: pageRange[pageRangeIndex].end, + isClear: false + }; + } + for (; clearRangeIndex < clearRange.length; ++clearRangeIndex) { + yield { + start: clearRange[clearRangeIndex].start, + end: clearRange[clearRangeIndex].end, + isClear: true + }; + } + } + function EscapePath(blobName) { + const split = blobName.split("/"); + for (let i = 0; i < split.length; i++) { + split[i] = encodeURIComponent(split[i]); + } + return split.join("/"); + } + function assertResponse(response) { + if (`_response` in response) { + return response; + } + throw new TypeError(`Unexpected response object ${response}`); + } + exports2.StorageRetryPolicyType = void 0; + (function(StorageRetryPolicyType2) { + StorageRetryPolicyType2[StorageRetryPolicyType2["EXPONENTIAL"] = 0] = "EXPONENTIAL"; + StorageRetryPolicyType2[StorageRetryPolicyType2["FIXED"] = 1] = "FIXED"; + })(exports2.StorageRetryPolicyType || (exports2.StorageRetryPolicyType = {})); + var DEFAULT_RETRY_OPTIONS$1 = { + maxRetryDelayInMs: 120 * 1e3, + maxTries: 4, + retryDelayInMs: 4 * 1e3, + retryPolicyType: exports2.StorageRetryPolicyType.EXPONENTIAL, + secondaryHost: "", + tryTimeoutInMs: void 0 + // Use server side default timeout strategy + }; + var RETRY_ABORT_ERROR$1 = new abortController.AbortError("The operation was aborted."); + var StorageRetryPolicy = class extends BaseRequestPolicy { + /** + * Creates an instance of RetryPolicy. + * + * @param nextPolicy - + * @param options - + * @param retryOptions - + */ + constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS$1) { + super(nextPolicy, options); + this.retryOptions = { + retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS$1.retryPolicyType, + maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 ? Math.floor(retryOptions.maxTries) : DEFAULT_RETRY_OPTIONS$1.maxTries, + tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 ? retryOptions.tryTimeoutInMs : DEFAULT_RETRY_OPTIONS$1.tryTimeoutInMs, + retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs) : DEFAULT_RETRY_OPTIONS$1.retryDelayInMs, + maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs, + secondaryHost: retryOptions.secondaryHost ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS$1.secondaryHost + }; + } + /** + * Sends request. + * + * @param request - + */ + async sendRequest(request) { + return this.attemptSendRequest(request, false, 1); + } + /** + * Decide and perform next retry. Won't mutate request parameter. + * + * @param request - + * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then + * the resource was not found. This may be due to replication delay. So, in this + * case, we'll never try the secondary again for this operation. + * @param attempt - How many retries has been attempted to performed, starting from 1, which includes + * the attempt will be performed by this method call. + */ + async attemptSendRequest(request, secondaryHas404, attempt) { + const newRequest = request.clone(); + const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || attempt % 2 === 1; + if (!isPrimaryRetry) { + newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); + } + if (this.retryOptions.tryTimeoutInMs) { + newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1e3).toString()); + } + let response; + try { + logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); + response = await this._nextPolicy.sendRequest(newRequest); + if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { + return response; + } + secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; + } catch (err) { + logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); + if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { + throw err; + } + } + await this.delay(isPrimaryRetry, attempt, request.abortSignal); + return this.attemptSendRequest(request, secondaryHas404, ++attempt); + } + /** + * Decide whether to retry according to last HTTP response and retry counters. + * + * @param isPrimaryRetry - + * @param attempt - + * @param response - + * @param err - + */ + shouldRetry(isPrimaryRetry, attempt, response, err) { + if (attempt >= this.retryOptions.maxTries) { + logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions.maxTries}, no further try.`); + return false; + } + const retriableErrors2 = [ + "ETIMEDOUT", + "ESOCKETTIMEDOUT", + "ECONNREFUSED", + "ECONNRESET", + "ENOENT", + "ENOTFOUND", + "TIMEOUT", + "EPIPE", + "REQUEST_SEND_ERROR" + // For default xhr based http client provided in ms-rest-js + ]; + if (err) { + for (const retriableError of retriableErrors2) { + if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || err.code && err.code.toString().toUpperCase() === retriableError) { + logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); + return true; + } + } + } + if (response || err) { + const statusCode = response ? response.status : err ? err.statusCode : 0; + if (!isPrimaryRetry && statusCode === 404) { + logger.info(`RetryPolicy: Secondary access with 404, will retry.`); + return true; + } + if (statusCode === 503 || statusCode === 500) { + logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); + return true; + } + } + if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith(`Error "Error: Unclosed root tag`))) { + logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); + return true; + } + return false; + } + /** + * Delay a calculated time between retries. + * + * @param isPrimaryRetry - + * @param attempt - + * @param abortSignal - + */ + async delay(isPrimaryRetry, attempt, abortSignal) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (this.retryOptions.retryPolicyType) { + case exports2.StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); + break; + case exports2.StorageRetryPolicyType.FIXED: + delayTimeInMs = this.retryOptions.retryDelayInMs; + break; + } + } else { + delayTimeInMs = Math.random() * 1e3; + } + logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR$1); + } + }; + var StorageRetryPolicyFactory = class { + /** + * Creates an instance of StorageRetryPolicyFactory. + * @param retryOptions - + */ + constructor(retryOptions) { + this.retryOptions = retryOptions; + } + /** + * Creates a StorageRetryPolicy object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); + } + }; + var CredentialPolicy = class extends BaseRequestPolicy { + /** + * Sends out request. + * + * @param request - + */ + sendRequest(request) { + return this._nextPolicy.sendRequest(this.signRequest(request)); + } + /** + * Child classes must implement this method with request signing. This method + * will be executed in {@link sendRequest}. + * + * @param request - + */ + signRequest(request) { + return request; + } + }; + var table_lv0 = new Uint32Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1820, + 0, + 1823, + 1825, + 1827, + 1829, + 0, + 0, + 0, + 1837, + 2051, + 0, + 0, + 1843, + 0, + 3331, + 3354, + 3356, + 3358, + 3360, + 3362, + 3364, + 3366, + 3368, + 3370, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 3586, + 3593, + 3594, + 3610, + 3617, + 3619, + 3621, + 3628, + 3634, + 3637, + 3638, + 3656, + 3665, + 3696, + 3708, + 3710, + 3721, + 3722, + 3729, + 3737, + 3743, + 3746, + 3748, + 3750, + 3751, + 3753, + 0, + 0, + 0, + 1859, + 1860, + 1864, + 3586, + 3593, + 3594, + 3610, + 3617, + 3619, + 3621, + 3628, + 3634, + 3637, + 3638, + 3656, + 3665, + 3696, + 3708, + 3710, + 3721, + 3722, + 3729, + 3737, + 3743, + 3746, + 3748, + 3750, + 3751, + 3753, + 0, + 1868, + 0, + 1872, + 0 + ]); + var table_lv2 = new Uint32Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 18, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]); + var table_lv4 = new Uint32Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 32786, + 0, + 0, + 0, + 0, + 0, + 33298, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]); + function compareHeader(lhs, rhs) { + if (isLessThan(lhs, rhs)) + return -1; + return 1; + } + function isLessThan(lhs, rhs) { + const tables = [table_lv0, table_lv2, table_lv4]; + let curr_level = 0; + let i = 0; + let j = 0; + while (curr_level < tables.length) { + if (curr_level === tables.length - 1 && i !== j) { + return i > j; + } + const weight1 = i < lhs.length ? tables[curr_level][lhs[i].charCodeAt(0)] : 1; + const weight2 = j < rhs.length ? tables[curr_level][rhs[j].charCodeAt(0)] : 1; + if (weight1 === 1 && weight2 === 1) { + i = 0; + j = 0; + ++curr_level; + } else if (weight1 === weight2) { + ++i; + ++j; + } else if (weight1 === 0) { + ++i; + } else if (weight2 === 0) { + ++j; + } else { + return weight1 < weight2; + } + } + return false; + } + var StorageSharedKeyCredentialPolicy = class extends CredentialPolicy { + /** + * Creates an instance of StorageSharedKeyCredentialPolicy. + * @param nextPolicy - + * @param options - + * @param factory - + */ + constructor(nextPolicy, options, factory) { + super(nextPolicy, options); + this.factory = factory; + } + /** + * Signs request. + * + * @param request - + */ + signRequest(request) { + request.headers.set(HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); + if (request.body && (typeof request.body === "string" || request.body !== void 0) && request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + const stringToSign = [ + request.method.toUpperCase(), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), + this.getHeaderValueToSign(request, HeaderConstants.DATE), + this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), + this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH), + this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), + this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), + this.getHeaderValueToSign(request, HeaderConstants.RANGE) + ].join("\n") + "\n" + this.getCanonicalizedHeadersString(request) + this.getCanonicalizedResourceString(request); + const signature = this.factory.computeHMACSHA256(stringToSign); + request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); + return request; + } + /** + * Retrieve header value according to shared key sign rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key + * + * @param request - + * @param headerName - + */ + getHeaderValueToSign(request, headerName) { + const value = request.headers.get(headerName); + if (!value) { + return ""; + } + if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { + return ""; + } + return value; + } + /** + * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: + * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. + * 2. Convert each HTTP header name to lowercase. + * 3. Sort the headers lexicographically by header name, in ascending order. + * Each header may appear only once in the string. + * 4. Replace any linear whitespace in the header value with a single space. + * 5. Trim any whitespace around the colon in the header. + * 6. Finally, append a new-line character to each canonicalized header in the resulting list. + * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. + * + * @param request - + */ + getCanonicalizedHeadersString(request) { + let headersArray = request.headers.headersArray().filter((value) => { + return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); + }); + headersArray.sort((a, b) => { + return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); + }); + headersArray = headersArray.filter((value, index, array) => { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { + return false; + } + return true; + }); + let canonicalizedHeadersStringToSign = ""; + headersArray.forEach((header) => { + canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} +`; + }); + return canonicalizedHeadersStringToSign; + } + /** + * Retrieves the webResource canonicalized resource string. + * + * @param request - + */ + getCanonicalizedResourceString(request) { + const path2 = getURLPath(request.url) || "/"; + let canonicalizedResourceString = ""; + canonicalizedResourceString += `/${this.factory.accountName}${path2}`; + const queries = getURLQueries(request.url); + const lowercaseQueries = {}; + if (queries) { + const queryKeys = []; + for (const key in queries) { + if (Object.prototype.hasOwnProperty.call(queries, key)) { + const lowercaseKey = key.toLowerCase(); + lowercaseQueries[lowercaseKey] = queries[key]; + queryKeys.push(lowercaseKey); + } + } + queryKeys.sort(); + for (const key of queryKeys) { + canonicalizedResourceString += ` +${key}:${decodeURIComponent(lowercaseQueries[key])}`; + } + } + return canonicalizedResourceString; + } + }; + var Credential = class { + /** + * Creates a RequestPolicy object. + * + * @param _nextPolicy - + * @param _options - + */ + create(_nextPolicy, _options) { + throw new Error("Method should be implemented in children classes."); + } + }; + var StorageSharedKeyCredential = class extends Credential { + /** + * Creates an instance of StorageSharedKeyCredential. + * @param accountName - + * @param accountKey - + */ + constructor(accountName, accountKey) { + super(); + this.accountName = accountName; + this.accountKey = Buffer.from(accountKey, "base64"); + } + /** + * Creates a StorageSharedKeyCredentialPolicy object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); + } + /** + * Generates a hash signature for an HTTP request or for a SAS. + * + * @param stringToSign - + */ + computeHMACSHA256(stringToSign) { + return crypto.createHmac("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); + } + }; + var AnonymousCredentialPolicy = class extends CredentialPolicy { + /** + * Creates an instance of AnonymousCredentialPolicy. + * @param nextPolicy - + * @param options - + */ + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + }; + var AnonymousCredential = class extends Credential { + /** + * Creates an {@link AnonymousCredentialPolicy} object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new AnonymousCredentialPolicy(nextPolicy, options); + } + }; + var _defaultHttpClient; + function getCachedDefaultHttpClient() { + if (!_defaultHttpClient) { + _defaultHttpClient = coreRestPipeline.createDefaultHttpClient(); + } + return _defaultHttpClient; + } + var storageBrowserPolicyName = "storageBrowserPolicy"; + function storageBrowserPolicy() { + return { + name: storageBrowserPolicyName, + async sendRequest(request, next) { + if (coreUtil.isNode) { + return next(request); + } + if (request.method === "GET" || request.method === "HEAD") { + request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); + } + request.headers.delete(HeaderConstants.COOKIE); + request.headers.delete(HeaderConstants.CONTENT_LENGTH); + return next(request); + } + }; + } + var storageRetryPolicyName = "storageRetryPolicy"; + var StorageRetryPolicyType; + (function(StorageRetryPolicyType2) { + StorageRetryPolicyType2[StorageRetryPolicyType2["EXPONENTIAL"] = 0] = "EXPONENTIAL"; + StorageRetryPolicyType2[StorageRetryPolicyType2["FIXED"] = 1] = "FIXED"; + })(StorageRetryPolicyType || (StorageRetryPolicyType = {})); + var DEFAULT_RETRY_OPTIONS = { + maxRetryDelayInMs: 120 * 1e3, + maxTries: 4, + retryDelayInMs: 4 * 1e3, + retryPolicyType: StorageRetryPolicyType.EXPONENTIAL, + secondaryHost: "", + tryTimeoutInMs: void 0 + // Use server side default timeout strategy + }; + var retriableErrors = [ + "ETIMEDOUT", + "ESOCKETTIMEDOUT", + "ECONNREFUSED", + "ECONNRESET", + "ENOENT", + "ENOTFOUND", + "TIMEOUT", + "EPIPE", + "REQUEST_SEND_ERROR" + ]; + var RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); + function storageRetryPolicy(options = {}) { + var _a, _b, _c, _d, _e, _f; + const retryPolicyType = (_a = options.retryPolicyType) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_OPTIONS.retryPolicyType; + const maxTries = (_b = options.maxTries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_OPTIONS.maxTries; + const retryDelayInMs = (_c = options.retryDelayInMs) !== null && _c !== void 0 ? _c : DEFAULT_RETRY_OPTIONS.retryDelayInMs; + const maxRetryDelayInMs = (_d = options.maxRetryDelayInMs) !== null && _d !== void 0 ? _d : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs; + const secondaryHost = (_e = options.secondaryHost) !== null && _e !== void 0 ? _e : DEFAULT_RETRY_OPTIONS.secondaryHost; + const tryTimeoutInMs = (_f = options.tryTimeoutInMs) !== null && _f !== void 0 ? _f : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs; + function shouldRetry({ isPrimaryRetry, attempt, response, error: error4 }) { + var _a2, _b2; + if (attempt >= maxTries) { + logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`); + return false; + } + if (error4) { + for (const retriableError of retriableErrors) { + if (error4.name.toUpperCase().includes(retriableError) || error4.message.toUpperCase().includes(retriableError) || error4.code && error4.code.toString().toUpperCase() === retriableError) { + logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); + return true; + } + } + if ((error4 === null || error4 === void 0 ? void 0 : error4.code) === "PARSE_ERROR" && (error4 === null || error4 === void 0 ? void 0 : error4.message.startsWith(`Error "Error: Unclosed root tag`))) { + logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); + return true; + } + } + if (response || error4) { + const statusCode = (_b2 = (_a2 = response === null || response === void 0 ? void 0 : response.status) !== null && _a2 !== void 0 ? _a2 : error4 === null || error4 === void 0 ? void 0 : error4.statusCode) !== null && _b2 !== void 0 ? _b2 : 0; + if (!isPrimaryRetry && statusCode === 404) { + logger.info(`RetryPolicy: Secondary access with 404, will retry.`); + return true; + } + if (statusCode === 503 || statusCode === 500) { + logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); + return true; + } + } + return false; + } + function calculateDelay(isPrimaryRetry, attempt) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (retryPolicyType) { + case StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs); + break; + case StorageRetryPolicyType.FIXED: + delayTimeInMs = retryDelayInMs; + break; + } + } else { + delayTimeInMs = Math.random() * 1e3; + } + logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return delayTimeInMs; + } + return { + name: storageRetryPolicyName, + async sendRequest(request, next) { + if (tryTimeoutInMs) { + request.url = setURLParameter(request.url, URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1e3))); + } + const primaryUrl = request.url; + const secondaryUrl = secondaryHost ? setURLHost(request.url, secondaryHost) : void 0; + let secondaryHas404 = false; + let attempt = 1; + let retryAgain = true; + let response; + let error4; + while (retryAgain) { + const isPrimaryRetry = secondaryHas404 || !secondaryUrl || !["GET", "HEAD", "OPTIONS"].includes(request.method) || attempt % 2 === 1; + request.url = isPrimaryRetry ? primaryUrl : secondaryUrl; + response = void 0; + error4 = void 0; + try { + logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); + response = await next(request); + secondaryHas404 = secondaryHas404 || !isPrimaryRetry && response.status === 404; + } catch (e) { + if (coreRestPipeline.isRestError(e)) { + logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`); + error4 = e; + } else { + logger.error(`RetryPolicy: Caught error, message: ${coreUtil.getErrorMessage(e)}`); + throw e; + } + } + retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error: error4 }); + if (retryAgain) { + await delay(calculateDelay(isPrimaryRetry, attempt), request.abortSignal, RETRY_ABORT_ERROR); + } + attempt++; + } + if (response) { + return response; + } + throw error4 !== null && error4 !== void 0 ? error4 : new coreRestPipeline.RestError("RetryPolicy failed without known error."); + } + }; + } + var storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy"; + function storageSharedKeyCredentialPolicy(options) { + function signRequest(request) { + request.headers.set(HeaderConstants.X_MS_DATE, (/* @__PURE__ */ new Date()).toUTCString()); + if (request.body && (typeof request.body === "string" || Buffer.isBuffer(request.body)) && request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + const stringToSign = [ + request.method.toUpperCase(), + getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), + getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), + getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), + getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), + getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), + getHeaderValueToSign(request, HeaderConstants.DATE), + getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), + getHeaderValueToSign(request, HeaderConstants.IF_MATCH), + getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), + getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), + getHeaderValueToSign(request, HeaderConstants.RANGE) + ].join("\n") + "\n" + getCanonicalizedHeadersString(request) + getCanonicalizedResourceString(request); + const signature = crypto.createHmac("sha256", options.accountKey).update(stringToSign, "utf8").digest("base64"); + request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`); + } + function getHeaderValueToSign(request, headerName) { + const value = request.headers.get(headerName); + if (!value) { + return ""; + } + if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { + return ""; + } + return value; + } + function getCanonicalizedHeadersString(request) { + let headersArray = []; + for (const [name, value] of request.headers) { + if (name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE)) { + headersArray.push({ name, value }); + } + } + headersArray.sort((a, b) => { + return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); + }); + headersArray = headersArray.filter((value, index, array) => { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { + return false; + } + return true; + }); + let canonicalizedHeadersStringToSign = ""; + headersArray.forEach((header) => { + canonicalizedHeadersStringToSign += `${header.name.toLowerCase().trimRight()}:${header.value.trimLeft()} +`; + }); + return canonicalizedHeadersStringToSign; + } + function getCanonicalizedResourceString(request) { + const path2 = getURLPath(request.url) || "/"; + let canonicalizedResourceString = ""; + canonicalizedResourceString += `/${options.accountName}${path2}`; + const queries = getURLQueries(request.url); + const lowercaseQueries = {}; + if (queries) { + const queryKeys = []; + for (const key in queries) { + if (Object.prototype.hasOwnProperty.call(queries, key)) { + const lowercaseKey = key.toLowerCase(); + lowercaseQueries[lowercaseKey] = queries[key]; + queryKeys.push(lowercaseKey); + } + } + queryKeys.sort(); + for (const key of queryKeys) { + canonicalizedResourceString += ` +${key}:${decodeURIComponent(lowercaseQueries[key])}`; + } + } + return canonicalizedResourceString; + } + return { + name: storageSharedKeyCredentialPolicyName, + async sendRequest(request, next) { + signRequest(request); + return next(request); + } + }; + } + var StorageBrowserPolicy = class extends BaseRequestPolicy { + /** + * Creates an instance of StorageBrowserPolicy. + * @param nextPolicy - + * @param options - + */ + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + /** + * Sends out request. + * + * @param request - + */ + async sendRequest(request) { + if (coreUtil.isNode) { + return this._nextPolicy.sendRequest(request); + } + if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { + request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, (/* @__PURE__ */ new Date()).getTime().toString()); + } + request.headers.remove(HeaderConstants.COOKIE); + request.headers.remove(HeaderConstants.CONTENT_LENGTH); + return this._nextPolicy.sendRequest(request); + } + }; + var StorageBrowserPolicyFactory = class { + /** + * Creates a StorageBrowserPolicyFactory object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new StorageBrowserPolicy(nextPolicy, options); + } + }; + var storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy"; + function storageCorrectContentLengthPolicy() { + function correctContentLength(request) { + if (request.body && (typeof request.body === "string" || Buffer.isBuffer(request.body)) && request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + } + return { + name: storageCorrectContentLengthPolicyName, + async sendRequest(request, next) { + correctContentLength(request); + return next(request); + } + }; + } + function isPipelineLike(pipeline) { + if (!pipeline || typeof pipeline !== "object") { + return false; + } + const castPipeline = pipeline; + return Array.isArray(castPipeline.factories) && typeof castPipeline.options === "object" && typeof castPipeline.toServiceClientOptions === "function"; + } + var Pipeline = class { + /** + * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. + * + * @param factories - + * @param options - + */ + constructor(factories, options = {}) { + this.factories = factories; + this.options = options; + } + /** + * Transfer Pipeline object to ServiceClientOptions object which is required by + * ServiceClient constructor. + * + * @returns The ServiceClientOptions object from this Pipeline. + */ + toServiceClientOptions() { + return { + httpClient: this.options.httpClient, + requestPolicyFactories: this.factories + }; + } + }; + function newPipeline(credential, pipelineOptions = {}) { + if (!credential) { + credential = new AnonymousCredential(); + } + const pipeline = new Pipeline([], pipelineOptions); + pipeline._credential = credential; + return pipeline; + } + function processDownlevelPipeline(pipeline) { + const knownFactoryFunctions = [ + isAnonymousCredential, + isStorageSharedKeyCredential, + isCoreHttpBearerTokenFactory, + isStorageBrowserPolicyFactory, + isStorageRetryPolicyFactory, + isStorageTelemetryPolicyFactory, + isCoreHttpPolicyFactory + ]; + if (pipeline.factories.length) { + const novelFactories = pipeline.factories.filter((factory) => { + return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory)); + }); + if (novelFactories.length) { + const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory)); + return { + wrappedPolicies: coreHttpCompat.createRequestPolicyFactoryPolicy(novelFactories), + afterRetry: hasInjector + }; + } + } + return void 0; + } + function getCoreClientOptions(pipeline) { + var _a; + const _b = pipeline.options, { httpClient: v1Client } = _b, restOptions = tslib.__rest(_b, ["httpClient"]); + let httpClient = pipeline._coreHttpClient; + if (!httpClient) { + httpClient = v1Client ? coreHttpCompat.convertHttpClient(v1Client) : getCachedDefaultHttpClient(); + pipeline._coreHttpClient = httpClient; + } + let corePipeline = pipeline._corePipeline; + if (!corePipeline) { + const packageDetails = `azsdk-js-azure-storage-blob/${SDK_VERSION}`; + const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; + corePipeline = coreClient.createClientPipeline(Object.assign(Object.assign({}, restOptions), { loggingOptions: { + additionalAllowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, + additionalAllowedQueryParameters: StorageBlobLoggingAllowedQueryParameters, + logger: logger.info + }, userAgentOptions: { + userAgentPrefix + }, serializationOptions: { + stringifyXML: coreXml.stringifyXML, + serializerOptions: { + xml: { + // Use customized XML char key of "#" so we can deserialize metadata + // with "_" key + xmlCharKey: "#" + } + } + }, deserializationOptions: { + parseXML: coreXml.parseXML, + serializerOptions: { + xml: { + // Use customized XML char key of "#" so we can deserialize metadata + // with "_" key + xmlCharKey: "#" + } + } + } })); + corePipeline.removePolicy({ phase: "Retry" }); + corePipeline.removePolicy({ name: coreRestPipeline.decompressResponsePolicyName }); + corePipeline.addPolicy(storageCorrectContentLengthPolicy()); + corePipeline.addPolicy(storageRetryPolicy(restOptions.retryOptions), { phase: "Retry" }); + corePipeline.addPolicy(storageBrowserPolicy()); + const downlevelResults = processDownlevelPipeline(pipeline); + if (downlevelResults) { + corePipeline.addPolicy(downlevelResults.wrappedPolicies, downlevelResults.afterRetry ? { afterPhase: "Retry" } : void 0); + } + const credential = getCredentialFromPipeline(pipeline); + if (coreAuth.isTokenCredential(credential)) { + corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ + credential, + scopes: (_a = restOptions.audience) !== null && _a !== void 0 ? _a : StorageOAuthScopes, + challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge } + }), { phase: "Sign" }); + } else if (credential instanceof StorageSharedKeyCredential) { + corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ + accountName: credential.accountName, + accountKey: credential.accountKey + }), { phase: "Sign" }); + } + pipeline._corePipeline = corePipeline; + } + return Object.assign(Object.assign({}, restOptions), { allowInsecureConnection: true, httpClient, pipeline: corePipeline }); + } + function getCredentialFromPipeline(pipeline) { + if (pipeline._credential) { + return pipeline._credential; + } + let credential = new AnonymousCredential(); + for (const factory of pipeline.factories) { + if (coreAuth.isTokenCredential(factory.credential)) { + credential = factory.credential; + } else if (isStorageSharedKeyCredential(factory)) { + return factory; + } + } + return credential; + } + function isStorageSharedKeyCredential(factory) { + if (factory instanceof StorageSharedKeyCredential) { + return true; + } + return factory.constructor.name === "StorageSharedKeyCredential"; + } + function isAnonymousCredential(factory) { + if (factory instanceof AnonymousCredential) { + return true; + } + return factory.constructor.name === "AnonymousCredential"; + } + function isCoreHttpBearerTokenFactory(factory) { + return coreAuth.isTokenCredential(factory.credential); + } + function isStorageBrowserPolicyFactory(factory) { + if (factory instanceof StorageBrowserPolicyFactory) { + return true; + } + return factory.constructor.name === "StorageBrowserPolicyFactory"; + } + function isStorageRetryPolicyFactory(factory) { + if (factory instanceof StorageRetryPolicyFactory) { + return true; + } + return factory.constructor.name === "StorageRetryPolicyFactory"; + } + function isStorageTelemetryPolicyFactory(factory) { + return factory.constructor.name === "TelemetryPolicyFactory"; + } + function isInjectorPolicyFactory(factory) { + return factory.constructor.name === "InjectorPolicyFactory"; + } + function isCoreHttpPolicyFactory(factory) { + const knownPolicies = [ + "GenerateClientRequestIdPolicy", + "TracingPolicy", + "LogPolicy", + "ProxyPolicy", + "DisableResponseDecompressionPolicy", + "KeepAlivePolicy", + "DeserializationPolicy" + ]; + const mockHttpClient = { + sendRequest: async (request) => { + return { + request, + headers: request.headers.clone(), + status: 500 + }; + } + }; + const mockRequestPolicyOptions = { + log(_logLevel, _message) { + }, + shouldLog(_logLevel) { + return false; + } + }; + const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions); + const policyName = policyInstance.constructor.name; + return knownPolicies.some((knownPolicyName) => { + return policyName.startsWith(knownPolicyName); + }); + } + var BlobServiceProperties = { + serializedName: "BlobServiceProperties", + xmlName: "StorageServiceProperties", + type: { + name: "Composite", + className: "BlobServiceProperties", + modelProperties: { + blobAnalyticsLogging: { + serializedName: "Logging", + xmlName: "Logging", + type: { + name: "Composite", + className: "Logging" + } + }, + hourMetrics: { + serializedName: "HourMetrics", + xmlName: "HourMetrics", + type: { + name: "Composite", + className: "Metrics" + } + }, + minuteMetrics: { + serializedName: "MinuteMetrics", + xmlName: "MinuteMetrics", + type: { + name: "Composite", + className: "Metrics" + } + }, + cors: { + serializedName: "Cors", + xmlName: "Cors", + xmlIsWrapped: true, + xmlElementName: "CorsRule", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "CorsRule" + } + } + } + }, + defaultServiceVersion: { + serializedName: "DefaultServiceVersion", + xmlName: "DefaultServiceVersion", + type: { + name: "String" + } + }, + deleteRetentionPolicy: { + serializedName: "DeleteRetentionPolicy", + xmlName: "DeleteRetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + }, + staticWebsite: { + serializedName: "StaticWebsite", + xmlName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite" + } + } + } + } + }; + var Logging = { + serializedName: "Logging", + type: { + name: "Composite", + className: "Logging", + modelProperties: { + version: { + serializedName: "Version", + required: true, + xmlName: "Version", + type: { + name: "String" + } + }, + deleteProperty: { + serializedName: "Delete", + required: true, + xmlName: "Delete", + type: { + name: "Boolean" + } + }, + read: { + serializedName: "Read", + required: true, + xmlName: "Read", + type: { + name: "Boolean" + } + }, + write: { + serializedName: "Write", + required: true, + xmlName: "Write", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + } + } + } + }; + var RetentionPolicy = { + serializedName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy", + modelProperties: { + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + days: { + constraints: { + InclusiveMinimum: 1 + }, + serializedName: "Days", + xmlName: "Days", + type: { + name: "Number" + } + } + } + } + }; + var Metrics = { + serializedName: "Metrics", + type: { + name: "Composite", + className: "Metrics", + modelProperties: { + version: { + serializedName: "Version", + xmlName: "Version", + type: { + name: "String" + } + }, + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + includeAPIs: { + serializedName: "IncludeAPIs", + xmlName: "IncludeAPIs", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + } + } + } + }; + var CorsRule = { + serializedName: "CorsRule", + type: { + name: "Composite", + className: "CorsRule", + modelProperties: { + allowedOrigins: { + serializedName: "AllowedOrigins", + required: true, + xmlName: "AllowedOrigins", + type: { + name: "String" + } + }, + allowedMethods: { + serializedName: "AllowedMethods", + required: true, + xmlName: "AllowedMethods", + type: { + name: "String" + } + }, + allowedHeaders: { + serializedName: "AllowedHeaders", + required: true, + xmlName: "AllowedHeaders", + type: { + name: "String" + } + }, + exposedHeaders: { + serializedName: "ExposedHeaders", + required: true, + xmlName: "ExposedHeaders", + type: { + name: "String" + } + }, + maxAgeInSeconds: { + constraints: { + InclusiveMinimum: 0 + }, + serializedName: "MaxAgeInSeconds", + required: true, + xmlName: "MaxAgeInSeconds", + type: { + name: "Number" + } + } + } + } + }; + var StaticWebsite = { + serializedName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite", + modelProperties: { + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + indexDocument: { + serializedName: "IndexDocument", + xmlName: "IndexDocument", + type: { + name: "String" + } + }, + errorDocument404Path: { + serializedName: "ErrorDocument404Path", + xmlName: "ErrorDocument404Path", + type: { + name: "String" + } + }, + defaultIndexDocumentPath: { + serializedName: "DefaultIndexDocumentPath", + xmlName: "DefaultIndexDocumentPath", + type: { + name: "String" + } + } + } + } + }; + var StorageError = { + serializedName: "StorageError", + type: { + name: "Composite", + className: "StorageError", + modelProperties: { + message: { + serializedName: "Message", + xmlName: "Message", + type: { + name: "String" + } + }, + code: { + serializedName: "Code", + xmlName: "Code", + type: { + name: "String" + } + }, + authenticationErrorDetail: { + serializedName: "AuthenticationErrorDetail", + xmlName: "AuthenticationErrorDetail", + type: { + name: "String" + } + } + } + } + }; + var BlobServiceStatistics = { + serializedName: "BlobServiceStatistics", + xmlName: "StorageServiceStats", + type: { + name: "Composite", + className: "BlobServiceStatistics", + modelProperties: { + geoReplication: { + serializedName: "GeoReplication", + xmlName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication" + } + } + } + } + }; + var GeoReplication = { + serializedName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication", + modelProperties: { + status: { + serializedName: "Status", + required: true, + xmlName: "Status", + type: { + name: "Enum", + allowedValues: ["live", "bootstrap", "unavailable"] + } + }, + lastSyncOn: { + serializedName: "LastSyncTime", + required: true, + xmlName: "LastSyncTime", + type: { + name: "DateTimeRfc1123" + } + } + } + } + }; + var ListContainersSegmentResponse = { + serializedName: "ListContainersSegmentResponse", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "ListContainersSegmentResponse", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + prefix: { + serializedName: "Prefix", + xmlName: "Prefix", + type: { + name: "String" + } + }, + marker: { + serializedName: "Marker", + xmlName: "Marker", + type: { + name: "String" + } + }, + maxPageSize: { + serializedName: "MaxResults", + xmlName: "MaxResults", + type: { + name: "Number" + } + }, + containerItems: { + serializedName: "ContainerItems", + required: true, + xmlName: "Containers", + xmlIsWrapped: true, + xmlElementName: "Container", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "ContainerItem" + } + } + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } + } + } + }; + var ContainerItem = { + serializedName: "ContainerItem", + xmlName: "Container", + type: { + name: "Composite", + className: "ContainerItem", + modelProperties: { + name: { + serializedName: "Name", + required: true, + xmlName: "Name", + type: { + name: "String" + } + }, + deleted: { + serializedName: "Deleted", + xmlName: "Deleted", + type: { + name: "Boolean" + } + }, + version: { + serializedName: "Version", + xmlName: "Version", + type: { + name: "String" + } + }, + properties: { + serializedName: "Properties", + xmlName: "Properties", + type: { + name: "Composite", + className: "ContainerProperties" + } + }, + metadata: { + serializedName: "Metadata", + xmlName: "Metadata", + type: { + name: "Dictionary", + value: { type: { name: "String" } } + } + } + } + } + }; + var ContainerProperties = { + serializedName: "ContainerProperties", + type: { + name: "Composite", + className: "ContainerProperties", + modelProperties: { + lastModified: { + serializedName: "Last-Modified", + required: true, + xmlName: "Last-Modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "Etag", + required: true, + xmlName: "Etag", + type: { + name: "String" + } + }, + leaseStatus: { + serializedName: "LeaseStatus", + xmlName: "LeaseStatus", + type: { + name: "Enum", + allowedValues: ["locked", "unlocked"] + } + }, + leaseState: { + serializedName: "LeaseState", + xmlName: "LeaseState", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseDuration: { + serializedName: "LeaseDuration", + xmlName: "LeaseDuration", + type: { + name: "Enum", + allowedValues: ["infinite", "fixed"] + } + }, + publicAccess: { + serializedName: "PublicAccess", + xmlName: "PublicAccess", + type: { + name: "Enum", + allowedValues: ["container", "blob"] + } + }, + hasImmutabilityPolicy: { + serializedName: "HasImmutabilityPolicy", + xmlName: "HasImmutabilityPolicy", + type: { + name: "Boolean" + } + }, + hasLegalHold: { + serializedName: "HasLegalHold", + xmlName: "HasLegalHold", + type: { + name: "Boolean" + } + }, + defaultEncryptionScope: { + serializedName: "DefaultEncryptionScope", + xmlName: "DefaultEncryptionScope", + type: { + name: "String" + } + }, + preventEncryptionScopeOverride: { + serializedName: "DenyEncryptionScopeOverride", + xmlName: "DenyEncryptionScopeOverride", + type: { + name: "Boolean" + } + }, + deletedOn: { + serializedName: "DeletedTime", + xmlName: "DeletedTime", + type: { + name: "DateTimeRfc1123" + } + }, + remainingRetentionDays: { + serializedName: "RemainingRetentionDays", + xmlName: "RemainingRetentionDays", + type: { + name: "Number" + } + }, + isImmutableStorageWithVersioningEnabled: { + serializedName: "ImmutableStorageWithVersioningEnabled", + xmlName: "ImmutableStorageWithVersioningEnabled", + type: { + name: "Boolean" + } + } + } + } + }; + var KeyInfo = { + serializedName: "KeyInfo", + type: { + name: "Composite", + className: "KeyInfo", + modelProperties: { + startsOn: { + serializedName: "Start", + required: true, + xmlName: "Start", + type: { + name: "String" + } + }, + expiresOn: { + serializedName: "Expiry", + required: true, + xmlName: "Expiry", + type: { + name: "String" + } + } + } + } + }; + var UserDelegationKey = { + serializedName: "UserDelegationKey", + type: { + name: "Composite", + className: "UserDelegationKey", + modelProperties: { + signedObjectId: { + serializedName: "SignedOid", + required: true, + xmlName: "SignedOid", + type: { + name: "String" + } + }, + signedTenantId: { + serializedName: "SignedTid", + required: true, + xmlName: "SignedTid", + type: { + name: "String" + } + }, + signedStartsOn: { + serializedName: "SignedStart", + required: true, + xmlName: "SignedStart", + type: { + name: "String" + } + }, + signedExpiresOn: { + serializedName: "SignedExpiry", + required: true, + xmlName: "SignedExpiry", + type: { + name: "String" + } + }, + signedService: { + serializedName: "SignedService", + required: true, + xmlName: "SignedService", + type: { + name: "String" + } + }, + signedVersion: { + serializedName: "SignedVersion", + required: true, + xmlName: "SignedVersion", + type: { + name: "String" + } + }, + value: { + serializedName: "Value", + required: true, + xmlName: "Value", + type: { + name: "String" + } + } + } + } + }; + var FilterBlobSegment = { + serializedName: "FilterBlobSegment", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "FilterBlobSegment", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + where: { + serializedName: "Where", + required: true, + xmlName: "Where", + type: { + name: "String" + } + }, + blobs: { + serializedName: "Blobs", + required: true, + xmlName: "Blobs", + xmlIsWrapped: true, + xmlElementName: "Blob", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "FilterBlobItem" + } + } + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } + } + } + }; + var FilterBlobItem = { + serializedName: "FilterBlobItem", + xmlName: "Blob", + type: { + name: "Composite", + className: "FilterBlobItem", + modelProperties: { + name: { + serializedName: "Name", + required: true, + xmlName: "Name", + type: { + name: "String" + } + }, + containerName: { + serializedName: "ContainerName", + required: true, + xmlName: "ContainerName", + type: { + name: "String" + } + }, + tags: { + serializedName: "Tags", + xmlName: "Tags", + type: { + name: "Composite", + className: "BlobTags" + } + } + } + } + }; + var BlobTags = { + serializedName: "BlobTags", + xmlName: "Tags", + type: { + name: "Composite", + className: "BlobTags", + modelProperties: { + blobTagSet: { + serializedName: "BlobTagSet", + required: true, + xmlName: "TagSet", + xmlIsWrapped: true, + xmlElementName: "Tag", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobTag" + } + } + } + } + } + } + }; + var BlobTag = { + serializedName: "BlobTag", + xmlName: "Tag", + type: { + name: "Composite", + className: "BlobTag", + modelProperties: { + key: { + serializedName: "Key", + required: true, + xmlName: "Key", + type: { + name: "String" + } + }, + value: { + serializedName: "Value", + required: true, + xmlName: "Value", + type: { + name: "String" + } + } + } + } + }; + var SignedIdentifier = { + serializedName: "SignedIdentifier", + xmlName: "SignedIdentifier", + type: { + name: "Composite", + className: "SignedIdentifier", + modelProperties: { + id: { + serializedName: "Id", + required: true, + xmlName: "Id", + type: { + name: "String" + } + }, + accessPolicy: { + serializedName: "AccessPolicy", + xmlName: "AccessPolicy", + type: { + name: "Composite", + className: "AccessPolicy" + } + } + } + } + }; + var AccessPolicy = { + serializedName: "AccessPolicy", + type: { + name: "Composite", + className: "AccessPolicy", + modelProperties: { + startsOn: { + serializedName: "Start", + xmlName: "Start", + type: { + name: "String" + } + }, + expiresOn: { + serializedName: "Expiry", + xmlName: "Expiry", + type: { + name: "String" + } + }, + permissions: { + serializedName: "Permission", + xmlName: "Permission", + type: { + name: "String" + } + } + } + } + }; + var ListBlobsFlatSegmentResponse = { + serializedName: "ListBlobsFlatSegmentResponse", + xmlName: "EnumerationResults", + type: { + name: "Composite", + className: "ListBlobsFlatSegmentResponse", + modelProperties: { + serviceEndpoint: { + serializedName: "ServiceEndpoint", + required: true, + xmlName: "ServiceEndpoint", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + containerName: { + serializedName: "ContainerName", + required: true, + xmlName: "ContainerName", + xmlIsAttribute: true, + type: { + name: "String" + } + }, + prefix: { + serializedName: "Prefix", + xmlName: "Prefix", + type: { + name: "String" + } + }, + marker: { + serializedName: "Marker", + xmlName: "Marker", + type: { + name: "String" + } + }, + maxPageSize: { + serializedName: "MaxResults", + xmlName: "MaxResults", + type: { + name: "Number" + } + }, + segment: { + serializedName: "Segment", + xmlName: "Blobs", + type: { + name: "Composite", + className: "BlobFlatListSegment" + } + }, + continuationToken: { + serializedName: "NextMarker", + xmlName: "NextMarker", + type: { + name: "String" + } + } + } + } + }; + var BlobFlatListSegment = { + serializedName: "BlobFlatListSegment", + xmlName: "Blobs", + type: { + name: "Composite", + className: "BlobFlatListSegment", + modelProperties: { + blobItems: { + serializedName: "BlobItems", + required: true, + xmlName: "BlobItems", + xmlElementName: "Blob", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobItemInternal" + } + } + } + } + } } }; var BlobItemInternal = { @@ -76531,4804 +78037,5623 @@ var require_isObjectLike = __commonJS({ } }); -// node_modules/lodash/_baseIsArguments.js -var require_baseIsArguments = __commonJS({ - "node_modules/lodash/_baseIsArguments.js"(exports2, module2) { - var baseGetTag = require_baseGetTag(); - var isObjectLike = require_isObjectLike(); - var argsTag = "[object Arguments]"; - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; +// node_modules/lodash/_baseIsArguments.js +var require_baseIsArguments = __commonJS({ + "node_modules/lodash/_baseIsArguments.js"(exports2, module2) { + var baseGetTag = require_baseGetTag(); + var isObjectLike = require_isObjectLike(); + var argsTag = "[object Arguments]"; + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + module2.exports = baseIsArguments; + } +}); + +// node_modules/lodash/isArguments.js +var require_isArguments = __commonJS({ + "node_modules/lodash/isArguments.js"(exports2, module2) { + var baseIsArguments = require_baseIsArguments(); + var isObjectLike = require_isObjectLike(); + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + var propertyIsEnumerable = objectProto.propertyIsEnumerable; + var isArguments = baseIsArguments(/* @__PURE__ */ (function() { + return arguments; + })()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); + }; + module2.exports = isArguments; + } +}); + +// node_modules/lodash/isArray.js +var require_isArray = __commonJS({ + "node_modules/lodash/isArray.js"(exports2, module2) { + var isArray = Array.isArray; + module2.exports = isArray; + } +}); + +// node_modules/lodash/stubFalse.js +var require_stubFalse = __commonJS({ + "node_modules/lodash/stubFalse.js"(exports2, module2) { + function stubFalse() { + return false; + } + module2.exports = stubFalse; + } +}); + +// node_modules/lodash/isBuffer.js +var require_isBuffer = __commonJS({ + "node_modules/lodash/isBuffer.js"(exports2, module2) { + var root = require_root(); + var stubFalse = require_stubFalse(); + var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2; + var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; + var moduleExports = freeModule && freeModule.exports === freeExports; + var Buffer2 = moduleExports ? root.Buffer : void 0; + var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0; + var isBuffer = nativeIsBuffer || stubFalse; + module2.exports = isBuffer; + } +}); + +// node_modules/lodash/_baseIsTypedArray.js +var require_baseIsTypedArray = __commonJS({ + "node_modules/lodash/_baseIsTypedArray.js"(exports2, module2) { + var baseGetTag = require_baseGetTag(); + var isLength = require_isLength(); + var isObjectLike = require_isObjectLike(); + var argsTag = "[object Arguments]"; + var arrayTag = "[object Array]"; + var boolTag = "[object Boolean]"; + var dateTag = "[object Date]"; + var errorTag = "[object Error]"; + var funcTag = "[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[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + function baseIsTypedArray(value) { + return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + module2.exports = baseIsTypedArray; + } +}); + +// node_modules/lodash/_baseUnary.js +var require_baseUnary = __commonJS({ + "node_modules/lodash/_baseUnary.js"(exports2, module2) { + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + module2.exports = baseUnary; + } +}); + +// node_modules/lodash/_nodeUtil.js +var require_nodeUtil = __commonJS({ + "node_modules/lodash/_nodeUtil.js"(exports2, module2) { + var freeGlobal = require_freeGlobal(); + var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2; + var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; + var moduleExports = freeModule && freeModule.exports === freeExports; + var freeProcess = moduleExports && freeGlobal.process; + var nodeUtil = (function() { + try { + var types = freeModule && freeModule.require && freeModule.require("util").types; + if (types) { + return types; + } + return freeProcess && freeProcess.binding && freeProcess.binding("util"); + } catch (e) { + } + })(); + module2.exports = nodeUtil; + } +}); + +// node_modules/lodash/isTypedArray.js +var require_isTypedArray = __commonJS({ + "node_modules/lodash/isTypedArray.js"(exports2, module2) { + var baseIsTypedArray = require_baseIsTypedArray(); + var baseUnary = require_baseUnary(); + var nodeUtil = require_nodeUtil(); + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + module2.exports = isTypedArray; + } +}); + +// node_modules/lodash/_arrayLikeKeys.js +var require_arrayLikeKeys = __commonJS({ + "node_modules/lodash/_arrayLikeKeys.js"(exports2, module2) { + var baseTimes = require_baseTimes(); + var isArguments = require_isArguments(); + var isArray = require_isArray(); + var isBuffer = require_isBuffer(); + var isIndex = require_isIndex(); + var isTypedArray = require_isTypedArray(); + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; + for (var key in value) { + if ((inherited || hasOwnProperty.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(key, length)))) { + result.push(key); + } + } + return result; + } + module2.exports = arrayLikeKeys; + } +}); + +// node_modules/lodash/_isPrototype.js +var require_isPrototype = __commonJS({ + "node_modules/lodash/_isPrototype.js"(exports2, module2) { + var objectProto = Object.prototype; + function isPrototype(value) { + var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; + return value === proto; + } + module2.exports = isPrototype; + } +}); + +// node_modules/lodash/_nativeKeysIn.js +var require_nativeKeysIn = __commonJS({ + "node_modules/lodash/_nativeKeysIn.js"(exports2, module2) { + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + module2.exports = nativeKeysIn; + } +}); + +// node_modules/lodash/_baseKeysIn.js +var require_baseKeysIn = __commonJS({ + "node_modules/lodash/_baseKeysIn.js"(exports2, module2) { + var isObject2 = require_isObject(); + var isPrototype = require_isPrototype(); + var nativeKeysIn = require_nativeKeysIn(); + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + function baseKeysIn(object) { + if (!isObject2(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), result = []; + for (var key in object) { + if (!(key == "constructor" && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + module2.exports = baseKeysIn; + } +}); + +// node_modules/lodash/keysIn.js +var require_keysIn = __commonJS({ + "node_modules/lodash/keysIn.js"(exports2, module2) { + var arrayLikeKeys = require_arrayLikeKeys(); + var baseKeysIn = require_baseKeysIn(); + var isArrayLike = require_isArrayLike(); + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } - module2.exports = baseIsArguments; + module2.exports = keysIn; } }); -// node_modules/lodash/isArguments.js -var require_isArguments = __commonJS({ - "node_modules/lodash/isArguments.js"(exports2, module2) { - var baseIsArguments = require_baseIsArguments(); - var isObjectLike = require_isObjectLike(); +// node_modules/lodash/defaults.js +var require_defaults = __commonJS({ + "node_modules/lodash/defaults.js"(exports2, module2) { + var baseRest = require_baseRest(); + var eq = require_eq2(); + var isIterateeCall = require_isIterateeCall(); + var keysIn = require_keysIn(); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; - var propertyIsEnumerable = objectProto.propertyIsEnumerable; - var isArguments = baseIsArguments(/* @__PURE__ */ (function() { - return arguments; - })()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); - }; - module2.exports = isArguments; + var defaults = baseRest(function(object, sources) { + object = Object(object); + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : void 0; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + if (value === void 0 || eq(value, objectProto[key]) && !hasOwnProperty.call(object, key)) { + object[key] = source[key]; + } + } + } + return object; + }); + module2.exports = defaults; } }); -// node_modules/lodash/isArray.js -var require_isArray = __commonJS({ - "node_modules/lodash/isArray.js"(exports2, module2) { - var isArray = Array.isArray; - module2.exports = isArray; +// node_modules/readable-stream/lib/ours/primordials.js +var require_primordials = __commonJS({ + "node_modules/readable-stream/lib/ours/primordials.js"(exports2, module2) { + "use strict"; + module2.exports = { + ArrayIsArray(self2) { + return Array.isArray(self2); + }, + ArrayPrototypeIncludes(self2, el) { + return self2.includes(el); + }, + ArrayPrototypeIndexOf(self2, el) { + return self2.indexOf(el); + }, + ArrayPrototypeJoin(self2, sep) { + return self2.join(sep); + }, + ArrayPrototypeMap(self2, fn) { + return self2.map(fn); + }, + ArrayPrototypePop(self2, el) { + return self2.pop(el); + }, + ArrayPrototypePush(self2, el) { + return self2.push(el); + }, + ArrayPrototypeSlice(self2, start, end) { + return self2.slice(start, end); + }, + Error, + FunctionPrototypeCall(fn, thisArgs, ...args) { + return fn.call(thisArgs, ...args); + }, + FunctionPrototypeSymbolHasInstance(self2, instance) { + return Function.prototype[Symbol.hasInstance].call(self2, instance); + }, + MathFloor: Math.floor, + Number, + NumberIsInteger: Number.isInteger, + NumberIsNaN: Number.isNaN, + NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, + NumberParseInt: Number.parseInt, + ObjectDefineProperties(self2, props) { + return Object.defineProperties(self2, props); + }, + ObjectDefineProperty(self2, name, prop) { + return Object.defineProperty(self2, name, prop); + }, + ObjectGetOwnPropertyDescriptor(self2, name) { + return Object.getOwnPropertyDescriptor(self2, name); + }, + ObjectKeys(obj) { + return Object.keys(obj); + }, + ObjectSetPrototypeOf(target, proto) { + return Object.setPrototypeOf(target, proto); + }, + Promise, + PromisePrototypeCatch(self2, fn) { + return self2.catch(fn); + }, + PromisePrototypeThen(self2, thenFn, catchFn) { + return self2.then(thenFn, catchFn); + }, + PromiseReject(err) { + return Promise.reject(err); + }, + PromiseResolve(val2) { + return Promise.resolve(val2); + }, + ReflectApply: Reflect.apply, + RegExpPrototypeTest(self2, value) { + return self2.test(value); + }, + SafeSet: Set, + String, + StringPrototypeSlice(self2, start, end) { + return self2.slice(start, end); + }, + StringPrototypeToLowerCase(self2) { + return self2.toLowerCase(); + }, + StringPrototypeToUpperCase(self2) { + return self2.toUpperCase(); + }, + StringPrototypeTrim(self2) { + return self2.trim(); + }, + Symbol, + SymbolFor: Symbol.for, + SymbolAsyncIterator: Symbol.asyncIterator, + SymbolHasInstance: Symbol.hasInstance, + SymbolIterator: Symbol.iterator, + SymbolDispose: Symbol.dispose || Symbol("Symbol.dispose"), + SymbolAsyncDispose: Symbol.asyncDispose || Symbol("Symbol.asyncDispose"), + TypedArrayPrototypeSet(self2, buf, len) { + return self2.set(buf, len); + }, + Boolean, + Uint8Array + }; } }); -// node_modules/lodash/stubFalse.js -var require_stubFalse = __commonJS({ - "node_modules/lodash/stubFalse.js"(exports2, module2) { - function stubFalse() { - return false; +// node_modules/event-target-shim/dist/event-target-shim.js +var require_event_target_shim = __commonJS({ + "node_modules/event-target-shim/dist/event-target-shim.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var privateData = /* @__PURE__ */ new WeakMap(); + var wrappers = /* @__PURE__ */ new WeakMap(); + function pd(event) { + const retv = privateData.get(event); + console.assert( + retv != null, + "'this' is expected an Event object, but got", + event + ); + return retv; } - module2.exports = stubFalse; - } -}); - -// node_modules/lodash/isBuffer.js -var require_isBuffer = __commonJS({ - "node_modules/lodash/isBuffer.js"(exports2, module2) { - var root = require_root(); - var stubFalse = require_stubFalse(); - var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2; - var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; - var moduleExports = freeModule && freeModule.exports === freeExports; - var Buffer2 = moduleExports ? root.Buffer : void 0; - var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0; - var isBuffer = nativeIsBuffer || stubFalse; - module2.exports = isBuffer; - } -}); - -// node_modules/lodash/_baseIsTypedArray.js -var require_baseIsTypedArray = __commonJS({ - "node_modules/lodash/_baseIsTypedArray.js"(exports2, module2) { - var baseGetTag = require_baseGetTag(); - var isLength = require_isLength(); - var isObjectLike = require_isObjectLike(); - var argsTag = "[object Arguments]"; - var arrayTag = "[object Array]"; - var boolTag = "[object Boolean]"; - var dateTag = "[object Date]"; - var errorTag = "[object Error]"; - var funcTag = "[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[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - function baseIsTypedArray(value) { - return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + function setCancelFlag(data) { + if (data.passiveListener != null) { + if (typeof console !== "undefined" && typeof console.error === "function") { + console.error( + "Unable to preventDefault inside passive event listener invocation.", + data.passiveListener + ); + } + return; + } + if (!data.event.cancelable) { + return; + } + data.canceled = true; + if (typeof data.event.preventDefault === "function") { + data.event.preventDefault(); + } + } + function Event2(eventTarget, event) { + privateData.set(this, { + eventTarget, + event, + eventPhase: 2, + currentTarget: eventTarget, + canceled: false, + stopped: false, + immediateStopped: false, + passiveListener: null, + timeStamp: event.timeStamp || Date.now() + }); + Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); + const keys = Object.keys(event); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in this)) { + Object.defineProperty(this, key, defineRedirectDescriptor(key)); + } + } + } + Event2.prototype = { + /** + * The type of this event. + * @type {string} + */ + get type() { + return pd(this).event.type; + }, + /** + * The target of this event. + * @type {EventTarget} + */ + get target() { + return pd(this).eventTarget; + }, + /** + * The target of this event. + * @type {EventTarget} + */ + get currentTarget() { + return pd(this).currentTarget; + }, + /** + * @returns {EventTarget[]} The composed path of this event. + */ + composedPath() { + const currentTarget = pd(this).currentTarget; + if (currentTarget == null) { + return []; + } + return [currentTarget]; + }, + /** + * Constant of NONE. + * @type {number} + */ + get NONE() { + return 0; + }, + /** + * Constant of CAPTURING_PHASE. + * @type {number} + */ + get CAPTURING_PHASE() { + return 1; + }, + /** + * Constant of AT_TARGET. + * @type {number} + */ + get AT_TARGET() { + return 2; + }, + /** + * Constant of BUBBLING_PHASE. + * @type {number} + */ + get BUBBLING_PHASE() { + return 3; + }, + /** + * The target of this event. + * @type {number} + */ + get eventPhase() { + return pd(this).eventPhase; + }, + /** + * Stop event bubbling. + * @returns {void} + */ + stopPropagation() { + const data = pd(this); + data.stopped = true; + if (typeof data.event.stopPropagation === "function") { + data.event.stopPropagation(); + } + }, + /** + * Stop event bubbling. + * @returns {void} + */ + stopImmediatePropagation() { + const data = pd(this); + data.stopped = true; + data.immediateStopped = true; + if (typeof data.event.stopImmediatePropagation === "function") { + data.event.stopImmediatePropagation(); + } + }, + /** + * The flag to be bubbling. + * @type {boolean} + */ + get bubbles() { + return Boolean(pd(this).event.bubbles); + }, + /** + * The flag to be cancelable. + * @type {boolean} + */ + get cancelable() { + return Boolean(pd(this).event.cancelable); + }, + /** + * Cancel this event. + * @returns {void} + */ + preventDefault() { + setCancelFlag(pd(this)); + }, + /** + * The flag to indicate cancellation state. + * @type {boolean} + */ + get defaultPrevented() { + return pd(this).canceled; + }, + /** + * The flag to be composed. + * @type {boolean} + */ + get composed() { + return Boolean(pd(this).event.composed); + }, + /** + * The unix time of this event. + * @type {number} + */ + get timeStamp() { + return pd(this).timeStamp; + }, + /** + * The target of this event. + * @type {EventTarget} + * @deprecated + */ + get srcElement() { + return pd(this).eventTarget; + }, + /** + * The flag to stop event bubbling. + * @type {boolean} + * @deprecated + */ + get cancelBubble() { + return pd(this).stopped; + }, + set cancelBubble(value) { + if (!value) { + return; + } + const data = pd(this); + data.stopped = true; + if (typeof data.event.cancelBubble === "boolean") { + data.event.cancelBubble = true; + } + }, + /** + * The flag to indicate cancellation state. + * @type {boolean} + * @deprecated + */ + get returnValue() { + return !pd(this).canceled; + }, + set returnValue(value) { + if (!value) { + setCancelFlag(pd(this)); + } + }, + /** + * Initialize this event object. But do nothing under event dispatching. + * @param {string} type The event type. + * @param {boolean} [bubbles=false] The flag to be possible to bubble up. + * @param {boolean} [cancelable=false] The flag to be possible to cancel. + * @deprecated + */ + initEvent() { + } + }; + Object.defineProperty(Event2.prototype, "constructor", { + value: Event2, + configurable: true, + writable: true + }); + if (typeof window !== "undefined" && typeof window.Event !== "undefined") { + Object.setPrototypeOf(Event2.prototype, window.Event.prototype); + wrappers.set(window.Event.prototype, Event2); + } + function defineRedirectDescriptor(key) { + return { + get() { + return pd(this).event[key]; + }, + set(value) { + pd(this).event[key] = value; + }, + configurable: true, + enumerable: true + }; + } + function defineCallDescriptor(key) { + return { + value() { + const event = pd(this).event; + return event[key].apply(event, arguments); + }, + configurable: true, + enumerable: true + }; + } + function defineWrapper(BaseEvent, proto) { + const keys = Object.keys(proto); + if (keys.length === 0) { + return BaseEvent; + } + function CustomEvent(eventTarget, event) { + BaseEvent.call(this, eventTarget, event); + } + CustomEvent.prototype = Object.create(BaseEvent.prototype, { + constructor: { value: CustomEvent, configurable: true, writable: true } + }); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in BaseEvent.prototype)) { + const descriptor = Object.getOwnPropertyDescriptor(proto, key); + const isFunc = typeof descriptor.value === "function"; + Object.defineProperty( + CustomEvent.prototype, + key, + isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key) + ); + } + } + return CustomEvent; } - module2.exports = baseIsTypedArray; - } -}); - -// node_modules/lodash/_baseUnary.js -var require_baseUnary = __commonJS({ - "node_modules/lodash/_baseUnary.js"(exports2, module2) { - function baseUnary(func) { - return function(value) { - return func(value); + function getWrapper(proto) { + if (proto == null || proto === Object.prototype) { + return Event2; + } + let wrapper = wrappers.get(proto); + if (wrapper == null) { + wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); + wrappers.set(proto, wrapper); + } + return wrapper; + } + function wrapEvent(eventTarget, event) { + const Wrapper = getWrapper(Object.getPrototypeOf(event)); + return new Wrapper(eventTarget, event); + } + function isStopped(event) { + return pd(event).immediateStopped; + } + function setEventPhase(event, eventPhase) { + pd(event).eventPhase = eventPhase; + } + function setCurrentTarget(event, currentTarget) { + pd(event).currentTarget = currentTarget; + } + function setPassiveListener(event, passiveListener) { + pd(event).passiveListener = passiveListener; + } + var listenersMap = /* @__PURE__ */ new WeakMap(); + var CAPTURE = 1; + var BUBBLE = 2; + var ATTRIBUTE = 3; + function isObject2(x) { + return x !== null && typeof x === "object"; + } + function getListeners(eventTarget) { + const listeners = listenersMap.get(eventTarget); + if (listeners == null) { + throw new TypeError( + "'this' is expected an EventTarget object, but got another value." + ); + } + return listeners; + } + function defineEventAttributeDescriptor(eventName) { + return { + get() { + const listeners = getListeners(this); + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + return node.listener; + } + node = node.next; + } + return null; + }, + set(listener) { + if (typeof listener !== "function" && !isObject2(listener)) { + listener = null; + } + const listeners = getListeners(this); + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + node = node.next; + } + if (listener !== null) { + const newNode = { + listener, + listenerType: ATTRIBUTE, + passive: false, + once: false, + next: null + }; + if (prev === null) { + listeners.set(eventName, newNode); + } else { + prev.next = newNode; + } + } + }, + configurable: true, + enumerable: true }; } - module2.exports = baseUnary; - } -}); - -// node_modules/lodash/_nodeUtil.js -var require_nodeUtil = __commonJS({ - "node_modules/lodash/_nodeUtil.js"(exports2, module2) { - var freeGlobal = require_freeGlobal(); - var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2; - var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; - var moduleExports = freeModule && freeModule.exports === freeExports; - var freeProcess = moduleExports && freeGlobal.process; - var nodeUtil = (function() { - try { - var types = freeModule && freeModule.require && freeModule.require("util").types; - if (types) { - return types; - } - return freeProcess && freeProcess.binding && freeProcess.binding("util"); - } catch (e) { + function defineEventAttribute(eventTargetPrototype, eventName) { + Object.defineProperty( + eventTargetPrototype, + `on${eventName}`, + defineEventAttributeDescriptor(eventName) + ); + } + function defineCustomEventTarget(eventNames) { + function CustomEventTarget() { + EventTarget2.call(this); } - })(); - module2.exports = nodeUtil; - } -}); - -// node_modules/lodash/isTypedArray.js -var require_isTypedArray = __commonJS({ - "node_modules/lodash/isTypedArray.js"(exports2, module2) { - var baseIsTypedArray = require_baseIsTypedArray(); - var baseUnary = require_baseUnary(); - var nodeUtil = require_nodeUtil(); - var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - module2.exports = isTypedArray; - } -}); - -// node_modules/lodash/_arrayLikeKeys.js -var require_arrayLikeKeys = __commonJS({ - "node_modules/lodash/_arrayLikeKeys.js"(exports2, module2) { - var baseTimes = require_baseTimes(); - var isArguments = require_isArguments(); - var isArray = require_isArray(); - var isBuffer = require_isBuffer(); - var isIndex = require_isIndex(); - var isTypedArray = require_isTypedArray(); - var objectProto = Object.prototype; - var hasOwnProperty = objectProto.hasOwnProperty; - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; - for (var key in value) { - if ((inherited || hasOwnProperty.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(key, length)))) { - result.push(key); + CustomEventTarget.prototype = Object.create(EventTarget2.prototype, { + constructor: { + value: CustomEventTarget, + configurable: true, + writable: true } + }); + for (let i = 0; i < eventNames.length; ++i) { + defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); } - return result; + return CustomEventTarget; } - module2.exports = arrayLikeKeys; - } -}); - -// node_modules/lodash/_isPrototype.js -var require_isPrototype = __commonJS({ - "node_modules/lodash/_isPrototype.js"(exports2, module2) { - var objectProto = Object.prototype; - function isPrototype(value) { - var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; - return value === proto; + function EventTarget2() { + if (this instanceof EventTarget2) { + listenersMap.set(this, /* @__PURE__ */ new Map()); + return; + } + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(arguments[0]); + } + if (arguments.length > 0) { + const types = new Array(arguments.length); + for (let i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + return defineCustomEventTarget(types); + } + throw new TypeError("Cannot call a class as a function"); } - module2.exports = isPrototype; - } -}); - -// node_modules/lodash/_nativeKeysIn.js -var require_nativeKeysIn = __commonJS({ - "node_modules/lodash/_nativeKeysIn.js"(exports2, module2) { - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); + EventTarget2.prototype = { + /** + * Add a given listener to this event target. + * @param {string} eventName The event name to add. + * @param {Function} listener The listener to add. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + addEventListener(eventName, listener, options) { + if (listener == null) { + return; + } + if (typeof listener !== "function" && !isObject2(listener)) { + throw new TypeError("'listener' should be a function or an object."); + } + const listeners = getListeners(this); + const optionsIsObj = isObject2(options); + const capture = optionsIsObj ? Boolean(options.capture) : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + const newNode = { + listener, + listenerType, + passive: optionsIsObj && Boolean(options.passive), + once: optionsIsObj && Boolean(options.once), + next: null + }; + let node = listeners.get(eventName); + if (node === void 0) { + listeners.set(eventName, newNode); + return; + } + let prev = null; + while (node != null) { + if (node.listener === listener && node.listenerType === listenerType) { + return; + } + prev = node; + node = node.next; + } + prev.next = newNode; + }, + /** + * Remove a given listener from this event target. + * @param {string} eventName The event name to remove. + * @param {Function} listener The listener to remove. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + removeEventListener(eventName, listener, options) { + if (listener == null) { + return; + } + const listeners = getListeners(this); + const capture = isObject2(options) ? Boolean(options.capture) : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listener === listener && node.listenerType === listenerType) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + return; + } + prev = node; + node = node.next; + } + }, + /** + * Dispatch a given event. + * @param {Event|{type:string}} event The event to dispatch. + * @returns {boolean} `false` if canceled. + */ + dispatchEvent(event) { + if (event == null || typeof event.type !== "string") { + throw new TypeError('"event.type" should be a string.'); + } + const listeners = getListeners(this); + const eventName = event.type; + let node = listeners.get(eventName); + if (node == null) { + return true; + } + const wrappedEvent = wrapEvent(this, event); + let prev = null; + while (node != null) { + if (node.once) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + setPassiveListener( + wrappedEvent, + node.passive ? node.listener : null + ); + if (typeof node.listener === "function") { + try { + node.listener.call(this, wrappedEvent); + } catch (err) { + if (typeof console !== "undefined" && typeof console.error === "function") { + console.error(err); + } + } + } else if (node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function") { + node.listener.handleEvent(wrappedEvent); + } + if (isStopped(wrappedEvent)) { + break; + } + node = node.next; } + setPassiveListener(wrappedEvent, null); + setEventPhase(wrappedEvent, 0); + setCurrentTarget(wrappedEvent, null); + return !wrappedEvent.defaultPrevented; } - return result; + }; + Object.defineProperty(EventTarget2.prototype, "constructor", { + value: EventTarget2, + configurable: true, + writable: true + }); + if (typeof window !== "undefined" && typeof window.EventTarget !== "undefined") { + Object.setPrototypeOf(EventTarget2.prototype, window.EventTarget.prototype); } - module2.exports = nativeKeysIn; + exports2.defineEventAttribute = defineEventAttribute; + exports2.EventTarget = EventTarget2; + exports2.default = EventTarget2; + module2.exports = EventTarget2; + module2.exports.EventTarget = module2.exports["default"] = EventTarget2; + module2.exports.defineEventAttribute = defineEventAttribute; } }); -// node_modules/lodash/_baseKeysIn.js -var require_baseKeysIn = __commonJS({ - "node_modules/lodash/_baseKeysIn.js"(exports2, module2) { - var isObject2 = require_isObject(); - var isPrototype = require_isPrototype(); - var nativeKeysIn = require_nativeKeysIn(); - var objectProto = Object.prototype; - var hasOwnProperty = objectProto.hasOwnProperty; - function baseKeysIn(object) { - if (!isObject2(object)) { - return nativeKeysIn(object); +// node_modules/abort-controller/dist/abort-controller.js +var require_abort_controller = __commonJS({ + "node_modules/abort-controller/dist/abort-controller.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var eventTargetShim = require_event_target_shim(); + var AbortSignal2 = class extends eventTargetShim.EventTarget { + /** + * AbortSignal cannot be constructed directly. + */ + constructor() { + super(); + throw new TypeError("AbortSignal cannot be constructed directly"); } - var isProto = isPrototype(object), result = []; - for (var key in object) { - if (!(key == "constructor" && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); + /** + * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. + */ + get aborted() { + const aborted = abortedFlags.get(this); + if (typeof aborted !== "boolean") { + throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); } + return aborted; } - return result; + }; + eventTargetShim.defineEventAttribute(AbortSignal2.prototype, "abort"); + function createAbortSignal() { + const signal = Object.create(AbortSignal2.prototype); + eventTargetShim.EventTarget.call(signal); + abortedFlags.set(signal, false); + return signal; } - module2.exports = baseKeysIn; - } -}); - -// node_modules/lodash/keysIn.js -var require_keysIn = __commonJS({ - "node_modules/lodash/keysIn.js"(exports2, module2) { - var arrayLikeKeys = require_arrayLikeKeys(); - var baseKeysIn = require_baseKeysIn(); - var isArrayLike = require_isArrayLike(); - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + function abortSignal(signal) { + if (abortedFlags.get(signal) !== false) { + return; + } + abortedFlags.set(signal, true); + signal.dispatchEvent({ type: "abort" }); } - module2.exports = keysIn; - } -}); - -// node_modules/lodash/defaults.js -var require_defaults = __commonJS({ - "node_modules/lodash/defaults.js"(exports2, module2) { - var baseRest = require_baseRest(); - var eq = require_eq2(); - var isIterateeCall = require_isIterateeCall(); - var keysIn = require_keysIn(); - var objectProto = Object.prototype; - var hasOwnProperty = objectProto.hasOwnProperty; - var defaults = baseRest(function(object, sources) { - object = Object(object); - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : void 0; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; + var abortedFlags = /* @__PURE__ */ new WeakMap(); + Object.defineProperties(AbortSignal2.prototype, { + aborted: { enumerable: true } + }); + if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortSignal2.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortSignal" + }); + } + var AbortController2 = class { + /** + * Initialize this controller. + */ + constructor() { + signals.set(this, createAbortSignal()); } - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - if (value === void 0 || eq(value, objectProto[key]) && !hasOwnProperty.call(object, key)) { - object[key] = source[key]; - } - } + /** + * Returns the `AbortSignal` object associated with this object. + */ + get signal() { + return getSignal(this); } - return object; + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + abort() { + abortSignal(getSignal(this)); + } + }; + var signals = /* @__PURE__ */ new WeakMap(); + function getSignal(controller) { + const signal = signals.get(controller); + if (signal == null) { + throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); + } + return signal; + } + Object.defineProperties(AbortController2.prototype, { + signal: { enumerable: true }, + abort: { enumerable: true } }); - module2.exports = defaults; + if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortController2.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortController" + }); + } + exports2.AbortController = AbortController2; + exports2.AbortSignal = AbortSignal2; + exports2.default = AbortController2; + module2.exports = AbortController2; + module2.exports.AbortController = module2.exports["default"] = AbortController2; + module2.exports.AbortSignal = AbortSignal2; } }); -// node_modules/readable-stream/lib/ours/primordials.js -var require_primordials = __commonJS({ - "node_modules/readable-stream/lib/ours/primordials.js"(exports2, module2) { +// node_modules/readable-stream/lib/ours/util.js +var require_util12 = __commonJS({ + "node_modules/readable-stream/lib/ours/util.js"(exports2, module2) { "use strict"; + var bufferModule = require("buffer"); + var { kResistStopPropagation, SymbolDispose } = require_primordials(); + var AbortSignal2 = globalThis.AbortSignal || require_abort_controller().AbortSignal; + var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; + var AsyncFunction = Object.getPrototypeOf(async function() { + }).constructor; + var Blob2 = globalThis.Blob || bufferModule.Blob; + var isBlob = typeof Blob2 !== "undefined" ? function isBlob2(b) { + return b instanceof Blob2; + } : function isBlob2(b) { + return false; + }; + var validateAbortSignal = (signal, name) => { + if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) { + throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal); + } + }; + var validateFunction = (value, name) => { + if (typeof value !== "function") throw new ERR_INVALID_ARG_TYPE(name, "Function", value); + }; + var AggregateError = class extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } + let message = ""; + for (let i = 0; i < errors.length; i++) { + message += ` ${errors[i].stack} +`; + } + super(message); + this.name = "AggregateError"; + this.errors = errors; + } + }; module2.exports = { - ArrayIsArray(self2) { - return Array.isArray(self2); - }, - ArrayPrototypeIncludes(self2, el) { - return self2.includes(el); - }, - ArrayPrototypeIndexOf(self2, el) { - return self2.indexOf(el); - }, - ArrayPrototypeJoin(self2, sep) { - return self2.join(sep); - }, - ArrayPrototypeMap(self2, fn) { - return self2.map(fn); - }, - ArrayPrototypePop(self2, el) { - return self2.pop(el); - }, - ArrayPrototypePush(self2, el) { - return self2.push(el); - }, - ArrayPrototypeSlice(self2, start, end) { - return self2.slice(start, end); - }, - Error, - FunctionPrototypeCall(fn, thisArgs, ...args) { - return fn.call(thisArgs, ...args); - }, - FunctionPrototypeSymbolHasInstance(self2, instance) { - return Function.prototype[Symbol.hasInstance].call(self2, instance); - }, - MathFloor: Math.floor, - Number, - NumberIsInteger: Number.isInteger, - NumberIsNaN: Number.isNaN, - NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, - NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, - NumberParseInt: Number.parseInt, - ObjectDefineProperties(self2, props) { - return Object.defineProperties(self2, props); - }, - ObjectDefineProperty(self2, name, prop) { - return Object.defineProperty(self2, name, prop); - }, - ObjectGetOwnPropertyDescriptor(self2, name) { - return Object.getOwnPropertyDescriptor(self2, name); - }, - ObjectKeys(obj) { - return Object.keys(obj); - }, - ObjectSetPrototypeOf(target, proto) { - return Object.setPrototypeOf(target, proto); - }, - Promise, - PromisePrototypeCatch(self2, fn) { - return self2.catch(fn); - }, - PromisePrototypeThen(self2, thenFn, catchFn) { - return self2.then(thenFn, catchFn); + AggregateError, + kEmptyObject: Object.freeze({}), + once(callback) { + let called = false; + return function(...args) { + if (called) { + return; + } + called = true; + callback.apply(this, args); + }; }, - PromiseReject(err) { - return Promise.reject(err); + createDeferredPromise: function() { + let resolve2; + let reject; + const promise = new Promise((res, rej) => { + resolve2 = res; + reject = rej; + }); + return { + promise, + resolve: resolve2, + reject + }; }, - PromiseResolve(val2) { - return Promise.resolve(val2); + promisify(fn) { + return new Promise((resolve2, reject) => { + fn((err, ...args) => { + if (err) { + return reject(err); + } + return resolve2(...args); + }); + }); }, - ReflectApply: Reflect.apply, - RegExpPrototypeTest(self2, value) { - return self2.test(value); + debuglog() { + return function() { + }; }, - SafeSet: Set, - String, - StringPrototypeSlice(self2, start, end) { - return self2.slice(start, end); + format(format, ...args) { + return format.replace(/%([sdifj])/g, function(...[_unused, type2]) { + const replacement = args.shift(); + if (type2 === "f") { + return replacement.toFixed(6); + } else if (type2 === "j") { + return JSON.stringify(replacement); + } else if (type2 === "s" && typeof replacement === "object") { + const ctor = replacement.constructor !== Object ? replacement.constructor.name : ""; + return `${ctor} {}`.trim(); + } else { + return replacement.toString(); + } + }); }, - StringPrototypeToLowerCase(self2) { - return self2.toLowerCase(); + inspect(value) { + switch (typeof value) { + case "string": + if (value.includes("'")) { + if (!value.includes('"')) { + return `"${value}"`; + } else if (!value.includes("`") && !value.includes("${")) { + return `\`${value}\``; + } + } + return `'${value}'`; + case "number": + if (isNaN(value)) { + return "NaN"; + } else if (Object.is(value, -0)) { + return String(value); + } + return value; + case "bigint": + return `${String(value)}n`; + case "boolean": + case "undefined": + return String(value); + case "object": + return "{}"; + } }, - StringPrototypeToUpperCase(self2) { - return self2.toUpperCase(); + types: { + isAsyncFunction(fn) { + return fn instanceof AsyncFunction; + }, + isArrayBufferView(arr) { + return ArrayBuffer.isView(arr); + } }, - StringPrototypeTrim(self2) { - return self2.trim(); + isBlob, + deprecate(fn, message) { + return fn; }, - Symbol, - SymbolFor: Symbol.for, - SymbolAsyncIterator: Symbol.asyncIterator, - SymbolHasInstance: Symbol.hasInstance, - SymbolIterator: Symbol.iterator, - SymbolDispose: Symbol.dispose || Symbol("Symbol.dispose"), - SymbolAsyncDispose: Symbol.asyncDispose || Symbol("Symbol.asyncDispose"), - TypedArrayPrototypeSet(self2, buf, len) { - return self2.set(buf, len); + addAbortListener: require("events").addAbortListener || function addAbortListener(signal, listener) { + if (signal === void 0) { + throw new ERR_INVALID_ARG_TYPE("signal", "AbortSignal", signal); + } + validateAbortSignal(signal, "signal"); + validateFunction(listener, "listener"); + let removeEventListener; + if (signal.aborted) { + queueMicrotask(() => listener()); + } else { + signal.addEventListener("abort", listener, { + __proto__: null, + once: true, + [kResistStopPropagation]: true + }); + removeEventListener = () => { + signal.removeEventListener("abort", listener); + }; + } + return { + __proto__: null, + [SymbolDispose]() { + var _removeEventListener; + (_removeEventListener = removeEventListener) === null || _removeEventListener === void 0 ? void 0 : _removeEventListener(); + } + }; }, - Boolean, - Uint8Array + AbortSignalAny: AbortSignal2.any || function AbortSignalAny(signals) { + if (signals.length === 1) { + return signals[0]; + } + const ac = new AbortController2(); + const abort = () => ac.abort(); + signals.forEach((signal) => { + validateAbortSignal(signal, "signals"); + signal.addEventListener("abort", abort, { + once: true + }); + }); + ac.signal.addEventListener( + "abort", + () => { + signals.forEach((signal) => signal.removeEventListener("abort", abort)); + }, + { + once: true + } + ); + return ac.signal; + } }; + module2.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom"); } }); -// node_modules/event-target-shim/dist/event-target-shim.js -var require_event_target_shim = __commonJS({ - "node_modules/event-target-shim/dist/event-target-shim.js"(exports2, module2) { +// node_modules/readable-stream/lib/ours/errors.js +var require_errors3 = __commonJS({ + "node_modules/readable-stream/lib/ours/errors.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var privateData = /* @__PURE__ */ new WeakMap(); - var wrappers = /* @__PURE__ */ new WeakMap(); - function pd(event) { - const retv = privateData.get(event); - console.assert( - retv != null, - "'this' is expected an Event object, but got", - event - ); - return retv; + var { format, inspect, AggregateError: CustomAggregateError } = require_util12(); + var AggregateError = globalThis.AggregateError || CustomAggregateError; + var kIsNodeError = Symbol("kIsNodeError"); + var kTypes = [ + "string", + "function", + "number", + "object", + // Accept 'Function' and 'Object' as alternative to the lower cased version. + "Function", + "Object", + "boolean", + "bigint", + "symbol" + ]; + var classRegExp = /^([A-Z][a-z0-9]*)+$/; + var nodeInternalPrefix = "__node_internal_"; + var codes = {}; + function assert(value, message) { + if (!value) { + throw new codes.ERR_INTERNAL_ASSERTION(message); + } } - function setCancelFlag(data) { - if (data.passiveListener != null) { - if (typeof console !== "undefined" && typeof console.error === "function") { - console.error( - "Unable to preventDefault inside passive event listener invocation.", - data.passiveListener - ); - } - return; + function addNumericalSeparator(val2) { + let res = ""; + let i = val2.length; + const start = val2[0] === "-" ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val2.slice(i - 3, i)}${res}`; } - if (!data.event.cancelable) { - return; + return `${val2.slice(0, i)}${res}`; + } + function getMessage(key, msg, args) { + if (typeof msg === "function") { + assert( + msg.length <= args.length, + // Default options do not count. + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` + ); + return msg(...args); } - data.canceled = true; - if (typeof data.event.preventDefault === "function") { - data.event.preventDefault(); + const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length; + assert( + expectedLength === args.length, + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` + ); + if (args.length === 0) { + return msg; } + return format(msg, ...args); } - function Event2(eventTarget, event) { - privateData.set(this, { - eventTarget, - event, - eventPhase: 2, - currentTarget: eventTarget, - canceled: false, - stopped: false, - immediateStopped: false, - passiveListener: null, - timeStamp: event.timeStamp || Date.now() + function E(code, message, Base) { + if (!Base) { + Base = Error; + } + class NodeError extends Base { + constructor(...args) { + super(getMessage(code, message, args)); + } + toString() { + return `${this.name} [${code}]: ${this.message}`; + } + } + Object.defineProperties(NodeError.prototype, { + name: { + value: Base.name, + writable: true, + enumerable: false, + configurable: true + }, + toString: { + value() { + return `${this.name} [${code}]: ${this.message}`; + }, + writable: true, + enumerable: false, + configurable: true + } }); - Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); - const keys = Object.keys(event); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in this)) { - Object.defineProperty(this, key, defineRedirectDescriptor(key)); + NodeError.prototype.code = code; + NodeError.prototype[kIsNodeError] = true; + codes[code] = NodeError; + } + function hideStackFrames(fn) { + const hidden = nodeInternalPrefix + fn.name; + Object.defineProperty(fn, "name", { + value: hidden + }); + return fn; + } + function aggregateTwoErrors(innerError, outerError) { + if (innerError && outerError && innerError !== outerError) { + if (Array.isArray(outerError.errors)) { + outerError.errors.push(innerError); + return outerError; } + const err = new AggregateError([outerError, innerError], outerError.message); + err.code = outerError.code; + return err; } + return innerError || outerError; } - Event2.prototype = { - /** - * The type of this event. - * @type {string} - */ - get type() { - return pd(this).event.type; - }, - /** - * The target of this event. - * @type {EventTarget} - */ - get target() { - return pd(this).eventTarget; - }, - /** - * The target of this event. - * @type {EventTarget} - */ - get currentTarget() { - return pd(this).currentTarget; - }, - /** - * @returns {EventTarget[]} The composed path of this event. - */ - composedPath() { - const currentTarget = pd(this).currentTarget; - if (currentTarget == null) { - return []; + var AbortError = class extends Error { + constructor(message = "The operation was aborted", options = void 0) { + if (options !== void 0 && typeof options !== "object") { + throw new codes.ERR_INVALID_ARG_TYPE("options", "Object", options); + } + super(message, options); + this.code = "ABORT_ERR"; + this.name = "AbortError"; + } + }; + E("ERR_ASSERTION", "%s", Error); + E( + "ERR_INVALID_ARG_TYPE", + (name, expected, actual) => { + assert(typeof name === "string", "'name' must be a string"); + if (!Array.isArray(expected)) { + expected = [expected]; + } + let msg = "The "; + if (name.endsWith(" argument")) { + msg += `${name} `; + } else { + msg += `"${name}" ${name.includes(".") ? "property" : "argument"} `; + } + msg += "must be "; + const types = []; + const instances = []; + const other = []; + for (const value of expected) { + assert(typeof value === "string", "All expected entries have to be of type string"); + if (kTypes.includes(value)) { + types.push(value.toLowerCase()); + } else if (classRegExp.test(value)) { + instances.push(value); + } else { + assert(value !== "object", 'The value "object" should be written as "Object"'); + other.push(value); + } + } + if (instances.length > 0) { + const pos = types.indexOf("object"); + if (pos !== -1) { + types.splice(types, pos, 1); + instances.push("Object"); + } + } + if (types.length > 0) { + switch (types.length) { + case 1: + msg += `of type ${types[0]}`; + break; + case 2: + msg += `one of type ${types[0]} or ${types[1]}`; + break; + default: { + const last = types.pop(); + msg += `one of type ${types.join(", ")}, or ${last}`; + } + } + if (instances.length > 0 || other.length > 0) { + msg += " or "; + } + } + if (instances.length > 0) { + switch (instances.length) { + case 1: + msg += `an instance of ${instances[0]}`; + break; + case 2: + msg += `an instance of ${instances[0]} or ${instances[1]}`; + break; + default: { + const last = instances.pop(); + msg += `an instance of ${instances.join(", ")}, or ${last}`; + } + } + if (other.length > 0) { + msg += " or "; + } } - return [currentTarget]; - }, - /** - * Constant of NONE. - * @type {number} - */ - get NONE() { - return 0; - }, - /** - * Constant of CAPTURING_PHASE. - * @type {number} - */ - get CAPTURING_PHASE() { - return 1; - }, - /** - * Constant of AT_TARGET. - * @type {number} - */ - get AT_TARGET() { - return 2; - }, - /** - * Constant of BUBBLING_PHASE. - * @type {number} - */ - get BUBBLING_PHASE() { - return 3; - }, - /** - * The target of this event. - * @type {number} - */ - get eventPhase() { - return pd(this).eventPhase; - }, - /** - * Stop event bubbling. - * @returns {void} - */ - stopPropagation() { - const data = pd(this); - data.stopped = true; - if (typeof data.event.stopPropagation === "function") { - data.event.stopPropagation(); + switch (other.length) { + case 0: + break; + case 1: + if (other[0].toLowerCase() !== other[0]) { + msg += "an "; + } + msg += `${other[0]}`; + break; + case 2: + msg += `one of ${other[0]} or ${other[1]}`; + break; + default: { + const last = other.pop(); + msg += `one of ${other.join(", ")}, or ${last}`; + } } - }, - /** - * Stop event bubbling. - * @returns {void} - */ - stopImmediatePropagation() { - const data = pd(this); - data.stopped = true; - data.immediateStopped = true; - if (typeof data.event.stopImmediatePropagation === "function") { - data.event.stopImmediatePropagation(); + if (actual == null) { + msg += `. Received ${actual}`; + } else if (typeof actual === "function" && actual.name) { + msg += `. Received function ${actual.name}`; + } else if (typeof actual === "object") { + var _actual$constructor; + if ((_actual$constructor = actual.constructor) !== null && _actual$constructor !== void 0 && _actual$constructor.name) { + msg += `. Received an instance of ${actual.constructor.name}`; + } else { + const inspected = inspect(actual, { + depth: -1 + }); + msg += `. Received ${inspected}`; + } + } else { + let inspected = inspect(actual, { + colors: false + }); + if (inspected.length > 25) { + inspected = `${inspected.slice(0, 25)}...`; + } + msg += `. Received type ${typeof actual} (${inspected})`; } + return msg; }, - /** - * The flag to be bubbling. - * @type {boolean} - */ - get bubbles() { - return Boolean(pd(this).event.bubbles); - }, - /** - * The flag to be cancelable. - * @type {boolean} - */ - get cancelable() { - return Boolean(pd(this).event.cancelable); - }, - /** - * Cancel this event. - * @returns {void} - */ - preventDefault() { - setCancelFlag(pd(this)); - }, - /** - * The flag to indicate cancellation state. - * @type {boolean} - */ - get defaultPrevented() { - return pd(this).canceled; - }, - /** - * The flag to be composed. - * @type {boolean} - */ - get composed() { - return Boolean(pd(this).event.composed); - }, - /** - * The unix time of this event. - * @type {number} - */ - get timeStamp() { - return pd(this).timeStamp; - }, - /** - * The target of this event. - * @type {EventTarget} - * @deprecated - */ - get srcElement() { - return pd(this).eventTarget; + TypeError + ); + E( + "ERR_INVALID_ARG_VALUE", + (name, value, reason = "is invalid") => { + let inspected = inspect(value); + if (inspected.length > 128) { + inspected = inspected.slice(0, 128) + "..."; + } + const type2 = name.includes(".") ? "property" : "argument"; + return `The ${type2} '${name}' ${reason}. Received ${inspected}`; }, - /** - * The flag to stop event bubbling. - * @type {boolean} - * @deprecated - */ - get cancelBubble() { - return pd(this).stopped; + TypeError + ); + E( + "ERR_INVALID_RETURN_VALUE", + (input, name, value) => { + var _value$constructor; + const type2 = value !== null && value !== void 0 && (_value$constructor = value.constructor) !== null && _value$constructor !== void 0 && _value$constructor.name ? `instance of ${value.constructor.name}` : `type ${typeof value}`; + return `Expected ${input} to be returned from the "${name}" function but got ${type2}.`; }, - set cancelBubble(value) { - if (!value) { - return; - } - const data = pd(this); - data.stopped = true; - if (typeof data.event.cancelBubble === "boolean") { - data.event.cancelBubble = true; + TypeError + ); + E( + "ERR_MISSING_ARGS", + (...args) => { + assert(args.length > 0, "At least one arg needs to be specified"); + let msg; + const len = args.length; + args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(" or "); + switch (len) { + case 1: + msg += `The ${args[0]} argument`; + break; + case 2: + msg += `The ${args[0]} and ${args[1]} arguments`; + break; + default: + { + const last = args.pop(); + msg += `The ${args.join(", ")}, and ${last} arguments`; + } + break; } + return `${msg} must be specified`; }, - /** - * The flag to indicate cancellation state. - * @type {boolean} - * @deprecated - */ - get returnValue() { - return !pd(this).canceled; - }, - set returnValue(value) { - if (!value) { - setCancelFlag(pd(this)); + TypeError + ); + E( + "ERR_OUT_OF_RANGE", + (str2, range, input) => { + assert(range, 'Missing "range" argument'); + let received; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > 2n ** 32n || input < -(2n ** 32n)) { + received = addNumericalSeparator(received); + } + received += "n"; + } else { + received = inspect(input); } + return `The value of "${str2}" is out of range. It must be ${range}. Received ${received}`; }, - /** - * Initialize this event object. But do nothing under event dispatching. - * @param {string} type The event type. - * @param {boolean} [bubbles=false] The flag to be possible to bubble up. - * @param {boolean} [cancelable=false] The flag to be possible to cancel. - * @deprecated - */ - initEvent() { - } + RangeError + ); + E("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error); + E("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error); + E("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error); + E("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error); + E("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error); + E("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + E("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error); + E("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error); + E("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error); + E("ERR_STREAM_WRITE_AFTER_END", "write after end", Error); + E("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError); + module2.exports = { + AbortError, + aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), + hideStackFrames, + codes }; - Object.defineProperty(Event2.prototype, "constructor", { - value: Event2, - configurable: true, - writable: true - }); - if (typeof window !== "undefined" && typeof window.Event !== "undefined") { - Object.setPrototypeOf(Event2.prototype, window.Event.prototype); - wrappers.set(window.Event.prototype, Event2); - } - function defineRedirectDescriptor(key) { - return { - get() { - return pd(this).event[key]; - }, - set(value) { - pd(this).event[key] = value; - }, - configurable: true, - enumerable: true - }; + } +}); + +// node_modules/readable-stream/lib/internal/validators.js +var require_validators = __commonJS({ + "node_modules/readable-stream/lib/internal/validators.js"(exports2, module2) { + "use strict"; + var { + ArrayIsArray, + ArrayPrototypeIncludes, + ArrayPrototypeJoin, + ArrayPrototypeMap, + NumberIsInteger, + NumberIsNaN, + NumberMAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER, + NumberParseInt, + ObjectPrototypeHasOwnProperty, + RegExpPrototypeExec, + String: String2, + StringPrototypeToUpperCase, + StringPrototypeTrim + } = require_primordials(); + var { + hideStackFrames, + codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } + } = require_errors3(); + var { normalizeEncoding } = require_util12(); + var { isAsyncFunction, isArrayBufferView } = require_util12().types; + var signals = {}; + function isInt32(value) { + return value === (value | 0); } - function defineCallDescriptor(key) { - return { - value() { - const event = pd(this).event; - return event[key].apply(event, arguments); - }, - configurable: true, - enumerable: true - }; + function isUint32(value) { + return value === value >>> 0; } - function defineWrapper(BaseEvent, proto) { - const keys = Object.keys(proto); - if (keys.length === 0) { - return BaseEvent; - } - function CustomEvent(eventTarget, event) { - BaseEvent.call(this, eventTarget, event); + var octalReg = /^[0-7]+$/; + var modeDesc = "must be a 32-bit unsigned integer or an octal string"; + function parseFileMode(value, name, def) { + if (typeof value === "undefined") { + value = def; } - CustomEvent.prototype = Object.create(BaseEvent.prototype, { - constructor: { value: CustomEvent, configurable: true, writable: true } - }); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in BaseEvent.prototype)) { - const descriptor = Object.getOwnPropertyDescriptor(proto, key); - const isFunc = typeof descriptor.value === "function"; - Object.defineProperty( - CustomEvent.prototype, - key, - isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key) - ); + if (typeof value === "string") { + if (RegExpPrototypeExec(octalReg, value) === null) { + throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc); } + value = NumberParseInt(value, 8); } - return CustomEvent; + validateUint32(value, name); + return value; } - function getWrapper(proto) { - if (proto == null || proto === Object.prototype) { - return Event2; + var validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => { + if (typeof value !== "number") throw new ERR_INVALID_ARG_TYPE2(name, "number", value); + if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, "an integer", value); + if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); + }); + var validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => { + if (typeof value !== "number") { + throw new ERR_INVALID_ARG_TYPE2(name, "number", value); } - let wrapper = wrappers.get(proto); - if (wrapper == null) { - wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); - wrappers.set(proto, wrapper); + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, "an integer", value); } - return wrapper; - } - function wrapEvent(eventTarget, event) { - const Wrapper = getWrapper(Object.getPrototypeOf(event)); - return new Wrapper(eventTarget, event); - } - function isStopped(event) { - return pd(event).immediateStopped; - } - function setEventPhase(event, eventPhase) { - pd(event).eventPhase = eventPhase; - } - function setCurrentTarget(event, currentTarget) { - pd(event).currentTarget = currentTarget; - } - function setPassiveListener(event, passiveListener) { - pd(event).passiveListener = passiveListener; + if (value < min || value > max) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); + } + }); + var validateUint32 = hideStackFrames((value, name, positive = false) => { + if (typeof value !== "number") { + throw new ERR_INVALID_ARG_TYPE2(name, "number", value); + } + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, "an integer", value); + } + const min = positive ? 1 : 0; + const max = 4294967295; + if (value < min || value > max) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); + } + }); + function validateString(value, name) { + if (typeof value !== "string") throw new ERR_INVALID_ARG_TYPE2(name, "string", value); } - var listenersMap = /* @__PURE__ */ new WeakMap(); - var CAPTURE = 1; - var BUBBLE = 2; - var ATTRIBUTE = 3; - function isObject2(x) { - return x !== null && typeof x === "object"; + function validateNumber(value, name, min = void 0, max) { + if (typeof value !== "number") throw new ERR_INVALID_ARG_TYPE2(name, "number", value); + if (min != null && value < min || max != null && value > max || (min != null || max != null) && NumberIsNaN(value)) { + throw new ERR_OUT_OF_RANGE( + name, + `${min != null ? `>= ${min}` : ""}${min != null && max != null ? " && " : ""}${max != null ? `<= ${max}` : ""}`, + value + ); + } } - function getListeners(eventTarget) { - const listeners = listenersMap.get(eventTarget); - if (listeners == null) { - throw new TypeError( - "'this' is expected an EventTarget object, but got another value." + var validateOneOf = hideStackFrames((value, name, oneOf) => { + if (!ArrayPrototypeIncludes(oneOf, value)) { + const allowed = ArrayPrototypeJoin( + ArrayPrototypeMap(oneOf, (v) => typeof v === "string" ? `'${v}'` : String2(v)), + ", " ); + const reason = "must be one of: " + allowed; + throw new ERR_INVALID_ARG_VALUE(name, value, reason); } - return listeners; + }); + function validateBoolean(value, name) { + if (typeof value !== "boolean") throw new ERR_INVALID_ARG_TYPE2(name, "boolean", value); } - function defineEventAttributeDescriptor(eventName) { - return { - get() { - const listeners = getListeners(this); - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - return node.listener; - } - node = node.next; - } - return null; - }, - set(listener) { - if (typeof listener !== "function" && !isObject2(listener)) { - listener = null; - } - const listeners = getListeners(this); - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - node = node.next; - } - if (listener !== null) { - const newNode = { - listener, - listenerType: ATTRIBUTE, - passive: false, - once: false, - next: null - }; - if (prev === null) { - listeners.set(eventName, newNode); - } else { - prev.next = newNode; - } - } - }, - configurable: true, - enumerable: true - }; + function getOwnPropertyValueOrDefault(options, key, defaultValue) { + return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key]; + } + var validateObject = hideStackFrames((value, name, options = null) => { + const allowArray = getOwnPropertyValueOrDefault(options, "allowArray", false); + const allowFunction = getOwnPropertyValueOrDefault(options, "allowFunction", false); + const nullable = getOwnPropertyValueOrDefault(options, "nullable", false); + if (!nullable && value === null || !allowArray && ArrayIsArray(value) || typeof value !== "object" && (!allowFunction || typeof value !== "function")) { + throw new ERR_INVALID_ARG_TYPE2(name, "Object", value); + } + }); + var validateDictionary = hideStackFrames((value, name) => { + if (value != null && typeof value !== "object" && typeof value !== "function") { + throw new ERR_INVALID_ARG_TYPE2(name, "a dictionary", value); + } + }); + var validateArray = hideStackFrames((value, name, minLength = 0) => { + if (!ArrayIsArray(value)) { + throw new ERR_INVALID_ARG_TYPE2(name, "Array", value); + } + if (value.length < minLength) { + const reason = `must be longer than ${minLength}`; + throw new ERR_INVALID_ARG_VALUE(name, value, reason); + } + }); + function validateStringArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + validateString(value[i], `${name}[${i}]`); + } } - function defineEventAttribute(eventTargetPrototype, eventName) { - Object.defineProperty( - eventTargetPrototype, - `on${eventName}`, - defineEventAttributeDescriptor(eventName) - ); + function validateBooleanArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + validateBoolean(value[i], `${name}[${i}]`); + } } - function defineCustomEventTarget(eventNames) { - function CustomEventTarget() { - EventTarget2.call(this); + function validateAbortSignalArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + const signal = value[i]; + const indexedName = `${name}[${i}]`; + if (signal == null) { + throw new ERR_INVALID_ARG_TYPE2(indexedName, "AbortSignal", signal); + } + validateAbortSignal(signal, indexedName); } - CustomEventTarget.prototype = Object.create(EventTarget2.prototype, { - constructor: { - value: CustomEventTarget, - configurable: true, - writable: true + } + function validateSignalName(signal, name = "signal") { + validateString(signal, name); + if (signals[signal] === void 0) { + if (signals[StringPrototypeToUpperCase(signal)] !== void 0) { + throw new ERR_UNKNOWN_SIGNAL(signal + " (signals must use all capital letters)"); } - }); - for (let i = 0; i < eventNames.length; ++i) { - defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); + throw new ERR_UNKNOWN_SIGNAL(signal); } - return CustomEventTarget; } - function EventTarget2() { - if (this instanceof EventTarget2) { - listenersMap.set(this, /* @__PURE__ */ new Map()); - return; + var validateBuffer = hideStackFrames((buffer, name = "buffer") => { + if (!isArrayBufferView(buffer)) { + throw new ERR_INVALID_ARG_TYPE2(name, ["Buffer", "TypedArray", "DataView"], buffer); } - if (arguments.length === 1 && Array.isArray(arguments[0])) { - return defineCustomEventTarget(arguments[0]); + }); + function validateEncoding(data, encoding) { + const normalizedEncoding = normalizeEncoding(encoding); + const length = data.length; + if (normalizedEncoding === "hex" && length % 2 !== 0) { + throw new ERR_INVALID_ARG_VALUE("encoding", encoding, `is invalid for data of length ${length}`); } - if (arguments.length > 0) { - const types = new Array(arguments.length); - for (let i = 0; i < arguments.length; ++i) { - types[i] = arguments[i]; - } - return defineCustomEventTarget(types); + } + function validatePort(port, name = "Port", allowZero = true) { + if (typeof port !== "number" && typeof port !== "string" || typeof port === "string" && StringPrototypeTrim(port).length === 0 || +port !== +port >>> 0 || port > 65535 || port === 0 && !allowZero) { + throw new ERR_SOCKET_BAD_PORT(name, port, allowZero); } - throw new TypeError("Cannot call a class as a function"); + return port | 0; } - EventTarget2.prototype = { - /** - * Add a given listener to this event target. - * @param {string} eventName The event name to add. - * @param {Function} listener The listener to add. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - addEventListener(eventName, listener, options) { - if (listener == null) { - return; - } - if (typeof listener !== "function" && !isObject2(listener)) { - throw new TypeError("'listener' should be a function or an object."); - } - const listeners = getListeners(this); - const optionsIsObj = isObject2(options); - const capture = optionsIsObj ? Boolean(options.capture) : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - const newNode = { - listener, - listenerType, - passive: optionsIsObj && Boolean(options.passive), - once: optionsIsObj && Boolean(options.once), - next: null - }; - let node = listeners.get(eventName); - if (node === void 0) { - listeners.set(eventName, newNode); - return; - } - let prev = null; - while (node != null) { - if (node.listener === listener && node.listenerType === listenerType) { - return; - } - prev = node; - node = node.next; - } - prev.next = newNode; - }, - /** - * Remove a given listener from this event target. - * @param {string} eventName The event name to remove. - * @param {Function} listener The listener to remove. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - removeEventListener(eventName, listener, options) { - if (listener == null) { - return; - } - const listeners = getListeners(this); - const capture = isObject2(options) ? Boolean(options.capture) : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if (node.listener === listener && node.listenerType === listenerType) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - return; - } - prev = node; - node = node.next; - } - }, - /** - * Dispatch a given event. - * @param {Event|{type:string}} event The event to dispatch. - * @returns {boolean} `false` if canceled. - */ - dispatchEvent(event) { - if (event == null || typeof event.type !== "string") { - throw new TypeError('"event.type" should be a string.'); - } - const listeners = getListeners(this); - const eventName = event.type; - let node = listeners.get(eventName); - if (node == null) { - return true; + var validateAbortSignal = hideStackFrames((signal, name) => { + if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) { + throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal); + } + }); + var validateFunction = hideStackFrames((value, name) => { + if (typeof value !== "function") throw new ERR_INVALID_ARG_TYPE2(name, "Function", value); + }); + var validatePlainFunction = hideStackFrames((value, name) => { + if (typeof value !== "function" || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE2(name, "Function", value); + }); + var validateUndefined = hideStackFrames((value, name) => { + if (value !== void 0) throw new ERR_INVALID_ARG_TYPE2(name, "undefined", value); + }); + function validateUnion(value, name, union) { + if (!ArrayPrototypeIncludes(union, value)) { + throw new ERR_INVALID_ARG_TYPE2(name, `('${ArrayPrototypeJoin(union, "|")}')`, value); + } + } + var linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/; + function validateLinkHeaderFormat(value, name) { + if (typeof value === "undefined" || !RegExpPrototypeExec(linkValueRegExp, value)) { + throw new ERR_INVALID_ARG_VALUE( + name, + value, + 'must be an array or string of format "; rel=preload; as=style"' + ); + } + } + function validateLinkHeaderValue(hints) { + if (typeof hints === "string") { + validateLinkHeaderFormat(hints, "hints"); + return hints; + } else if (ArrayIsArray(hints)) { + const hintsLength = hints.length; + let result = ""; + if (hintsLength === 0) { + return result; } - const wrappedEvent = wrapEvent(this, event); - let prev = null; - while (node != null) { - if (node.once) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - setPassiveListener( - wrappedEvent, - node.passive ? node.listener : null - ); - if (typeof node.listener === "function") { - try { - node.listener.call(this, wrappedEvent); - } catch (err) { - if (typeof console !== "undefined" && typeof console.error === "function") { - console.error(err); - } - } - } else if (node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function") { - node.listener.handleEvent(wrappedEvent); - } - if (isStopped(wrappedEvent)) { - break; + for (let i = 0; i < hintsLength; i++) { + const link = hints[i]; + validateLinkHeaderFormat(link, "hints"); + result += link; + if (i !== hintsLength - 1) { + result += ", "; } - node = node.next; } - setPassiveListener(wrappedEvent, null); - setEventPhase(wrappedEvent, 0); - setCurrentTarget(wrappedEvent, null); - return !wrappedEvent.defaultPrevented; + return result; } - }; - Object.defineProperty(EventTarget2.prototype, "constructor", { - value: EventTarget2, - configurable: true, - writable: true - }); - if (typeof window !== "undefined" && typeof window.EventTarget !== "undefined") { - Object.setPrototypeOf(EventTarget2.prototype, window.EventTarget.prototype); + throw new ERR_INVALID_ARG_VALUE( + "hints", + hints, + 'must be an array or string of format "; rel=preload; as=style"' + ); } - exports2.defineEventAttribute = defineEventAttribute; - exports2.EventTarget = EventTarget2; - exports2.default = EventTarget2; - module2.exports = EventTarget2; - module2.exports.EventTarget = module2.exports["default"] = EventTarget2; - module2.exports.defineEventAttribute = defineEventAttribute; + module2.exports = { + isInt32, + isUint32, + parseFileMode, + validateArray, + validateStringArray, + validateBooleanArray, + validateAbortSignalArray, + validateBoolean, + validateBuffer, + validateDictionary, + validateEncoding, + validateFunction, + validateInt32, + validateInteger, + validateNumber, + validateObject, + validateOneOf, + validatePlainFunction, + validatePort, + validateSignalName, + validateString, + validateUint32, + validateUndefined, + validateUnion, + validateAbortSignal, + validateLinkHeaderValue + }; } }); -// node_modules/abort-controller/dist/abort-controller.js -var require_abort_controller = __commonJS({ - "node_modules/abort-controller/dist/abort-controller.js"(exports2, module2) { +// node_modules/process/index.js +var require_process = __commonJS({ + "node_modules/process/index.js"(exports2, module2) { + module2.exports = global.process; + } +}); + +// node_modules/readable-stream/lib/internal/streams/utils.js +var require_utils6 = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/utils.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var eventTargetShim = require_event_target_shim(); - var AbortSignal2 = class extends eventTargetShim.EventTarget { - /** - * AbortSignal cannot be constructed directly. - */ - constructor() { - super(); - throw new TypeError("AbortSignal cannot be constructed directly"); + var { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require_primordials(); + var kIsDestroyed = SymbolFor("nodejs.stream.destroyed"); + var kIsErrored = SymbolFor("nodejs.stream.errored"); + var kIsReadable = SymbolFor("nodejs.stream.readable"); + var kIsWritable = SymbolFor("nodejs.stream.writable"); + var kIsDisturbed = SymbolFor("nodejs.stream.disturbed"); + var kIsClosedPromise = SymbolFor("nodejs.webstream.isClosedPromise"); + var kControllerErrorFunction = SymbolFor("nodejs.webstream.controllerErrorFunction"); + function isReadableNodeStream(obj, strict = false) { + var _obj$_readableState; + return !!(obj && typeof obj.pipe === "function" && typeof obj.on === "function" && (!strict || typeof obj.pause === "function" && typeof obj.resume === "function") && (!obj._writableState || ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === void 0 ? void 0 : _obj$_readableState.readable) !== false) && // Duplex + (!obj._writableState || obj._readableState)); + } + function isWritableNodeStream(obj) { + var _obj$_writableState; + return !!(obj && typeof obj.write === "function" && typeof obj.on === "function" && (!obj._readableState || ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === void 0 ? void 0 : _obj$_writableState.writable) !== false)); + } + function isDuplexNodeStream(obj) { + return !!(obj && typeof obj.pipe === "function" && obj._readableState && typeof obj.on === "function" && typeof obj.write === "function"); + } + function isNodeStream(obj) { + return obj && (obj._readableState || obj._writableState || typeof obj.write === "function" && typeof obj.on === "function" || typeof obj.pipe === "function" && typeof obj.on === "function"); + } + function isReadableStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.pipeThrough === "function" && typeof obj.getReader === "function" && typeof obj.cancel === "function"); + } + function isWritableStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === "function" && typeof obj.abort === "function"); + } + function isTransformStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.readable === "object" && typeof obj.writable === "object"); + } + function isWebStream(obj) { + return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj); + } + function isIterable(obj, isAsync) { + if (obj == null) return false; + if (isAsync === true) return typeof obj[SymbolAsyncIterator] === "function"; + if (isAsync === false) return typeof obj[SymbolIterator] === "function"; + return typeof obj[SymbolAsyncIterator] === "function" || typeof obj[SymbolIterator] === "function"; + } + function isDestroyed(stream) { + if (!isNodeStream(stream)) return null; + const wState = stream._writableState; + const rState = stream._readableState; + const state = wState || rState; + return !!(stream.destroyed || stream[kIsDestroyed] || state !== null && state !== void 0 && state.destroyed); + } + function isWritableEnded(stream) { + if (!isWritableNodeStream(stream)) return null; + if (stream.writableEnded === true) return true; + const wState = stream._writableState; + if (wState !== null && wState !== void 0 && wState.errored) return false; + if (typeof (wState === null || wState === void 0 ? void 0 : wState.ended) !== "boolean") return null; + return wState.ended; + } + function isWritableFinished(stream, strict) { + if (!isWritableNodeStream(stream)) return null; + if (stream.writableFinished === true) return true; + const wState = stream._writableState; + if (wState !== null && wState !== void 0 && wState.errored) return false; + if (typeof (wState === null || wState === void 0 ? void 0 : wState.finished) !== "boolean") return null; + return !!(wState.finished || strict === false && wState.ended === true && wState.length === 0); + } + function isReadableEnded(stream) { + if (!isReadableNodeStream(stream)) return null; + if (stream.readableEnded === true) return true; + const rState = stream._readableState; + if (!rState || rState.errored) return false; + if (typeof (rState === null || rState === void 0 ? void 0 : rState.ended) !== "boolean") return null; + return rState.ended; + } + function isReadableFinished(stream, strict) { + if (!isReadableNodeStream(stream)) return null; + const rState = stream._readableState; + if (rState !== null && rState !== void 0 && rState.errored) return false; + if (typeof (rState === null || rState === void 0 ? void 0 : rState.endEmitted) !== "boolean") return null; + return !!(rState.endEmitted || strict === false && rState.ended === true && rState.length === 0); + } + function isReadable(stream) { + if (stream && stream[kIsReadable] != null) return stream[kIsReadable]; + if (typeof (stream === null || stream === void 0 ? void 0 : stream.readable) !== "boolean") return null; + if (isDestroyed(stream)) return false; + return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream); + } + function isWritable(stream) { + if (stream && stream[kIsWritable] != null) return stream[kIsWritable]; + if (typeof (stream === null || stream === void 0 ? void 0 : stream.writable) !== "boolean") return null; + if (isDestroyed(stream)) return false; + return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream); + } + function isFinished(stream, opts) { + if (!isNodeStream(stream)) { + return null; } - /** - * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. - */ - get aborted() { - const aborted = abortedFlags.get(this); - if (typeof aborted !== "boolean") { - throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); - } - return aborted; + if (isDestroyed(stream)) { + return true; } - }; - eventTargetShim.defineEventAttribute(AbortSignal2.prototype, "abort"); - function createAbortSignal() { - const signal = Object.create(AbortSignal2.prototype); - eventTargetShim.EventTarget.call(signal); - abortedFlags.set(signal, false); - return signal; + if ((opts === null || opts === void 0 ? void 0 : opts.readable) !== false && isReadable(stream)) { + return false; + } + if ((opts === null || opts === void 0 ? void 0 : opts.writable) !== false && isWritable(stream)) { + return false; + } + return true; } - function abortSignal(signal) { - if (abortedFlags.get(signal) !== false) { - return; + function isWritableErrored(stream) { + var _stream$_writableStat, _stream$_writableStat2; + if (!isNodeStream(stream)) { + return null; } - abortedFlags.set(signal, true); - signal.dispatchEvent({ type: "abort" }); + if (stream.writableErrored) { + return stream.writableErrored; + } + return (_stream$_writableStat = (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === void 0 ? void 0 : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== void 0 ? _stream$_writableStat : null; } - var abortedFlags = /* @__PURE__ */ new WeakMap(); - Object.defineProperties(AbortSignal2.prototype, { - aborted: { enumerable: true } - }); - if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortSignal2.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortSignal" - }); + function isReadableErrored(stream) { + var _stream$_readableStat, _stream$_readableStat2; + if (!isNodeStream(stream)) { + return null; + } + if (stream.readableErrored) { + return stream.readableErrored; + } + return (_stream$_readableStat = (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === void 0 ? void 0 : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== void 0 ? _stream$_readableStat : null; } - var AbortController2 = class { - /** - * Initialize this controller. - */ - constructor() { - signals.set(this, createAbortSignal()); + function isClosed(stream) { + if (!isNodeStream(stream)) { + return null; } - /** - * Returns the `AbortSignal` object associated with this object. - */ - get signal() { - return getSignal(this); + if (typeof stream.closed === "boolean") { + return stream.closed; } - /** - * Abort and signal to any observers that the associated activity is to be aborted. - */ - abort() { - abortSignal(getSignal(this)); + const wState = stream._writableState; + const rState = stream._readableState; + if (typeof (wState === null || wState === void 0 ? void 0 : wState.closed) === "boolean" || typeof (rState === null || rState === void 0 ? void 0 : rState.closed) === "boolean") { + return (wState === null || wState === void 0 ? void 0 : wState.closed) || (rState === null || rState === void 0 ? void 0 : rState.closed); } - }; - var signals = /* @__PURE__ */ new WeakMap(); - function getSignal(controller) { - const signal = signals.get(controller); - if (signal == null) { - throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); + if (typeof stream._closed === "boolean" && isOutgoingMessage(stream)) { + return stream._closed; } - return signal; + return null; + } + function isOutgoingMessage(stream) { + return typeof stream._closed === "boolean" && typeof stream._defaultKeepAlive === "boolean" && typeof stream._removedConnection === "boolean" && typeof stream._removedContLen === "boolean"; + } + function isServerResponse(stream) { + return typeof stream._sent100 === "boolean" && isOutgoingMessage(stream); + } + function isServerRequest(stream) { + var _stream$req; + return typeof stream._consuming === "boolean" && typeof stream._dumped === "boolean" && ((_stream$req = stream.req) === null || _stream$req === void 0 ? void 0 : _stream$req.upgradeOrConnect) === void 0; + } + function willEmitClose(stream) { + if (!isNodeStream(stream)) return null; + const wState = stream._writableState; + const rState = stream._readableState; + const state = wState || rState; + return !state && isServerResponse(stream) || !!(state && state.autoDestroy && state.emitClose && state.closed === false); + } + function isDisturbed(stream) { + var _stream$kIsDisturbed; + return !!(stream && ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== void 0 ? _stream$kIsDisturbed : stream.readableDidRead || stream.readableAborted)); } - Object.defineProperties(AbortController2.prototype, { - signal: { enumerable: true }, - abort: { enumerable: true } - }); - if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortController2.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortController" - }); + function isErrored(stream) { + var _ref, _ref2, _ref3, _ref4, _ref5, _stream$kIsErrored, _stream$_readableStat3, _stream$_writableStat3, _stream$_readableStat4, _stream$_writableStat4; + return !!(stream && ((_ref = (_ref2 = (_ref3 = (_ref4 = (_ref5 = (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== void 0 ? _stream$kIsErrored : stream.readableErrored) !== null && _ref5 !== void 0 ? _ref5 : stream.writableErrored) !== null && _ref4 !== void 0 ? _ref4 : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === void 0 ? void 0 : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== void 0 ? _ref3 : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === void 0 ? void 0 : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== void 0 ? _ref2 : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === void 0 ? void 0 : _stream$_readableStat4.errored) !== null && _ref !== void 0 ? _ref : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === void 0 ? void 0 : _stream$_writableStat4.errored)); } - exports2.AbortController = AbortController2; - exports2.AbortSignal = AbortSignal2; - exports2.default = AbortController2; - module2.exports = AbortController2; - module2.exports.AbortController = module2.exports["default"] = AbortController2; - module2.exports.AbortSignal = AbortSignal2; + module2.exports = { + isDestroyed, + kIsDestroyed, + isDisturbed, + kIsDisturbed, + isErrored, + kIsErrored, + isReadable, + kIsReadable, + kIsClosedPromise, + kControllerErrorFunction, + kIsWritable, + isClosed, + isDuplexNodeStream, + isFinished, + isIterable, + isReadableNodeStream, + isReadableStream, + isReadableEnded, + isReadableFinished, + isReadableErrored, + isNodeStream, + isWebStream, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableEnded, + isWritableFinished, + isWritableErrored, + isServerRequest, + isServerResponse, + willEmitClose, + isTransformStream + }; } }); -// node_modules/readable-stream/lib/ours/util.js -var require_util12 = __commonJS({ - "node_modules/readable-stream/lib/ours/util.js"(exports2, module2) { - "use strict"; - var bufferModule = require("buffer"); - var { kResistStopPropagation, SymbolDispose } = require_primordials(); - var AbortSignal2 = globalThis.AbortSignal || require_abort_controller().AbortSignal; - var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; - var AsyncFunction = Object.getPrototypeOf(async function() { - }).constructor; - var Blob2 = globalThis.Blob || bufferModule.Blob; - var isBlob = typeof Blob2 !== "undefined" ? function isBlob2(b) { - return b instanceof Blob2; - } : function isBlob2(b) { - return false; +// node_modules/readable-stream/lib/internal/streams/end-of-stream.js +var require_end_of_stream = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { + var process2 = require_process(); + var { AbortError, codes } = require_errors3(); + var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_PREMATURE_CLOSE } = codes; + var { kEmptyObject, once } = require_util12(); + var { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require_validators(); + var { Promise: Promise2, PromisePrototypeThen, SymbolDispose } = require_primordials(); + var { + isClosed, + isReadable, + isReadableNodeStream, + isReadableStream, + isReadableFinished, + isReadableErrored, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableFinished, + isWritableErrored, + isNodeStream, + willEmitClose: _willEmitClose, + kIsClosedPromise + } = require_utils6(); + var addAbortListener; + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === "function"; + } + var nop = () => { }; - var validateAbortSignal = (signal, name) => { - if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) { - throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal); + function eos(stream, options, callback) { + var _options$readable, _options$writable; + if (arguments.length === 2) { + callback = options; + options = kEmptyObject; + } else if (options == null) { + options = kEmptyObject; + } else { + validateObject(options, "options"); } - }; - var validateFunction = (value, name) => { - if (typeof value !== "function") throw new ERR_INVALID_ARG_TYPE(name, "Function", value); - }; - var AggregateError = class extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + validateFunction(callback, "callback"); + validateAbortSignal(options.signal, "options.signal"); + callback = once(callback); + if (isReadableStream(stream) || isWritableStream(stream)) { + return eosWeb(stream, options, callback); + } + if (!isNodeStream(stream)) { + throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream); + } + const readable = (_options$readable = options.readable) !== null && _options$readable !== void 0 ? _options$readable : isReadableNodeStream(stream); + const writable = (_options$writable = options.writable) !== null && _options$writable !== void 0 ? _options$writable : isWritableNodeStream(stream); + const wState = stream._writableState; + const rState = stream._readableState; + const onlegacyfinish = () => { + if (!stream.writable) { + onfinish(); } - let message = ""; - for (let i = 0; i < errors.length; i++) { - message += ` ${errors[i].stack} -`; + }; + let willEmitClose = _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable; + let writableFinished = isWritableFinished(stream, false); + const onfinish = () => { + writableFinished = true; + if (stream.destroyed) { + willEmitClose = false; } - super(message); - this.name = "AggregateError"; - this.errors = errors; - } - }; - module2.exports = { - AggregateError, - kEmptyObject: Object.freeze({}), - once(callback) { - let called = false; - return function(...args) { - if (called) { - return; - } - called = true; - callback.apply(this, args); - }; - }, - createDeferredPromise: function() { - let resolve2; - let reject; - const promise = new Promise((res, rej) => { - resolve2 = res; - reject = rej; - }); - return { - promise, - resolve: resolve2, - reject - }; - }, - promisify(fn) { - return new Promise((resolve2, reject) => { - fn((err, ...args) => { - if (err) { - return reject(err); - } - return resolve2(...args); - }); - }); - }, - debuglog() { - return function() { - }; - }, - format(format, ...args) { - return format.replace(/%([sdifj])/g, function(...[_unused, type2]) { - const replacement = args.shift(); - if (type2 === "f") { - return replacement.toFixed(6); - } else if (type2 === "j") { - return JSON.stringify(replacement); - } else if (type2 === "s" && typeof replacement === "object") { - const ctor = replacement.constructor !== Object ? replacement.constructor.name : ""; - return `${ctor} {}`.trim(); - } else { - return replacement.toString(); - } - }); - }, - inspect(value) { - switch (typeof value) { - case "string": - if (value.includes("'")) { - if (!value.includes('"')) { - return `"${value}"`; - } else if (!value.includes("`") && !value.includes("${")) { - return `\`${value}\``; - } - } - return `'${value}'`; - case "number": - if (isNaN(value)) { - return "NaN"; - } else if (Object.is(value, -0)) { - return String(value); - } - return value; - case "bigint": - return `${String(value)}n`; - case "boolean": - case "undefined": - return String(value); - case "object": - return "{}"; + if (willEmitClose && (!stream.readable || readable)) { + return; } - }, - types: { - isAsyncFunction(fn) { - return fn instanceof AsyncFunction; - }, - isArrayBufferView(arr) { - return ArrayBuffer.isView(arr); + if (!readable || readableFinished) { + callback.call(stream); } - }, - isBlob, - deprecate(fn, message) { - return fn; - }, - addAbortListener: require("events").addAbortListener || function addAbortListener(signal, listener) { - if (signal === void 0) { - throw new ERR_INVALID_ARG_TYPE("signal", "AbortSignal", signal); + }; + let readableFinished = isReadableFinished(stream, false); + const onend = () => { + readableFinished = true; + if (stream.destroyed) { + willEmitClose = false; } - validateAbortSignal(signal, "signal"); - validateFunction(listener, "listener"); - let removeEventListener; - if (signal.aborted) { - queueMicrotask(() => listener()); - } else { - signal.addEventListener("abort", listener, { - __proto__: null, - once: true, - [kResistStopPropagation]: true - }); - removeEventListener = () => { - signal.removeEventListener("abort", listener); - }; + if (willEmitClose && (!stream.writable || writable)) { + return; } - return { - __proto__: null, - [SymbolDispose]() { - var _removeEventListener; - (_removeEventListener = removeEventListener) === null || _removeEventListener === void 0 ? void 0 : _removeEventListener(); - } - }; - }, - AbortSignalAny: AbortSignal2.any || function AbortSignalAny(signals) { - if (signals.length === 1) { - return signals[0]; + if (!writable || writableFinished) { + callback.call(stream); } - const ac = new AbortController2(); - const abort = () => ac.abort(); - signals.forEach((signal) => { - validateAbortSignal(signal, "signals"); - signal.addEventListener("abort", abort, { - once: true - }); - }); - ac.signal.addEventListener( - "abort", - () => { - signals.forEach((signal) => signal.removeEventListener("abort", abort)); - }, - { - once: true - } - ); - return ac.signal; - } - }; - module2.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom"); - } -}); - -// node_modules/readable-stream/lib/ours/errors.js -var require_errors3 = __commonJS({ - "node_modules/readable-stream/lib/ours/errors.js"(exports2, module2) { - "use strict"; - var { format, inspect, AggregateError: CustomAggregateError } = require_util12(); - var AggregateError = globalThis.AggregateError || CustomAggregateError; - var kIsNodeError = Symbol("kIsNodeError"); - var kTypes = [ - "string", - "function", - "number", - "object", - // Accept 'Function' and 'Object' as alternative to the lower cased version. - "Function", - "Object", - "boolean", - "bigint", - "symbol" - ]; - var classRegExp = /^([A-Z][a-z0-9]*)+$/; - var nodeInternalPrefix = "__node_internal_"; - var codes = {}; - function assert(value, message) { - if (!value) { - throw new codes.ERR_INTERNAL_ASSERTION(message); - } - } - function addNumericalSeparator(val2) { - let res = ""; - let i = val2.length; - const start = val2[0] === "-" ? 1 : 0; - for (; i >= start + 4; i -= 3) { - res = `_${val2.slice(i - 3, i)}${res}`; - } - return `${val2.slice(0, i)}${res}`; - } - function getMessage(key, msg, args) { - if (typeof msg === "function") { - assert( - msg.length <= args.length, - // Default options do not count. - `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` - ); - return msg(...args); + }; + const onerror = (err) => { + callback.call(stream, err); + }; + let closed = isClosed(stream); + const onclose = () => { + closed = true; + const errored = isWritableErrored(stream) || isReadableErrored(stream); + if (errored && typeof errored !== "boolean") { + return callback.call(stream, errored); + } + if (readable && !readableFinished && isReadableNodeStream(stream, true)) { + if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()); + } + if (writable && !writableFinished) { + if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()); + } + callback.call(stream); + }; + const onclosed = () => { + closed = true; + const errored = isWritableErrored(stream) || isReadableErrored(stream); + if (errored && typeof errored !== "boolean") { + return callback.call(stream, errored); + } + callback.call(stream); + }; + const onrequest = () => { + stream.req.on("finish", onfinish); + }; + if (isRequest(stream)) { + stream.on("complete", onfinish); + if (!willEmitClose) { + stream.on("abort", onclose); + } + if (stream.req) { + onrequest(); + } else { + stream.on("request", onrequest); + } + } else if (writable && !wState) { + stream.on("end", onlegacyfinish); + stream.on("close", onlegacyfinish); } - const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length; - assert( - expectedLength === args.length, - `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` - ); - if (args.length === 0) { - return msg; + if (!willEmitClose && typeof stream.aborted === "boolean") { + stream.on("aborted", onclose); } - return format(msg, ...args); - } - function E(code, message, Base) { - if (!Base) { - Base = Error; + stream.on("end", onend); + stream.on("finish", onfinish); + if (options.error !== false) { + stream.on("error", onerror); } - class NodeError extends Base { - constructor(...args) { - super(getMessage(code, message, args)); - } - toString() { - return `${this.name} [${code}]: ${this.message}`; + stream.on("close", onclose); + if (closed) { + process2.nextTick(onclose); + } else if (wState !== null && wState !== void 0 && wState.errorEmitted || rState !== null && rState !== void 0 && rState.errorEmitted) { + if (!willEmitClose) { + process2.nextTick(onclosed); } + } else if (!readable && (!willEmitClose || isReadable(stream)) && (writableFinished || isWritable(stream) === false)) { + process2.nextTick(onclosed); + } else if (!writable && (!willEmitClose || isWritable(stream)) && (readableFinished || isReadable(stream) === false)) { + process2.nextTick(onclosed); + } else if (rState && stream.req && stream.aborted) { + process2.nextTick(onclosed); } - Object.defineProperties(NodeError.prototype, { - name: { - value: Base.name, - writable: true, - enumerable: false, - configurable: true - }, - toString: { - value() { - return `${this.name} [${code}]: ${this.message}`; - }, - writable: true, - enumerable: false, - configurable: true + const cleanup = () => { + callback = nop; + stream.removeListener("aborted", onclose); + stream.removeListener("complete", onfinish); + stream.removeListener("abort", onclose); + stream.removeListener("request", onrequest); + if (stream.req) stream.req.removeListener("finish", onfinish); + stream.removeListener("end", onlegacyfinish); + stream.removeListener("close", onlegacyfinish); + stream.removeListener("finish", onfinish); + stream.removeListener("end", onend); + stream.removeListener("error", onerror); + stream.removeListener("close", onclose); + }; + if (options.signal && !closed) { + const abort = () => { + const endCallback = callback; + cleanup(); + endCallback.call( + stream, + new AbortError(void 0, { + cause: options.signal.reason + }) + ); + }; + if (options.signal.aborted) { + process2.nextTick(abort); + } else { + addAbortListener = addAbortListener || require_util12().addAbortListener; + const disposable = addAbortListener(options.signal, abort); + const originalCallback = callback; + callback = once((...args) => { + disposable[SymbolDispose](); + originalCallback.apply(stream, args); + }); } - }); - NodeError.prototype.code = code; - NodeError.prototype[kIsNodeError] = true; - codes[code] = NodeError; - } - function hideStackFrames(fn) { - const hidden = nodeInternalPrefix + fn.name; - Object.defineProperty(fn, "name", { - value: hidden - }); - return fn; + } + return cleanup; } - function aggregateTwoErrors(innerError, outerError) { - if (innerError && outerError && innerError !== outerError) { - if (Array.isArray(outerError.errors)) { - outerError.errors.push(innerError); - return outerError; + function eosWeb(stream, options, callback) { + let isAborted = false; + let abort = nop; + if (options.signal) { + abort = () => { + isAborted = true; + callback.call( + stream, + new AbortError(void 0, { + cause: options.signal.reason + }) + ); + }; + if (options.signal.aborted) { + process2.nextTick(abort); + } else { + addAbortListener = addAbortListener || require_util12().addAbortListener; + const disposable = addAbortListener(options.signal, abort); + const originalCallback = callback; + callback = once((...args) => { + disposable[SymbolDispose](); + originalCallback.apply(stream, args); + }); } - const err = new AggregateError([outerError, innerError], outerError.message); - err.code = outerError.code; - return err; } - return innerError || outerError; - } - var AbortError = class extends Error { - constructor(message = "The operation was aborted", options = void 0) { - if (options !== void 0 && typeof options !== "object") { - throw new codes.ERR_INVALID_ARG_TYPE("options", "Object", options); + const resolverFn = (...args) => { + if (!isAborted) { + process2.nextTick(() => callback.apply(stream, args)); } - super(message, options); - this.code = "ABORT_ERR"; - this.name = "AbortError"; + }; + PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn); + return nop; + } + function finished(stream, opts) { + var _opts; + let autoCleanup = false; + if (opts === null) { + opts = kEmptyObject; } - }; - E("ERR_ASSERTION", "%s", Error); - E( - "ERR_INVALID_ARG_TYPE", - (name, expected, actual) => { - assert(typeof name === "string", "'name' must be a string"); - if (!Array.isArray(expected)) { - expected = [expected]; - } - let msg = "The "; - if (name.endsWith(" argument")) { - msg += `${name} `; - } else { - msg += `"${name}" ${name.includes(".") ? "property" : "argument"} `; - } - msg += "must be "; - const types = []; - const instances = []; - const other = []; - for (const value of expected) { - assert(typeof value === "string", "All expected entries have to be of type string"); - if (kTypes.includes(value)) { - types.push(value.toLowerCase()); - } else if (classRegExp.test(value)) { - instances.push(value); - } else { - assert(value !== "object", 'The value "object" should be written as "Object"'); - other.push(value); + if ((_opts = opts) !== null && _opts !== void 0 && _opts.cleanup) { + validateBoolean(opts.cleanup, "cleanup"); + autoCleanup = opts.cleanup; + } + return new Promise2((resolve2, reject) => { + const cleanup = eos(stream, opts, (err) => { + if (autoCleanup) { + cleanup(); } - } - if (instances.length > 0) { - const pos = types.indexOf("object"); - if (pos !== -1) { - types.splice(types, pos, 1); - instances.push("Object"); + if (err) { + reject(err); + } else { + resolve2(); } + }); + }); + } + module2.exports = eos; + module2.exports.finished = finished; + } +}); + +// node_modules/readable-stream/lib/internal/streams/destroy.js +var require_destroy2 = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module2) { + "use strict"; + var process2 = require_process(); + var { + aggregateTwoErrors, + codes: { ERR_MULTIPLE_CALLBACK }, + AbortError + } = require_errors3(); + var { Symbol: Symbol2 } = require_primordials(); + var { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require_utils6(); + var kDestroy = Symbol2("kDestroy"); + var kConstruct = Symbol2("kConstruct"); + function checkError(err, w, r) { + if (err) { + err.stack; + if (w && !w.errored) { + w.errored = err; } - if (types.length > 0) { - switch (types.length) { - case 1: - msg += `of type ${types[0]}`; - break; - case 2: - msg += `one of type ${types[0]} or ${types[1]}`; - break; - default: { - const last = types.pop(); - msg += `one of type ${types.join(", ")}, or ${last}`; - } - } - if (instances.length > 0 || other.length > 0) { - msg += " or "; - } + if (r && !r.errored) { + r.errored = err; } - if (instances.length > 0) { - switch (instances.length) { - case 1: - msg += `an instance of ${instances[0]}`; - break; - case 2: - msg += `an instance of ${instances[0]} or ${instances[1]}`; - break; - default: { - const last = instances.pop(); - msg += `an instance of ${instances.join(", ")}, or ${last}`; - } - } - if (other.length > 0) { - msg += " or "; - } + } + } + function destroy(err, cb) { + const r = this._readableState; + const w = this._writableState; + const s = w || r; + if (w !== null && w !== void 0 && w.destroyed || r !== null && r !== void 0 && r.destroyed) { + if (typeof cb === "function") { + cb(); } - switch (other.length) { - case 0: - break; - case 1: - if (other[0].toLowerCase() !== other[0]) { - msg += "an "; - } - msg += `${other[0]}`; - break; - case 2: - msg += `one of ${other[0]} or ${other[1]}`; - break; - default: { - const last = other.pop(); - msg += `one of ${other.join(", ")}, or ${last}`; - } + return this; + } + checkError(err, w, r); + if (w) { + w.destroyed = true; + } + if (r) { + r.destroyed = true; + } + if (!s.constructed) { + this.once(kDestroy, function(er) { + _destroy(this, aggregateTwoErrors(er, err), cb); + }); + } else { + _destroy(this, err, cb); + } + return this; + } + function _destroy(self2, err, cb) { + let called = false; + function onDestroy(err2) { + if (called) { + return; } - if (actual == null) { - msg += `. Received ${actual}`; - } else if (typeof actual === "function" && actual.name) { - msg += `. Received function ${actual.name}`; - } else if (typeof actual === "object") { - var _actual$constructor; - if ((_actual$constructor = actual.constructor) !== null && _actual$constructor !== void 0 && _actual$constructor.name) { - msg += `. Received an instance of ${actual.constructor.name}`; - } else { - const inspected = inspect(actual, { - depth: -1 - }); - msg += `. Received ${inspected}`; - } - } else { - let inspected = inspect(actual, { - colors: false - }); - if (inspected.length > 25) { - inspected = `${inspected.slice(0, 25)}...`; - } - msg += `. Received type ${typeof actual} (${inspected})`; + called = true; + const r = self2._readableState; + const w = self2._writableState; + checkError(err2, w, r); + if (w) { + w.closed = true; } - return msg; - }, - TypeError - ); - E( - "ERR_INVALID_ARG_VALUE", - (name, value, reason = "is invalid") => { - let inspected = inspect(value); - if (inspected.length > 128) { - inspected = inspected.slice(0, 128) + "..."; + if (r) { + r.closed = true; } - const type2 = name.includes(".") ? "property" : "argument"; - return `The ${type2} '${name}' ${reason}. Received ${inspected}`; - }, - TypeError - ); - E( - "ERR_INVALID_RETURN_VALUE", - (input, name, value) => { - var _value$constructor; - const type2 = value !== null && value !== void 0 && (_value$constructor = value.constructor) !== null && _value$constructor !== void 0 && _value$constructor.name ? `instance of ${value.constructor.name}` : `type ${typeof value}`; - return `Expected ${input} to be returned from the "${name}" function but got ${type2}.`; - }, - TypeError - ); - E( - "ERR_MISSING_ARGS", - (...args) => { - assert(args.length > 0, "At least one arg needs to be specified"); - let msg; - const len = args.length; - args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(" or "); - switch (len) { - case 1: - msg += `The ${args[0]} argument`; - break; - case 2: - msg += `The ${args[0]} and ${args[1]} arguments`; - break; - default: - { - const last = args.pop(); - msg += `The ${args.join(", ")}, and ${last} arguments`; - } - break; + if (typeof cb === "function") { + cb(err2); } - return `${msg} must be specified`; - }, - TypeError - ); - E( - "ERR_OUT_OF_RANGE", - (str2, range, input) => { - assert(range, 'Missing "range" argument'); - let received; - if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === "bigint") { - received = String(input); - if (input > 2n ** 32n || input < -(2n ** 32n)) { - received = addNumericalSeparator(received); - } - received += "n"; + if (err2) { + process2.nextTick(emitErrorCloseNT, self2, err2); } else { - received = inspect(input); + process2.nextTick(emitCloseNT, self2); } - return `The value of "${str2}" is out of range. It must be ${range}. Received ${received}`; - }, - RangeError - ); - E("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error); - E("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error); - E("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error); - E("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error); - E("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error); - E("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); - E("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error); - E("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error); - E("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error); - E("ERR_STREAM_WRITE_AFTER_END", "write after end", Error); - E("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError); - module2.exports = { - AbortError, - aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), - hideStackFrames, - codes - }; - } -}); - -// node_modules/readable-stream/lib/internal/validators.js -var require_validators = __commonJS({ - "node_modules/readable-stream/lib/internal/validators.js"(exports2, module2) { - "use strict"; - var { - ArrayIsArray, - ArrayPrototypeIncludes, - ArrayPrototypeJoin, - ArrayPrototypeMap, - NumberIsInteger, - NumberIsNaN, - NumberMAX_SAFE_INTEGER, - NumberMIN_SAFE_INTEGER, - NumberParseInt, - ObjectPrototypeHasOwnProperty, - RegExpPrototypeExec, - String: String2, - StringPrototypeToUpperCase, - StringPrototypeTrim - } = require_primordials(); - var { - hideStackFrames, - codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } - } = require_errors3(); - var { normalizeEncoding } = require_util12(); - var { isAsyncFunction, isArrayBufferView } = require_util12().types; - var signals = {}; - function isInt32(value) { - return value === (value | 0); + } + try { + self2._destroy(err || null, onDestroy); + } catch (err2) { + onDestroy(err2); + } } - function isUint32(value) { - return value === value >>> 0; + function emitErrorCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); } - var octalReg = /^[0-7]+$/; - var modeDesc = "must be a 32-bit unsigned integer or an octal string"; - function parseFileMode(value, name, def) { - if (typeof value === "undefined") { - value = def; + function emitCloseNT(self2) { + const r = self2._readableState; + const w = self2._writableState; + if (w) { + w.closeEmitted = true; } - if (typeof value === "string") { - if (RegExpPrototypeExec(octalReg, value) === null) { - throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc); - } - value = NumberParseInt(value, 8); + if (r) { + r.closeEmitted = true; + } + if (w !== null && w !== void 0 && w.emitClose || r !== null && r !== void 0 && r.emitClose) { + self2.emit("close"); } - validateUint32(value, name); - return value; } - var validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => { - if (typeof value !== "number") throw new ERR_INVALID_ARG_TYPE2(name, "number", value); - if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, "an integer", value); - if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); - }); - var validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => { - if (typeof value !== "number") { - throw new ERR_INVALID_ARG_TYPE2(name, "number", value); + function emitErrorNT(self2, err) { + const r = self2._readableState; + const w = self2._writableState; + if (w !== null && w !== void 0 && w.errorEmitted || r !== null && r !== void 0 && r.errorEmitted) { + return; } - if (!NumberIsInteger(value)) { - throw new ERR_OUT_OF_RANGE(name, "an integer", value); + if (w) { + w.errorEmitted = true; } - if (value < min || value > max) { - throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); + if (r) { + r.errorEmitted = true; } - }); - var validateUint32 = hideStackFrames((value, name, positive = false) => { - if (typeof value !== "number") { - throw new ERR_INVALID_ARG_TYPE2(name, "number", value); + self2.emit("error", err); + } + function undestroy() { + const r = this._readableState; + const w = this._writableState; + if (r) { + r.constructed = true; + r.closed = false; + r.closeEmitted = false; + r.destroyed = false; + r.errored = null; + r.errorEmitted = false; + r.reading = false; + r.ended = r.readable === false; + r.endEmitted = r.readable === false; } - if (!NumberIsInteger(value)) { - throw new ERR_OUT_OF_RANGE(name, "an integer", value); + if (w) { + w.constructed = true; + w.destroyed = false; + w.closed = false; + w.closeEmitted = false; + w.errored = null; + w.errorEmitted = false; + w.finalCalled = false; + w.prefinished = false; + w.ended = w.writable === false; + w.ending = w.writable === false; + w.finished = w.writable === false; } - const min = positive ? 1 : 0; - const max = 4294967295; - if (value < min || value > max) { - throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); + } + function errorOrDestroy(stream, err, sync) { + const r = stream._readableState; + const w = stream._writableState; + if (w !== null && w !== void 0 && w.destroyed || r !== null && r !== void 0 && r.destroyed) { + return this; + } + if (r !== null && r !== void 0 && r.autoDestroy || w !== null && w !== void 0 && w.autoDestroy) + stream.destroy(err); + else if (err) { + err.stack; + if (w && !w.errored) { + w.errored = err; + } + if (r && !r.errored) { + r.errored = err; + } + if (sync) { + process2.nextTick(emitErrorNT, stream, err); + } else { + emitErrorNT(stream, err); + } } - }); - function validateString(value, name) { - if (typeof value !== "string") throw new ERR_INVALID_ARG_TYPE2(name, "string", value); } - function validateNumber(value, name, min = void 0, max) { - if (typeof value !== "number") throw new ERR_INVALID_ARG_TYPE2(name, "number", value); - if (min != null && value < min || max != null && value > max || (min != null || max != null) && NumberIsNaN(value)) { - throw new ERR_OUT_OF_RANGE( - name, - `${min != null ? `>= ${min}` : ""}${min != null && max != null ? " && " : ""}${max != null ? `<= ${max}` : ""}`, - value - ); + function construct(stream, cb) { + if (typeof stream._construct !== "function") { + return; + } + const r = stream._readableState; + const w = stream._writableState; + if (r) { + r.constructed = false; } + if (w) { + w.constructed = false; + } + stream.once(kConstruct, cb); + if (stream.listenerCount(kConstruct) > 1) { + return; + } + process2.nextTick(constructNT, stream); } - var validateOneOf = hideStackFrames((value, name, oneOf) => { - if (!ArrayPrototypeIncludes(oneOf, value)) { - const allowed = ArrayPrototypeJoin( - ArrayPrototypeMap(oneOf, (v) => typeof v === "string" ? `'${v}'` : String2(v)), - ", " - ); - const reason = "must be one of: " + allowed; - throw new ERR_INVALID_ARG_VALUE(name, value, reason); + function constructNT(stream) { + let called = false; + function onConstruct(err) { + if (called) { + errorOrDestroy(stream, err !== null && err !== void 0 ? err : new ERR_MULTIPLE_CALLBACK()); + return; + } + called = true; + const r = stream._readableState; + const w = stream._writableState; + const s = w || r; + if (r) { + r.constructed = true; + } + if (w) { + w.constructed = true; + } + if (s.destroyed) { + stream.emit(kDestroy, err); + } else if (err) { + errorOrDestroy(stream, err, true); + } else { + process2.nextTick(emitConstructNT, stream); + } + } + try { + stream._construct((err) => { + process2.nextTick(onConstruct, err); + }); + } catch (err) { + process2.nextTick(onConstruct, err); } - }); - function validateBoolean(value, name) { - if (typeof value !== "boolean") throw new ERR_INVALID_ARG_TYPE2(name, "boolean", value); } - function getOwnPropertyValueOrDefault(options, key, defaultValue) { - return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key]; + function emitConstructNT(stream) { + stream.emit(kConstruct); } - var validateObject = hideStackFrames((value, name, options = null) => { - const allowArray = getOwnPropertyValueOrDefault(options, "allowArray", false); - const allowFunction = getOwnPropertyValueOrDefault(options, "allowFunction", false); - const nullable = getOwnPropertyValueOrDefault(options, "nullable", false); - if (!nullable && value === null || !allowArray && ArrayIsArray(value) || typeof value !== "object" && (!allowFunction || typeof value !== "function")) { - throw new ERR_INVALID_ARG_TYPE2(name, "Object", value); - } - }); - var validateDictionary = hideStackFrames((value, name) => { - if (value != null && typeof value !== "object" && typeof value !== "function") { - throw new ERR_INVALID_ARG_TYPE2(name, "a dictionary", value); + function isRequest(stream) { + return (stream === null || stream === void 0 ? void 0 : stream.setHeader) && typeof stream.abort === "function"; + } + function emitCloseLegacy(stream) { + stream.emit("close"); + } + function emitErrorCloseLegacy(stream, err) { + stream.emit("error", err); + process2.nextTick(emitCloseLegacy, stream); + } + function destroyer(stream, err) { + if (!stream || isDestroyed(stream)) { + return; } - }); - var validateArray = hideStackFrames((value, name, minLength = 0) => { - if (!ArrayIsArray(value)) { - throw new ERR_INVALID_ARG_TYPE2(name, "Array", value); + if (!err && !isFinished(stream)) { + err = new AbortError(); } - if (value.length < minLength) { - const reason = `must be longer than ${minLength}`; - throw new ERR_INVALID_ARG_VALUE(name, value, reason); + if (isServerRequest(stream)) { + stream.socket = null; + stream.destroy(err); + } else if (isRequest(stream)) { + stream.abort(); + } else if (isRequest(stream.req)) { + stream.req.abort(); + } else if (typeof stream.destroy === "function") { + stream.destroy(err); + } else if (typeof stream.close === "function") { + stream.close(); + } else if (err) { + process2.nextTick(emitErrorCloseLegacy, stream, err); + } else { + process2.nextTick(emitCloseLegacy, stream); } - }); - function validateStringArray(value, name) { - validateArray(value, name); - for (let i = 0; i < value.length; i++) { - validateString(value[i], `${name}[${i}]`); + if (!stream.destroyed) { + stream[kIsDestroyed] = true; } } - function validateBooleanArray(value, name) { - validateArray(value, name); - for (let i = 0; i < value.length; i++) { - validateBoolean(value[i], `${name}[${i}]`); - } + module2.exports = { + construct, + destroyer, + destroy, + undestroy, + errorOrDestroy + }; + } +}); + +// node_modules/readable-stream/lib/internal/streams/legacy.js +var require_legacy = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/legacy.js"(exports2, module2) { + "use strict"; + var { ArrayIsArray, ObjectSetPrototypeOf } = require_primordials(); + var { EventEmitter: EE } = require("events"); + function Stream(opts) { + EE.call(this, opts); } - function validateAbortSignalArray(value, name) { - validateArray(value, name); - for (let i = 0; i < value.length; i++) { - const signal = value[i]; - const indexedName = `${name}[${i}]`; - if (signal == null) { - throw new ERR_INVALID_ARG_TYPE2(indexedName, "AbortSignal", signal); + ObjectSetPrototypeOf(Stream.prototype, EE.prototype); + ObjectSetPrototypeOf(Stream, EE); + Stream.prototype.pipe = function(dest, options) { + const source = this; + function ondata(chunk) { + if (dest.writable && dest.write(chunk) === false && source.pause) { + source.pause(); } - validateAbortSignal(signal, indexedName); } - } - function validateSignalName(signal, name = "signal") { - validateString(signal, name); - if (signals[signal] === void 0) { - if (signals[StringPrototypeToUpperCase(signal)] !== void 0) { - throw new ERR_UNKNOWN_SIGNAL(signal + " (signals must use all capital letters)"); + source.on("data", ondata); + function ondrain() { + if (source.readable && source.resume) { + source.resume(); } - throw new ERR_UNKNOWN_SIGNAL(signal); - } - } - var validateBuffer = hideStackFrames((buffer, name = "buffer") => { - if (!isArrayBufferView(buffer)) { - throw new ERR_INVALID_ARG_TYPE2(name, ["Buffer", "TypedArray", "DataView"], buffer); - } - }); - function validateEncoding(data, encoding) { - const normalizedEncoding = normalizeEncoding(encoding); - const length = data.length; - if (normalizedEncoding === "hex" && length % 2 !== 0) { - throw new ERR_INVALID_ARG_VALUE("encoding", encoding, `is invalid for data of length ${length}`); - } - } - function validatePort(port, name = "Port", allowZero = true) { - if (typeof port !== "number" && typeof port !== "string" || typeof port === "string" && StringPrototypeTrim(port).length === 0 || +port !== +port >>> 0 || port > 65535 || port === 0 && !allowZero) { - throw new ERR_SOCKET_BAD_PORT(name, port, allowZero); } - return port | 0; - } - var validateAbortSignal = hideStackFrames((signal, name) => { - if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) { - throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal); + dest.on("drain", ondrain); + if (!dest._isStdio && (!options || options.end !== false)) { + source.on("end", onend); + source.on("close", onclose); } - }); - var validateFunction = hideStackFrames((value, name) => { - if (typeof value !== "function") throw new ERR_INVALID_ARG_TYPE2(name, "Function", value); - }); - var validatePlainFunction = hideStackFrames((value, name) => { - if (typeof value !== "function" || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE2(name, "Function", value); - }); - var validateUndefined = hideStackFrames((value, name) => { - if (value !== void 0) throw new ERR_INVALID_ARG_TYPE2(name, "undefined", value); - }); - function validateUnion(value, name, union) { - if (!ArrayPrototypeIncludes(union, value)) { - throw new ERR_INVALID_ARG_TYPE2(name, `('${ArrayPrototypeJoin(union, "|")}')`, value); + let didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + dest.end(); } - } - var linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/; - function validateLinkHeaderFormat(value, name) { - if (typeof value === "undefined" || !RegExpPrototypeExec(linkValueRegExp, value)) { - throw new ERR_INVALID_ARG_VALUE( - name, - value, - 'must be an array or string of format "; rel=preload; as=style"' - ); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + if (typeof dest.destroy === "function") dest.destroy(); } - } - function validateLinkHeaderValue(hints) { - if (typeof hints === "string") { - validateLinkHeaderFormat(hints, "hints"); - return hints; - } else if (ArrayIsArray(hints)) { - const hintsLength = hints.length; - let result = ""; - if (hintsLength === 0) { - return result; - } - for (let i = 0; i < hintsLength; i++) { - const link = hints[i]; - validateLinkHeaderFormat(link, "hints"); - result += link; - if (i !== hintsLength - 1) { - result += ", "; - } + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, "error") === 0) { + this.emit("error", er); } - return result; } - throw new ERR_INVALID_ARG_VALUE( - "hints", - hints, - 'must be an array or string of format "; rel=preload; as=style"' - ); + prependListener(source, "error", onerror); + prependListener(dest, "error", onerror); + function cleanup() { + source.removeListener("data", ondata); + dest.removeListener("drain", ondrain); + source.removeListener("end", onend); + source.removeListener("close", onclose); + source.removeListener("error", onerror); + dest.removeListener("error", onerror); + source.removeListener("end", cleanup); + source.removeListener("close", cleanup); + dest.removeListener("close", cleanup); + } + source.on("end", cleanup); + source.on("close", cleanup); + dest.on("close", cleanup); + dest.emit("pipe", source); + return dest; + }; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); + else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; } module2.exports = { - isInt32, - isUint32, - parseFileMode, - validateArray, - validateStringArray, - validateBooleanArray, - validateAbortSignalArray, - validateBoolean, - validateBuffer, - validateDictionary, - validateEncoding, - validateFunction, - validateInt32, - validateInteger, - validateNumber, - validateObject, - validateOneOf, - validatePlainFunction, - validatePort, - validateSignalName, - validateString, - validateUint32, - validateUndefined, - validateUnion, - validateAbortSignal, - validateLinkHeaderValue + Stream, + prependListener }; } }); -// node_modules/process/index.js -var require_process = __commonJS({ - "node_modules/process/index.js"(exports2, module2) { - module2.exports = global.process; +// node_modules/readable-stream/lib/internal/streams/add-abort-signal.js +var require_add_abort_signal = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/add-abort-signal.js"(exports2, module2) { + "use strict"; + var { SymbolDispose } = require_primordials(); + var { AbortError, codes } = require_errors3(); + var { isNodeStream, isWebStream, kControllerErrorFunction } = require_utils6(); + var eos = require_end_of_stream(); + var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2 } = codes; + var addAbortListener; + var validateAbortSignal = (signal, name) => { + if (typeof signal !== "object" || !("aborted" in signal)) { + throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal); + } + }; + module2.exports.addAbortSignal = function addAbortSignal(signal, stream) { + validateAbortSignal(signal, "signal"); + if (!isNodeStream(stream) && !isWebStream(stream)) { + throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream); + } + return module2.exports.addAbortSignalNoValidate(signal, stream); + }; + module2.exports.addAbortSignalNoValidate = function(signal, stream) { + if (typeof signal !== "object" || !("aborted" in signal)) { + return stream; + } + const onAbort = isNodeStream(stream) ? () => { + stream.destroy( + new AbortError(void 0, { + cause: signal.reason + }) + ); + } : () => { + stream[kControllerErrorFunction]( + new AbortError(void 0, { + cause: signal.reason + }) + ); + }; + if (signal.aborted) { + onAbort(); + } else { + addAbortListener = addAbortListener || require_util12().addAbortListener; + const disposable = addAbortListener(signal, onAbort); + eos(stream, disposable[SymbolDispose]); + } + return stream; + }; } }); -// node_modules/readable-stream/lib/internal/streams/utils.js -var require_utils6 = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/utils.js"(exports2, module2) { +// node_modules/readable-stream/lib/internal/streams/buffer_list.js +var require_buffer_list = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { "use strict"; - var { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require_primordials(); - var kIsDestroyed = SymbolFor("nodejs.stream.destroyed"); - var kIsErrored = SymbolFor("nodejs.stream.errored"); - var kIsReadable = SymbolFor("nodejs.stream.readable"); - var kIsWritable = SymbolFor("nodejs.stream.writable"); - var kIsDisturbed = SymbolFor("nodejs.stream.disturbed"); - var kIsClosedPromise = SymbolFor("nodejs.webstream.isClosedPromise"); - var kControllerErrorFunction = SymbolFor("nodejs.webstream.controllerErrorFunction"); - function isReadableNodeStream(obj, strict = false) { - var _obj$_readableState; - return !!(obj && typeof obj.pipe === "function" && typeof obj.on === "function" && (!strict || typeof obj.pause === "function" && typeof obj.resume === "function") && (!obj._writableState || ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === void 0 ? void 0 : _obj$_readableState.readable) !== false) && // Duplex - (!obj._writableState || obj._readableState)); - } - function isWritableNodeStream(obj) { - var _obj$_writableState; - return !!(obj && typeof obj.write === "function" && typeof obj.on === "function" && (!obj._readableState || ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === void 0 ? void 0 : _obj$_writableState.writable) !== false)); - } - function isDuplexNodeStream(obj) { - return !!(obj && typeof obj.pipe === "function" && obj._readableState && typeof obj.on === "function" && typeof obj.write === "function"); - } - function isNodeStream(obj) { - return obj && (obj._readableState || obj._writableState || typeof obj.write === "function" && typeof obj.on === "function" || typeof obj.pipe === "function" && typeof obj.on === "function"); - } - function isReadableStream(obj) { - return !!(obj && !isNodeStream(obj) && typeof obj.pipeThrough === "function" && typeof obj.getReader === "function" && typeof obj.cancel === "function"); - } - function isWritableStream(obj) { - return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === "function" && typeof obj.abort === "function"); - } - function isTransformStream(obj) { - return !!(obj && !isNodeStream(obj) && typeof obj.readable === "object" && typeof obj.writable === "object"); - } - function isWebStream(obj) { - return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj); - } - function isIterable(obj, isAsync) { - if (obj == null) return false; - if (isAsync === true) return typeof obj[SymbolAsyncIterator] === "function"; - if (isAsync === false) return typeof obj[SymbolIterator] === "function"; - return typeof obj[SymbolAsyncIterator] === "function" || typeof obj[SymbolIterator] === "function"; - } - function isDestroyed(stream) { - if (!isNodeStream(stream)) return null; - const wState = stream._writableState; - const rState = stream._readableState; - const state = wState || rState; - return !!(stream.destroyed || stream[kIsDestroyed] || state !== null && state !== void 0 && state.destroyed); - } - function isWritableEnded(stream) { - if (!isWritableNodeStream(stream)) return null; - if (stream.writableEnded === true) return true; - const wState = stream._writableState; - if (wState !== null && wState !== void 0 && wState.errored) return false; - if (typeof (wState === null || wState === void 0 ? void 0 : wState.ended) !== "boolean") return null; - return wState.ended; - } - function isWritableFinished(stream, strict) { - if (!isWritableNodeStream(stream)) return null; - if (stream.writableFinished === true) return true; - const wState = stream._writableState; - if (wState !== null && wState !== void 0 && wState.errored) return false; - if (typeof (wState === null || wState === void 0 ? void 0 : wState.finished) !== "boolean") return null; - return !!(wState.finished || strict === false && wState.ended === true && wState.length === 0); - } - function isReadableEnded(stream) { - if (!isReadableNodeStream(stream)) return null; - if (stream.readableEnded === true) return true; - const rState = stream._readableState; - if (!rState || rState.errored) return false; - if (typeof (rState === null || rState === void 0 ? void 0 : rState.ended) !== "boolean") return null; - return rState.ended; - } - function isReadableFinished(stream, strict) { - if (!isReadableNodeStream(stream)) return null; - const rState = stream._readableState; - if (rState !== null && rState !== void 0 && rState.errored) return false; - if (typeof (rState === null || rState === void 0 ? void 0 : rState.endEmitted) !== "boolean") return null; - return !!(rState.endEmitted || strict === false && rState.ended === true && rState.length === 0); - } - function isReadable(stream) { - if (stream && stream[kIsReadable] != null) return stream[kIsReadable]; - if (typeof (stream === null || stream === void 0 ? void 0 : stream.readable) !== "boolean") return null; - if (isDestroyed(stream)) return false; - return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream); - } - function isWritable(stream) { - if (stream && stream[kIsWritable] != null) return stream[kIsWritable]; - if (typeof (stream === null || stream === void 0 ? void 0 : stream.writable) !== "boolean") return null; - if (isDestroyed(stream)) return false; - return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream); - } - function isFinished(stream, opts) { - if (!isNodeStream(stream)) { - return null; + var { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array: Uint8Array2 } = require_primordials(); + var { Buffer: Buffer2 } = require("buffer"); + var { inspect } = require_util12(); + module2.exports = class BufferList { + constructor() { + this.head = null; + this.tail = null; + this.length = 0; } - if (isDestroyed(stream)) { - return true; + push(v) { + const entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + } + unshift(v) { + const entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + shift() { + if (this.length === 0) return; + const ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + } + clear() { + this.head = this.tail = null; + this.length = 0; + } + join(s) { + if (this.length === 0) return ""; + let p = this.head; + let ret = "" + p.data; + while ((p = p.next) !== null) ret += s + p.data; + return ret; + } + concat(n) { + if (this.length === 0) return Buffer2.alloc(0); + const ret = Buffer2.allocUnsafe(n >>> 0); + let p = this.head; + let i = 0; + while (p) { + TypedArrayPrototypeSet(ret, p.data, i); + i += p.data.length; + p = p.next; + } + return ret; + } + // Consumes a specified amount of bytes or characters from the buffered data. + consume(n, hasStrings) { + const data = this.head.data; + if (n < data.length) { + const slice = data.slice(0, n); + this.head.data = data.slice(n); + return slice; + } + if (n === data.length) { + return this.shift(); + } + return hasStrings ? this._getString(n) : this._getBuffer(n); + } + first() { + return this.head.data; + } + *[SymbolIterator]() { + for (let p = this.head; p; p = p.next) { + yield p.data; + } + } + // Consumes a specified amount of characters from the buffered data. + _getString(n) { + let ret = ""; + let p = this.head; + let c = 0; + do { + const str2 = p.data; + if (n > str2.length) { + ret += str2; + n -= str2.length; + } else { + if (n === str2.length) { + ret += str2; + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + ret += StringPrototypeSlice(str2, 0, n); + this.head = p; + p.data = StringPrototypeSlice(str2, n); + } + break; + } + ++c; + } while ((p = p.next) !== null); + this.length -= c; + return ret; } - if ((opts === null || opts === void 0 ? void 0 : opts.readable) !== false && isReadable(stream)) { - return false; + // Consumes a specified amount of bytes from the buffered data. + _getBuffer(n) { + const ret = Buffer2.allocUnsafe(n); + const retLen = n; + let p = this.head; + let c = 0; + do { + const buf = p.data; + if (n > buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n); + n -= buf.length; + } else { + if (n === buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n); + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + TypedArrayPrototypeSet(ret, new Uint8Array2(buf.buffer, buf.byteOffset, n), retLen - n); + this.head = p; + p.data = buf.slice(n); + } + break; + } + ++c; + } while ((p = p.next) !== null); + this.length -= c; + return ret; } - if ((opts === null || opts === void 0 ? void 0 : opts.writable) !== false && isWritable(stream)) { - return false; + // Make sure the linked list only shows the minimal necessary information. + [Symbol.for("nodejs.util.inspect.custom")](_2, options) { + return inspect(this, { + ...options, + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + }); } - return true; + }; + } +}); + +// node_modules/readable-stream/lib/internal/streams/state.js +var require_state3 = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { + "use strict"; + var { MathFloor, NumberIsInteger } = require_primordials(); + var { validateInteger } = require_validators(); + var { ERR_INVALID_ARG_VALUE } = require_errors3().codes; + var defaultHighWaterMarkBytes = 16 * 1024; + var defaultHighWaterMarkObjectMode = 16; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } - function isWritableErrored(stream) { - var _stream$_writableStat, _stream$_writableStat2; - if (!isNodeStream(stream)) { - return null; - } - if (stream.writableErrored) { - return stream.writableErrored; - } - return (_stream$_writableStat = (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === void 0 ? void 0 : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== void 0 ? _stream$_writableStat : null; + function getDefaultHighWaterMark(objectMode) { + return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes; } - function isReadableErrored(stream) { - var _stream$_readableStat, _stream$_readableStat2; - if (!isNodeStream(stream)) { - return null; - } - if (stream.readableErrored) { - return stream.readableErrored; + function setDefaultHighWaterMark(objectMode, value) { + validateInteger(value, "value", 0); + if (objectMode) { + defaultHighWaterMarkObjectMode = value; + } else { + defaultHighWaterMarkBytes = value; } - return (_stream$_readableStat = (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === void 0 ? void 0 : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== void 0 ? _stream$_readableStat : null; } - function isClosed(stream) { - if (!isNodeStream(stream)) { - return null; - } - if (typeof stream.closed === "boolean") { - return stream.closed; - } - const wState = stream._writableState; - const rState = stream._readableState; - if (typeof (wState === null || wState === void 0 ? void 0 : wState.closed) === "boolean" || typeof (rState === null || rState === void 0 ? void 0 : rState.closed) === "boolean") { - return (wState === null || wState === void 0 ? void 0 : wState.closed) || (rState === null || rState === void 0 ? void 0 : rState.closed); - } - if (typeof stream._closed === "boolean" && isOutgoingMessage(stream)) { - return stream._closed; + function getHighWaterMark(state, options, duplexKey, isDuplex) { + const hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!NumberIsInteger(hwm) || hwm < 0) { + const name = isDuplex ? `options.${duplexKey}` : "options.highWaterMark"; + throw new ERR_INVALID_ARG_VALUE(name, hwm); + } + return MathFloor(hwm); } - return null; - } - function isOutgoingMessage(stream) { - return typeof stream._closed === "boolean" && typeof stream._defaultKeepAlive === "boolean" && typeof stream._removedConnection === "boolean" && typeof stream._removedContLen === "boolean"; - } - function isServerResponse(stream) { - return typeof stream._sent100 === "boolean" && isOutgoingMessage(stream); - } - function isServerRequest(stream) { - var _stream$req; - return typeof stream._consuming === "boolean" && typeof stream._dumped === "boolean" && ((_stream$req = stream.req) === null || _stream$req === void 0 ? void 0 : _stream$req.upgradeOrConnect) === void 0; - } - function willEmitClose(stream) { - if (!isNodeStream(stream)) return null; - const wState = stream._writableState; - const rState = stream._readableState; - const state = wState || rState; - return !state && isServerResponse(stream) || !!(state && state.autoDestroy && state.emitClose && state.closed === false); - } - function isDisturbed(stream) { - var _stream$kIsDisturbed; - return !!(stream && ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== void 0 ? _stream$kIsDisturbed : stream.readableDidRead || stream.readableAborted)); - } - function isErrored(stream) { - var _ref, _ref2, _ref3, _ref4, _ref5, _stream$kIsErrored, _stream$_readableStat3, _stream$_writableStat3, _stream$_readableStat4, _stream$_writableStat4; - return !!(stream && ((_ref = (_ref2 = (_ref3 = (_ref4 = (_ref5 = (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== void 0 ? _stream$kIsErrored : stream.readableErrored) !== null && _ref5 !== void 0 ? _ref5 : stream.writableErrored) !== null && _ref4 !== void 0 ? _ref4 : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === void 0 ? void 0 : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== void 0 ? _ref3 : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === void 0 ? void 0 : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== void 0 ? _ref2 : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === void 0 ? void 0 : _stream$_readableStat4.errored) !== null && _ref !== void 0 ? _ref : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === void 0 ? void 0 : _stream$_writableStat4.errored)); + return getDefaultHighWaterMark(state.objectMode); } module2.exports = { - isDestroyed, - kIsDestroyed, - isDisturbed, - kIsDisturbed, - isErrored, - kIsErrored, - isReadable, - kIsReadable, - kIsClosedPromise, - kControllerErrorFunction, - kIsWritable, - isClosed, - isDuplexNodeStream, - isFinished, - isIterable, - isReadableNodeStream, - isReadableStream, - isReadableEnded, - isReadableFinished, - isReadableErrored, - isNodeStream, - isWebStream, - isWritable, - isWritableNodeStream, - isWritableStream, - isWritableEnded, - isWritableFinished, - isWritableErrored, - isServerRequest, - isServerResponse, - willEmitClose, - isTransformStream + getHighWaterMark, + getDefaultHighWaterMark, + setDefaultHighWaterMark }; } }); -// node_modules/readable-stream/lib/internal/streams/end-of-stream.js -var require_end_of_stream = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { +// node_modules/readable-stream/lib/internal/streams/from.js +var require_from = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/from.js"(exports2, module2) { + "use strict"; var process2 = require_process(); - var { AbortError, codes } = require_errors3(); - var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_PREMATURE_CLOSE } = codes; - var { kEmptyObject, once } = require_util12(); - var { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require_validators(); - var { Promise: Promise2, PromisePrototypeThen, SymbolDispose } = require_primordials(); - var { - isClosed, - isReadable, - isReadableNodeStream, - isReadableStream, - isReadableFinished, - isReadableErrored, - isWritable, - isWritableNodeStream, - isWritableStream, - isWritableFinished, - isWritableErrored, - isNodeStream, - willEmitClose: _willEmitClose, - kIsClosedPromise - } = require_utils6(); - var addAbortListener; - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === "function"; - } - var nop = () => { - }; - function eos(stream, options, callback) { - var _options$readable, _options$writable; - if (arguments.length === 2) { - callback = options; - options = kEmptyObject; - } else if (options == null) { - options = kEmptyObject; - } else { - validateObject(options, "options"); - } - validateFunction(callback, "callback"); - validateAbortSignal(options.signal, "options.signal"); - callback = once(callback); - if (isReadableStream(stream) || isWritableStream(stream)) { - return eosWeb(stream, options, callback); + var { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require_primordials(); + var { Buffer: Buffer2 } = require("buffer"); + var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_NULL_VALUES } = require_errors3().codes; + function from(Readable, iterable, opts) { + let iterator; + if (typeof iterable === "string" || iterable instanceof Buffer2) { + return new Readable({ + objectMode: true, + ...opts, + read() { + this.push(iterable); + this.push(null); + } + }); } - if (!isNodeStream(stream)) { - throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream); + let isAsync; + if (iterable && iterable[SymbolAsyncIterator]) { + isAsync = true; + iterator = iterable[SymbolAsyncIterator](); + } else if (iterable && iterable[SymbolIterator]) { + isAsync = false; + iterator = iterable[SymbolIterator](); + } else { + throw new ERR_INVALID_ARG_TYPE2("iterable", ["Iterable"], iterable); } - const readable = (_options$readable = options.readable) !== null && _options$readable !== void 0 ? _options$readable : isReadableNodeStream(stream); - const writable = (_options$writable = options.writable) !== null && _options$writable !== void 0 ? _options$writable : isWritableNodeStream(stream); - const wState = stream._writableState; - const rState = stream._readableState; - const onlegacyfinish = () => { - if (!stream.writable) { - onfinish(); - } - }; - let willEmitClose = _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable; - let writableFinished = isWritableFinished(stream, false); - const onfinish = () => { - writableFinished = true; - if (stream.destroyed) { - willEmitClose = false; - } - if (willEmitClose && (!stream.readable || readable)) { - return; - } - if (!readable || readableFinished) { - callback.call(stream); - } - }; - let readableFinished = isReadableFinished(stream, false); - const onend = () => { - readableFinished = true; - if (stream.destroyed) { - willEmitClose = false; - } - if (willEmitClose && (!stream.writable || writable)) { - return; - } - if (!writable || writableFinished) { - callback.call(stream); - } - }; - const onerror = (err) => { - callback.call(stream, err); - }; - let closed = isClosed(stream); - const onclose = () => { - closed = true; - const errored = isWritableErrored(stream) || isReadableErrored(stream); - if (errored && typeof errored !== "boolean") { - return callback.call(stream, errored); - } - if (readable && !readableFinished && isReadableNodeStream(stream, true)) { - if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()); - } - if (writable && !writableFinished) { - if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()); - } - callback.call(stream); - }; - const onclosed = () => { - closed = true; - const errored = isWritableErrored(stream) || isReadableErrored(stream); - if (errored && typeof errored !== "boolean") { - return callback.call(stream, errored); + const readable = new Readable({ + objectMode: true, + highWaterMark: 1, + // TODO(ronag): What options should be allowed? + ...opts + }); + let reading = false; + readable._read = function() { + if (!reading) { + reading = true; + next(); } - callback.call(stream); }; - const onrequest = () => { - stream.req.on("finish", onfinish); + readable._destroy = function(error4, cb) { + PromisePrototypeThen( + close(error4), + () => process2.nextTick(cb, error4), + // nextTick is here in case cb throws + (e) => process2.nextTick(cb, e || error4) + ); }; - if (isRequest(stream)) { - stream.on("complete", onfinish); - if (!willEmitClose) { - stream.on("abort", onclose); + async function close(error4) { + const hadError = error4 !== void 0 && error4 !== null; + const hasThrow = typeof iterator.throw === "function"; + if (hadError && hasThrow) { + const { value, done } = await iterator.throw(error4); + await value; + if (done) { + return; + } } - if (stream.req) { - onrequest(); - } else { - stream.on("request", onrequest); + if (typeof iterator.return === "function") { + const { value } = await iterator.return(); + await value; } - } else if (writable && !wState) { - stream.on("end", onlegacyfinish); - stream.on("close", onlegacyfinish); - } - if (!willEmitClose && typeof stream.aborted === "boolean") { - stream.on("aborted", onclose); - } - stream.on("end", onend); - stream.on("finish", onfinish); - if (options.error !== false) { - stream.on("error", onerror); } - stream.on("close", onclose); - if (closed) { - process2.nextTick(onclose); - } else if (wState !== null && wState !== void 0 && wState.errorEmitted || rState !== null && rState !== void 0 && rState.errorEmitted) { - if (!willEmitClose) { - process2.nextTick(onclosed); + async function next() { + for (; ; ) { + try { + const { value, done } = isAsync ? await iterator.next() : iterator.next(); + if (done) { + readable.push(null); + } else { + const res = value && typeof value.then === "function" ? await value : value; + if (res === null) { + reading = false; + throw new ERR_STREAM_NULL_VALUES(); + } else if (readable.push(res)) { + continue; + } else { + reading = false; + } + } + } catch (err) { + readable.destroy(err); + } + break; } - } else if (!readable && (!willEmitClose || isReadable(stream)) && (writableFinished || isWritable(stream) === false)) { - process2.nextTick(onclosed); - } else if (!writable && (!willEmitClose || isWritable(stream)) && (readableFinished || isReadable(stream) === false)) { - process2.nextTick(onclosed); - } else if (rState && stream.req && stream.aborted) { - process2.nextTick(onclosed); } - const cleanup = () => { - callback = nop; - stream.removeListener("aborted", onclose); - stream.removeListener("complete", onfinish); - stream.removeListener("abort", onclose); - stream.removeListener("request", onrequest); - if (stream.req) stream.req.removeListener("finish", onfinish); - stream.removeListener("end", onlegacyfinish); - stream.removeListener("close", onlegacyfinish); - stream.removeListener("finish", onfinish); - stream.removeListener("end", onend); - stream.removeListener("error", onerror); - stream.removeListener("close", onclose); - }; - if (options.signal && !closed) { - const abort = () => { - const endCallback = callback; - cleanup(); - endCallback.call( - stream, - new AbortError(void 0, { - cause: options.signal.reason - }) - ); - }; - if (options.signal.aborted) { - process2.nextTick(abort); - } else { - addAbortListener = addAbortListener || require_util12().addAbortListener; - const disposable = addAbortListener(options.signal, abort); - const originalCallback = callback; - callback = once((...args) => { - disposable[SymbolDispose](); - originalCallback.apply(stream, args); - }); + return readable; + } + module2.exports = from; + } +}); + +// node_modules/readable-stream/lib/internal/streams/readable.js +var require_readable3 = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/readable.js"(exports2, module2) { + var process2 = require_process(); + var { + ArrayPrototypeIndexOf, + NumberIsInteger, + NumberIsNaN, + NumberParseInt, + ObjectDefineProperties, + ObjectKeys, + ObjectSetPrototypeOf, + Promise: Promise2, + SafeSet, + SymbolAsyncDispose, + SymbolAsyncIterator, + Symbol: Symbol2 + } = require_primordials(); + module2.exports = Readable; + Readable.ReadableState = ReadableState; + var { EventEmitter: EE } = require("events"); + var { Stream, prependListener } = require_legacy(); + var { Buffer: Buffer2 } = require("buffer"); + var { addAbortSignal } = require_add_abort_signal(); + var eos = require_end_of_stream(); + var debug4 = require_util12().debuglog("stream", (fn) => { + debug4 = fn; + }); + var BufferList = require_buffer_list(); + var destroyImpl = require_destroy2(); + var { getHighWaterMark, getDefaultHighWaterMark } = require_state3(); + var { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_OUT_OF_RANGE, + ERR_STREAM_PUSH_AFTER_EOF, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT + }, + AbortError + } = require_errors3(); + var { validateObject } = require_validators(); + var kPaused = Symbol2("kPaused"); + var { StringDecoder } = require("string_decoder"); + var from = require_from(); + ObjectSetPrototypeOf(Readable.prototype, Stream.prototype); + ObjectSetPrototypeOf(Readable, Stream); + var nop = () => { + }; + var { errorOrDestroy } = destroyImpl; + var kObjectMode = 1 << 0; + var kEnded = 1 << 1; + var kEndEmitted = 1 << 2; + var kReading = 1 << 3; + var kConstructed = 1 << 4; + var kSync = 1 << 5; + var kNeedReadable = 1 << 6; + var kEmittedReadable = 1 << 7; + var kReadableListening = 1 << 8; + var kResumeScheduled = 1 << 9; + var kErrorEmitted = 1 << 10; + var kEmitClose = 1 << 11; + var kAutoDestroy = 1 << 12; + var kDestroyed = 1 << 13; + var kClosed = 1 << 14; + var kCloseEmitted = 1 << 15; + var kMultiAwaitDrain = 1 << 16; + var kReadingMore = 1 << 17; + var kDataEmitted = 1 << 18; + function makeBitMapDescriptor(bit) { + return { + enumerable: false, + get() { + return (this.state & bit) !== 0; + }, + set(value) { + if (value) this.state |= bit; + else this.state &= ~bit; } + }; + } + ObjectDefineProperties(ReadableState.prototype, { + objectMode: makeBitMapDescriptor(kObjectMode), + ended: makeBitMapDescriptor(kEnded), + endEmitted: makeBitMapDescriptor(kEndEmitted), + reading: makeBitMapDescriptor(kReading), + // Stream is still being constructed and cannot be + // destroyed until construction finished or failed. + // Async construction is opt in, therefore we start as + // constructed. + constructed: makeBitMapDescriptor(kConstructed), + // A flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + sync: makeBitMapDescriptor(kSync), + // Whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + needReadable: makeBitMapDescriptor(kNeedReadable), + emittedReadable: makeBitMapDescriptor(kEmittedReadable), + readableListening: makeBitMapDescriptor(kReadableListening), + resumeScheduled: makeBitMapDescriptor(kResumeScheduled), + // True if the error was already emitted and should not be thrown again. + errorEmitted: makeBitMapDescriptor(kErrorEmitted), + emitClose: makeBitMapDescriptor(kEmitClose), + autoDestroy: makeBitMapDescriptor(kAutoDestroy), + // Has it been destroyed. + destroyed: makeBitMapDescriptor(kDestroyed), + // Indicates whether the stream has finished destroying. + closed: makeBitMapDescriptor(kClosed), + // True if close has been emitted or would have been emitted + // depending on emitClose. + closeEmitted: makeBitMapDescriptor(kCloseEmitted), + multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), + // If true, a maybeReadMore has been scheduled. + readingMore: makeBitMapDescriptor(kReadingMore), + dataEmitted: makeBitMapDescriptor(kDataEmitted) + }); + function ReadableState(options, stream, isDuplex) { + if (typeof isDuplex !== "boolean") isDuplex = stream instanceof require_duplex(); + this.state = kEmitClose | kAutoDestroy | kConstructed | kSync; + if (options && options.objectMode) this.state |= kObjectMode; + if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode; + this.highWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = []; + this.flowing = null; + this[kPaused] = null; + if (options && options.emitClose === false) this.state &= ~kEmitClose; + if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy; + this.errored = null; + this.defaultEncoding = options && options.defaultEncoding || "utf8"; + this.awaitDrainWriters = null; + this.decoder = null; + this.encoding = null; + if (options && options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; } - return cleanup; } - function eosWeb(stream, options, callback) { - let isAborted = false; - let abort = nop; - if (options.signal) { - abort = () => { - isAborted = true; - callback.call( - stream, - new AbortError(void 0, { - cause: options.signal.reason - }) - ); - }; - if (options.signal.aborted) { - process2.nextTick(abort); - } else { - addAbortListener = addAbortListener || require_util12().addAbortListener; - const disposable = addAbortListener(options.signal, abort); - const originalCallback = callback; - callback = once((...args) => { - disposable[SymbolDispose](); - originalCallback.apply(stream, args); - }); - } + function Readable(options) { + if (!(this instanceof Readable)) return new Readable(options); + const isDuplex = this instanceof require_duplex(); + this._readableState = new ReadableState(options, this, isDuplex); + if (options) { + if (typeof options.read === "function") this._read = options.read; + if (typeof options.destroy === "function") this._destroy = options.destroy; + if (typeof options.construct === "function") this._construct = options.construct; + if (options.signal && !isDuplex) addAbortSignal(options.signal, this); } - const resolverFn = (...args) => { - if (!isAborted) { - process2.nextTick(() => callback.apply(stream, args)); + Stream.call(this, options); + destroyImpl.construct(this, () => { + if (this._readableState.needReadable) { + maybeReadMore(this, this._readableState); } - }; - PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn); - return nop; + }); } - function finished(stream, opts) { - var _opts; - let autoCleanup = false; - if (opts === null) { - opts = kEmptyObject; - } - if ((_opts = opts) !== null && _opts !== void 0 && _opts.cleanup) { - validateBoolean(opts.cleanup, "cleanup"); - autoCleanup = opts.cleanup; + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable.prototype[EE.captureRejectionSymbol] = function(err) { + this.destroy(err); + }; + Readable.prototype[SymbolAsyncDispose] = function() { + let error4; + if (!this.destroyed) { + error4 = this.readableEnded ? null : new AbortError(); + this.destroy(error4); } - return new Promise2((resolve2, reject) => { - const cleanup = eos(stream, opts, (err) => { - if (autoCleanup) { - cleanup(); + return new Promise2((resolve2, reject) => eos(this, (err) => err && err !== error4 ? reject(err) : resolve2(null))); + }; + Readable.prototype.push = function(chunk, encoding) { + return readableAddChunk(this, chunk, encoding, false); + }; + Readable.prototype.unshift = function(chunk, encoding) { + return readableAddChunk(this, chunk, encoding, true); + }; + function readableAddChunk(stream, chunk, encoding, addToFront) { + debug4("readableAddChunk", chunk); + const state = stream._readableState; + let err; + if ((state.state & kObjectMode) === 0) { + if (typeof chunk === "string") { + encoding = encoding || state.defaultEncoding; + if (state.encoding !== encoding) { + if (addToFront && state.encoding) { + chunk = Buffer2.from(chunk, encoding).toString(state.encoding); + } else { + chunk = Buffer2.from(chunk, encoding); + encoding = ""; + } } - if (err) { - reject(err); + } else if (chunk instanceof Buffer2) { + encoding = ""; + } else if (Stream._isUint8Array(chunk)) { + chunk = Stream._uint8ArrayToBuffer(chunk); + encoding = ""; + } else if (chunk != null) { + err = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + } + if (err) { + errorOrDestroy(stream, err); + } else if (chunk === null) { + state.state &= ~kReading; + onEofChunk(stream, state); + } else if ((state.state & kObjectMode) !== 0 || chunk && chunk.length > 0) { + if (addToFront) { + if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else if (state.destroyed || state.errored) return false; + else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed || state.errored) { + return false; + } else { + state.state &= ~kReading; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false); + else maybeReadMore(stream, state); } else { - resolve2(); + addChunk(stream, state, chunk, false); } - }); - }); - } - module2.exports = eos; - module2.exports.finished = finished; - } -}); - -// node_modules/readable-stream/lib/internal/streams/destroy.js -var require_destroy2 = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module2) { - "use strict"; - var process2 = require_process(); - var { - aggregateTwoErrors, - codes: { ERR_MULTIPLE_CALLBACK }, - AbortError - } = require_errors3(); - var { Symbol: Symbol2 } = require_primordials(); - var { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require_utils6(); - var kDestroy = Symbol2("kDestroy"); - var kConstruct = Symbol2("kConstruct"); - function checkError(err, w, r) { - if (err) { - err.stack; - if (w && !w.errored) { - w.errored = err; - } - if (r && !r.errored) { - r.errored = err; } + } else if (!addToFront) { + state.state &= ~kReading; + maybeReadMore(stream, state); } + return !state.ended && (state.length < state.highWaterMark || state.length === 0); } - function destroy(err, cb) { - const r = this._readableState; - const w = this._writableState; - const s = w || r; - if (w !== null && w !== void 0 && w.destroyed || r !== null && r !== void 0 && r.destroyed) { - if (typeof cb === "function") { - cb(); + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount("data") > 0) { + if ((state.state & kMultiAwaitDrain) !== 0) { + state.awaitDrainWriters.clear(); + } else { + state.awaitDrainWriters = null; } - return this; - } - checkError(err, w, r); - if (w) { - w.destroyed = true; - } - if (r) { - r.destroyed = true; - } - if (!s.constructed) { - this.once(kDestroy, function(er) { - _destroy(this, aggregateTwoErrors(er, err), cb); - }); + state.dataEmitted = true; + stream.emit("data", chunk); } else { - _destroy(this, err, cb); + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk); + else state.buffer.push(chunk); + if ((state.state & kNeedReadable) !== 0) emitReadable(stream); } - return this; + maybeReadMore(stream, state); } - function _destroy(self2, err, cb) { - let called = false; - function onDestroy(err2) { - if (called) { - return; - } - called = true; - const r = self2._readableState; - const w = self2._writableState; - checkError(err2, w, r); - if (w) { - w.closed = true; - } - if (r) { - r.closed = true; - } - if (typeof cb === "function") { - cb(err2); - } - if (err2) { - process2.nextTick(emitErrorCloseNT, self2, err2); - } else { - process2.nextTick(emitCloseNT, self2); - } + Readable.prototype.isPaused = function() { + const state = this._readableState; + return state[kPaused] === true || state.flowing === false; + }; + Readable.prototype.setEncoding = function(enc) { + const decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + this._readableState.encoding = this._readableState.decoder.encoding; + const buffer = this._readableState.buffer; + let content = ""; + for (const data of buffer) { + content += decoder.write(data); } - try { - self2._destroy(err || null, onDestroy); - } catch (err2) { - onDestroy(err2); + buffer.clear(); + if (content !== "") buffer.push(content); + this._readableState.length = content.length; + return this; + }; + var MAX_HWM = 1073741824; + function computeNewHighWaterMark(n) { + if (n > MAX_HWM) { + throw new ERR_OUT_OF_RANGE("size", "<= 1GiB", n); + } else { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } + return n; } - function emitErrorCloseNT(self2, err) { - emitErrorNT(self2, err); - emitCloseNT(self2); - } - function emitCloseNT(self2) { - const r = self2._readableState; - const w = self2._writableState; - if (w) { - w.closeEmitted = true; - } - if (r) { - r.closeEmitted = true; - } - if (w !== null && w !== void 0 && w.emitClose || r !== null && r !== void 0 && r.emitClose) { - self2.emit("close"); + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if ((state.state & kObjectMode) !== 0) return 1; + if (NumberIsNaN(n)) { + if (state.flowing && state.length) return state.buffer.first().length; + return state.length; } + if (n <= state.length) return n; + return state.ended ? state.length : 0; } - function emitErrorNT(self2, err) { - const r = self2._readableState; - const w = self2._writableState; - if (w !== null && w !== void 0 && w.errorEmitted || r !== null && r !== void 0 && r.errorEmitted) { - return; - } - if (w) { - w.errorEmitted = true; - } - if (r) { - r.errorEmitted = true; + Readable.prototype.read = function(n) { + debug4("read", n); + if (n === void 0) { + n = NaN; + } else if (!NumberIsInteger(n)) { + n = NumberParseInt(n, 10); } - self2.emit("error", err); - } - function undestroy() { - const r = this._readableState; - const w = this._writableState; - if (r) { - r.constructed = true; - r.closed = false; - r.closeEmitted = false; - r.destroyed = false; - r.errored = null; - r.errorEmitted = false; - r.reading = false; - r.ended = r.readable === false; - r.endEmitted = r.readable === false; + const state = this._readableState; + const nOrig = n; + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n !== 0) state.state &= ~kEmittedReadable; + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug4("read: emitReadable", state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this); + else emitReadable(this); + return null; } - if (w) { - w.constructed = true; - w.destroyed = false; - w.closed = false; - w.closeEmitted = false; - w.errored = null; - w.errorEmitted = false; - w.finalCalled = false; - w.prefinished = false; - w.ended = w.writable === false; - w.ending = w.writable === false; - w.finished = w.writable === false; + n = howMuchToRead(n, state); + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; } - } - function errorOrDestroy(stream, err, sync) { - const r = stream._readableState; - const w = stream._writableState; - if (w !== null && w !== void 0 && w.destroyed || r !== null && r !== void 0 && r.destroyed) { - return this; + let doRead = (state.state & kNeedReadable) !== 0; + debug4("need readable", doRead); + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug4("length less than watermark", doRead); } - if (r !== null && r !== void 0 && r.autoDestroy || w !== null && w !== void 0 && w.autoDestroy) - stream.destroy(err); - else if (err) { - err.stack; - if (w && !w.errored) { - w.errored = err; - } - if (r && !r.errored) { - r.errored = err; + if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) { + doRead = false; + debug4("reading, ended or constructing", doRead); + } else if (doRead) { + debug4("do read"); + state.state |= kReading | kSync; + if (state.length === 0) state.state |= kNeedReadable; + try { + this._read(state.highWaterMark); + } catch (err) { + errorOrDestroy(this, err); } - if (sync) { - process2.nextTick(emitErrorNT, stream, err); + state.state &= ~kSync; + if (!state.reading) n = howMuchToRead(nOrig, state); + } + let ret; + if (n > 0) ret = fromList(n, state); + else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + if (state.multiAwaitDrain) { + state.awaitDrainWriters.clear(); } else { - emitErrorNT(stream, err); + state.awaitDrainWriters = null; } } - } - function construct(stream, cb) { - if (typeof stream._construct !== "function") { - return; - } - const r = stream._readableState; - const w = stream._writableState; - if (r) { - r.constructed = false; - } - if (w) { - w.constructed = false; + if (state.length === 0) { + if (!state.ended) state.needReadable = true; + if (nOrig !== n && state.ended) endReadable(this); } - stream.once(kConstruct, cb); - if (stream.listenerCount(kConstruct) > 1) { - return; + if (ret !== null && !state.errorEmitted && !state.closeEmitted) { + state.dataEmitted = true; + this.emit("data", ret); } - process2.nextTick(constructNT, stream); - } - function constructNT(stream) { - let called = false; - function onConstruct(err) { - if (called) { - errorOrDestroy(stream, err !== null && err !== void 0 ? err : new ERR_MULTIPLE_CALLBACK()); - return; - } - called = true; - const r = stream._readableState; - const w = stream._writableState; - const s = w || r; - if (r) { - r.constructed = true; - } - if (w) { - w.constructed = true; - } - if (s.destroyed) { - stream.emit(kDestroy, err); - } else if (err) { - errorOrDestroy(stream, err, true); - } else { - process2.nextTick(emitConstructNT, stream); + return ret; + }; + function onEofChunk(stream, state) { + debug4("onEofChunk"); + if (state.ended) return; + if (state.decoder) { + const chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } } - try { - stream._construct((err) => { - process2.nextTick(onConstruct, err); - }); - } catch (err) { - process2.nextTick(onConstruct, err); - } - } - function emitConstructNT(stream) { - stream.emit(kConstruct); - } - function isRequest(stream) { - return (stream === null || stream === void 0 ? void 0 : stream.setHeader) && typeof stream.abort === "function"; - } - function emitCloseLegacy(stream) { - stream.emit("close"); - } - function emitErrorCloseLegacy(stream, err) { - stream.emit("error", err); - process2.nextTick(emitCloseLegacy, stream); + state.ended = true; + if (state.sync) { + emitReadable(stream); + } else { + state.needReadable = false; + state.emittedReadable = true; + emitReadable_(stream); + } } - function destroyer(stream, err) { - if (!stream || isDestroyed(stream)) { - return; + function emitReadable(stream) { + const state = stream._readableState; + debug4("emitReadable", state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug4("emitReadable", state.flowing); + state.emittedReadable = true; + process2.nextTick(emitReadable_, stream); } - if (!err && !isFinished(stream)) { - err = new AbortError(); + } + function emitReadable_(stream) { + const state = stream._readableState; + debug4("emitReadable_", state.destroyed, state.length, state.ended); + if (!state.destroyed && !state.errored && (state.length || state.ended)) { + stream.emit("readable"); + state.emittedReadable = false; } - if (isServerRequest(stream)) { - stream.socket = null; - stream.destroy(err); - } else if (isRequest(stream)) { - stream.abort(); - } else if (isRequest(stream.req)) { - stream.req.abort(); - } else if (typeof stream.destroy === "function") { - stream.destroy(err); - } else if (typeof stream.close === "function") { - stream.close(); - } else if (err) { - process2.nextTick(emitErrorCloseLegacy, stream, err); - } else { - process2.nextTick(emitCloseLegacy, stream); + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); + } + function maybeReadMore(stream, state) { + if (!state.readingMore && state.constructed) { + state.readingMore = true; + process2.nextTick(maybeReadMore_, stream, state); } - if (!stream.destroyed) { - stream[kIsDestroyed] = true; + } + function maybeReadMore_(stream, state) { + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + const len = state.length; + debug4("maybeReadMore read 0"); + stream.read(0); + if (len === state.length) + break; } + state.readingMore = false; } - module2.exports = { - construct, - destroyer, - destroy, - undestroy, - errorOrDestroy + Readable.prototype._read = function(n) { + throw new ERR_METHOD_NOT_IMPLEMENTED("_read()"); }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/legacy.js -var require_legacy = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/legacy.js"(exports2, module2) { - "use strict"; - var { ArrayIsArray, ObjectSetPrototypeOf } = require_primordials(); - var { EventEmitter: EE } = require("events"); - function Stream(opts) { - EE.call(this, opts); - } - ObjectSetPrototypeOf(Stream.prototype, EE.prototype); - ObjectSetPrototypeOf(Stream, EE); - Stream.prototype.pipe = function(dest, options) { - const source = this; - function ondata(chunk) { - if (dest.writable && dest.write(chunk) === false && source.pause) { - source.pause(); + Readable.prototype.pipe = function(dest, pipeOpts) { + const src = this; + const state = this._readableState; + if (state.pipes.length === 1) { + if (!state.multiAwaitDrain) { + state.multiAwaitDrain = true; + state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []); } } - source.on("data", ondata); - function ondrain() { - if (source.readable && source.resume) { - source.resume(); + state.pipes.push(dest); + debug4("pipe count=%d opts=%j", state.pipes.length, pipeOpts); + const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process2.stdout && dest !== process2.stderr; + const endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process2.nextTick(endFn); + else src.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable, unpipeInfo) { + debug4("onunpipe"); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } } - dest.on("drain", ondrain); - if (!dest._isStdio && (!options || options.end !== false)) { - source.on("end", onend); - source.on("close", onclose); - } - let didOnEnd = false; function onend() { - if (didOnEnd) return; - didOnEnd = true; + debug4("onend"); dest.end(); } - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - if (typeof dest.destroy === "function") dest.destroy(); - } - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, "error") === 0) { - this.emit("error", er); - } - } - prependListener(source, "error", onerror); - prependListener(dest, "error", onerror); + let ondrain; + let cleanedUp = false; function cleanup() { - source.removeListener("data", ondata); - dest.removeListener("drain", ondrain); - source.removeListener("end", onend); - source.removeListener("close", onclose); - source.removeListener("error", onerror); + debug4("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + if (ondrain) { + dest.removeListener("drain", ondrain); + } dest.removeListener("error", onerror); - source.removeListener("end", cleanup); - source.removeListener("close", cleanup); - dest.removeListener("close", cleanup); - } - source.on("end", cleanup); - source.on("close", cleanup); - dest.on("close", cleanup); - dest.emit("pipe", source); - return dest; - }; - function prependListener(emitter, event, fn) { - if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); - else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn); - else emitter._events[event] = [fn, emitter._events[event]]; - } - module2.exports = { - Stream, - prependListener - }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/add-abort-signal.js -var require_add_abort_signal = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/add-abort-signal.js"(exports2, module2) { - "use strict"; - var { SymbolDispose } = require_primordials(); - var { AbortError, codes } = require_errors3(); - var { isNodeStream, isWebStream, kControllerErrorFunction } = require_utils6(); - var eos = require_end_of_stream(); - var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2 } = codes; - var addAbortListener; - var validateAbortSignal = (signal, name) => { - if (typeof signal !== "object" || !("aborted" in signal)) { - throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal); - } - }; - module2.exports.addAbortSignal = function addAbortSignal(signal, stream) { - validateAbortSignal(signal, "signal"); - if (!isNodeStream(stream) && !isWebStream(stream)) { - throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream); - } - return module2.exports.addAbortSignalNoValidate(signal, stream); - }; - module2.exports.addAbortSignalNoValidate = function(signal, stream) { - if (typeof signal !== "object" || !("aborted" in signal)) { - return stream; + dest.removeListener("unpipe", onunpipe); + src.removeListener("end", onend); + src.removeListener("end", unpipe); + src.removeListener("data", ondata); + cleanedUp = true; + if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - const onAbort = isNodeStream(stream) ? () => { - stream.destroy( - new AbortError(void 0, { - cause: signal.reason - }) - ); - } : () => { - stream[kControllerErrorFunction]( - new AbortError(void 0, { - cause: signal.reason - }) - ); - }; - if (signal.aborted) { - onAbort(); - } else { - addAbortListener = addAbortListener || require_util12().addAbortListener; - const disposable = addAbortListener(signal, onAbort); - eos(stream, disposable[SymbolDispose]); + function pause() { + if (!cleanedUp) { + if (state.pipes.length === 1 && state.pipes[0] === dest) { + debug4("false write response, pause", 0); + state.awaitDrainWriters = dest; + state.multiAwaitDrain = false; + } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { + debug4("false write response, pause", state.awaitDrainWriters.size); + state.awaitDrainWriters.add(dest); + } + src.pause(); + } + if (!ondrain) { + ondrain = pipeOnDrain(src, dest); + dest.on("drain", ondrain); + } } - return stream; - }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/buffer_list.js -var require_buffer_list = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { - "use strict"; - var { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array: Uint8Array2 } = require_primordials(); - var { Buffer: Buffer2 } = require("buffer"); - var { inspect } = require_util12(); - module2.exports = class BufferList { - constructor() { - this.head = null; - this.tail = null; - this.length = 0; + src.on("data", ondata); + function ondata(chunk) { + debug4("ondata"); + const ret = dest.write(chunk); + debug4("dest.write", ret); + if (ret === false) { + pause(); + } } - push(v) { - const entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry; - else this.head = entry; - this.tail = entry; - ++this.length; + function onerror(er) { + debug4("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (dest.listenerCount("error") === 0) { + const s = dest._writableState || dest._readableState; + if (s && !s.errorEmitted) { + errorOrDestroy(dest, er); + } else { + dest.emit("error", er); + } + } } - unshift(v) { - const entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); } - shift() { - if (this.length === 0) return; - const ret = this.head.data; - if (this.length === 1) this.head = this.tail = null; - else this.head = this.head.next; - --this.length; - return ret; + dest.once("close", onclose); + function onfinish() { + debug4("onfinish"); + dest.removeListener("close", onclose); + unpipe(); } - clear() { - this.head = this.tail = null; - this.length = 0; + dest.once("finish", onfinish); + function unpipe() { + debug4("unpipe"); + src.unpipe(dest); } - join(s) { - if (this.length === 0) return ""; - let p = this.head; - let ret = "" + p.data; - while ((p = p.next) !== null) ret += s + p.data; - return ret; + dest.emit("pipe", src); + if (dest.writableNeedDrain === true) { + pause(); + } else if (!state.flowing) { + debug4("pipe resume"); + src.resume(); } - concat(n) { - if (this.length === 0) return Buffer2.alloc(0); - const ret = Buffer2.allocUnsafe(n >>> 0); - let p = this.head; - let i = 0; - while (p) { - TypedArrayPrototypeSet(ret, p.data, i); - i += p.data.length; - p = p.next; + return dest; + }; + function pipeOnDrain(src, dest) { + return function pipeOnDrainFunctionResult() { + const state = src._readableState; + if (state.awaitDrainWriters === dest) { + debug4("pipeOnDrain", 1); + state.awaitDrainWriters = null; + } else if (state.multiAwaitDrain) { + debug4("pipeOnDrain", state.awaitDrainWriters.size); + state.awaitDrainWriters.delete(dest); } - return ret; - } - // Consumes a specified amount of bytes or characters from the buffered data. - consume(n, hasStrings) { - const data = this.head.data; - if (n < data.length) { - const slice = data.slice(0, n); - this.head.data = data.slice(n); - return slice; + if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount("data")) { + src.resume(); } - if (n === data.length) { - return this.shift(); + }; + } + Readable.prototype.unpipe = function(dest) { + const state = this._readableState; + const unpipeInfo = { + hasUnpiped: false + }; + if (state.pipes.length === 0) return this; + if (!dest) { + const dests = state.pipes; + state.pipes = []; + this.pause(); + for (let i = 0; i < dests.length; i++) + dests[i].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + const index = ArrayPrototypeIndexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + if (state.pipes.length === 0) this.pause(); + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable.prototype.on = function(ev, fn) { + const res = Stream.prototype.on.call(this, ev, fn); + const state = this._readableState; + if (ev === "data") { + state.readableListening = this.listenerCount("readable") > 0; + if (state.flowing !== false) this.resume(); + } else if (ev === "readable") { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug4("on readable", state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process2.nextTick(nReadingNextTick, this); + } } - return hasStrings ? this._getString(n) : this._getBuffer(n); } - first() { - return this.head.data; + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + Readable.prototype.removeListener = function(ev, fn) { + const res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === "readable") { + process2.nextTick(updateReadableListening, this); } - *[SymbolIterator]() { - for (let p = this.head; p; p = p.next) { - yield p.data; - } + return res; + }; + Readable.prototype.off = Readable.prototype.removeListener; + Readable.prototype.removeAllListeners = function(ev) { + const res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + process2.nextTick(updateReadableListening, this); } - // Consumes a specified amount of characters from the buffered data. - _getString(n) { - let ret = ""; - let p = this.head; - let c = 0; - do { - const str2 = p.data; - if (n > str2.length) { - ret += str2; - n -= str2.length; - } else { - if (n === str2.length) { - ret += str2; - ++c; - if (p.next) this.head = p.next; - else this.head = this.tail = null; - } else { - ret += StringPrototypeSlice(str2, 0, n); - this.head = p; - p.data = StringPrototypeSlice(str2, n); - } - break; - } - ++c; - } while ((p = p.next) !== null); - this.length -= c; - return ret; + return res; + }; + function updateReadableListening(self2) { + const state = self2._readableState; + state.readableListening = self2.listenerCount("readable") > 0; + if (state.resumeScheduled && state[kPaused] === false) { + state.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); + } else if (!state.readableListening) { + state.flowing = null; } - // Consumes a specified amount of bytes from the buffered data. - _getBuffer(n) { - const ret = Buffer2.allocUnsafe(n); - const retLen = n; - let p = this.head; - let c = 0; - do { - const buf = p.data; - if (n > buf.length) { - TypedArrayPrototypeSet(ret, buf, retLen - n); - n -= buf.length; - } else { - if (n === buf.length) { - TypedArrayPrototypeSet(ret, buf, retLen - n); - ++c; - if (p.next) this.head = p.next; - else this.head = this.tail = null; - } else { - TypedArrayPrototypeSet(ret, new Uint8Array2(buf.buffer, buf.byteOffset, n), retLen - n); - this.head = p; - p.data = buf.slice(n); - } - break; - } - ++c; - } while ((p = p.next) !== null); - this.length -= c; - return ret; + } + function nReadingNextTick(self2) { + debug4("readable nexttick read 0"); + self2.read(0); + } + Readable.prototype.resume = function() { + const state = this._readableState; + if (!state.flowing) { + debug4("resume"); + state.flowing = !state.readableListening; + resume(this, state); } - // Make sure the linked list only shows the minimal necessary information. - [Symbol.for("nodejs.util.inspect.custom")](_2, options) { - return inspect(this, { - ...options, - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - }); + state[kPaused] = false; + return this; + }; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process2.nextTick(resume_, stream, state); } - }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/state.js -var require_state3 = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { - "use strict"; - var { MathFloor, NumberIsInteger } = require_primordials(); - var { validateInteger } = require_validators(); - var { ERR_INVALID_ARG_VALUE } = require_errors3().codes; - var defaultHighWaterMarkBytes = 16 * 1024; - var defaultHighWaterMarkObjectMode = 16; - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } - function getDefaultHighWaterMark(objectMode) { - return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes; + function resume_(stream, state) { + debug4("resume", state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit("resume"); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); } - function setDefaultHighWaterMark(objectMode, value) { - validateInteger(value, "value", 0); - if (objectMode) { - defaultHighWaterMarkObjectMode = value; - } else { - defaultHighWaterMarkBytes = value; + Readable.prototype.pause = function() { + debug4("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug4("pause"); + this._readableState.flowing = false; + this.emit("pause"); } + this._readableState[kPaused] = true; + return this; + }; + function flow(stream) { + const state = stream._readableState; + debug4("flow", state.flowing); + while (state.flowing && stream.read() !== null) ; } - function getHighWaterMark(state, options, duplexKey, isDuplex) { - const hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - if (hwm != null) { - if (!NumberIsInteger(hwm) || hwm < 0) { - const name = isDuplex ? `options.${duplexKey}` : "options.highWaterMark"; - throw new ERR_INVALID_ARG_VALUE(name, hwm); + Readable.prototype.wrap = function(stream) { + let paused = false; + stream.on("data", (chunk) => { + if (!this.push(chunk) && stream.pause) { + paused = true; + stream.pause(); + } + }); + stream.on("end", () => { + this.push(null); + }); + stream.on("error", (err) => { + errorOrDestroy(this, err); + }); + stream.on("close", () => { + this.destroy(); + }); + stream.on("destroy", () => { + this.destroy(); + }); + this._read = () => { + if (paused && stream.resume) { + paused = false; + stream.resume(); + } + }; + const streamKeys = ObjectKeys(stream); + for (let j = 1; j < streamKeys.length; j++) { + const i = streamKeys[j]; + if (this[i] === void 0 && typeof stream[i] === "function") { + this[i] = stream[i].bind(stream); } - return MathFloor(hwm); } - return getDefaultHighWaterMark(state.objectMode); - } - module2.exports = { - getHighWaterMark, - getDefaultHighWaterMark, - setDefaultHighWaterMark + return this; }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/from.js -var require_from = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/from.js"(exports2, module2) { - "use strict"; - var process2 = require_process(); - var { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require_primordials(); - var { Buffer: Buffer2 } = require("buffer"); - var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_NULL_VALUES } = require_errors3().codes; - function from(Readable, iterable, opts) { - let iterator; - if (typeof iterable === "string" || iterable instanceof Buffer2) { - return new Readable({ - objectMode: true, - ...opts, - read() { - this.push(iterable); - this.push(null); - } + Readable.prototype[SymbolAsyncIterator] = function() { + return streamToAsyncIterator(this); + }; + Readable.prototype.iterator = function(options) { + if (options !== void 0) { + validateObject(options, "options"); + } + return streamToAsyncIterator(this, options); + }; + function streamToAsyncIterator(stream, options) { + if (typeof stream.read !== "function") { + stream = Readable.wrap(stream, { + objectMode: true }); } - let isAsync; - if (iterable && iterable[SymbolAsyncIterator]) { - isAsync = true; - iterator = iterable[SymbolAsyncIterator](); - } else if (iterable && iterable[SymbolIterator]) { - isAsync = false; - iterator = iterable[SymbolIterator](); - } else { - throw new ERR_INVALID_ARG_TYPE2("iterable", ["Iterable"], iterable); + const iter = createAsyncIterator(stream, options); + iter.stream = stream; + return iter; + } + async function* createAsyncIterator(stream, options) { + let callback = nop; + function next(resolve2) { + if (this === stream) { + callback(); + callback = nop; + } else { + callback = resolve2; + } } - const readable = new Readable({ - objectMode: true, - highWaterMark: 1, - // TODO(ronag): What options should be allowed? - ...opts - }); - let reading = false; - readable._read = function() { - if (!reading) { - reading = true; - next(); + stream.on("readable", next); + let error4; + const cleanup = eos( + stream, + { + writable: false + }, + (err) => { + error4 = err ? aggregateTwoErrors(error4, err) : null; + callback(); + callback = nop; } - }; - readable._destroy = function(error4, cb) { - PromisePrototypeThen( - close(error4), - () => process2.nextTick(cb, error4), - // nextTick is here in case cb throws - (e) => process2.nextTick(cb, e || error4) - ); - }; - async function close(error4) { - const hadError = error4 !== void 0 && error4 !== null; - const hasThrow = typeof iterator.throw === "function"; - if (hadError && hasThrow) { - const { value, done } = await iterator.throw(error4); - await value; - if (done) { + ); + try { + while (true) { + const chunk = stream.destroyed ? null : stream.read(); + if (chunk !== null) { + yield chunk; + } else if (error4) { + throw error4; + } else if (error4 === null) { return; + } else { + await new Promise2(next); } } - if (typeof iterator.return === "function") { - const { value } = await iterator.return(); - await value; + } catch (err) { + error4 = aggregateTwoErrors(error4, err); + throw error4; + } finally { + if ((error4 || (options === null || options === void 0 ? void 0 : options.destroyOnReturn) !== false) && (error4 === void 0 || stream._readableState.autoDestroy)) { + destroyImpl.destroyer(stream, null); + } else { + stream.off("readable", next); + cleanup(); } } - async function next() { - for (; ; ) { - try { - const { value, done } = isAsync ? await iterator.next() : iterator.next(); - if (done) { - readable.push(null); - } else { - const res = value && typeof value.then === "function" ? await value : value; - if (res === null) { - reading = false; - throw new ERR_STREAM_NULL_VALUES(); - } else if (readable.push(res)) { - continue; - } else { - reading = false; - } - } - } catch (err) { - readable.destroy(err); + } + ObjectDefineProperties(Readable.prototype, { + readable: { + __proto__: null, + get() { + const r = this._readableState; + return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted; + }, + set(val2) { + if (this._readableState) { + this._readableState.readable = !!val2; } - break; + } + }, + readableDidRead: { + __proto__: null, + enumerable: false, + get: function() { + return this._readableState.dataEmitted; + } + }, + readableAborted: { + __proto__: null, + enumerable: false, + get: function() { + return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted); + } + }, + readableHighWaterMark: { + __proto__: null, + enumerable: false, + get: function() { + return this._readableState.highWaterMark; + } + }, + readableBuffer: { + __proto__: null, + enumerable: false, + get: function() { + return this._readableState && this._readableState.buffer; + } + }, + readableFlowing: { + __proto__: null, + enumerable: false, + get: function() { + return this._readableState.flowing; + }, + set: function(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }, + readableLength: { + __proto__: null, + enumerable: false, + get() { + return this._readableState.length; + } + }, + readableObjectMode: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.objectMode : false; + } + }, + readableEncoding: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.encoding : null; + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.errored : null; + } + }, + closed: { + __proto__: null, + get() { + return this._readableState ? this._readableState.closed : false; + } + }, + destroyed: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.destroyed : false; + }, + set(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }, + readableEnded: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.endEmitted : false; } } - return readable; + }); + ObjectDefineProperties(ReadableState.prototype, { + // Legacy getter for `pipesCount`. + pipesCount: { + __proto__: null, + get() { + return this.pipes.length; + } + }, + // Legacy property for `paused`. + paused: { + __proto__: null, + get() { + return this[kPaused] !== false; + }, + set(value) { + this[kPaused] = !!value; + } + } + }); + Readable._fromList = fromList; + function fromList(n, state) { + if (state.length === 0) return null; + let ret; + if (state.objectMode) ret = state.buffer.shift(); + else if (!n || n >= state.length) { + if (state.decoder) ret = state.buffer.join(""); + else if (state.buffer.length === 1) ret = state.buffer.first(); + else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + ret = state.buffer.consume(n, state.decoder); + } + return ret; } - module2.exports = from; + function endReadable(stream) { + const state = stream._readableState; + debug4("endReadable", state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process2.nextTick(endReadableNT, state, stream); + } + } + function endReadableNT(state, stream) { + debug4("endReadableNT", state.endEmitted, state.length); + if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.emit("end"); + if (stream.writable && stream.allowHalfOpen === false) { + process2.nextTick(endWritableNT, stream); + } else if (state.autoDestroy) { + const wState = stream._writableState; + const autoDestroy = !wState || wState.autoDestroy && // We don't expect the writable to ever 'finish' + // if writable is explicitly set to false. + (wState.finished || wState.writable === false); + if (autoDestroy) { + stream.destroy(); + } + } + } + } + function endWritableNT(stream) { + const writable = stream.writable && !stream.writableEnded && !stream.destroyed; + if (writable) { + stream.end(); + } + } + Readable.from = function(iterable, opts) { + return from(Readable, iterable, opts); + }; + var webStreamsAdapters; + function lazyWebStreams() { + if (webStreamsAdapters === void 0) webStreamsAdapters = {}; + return webStreamsAdapters; + } + Readable.fromWeb = function(readableStream, options) { + return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options); + }; + Readable.toWeb = function(streamReadable, options) { + return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options); + }; + Readable.wrap = function(src, options) { + var _ref, _src$readableObjectMo; + return new Readable({ + objectMode: (_ref = (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== void 0 ? _src$readableObjectMo : src.objectMode) !== null && _ref !== void 0 ? _ref : true, + ...options, + destroy(err, callback) { + destroyImpl.destroyer(src, err); + callback(err); + } + }).wrap(src); + }; } }); -// node_modules/readable-stream/lib/internal/streams/readable.js -var require_readable3 = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/readable.js"(exports2, module2) { +// node_modules/readable-stream/lib/internal/streams/writable.js +var require_writable = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/writable.js"(exports2, module2) { var process2 = require_process(); var { - ArrayPrototypeIndexOf, - NumberIsInteger, - NumberIsNaN, - NumberParseInt, + ArrayPrototypeSlice, + Error: Error2, + FunctionPrototypeSymbolHasInstance, + ObjectDefineProperty, ObjectDefineProperties, - ObjectKeys, ObjectSetPrototypeOf, - Promise: Promise2, - SafeSet, - SymbolAsyncDispose, - SymbolAsyncIterator, - Symbol: Symbol2 - } = require_primordials(); - module2.exports = Readable; - Readable.ReadableState = ReadableState; - var { EventEmitter: EE } = require("events"); - var { Stream, prependListener } = require_legacy(); - var { Buffer: Buffer2 } = require("buffer"); - var { addAbortSignal } = require_add_abort_signal(); - var eos = require_end_of_stream(); - var debug4 = require_util12().debuglog("stream", (fn) => { - debug4 = fn; - }); - var BufferList = require_buffer_list(); - var destroyImpl = require_destroy2(); - var { getHighWaterMark, getDefaultHighWaterMark } = require_state3(); - var { - aggregateTwoErrors, - codes: { - ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, - ERR_METHOD_NOT_IMPLEMENTED, - ERR_OUT_OF_RANGE, - ERR_STREAM_PUSH_AFTER_EOF, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT - }, - AbortError - } = require_errors3(); - var { validateObject } = require_validators(); - var kPaused = Symbol2("kPaused"); - var { StringDecoder } = require("string_decoder"); - var from = require_from(); - ObjectSetPrototypeOf(Readable.prototype, Stream.prototype); - ObjectSetPrototypeOf(Readable, Stream); - var nop = () => { - }; - var { errorOrDestroy } = destroyImpl; - var kObjectMode = 1 << 0; - var kEnded = 1 << 1; - var kEndEmitted = 1 << 2; - var kReading = 1 << 3; - var kConstructed = 1 << 4; - var kSync = 1 << 5; - var kNeedReadable = 1 << 6; - var kEmittedReadable = 1 << 7; - var kReadableListening = 1 << 8; - var kResumeScheduled = 1 << 9; - var kErrorEmitted = 1 << 10; - var kEmitClose = 1 << 11; - var kAutoDestroy = 1 << 12; - var kDestroyed = 1 << 13; - var kClosed = 1 << 14; - var kCloseEmitted = 1 << 15; - var kMultiAwaitDrain = 1 << 16; - var kReadingMore = 1 << 17; - var kDataEmitted = 1 << 18; - function makeBitMapDescriptor(bit) { - return { - enumerable: false, - get() { - return (this.state & bit) !== 0; - }, - set(value) { - if (value) this.state |= bit; - else this.state &= ~bit; - } - }; + StringPrototypeToLowerCase, + Symbol: Symbol2, + SymbolHasInstance + } = require_primordials(); + module2.exports = Writable; + Writable.WritableState = WritableState; + var { EventEmitter: EE } = require("events"); + var Stream = require_legacy().Stream; + var { Buffer: Buffer2 } = require("buffer"); + var destroyImpl = require_destroy2(); + var { addAbortSignal } = require_add_abort_signal(); + var { getHighWaterMark, getDefaultHighWaterMark } = require_state3(); + var { + ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED, + ERR_STREAM_ALREADY_FINISHED, + ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING + } = require_errors3().codes; + var { errorOrDestroy } = destroyImpl; + ObjectSetPrototypeOf(Writable.prototype, Stream.prototype); + ObjectSetPrototypeOf(Writable, Stream); + function nop() { } - ObjectDefineProperties(ReadableState.prototype, { - objectMode: makeBitMapDescriptor(kObjectMode), - ended: makeBitMapDescriptor(kEnded), - endEmitted: makeBitMapDescriptor(kEndEmitted), - reading: makeBitMapDescriptor(kReading), - // Stream is still being constructed and cannot be - // destroyed until construction finished or failed. - // Async construction is opt in, therefore we start as - // constructed. - constructed: makeBitMapDescriptor(kConstructed), - // A flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - sync: makeBitMapDescriptor(kSync), - // Whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - needReadable: makeBitMapDescriptor(kNeedReadable), - emittedReadable: makeBitMapDescriptor(kEmittedReadable), - readableListening: makeBitMapDescriptor(kReadableListening), - resumeScheduled: makeBitMapDescriptor(kResumeScheduled), - // True if the error was already emitted and should not be thrown again. - errorEmitted: makeBitMapDescriptor(kErrorEmitted), - emitClose: makeBitMapDescriptor(kEmitClose), - autoDestroy: makeBitMapDescriptor(kAutoDestroy), - // Has it been destroyed. - destroyed: makeBitMapDescriptor(kDestroyed), - // Indicates whether the stream has finished destroying. - closed: makeBitMapDescriptor(kClosed), - // True if close has been emitted or would have been emitted - // depending on emitClose. - closeEmitted: makeBitMapDescriptor(kCloseEmitted), - multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), - // If true, a maybeReadMore has been scheduled. - readingMore: makeBitMapDescriptor(kReadingMore), - dataEmitted: makeBitMapDescriptor(kDataEmitted) - }); - function ReadableState(options, stream, isDuplex) { + var kOnFinished = Symbol2("kOnFinished"); + function WritableState(options, stream, isDuplex) { if (typeof isDuplex !== "boolean") isDuplex = stream instanceof require_duplex(); - this.state = kEmitClose | kAutoDestroy | kConstructed | kSync; - if (options && options.objectMode) this.state |= kObjectMode; - if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode; - this.highWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false); - this.buffer = new BufferList(); + this.objectMode = !!(options && options.objectMode); + if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode); + this.highWaterMark = options ? getHighWaterMark(this, options, "writableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + const noDecode = !!(options && options.decodeStrings === false); + this.decodeStrings = !noDecode; + this.defaultEncoding = options && options.defaultEncoding || "utf8"; this.length = 0; - this.pipes = []; - this.flowing = null; - this[kPaused] = null; - if (options && options.emitClose === false) this.state &= ~kEmitClose; - if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = onwrite.bind(void 0, stream); + this.writecb = null; + this.writelen = 0; + this.afterWriteTickInfo = null; + resetBuffer(this); + this.pendingcb = 0; + this.constructed = true; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = !options || options.emitClose !== false; + this.autoDestroy = !options || options.autoDestroy !== false; this.errored = null; - this.defaultEncoding = options && options.defaultEncoding || "utf8"; - this.awaitDrainWriters = null; - this.decoder = null; - this.encoding = null; - if (options && options.encoding) { - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } + this.closed = false; + this.closeEmitted = false; + this[kOnFinished] = []; } - function Readable(options) { - if (!(this instanceof Readable)) return new Readable(options); + function resetBuffer(state) { + state.buffered = []; + state.bufferedIndex = 0; + state.allBuffers = true; + state.allNoop = true; + } + WritableState.prototype.getBuffer = function getBuffer() { + return ArrayPrototypeSlice(this.buffered, this.bufferedIndex); + }; + ObjectDefineProperty(WritableState.prototype, "bufferedRequestCount", { + __proto__: null, + get() { + return this.buffered.length - this.bufferedIndex; + } + }); + function Writable(options) { const isDuplex = this instanceof require_duplex(); - this._readableState = new ReadableState(options, this, isDuplex); + if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); if (options) { - if (typeof options.read === "function") this._read = options.read; + if (typeof options.write === "function") this._write = options.write; + if (typeof options.writev === "function") this._writev = options.writev; if (typeof options.destroy === "function") this._destroy = options.destroy; + if (typeof options.final === "function") this._final = options.final; if (typeof options.construct === "function") this._construct = options.construct; - if (options.signal && !isDuplex) addAbortSignal(options.signal, this); + if (options.signal) addAbortSignal(options.signal, this); } Stream.call(this, options); destroyImpl.construct(this, () => { - if (this._readableState.needReadable) { - maybeReadMore(this, this._readableState); + const state = this._writableState; + if (!state.writing) { + clearBuffer(this, state); } + finishMaybe(this, state); }); } - Readable.prototype.destroy = destroyImpl.destroy; - Readable.prototype._undestroy = destroyImpl.undestroy; - Readable.prototype._destroy = function(err, cb) { - cb(err); - }; - Readable.prototype[EE.captureRejectionSymbol] = function(err) { - this.destroy(err); - }; - Readable.prototype[SymbolAsyncDispose] = function() { - let error4; - if (!this.destroyed) { - error4 = this.readableEnded ? null : new AbortError(); - this.destroy(error4); + ObjectDefineProperty(Writable, SymbolHasInstance, { + __proto__: null, + value: function(object) { + if (FunctionPrototypeSymbolHasInstance(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; } - return new Promise2((resolve2, reject) => eos(this, (err) => err && err !== error4 ? reject(err) : resolve2(null))); - }; - Readable.prototype.push = function(chunk, encoding) { - return readableAddChunk(this, chunk, encoding, false); - }; - Readable.prototype.unshift = function(chunk, encoding) { - return readableAddChunk(this, chunk, encoding, true); + }); + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; - function readableAddChunk(stream, chunk, encoding, addToFront) { - debug4("readableAddChunk", chunk); - const state = stream._readableState; - let err; - if ((state.state & kObjectMode) === 0) { + function _write(stream, chunk, encoding, cb) { + const state = stream._writableState; + if (typeof encoding === "function") { + cb = encoding; + encoding = state.defaultEncoding; + } else { + if (!encoding) encoding = state.defaultEncoding; + else if (encoding !== "buffer" && !Buffer2.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding); + if (typeof cb !== "function") cb = nop; + } + if (chunk === null) { + throw new ERR_STREAM_NULL_VALUES(); + } else if (!state.objectMode) { if (typeof chunk === "string") { - encoding = encoding || state.defaultEncoding; - if (state.encoding !== encoding) { - if (addToFront && state.encoding) { - chunk = Buffer2.from(chunk, encoding).toString(state.encoding); - } else { - chunk = Buffer2.from(chunk, encoding); - encoding = ""; - } + if (state.decodeStrings !== false) { + chunk = Buffer2.from(chunk, encoding); + encoding = "buffer"; } } else if (chunk instanceof Buffer2) { - encoding = ""; + encoding = "buffer"; } else if (Stream._isUint8Array(chunk)) { chunk = Stream._uint8ArrayToBuffer(chunk); - encoding = ""; - } else if (chunk != null) { - err = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk); - } - } - if (err) { - errorOrDestroy(stream, err); - } else if (chunk === null) { - state.state &= ~kReading; - onEofChunk(stream, state); - } else if ((state.state & kObjectMode) !== 0 || chunk && chunk.length > 0) { - if (addToFront) { - if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); - else if (state.destroyed || state.errored) return false; - else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed || state.errored) { - return false; + encoding = "buffer"; } else { - state.state &= ~kReading; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false); - else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } + throw new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk); } - } else if (!addToFront) { - state.state &= ~kReading; - maybeReadMore(stream, state); } - return !state.ended && (state.length < state.highWaterMark || state.length === 0); - } - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount("data") > 0) { - if ((state.state & kMultiAwaitDrain) !== 0) { - state.awaitDrainWriters.clear(); - } else { - state.awaitDrainWriters = null; - } - state.dataEmitted = true; - stream.emit("data", chunk); - } else { - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk); - else state.buffer.push(chunk); - if ((state.state & kNeedReadable) !== 0) emitReadable(stream); + let err; + if (state.ending) { + err = new ERR_STREAM_WRITE_AFTER_END(); + } else if (state.destroyed) { + err = new ERR_STREAM_DESTROYED("write"); } - maybeReadMore(stream, state); + if (err) { + process2.nextTick(cb, err); + errorOrDestroy(stream, err, true); + return err; + } + state.pendingcb++; + return writeOrBuffer(stream, state, chunk, encoding, cb); } - Readable.prototype.isPaused = function() { - const state = this._readableState; - return state[kPaused] === true || state.flowing === false; + Writable.prototype.write = function(chunk, encoding, cb) { + return _write(this, chunk, encoding, cb) === true; }; - Readable.prototype.setEncoding = function(enc) { - const decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; - this._readableState.encoding = this._readableState.decoder.encoding; - const buffer = this._readableState.buffer; - let content = ""; - for (const data of buffer) { - content += decoder.write(data); + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + const state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing) clearBuffer(this, state); } - buffer.clear(); - if (content !== "") buffer.push(content); - this._readableState.length = content.length; + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + if (typeof encoding === "string") encoding = StringPrototypeToLowerCase(encoding); + if (!Buffer2.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; return this; }; - var MAX_HWM = 1073741824; - function computeNewHighWaterMark(n) { - if (n > MAX_HWM) { - throw new ERR_OUT_OF_RANGE("size", "<= 1GiB", n); - } else { - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; - } - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if ((state.state & kObjectMode) !== 0) return 1; - if (NumberIsNaN(n)) { - if (state.flowing && state.length) return state.buffer.first().length; - return state.length; - } - if (n <= state.length) return n; - return state.ended ? state.length : 0; - } - Readable.prototype.read = function(n) { - debug4("read", n); - if (n === void 0) { - n = NaN; - } else if (!NumberIsInteger(n)) { - n = NumberParseInt(n, 10); - } - const state = this._readableState; - const nOrig = n; - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n !== 0) state.state &= ~kEmittedReadable; - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug4("read: emitReadable", state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this); - else emitReadable(this); - return null; - } - n = howMuchToRead(n, state); - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - let doRead = (state.state & kNeedReadable) !== 0; - debug4("need readable", doRead); - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug4("length less than watermark", doRead); - } - if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) { - doRead = false; - debug4("reading, ended or constructing", doRead); - } else if (doRead) { - debug4("do read"); - state.state |= kReading | kSync; - if (state.length === 0) state.state |= kNeedReadable; - try { - this._read(state.highWaterMark); - } catch (err) { - errorOrDestroy(this, err); - } - state.state &= ~kSync; - if (!state.reading) n = howMuchToRead(nOrig, state); - } - let ret; - if (n > 0) ret = fromList(n, state); - else ret = null; - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - if (state.multiAwaitDrain) { - state.awaitDrainWriters.clear(); - } else { - state.awaitDrainWriters = null; + function writeOrBuffer(stream, state, chunk, encoding, callback) { + const len = state.objectMode ? 1 : chunk.length; + state.length += len; + const ret = state.length < state.highWaterMark; + if (!ret) state.needDrain = true; + if (state.writing || state.corked || state.errored || !state.constructed) { + state.buffered.push({ + chunk, + encoding, + callback + }); + if (state.allBuffers && encoding !== "buffer") { + state.allBuffers = false; } - } - if (state.length === 0) { - if (!state.ended) state.needReadable = true; - if (nOrig !== n && state.ended) endReadable(this); - } - if (ret !== null && !state.errorEmitted && !state.closeEmitted) { - state.dataEmitted = true; - this.emit("data", ret); - } - return ret; - }; - function onEofChunk(stream, state) { - debug4("onEofChunk"); - if (state.ended) return; - if (state.decoder) { - const chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + if (state.allNoop && callback !== nop) { + state.allNoop = false; } - } - state.ended = true; - if (state.sync) { - emitReadable(stream); } else { - state.needReadable = false; - state.emittedReadable = true; - emitReadable_(stream); - } - } - function emitReadable(stream) { - const state = stream._readableState; - debug4("emitReadable", state.needReadable, state.emittedReadable); - state.needReadable = false; - if (!state.emittedReadable) { - debug4("emitReadable", state.flowing); - state.emittedReadable = true; - process2.nextTick(emitReadable_, stream); - } - } - function emitReadable_(stream) { - const state = stream._readableState; - debug4("emitReadable_", state.destroyed, state.length, state.ended); - if (!state.destroyed && !state.errored && (state.length || state.ended)) { - stream.emit("readable"); - state.emittedReadable = false; + state.writelen = len; + state.writecb = callback; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); + return ret && !state.errored && !state.destroyed; } - function maybeReadMore(stream, state) { - if (!state.readingMore && state.constructed) { - state.readingMore = true; - process2.nextTick(maybeReadMore_, stream, state); - } + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev) stream._writev(chunk, state.onwrite); + else stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - function maybeReadMore_(stream, state) { - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - const len = state.length; - debug4("maybeReadMore read 0"); - stream.read(0); - if (len === state.length) - break; - } - state.readingMore = false; + function onwriteError(stream, state, er, cb) { + --state.pendingcb; + cb(er); + errorBuffer(state); + errorOrDestroy(stream, er); } - Readable.prototype._read = function(n) { - throw new ERR_METHOD_NOT_IMPLEMENTED("_read()"); - }; - Readable.prototype.pipe = function(dest, pipeOpts) { - const src = this; - const state = this._readableState; - if (state.pipes.length === 1) { - if (!state.multiAwaitDrain) { - state.multiAwaitDrain = true; - state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []); - } - } - state.pipes.push(dest); - debug4("pipe count=%d opts=%j", state.pipes.length, pipeOpts); - const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process2.stdout && dest !== process2.stderr; - const endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process2.nextTick(endFn); - else src.once("end", endFn); - dest.on("unpipe", onunpipe); - function onunpipe(readable, unpipeInfo) { - debug4("onunpipe"); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - function onend() { - debug4("onend"); - dest.end(); + function onwrite(stream, er) { + const state = stream._writableState; + const sync = state.sync; + const cb = state.writecb; + if (typeof cb !== "function") { + errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK()); + return; } - let ondrain; - let cleanedUp = false; - function cleanup() { - debug4("cleanup"); - dest.removeListener("close", onclose); - dest.removeListener("finish", onfinish); - if (ondrain) { - dest.removeListener("drain", ondrain); + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + if (er) { + er.stack; + if (!state.errored) { + state.errored = er; } - dest.removeListener("error", onerror); - dest.removeListener("unpipe", onunpipe); - src.removeListener("end", onend); - src.removeListener("end", unpipe); - src.removeListener("data", ondata); - cleanedUp = true; - if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - function pause() { - if (!cleanedUp) { - if (state.pipes.length === 1 && state.pipes[0] === dest) { - debug4("false write response, pause", 0); - state.awaitDrainWriters = dest; - state.multiAwaitDrain = false; - } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { - debug4("false write response, pause", state.awaitDrainWriters.size); - state.awaitDrainWriters.add(dest); - } - src.pause(); + if (stream._readableState && !stream._readableState.errored) { + stream._readableState.errored = er; } - if (!ondrain) { - ondrain = pipeOnDrain(src, dest); - dest.on("drain", ondrain); + if (sync) { + process2.nextTick(onwriteError, stream, state, er, cb); + } else { + onwriteError(stream, state, er, cb); } - } - src.on("data", ondata); - function ondata(chunk) { - debug4("ondata"); - const ret = dest.write(chunk); - debug4("dest.write", ret); - if (ret === false) { - pause(); + } else { + if (state.buffered.length > state.bufferedIndex) { + clearBuffer(stream, state); } - } - function onerror(er) { - debug4("onerror", er); - unpipe(); - dest.removeListener("error", onerror); - if (dest.listenerCount("error") === 0) { - const s = dest._writableState || dest._readableState; - if (s && !s.errorEmitted) { - errorOrDestroy(dest, er); + if (sync) { + if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) { + state.afterWriteTickInfo.count++; } else { - dest.emit("error", er); + state.afterWriteTickInfo = { + count: 1, + cb, + stream, + state + }; + process2.nextTick(afterWriteTick, state.afterWriteTickInfo); } + } else { + afterWrite(stream, state, 1, cb); } } - prependListener(dest, "error", onerror); - function onclose() { - dest.removeListener("finish", onfinish); - unpipe(); + } + function afterWriteTick({ stream, state, count, cb }) { + state.afterWriteTickInfo = null; + return afterWrite(stream, state, count, cb); + } + function afterWrite(stream, state, count, cb) { + const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain; + if (needDrain) { + state.needDrain = false; + stream.emit("drain"); } - dest.once("close", onclose); - function onfinish() { - debug4("onfinish"); - dest.removeListener("close", onclose); - unpipe(); + while (count-- > 0) { + state.pendingcb--; + cb(); } - dest.once("finish", onfinish); - function unpipe() { - debug4("unpipe"); - src.unpipe(dest); + if (state.destroyed) { + errorBuffer(state); } - dest.emit("pipe", src); - if (dest.writableNeedDrain === true) { - pause(); - } else if (!state.flowing) { - debug4("pipe resume"); - src.resume(); + finishMaybe(stream, state); + } + function errorBuffer(state) { + if (state.writing) { + return; } - return dest; - }; - function pipeOnDrain(src, dest) { - return function pipeOnDrainFunctionResult() { - const state = src._readableState; - if (state.awaitDrainWriters === dest) { - debug4("pipeOnDrain", 1); - state.awaitDrainWriters = null; - } else if (state.multiAwaitDrain) { - debug4("pipeOnDrain", state.awaitDrainWriters.size); - state.awaitDrainWriters.delete(dest); - } - if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount("data")) { - src.resume(); - } - }; + for (let n = state.bufferedIndex; n < state.buffered.length; ++n) { + var _state$errored; + const { chunk, callback } = state.buffered[n]; + const len = state.objectMode ? 1 : chunk.length; + state.length -= len; + callback( + (_state$errored = state.errored) !== null && _state$errored !== void 0 ? _state$errored : new ERR_STREAM_DESTROYED("write") + ); + } + const onfinishCallbacks = state[kOnFinished].splice(0); + for (let i = 0; i < onfinishCallbacks.length; i++) { + var _state$errored2; + onfinishCallbacks[i]( + (_state$errored2 = state.errored) !== null && _state$errored2 !== void 0 ? _state$errored2 : new ERR_STREAM_DESTROYED("end") + ); + } + resetBuffer(state); } - Readable.prototype.unpipe = function(dest) { - const state = this._readableState; - const unpipeInfo = { - hasUnpiped: false - }; - if (state.pipes.length === 0) return this; - if (!dest) { - const dests = state.pipes; - state.pipes = []; - this.pause(); - for (let i = 0; i < dests.length; i++) - dests[i].emit("unpipe", this, { - hasUnpiped: false - }); - return this; + function clearBuffer(stream, state) { + if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) { + return; } - const index = ArrayPrototypeIndexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - if (state.pipes.length === 0) this.pause(); - dest.emit("unpipe", this, unpipeInfo); - return this; - }; - Readable.prototype.on = function(ev, fn) { - const res = Stream.prototype.on.call(this, ev, fn); - const state = this._readableState; - if (ev === "data") { - state.readableListening = this.listenerCount("readable") > 0; - if (state.flowing !== false) this.resume(); - } else if (ev === "readable") { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug4("on readable", state.length, state.reading); - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process2.nextTick(nReadingNextTick, this); + const { buffered, bufferedIndex, objectMode } = state; + const bufferedLength = buffered.length - bufferedIndex; + if (!bufferedLength) { + return; + } + let i = bufferedIndex; + state.bufferProcessing = true; + if (bufferedLength > 1 && stream._writev) { + state.pendingcb -= bufferedLength - 1; + const callback = state.allNoop ? nop : (err) => { + for (let n = i; n < buffered.length; ++n) { + buffered[n].callback(err); } + }; + const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i); + chunks.allBuffers = state.allBuffers; + doWrite(stream, state, true, state.length, chunks, "", callback); + resetBuffer(state); + } else { + do { + const { chunk, encoding, callback } = buffered[i]; + buffered[i++] = null; + const len = objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, callback); + } while (i < buffered.length && !state.writing); + if (i === buffered.length) { + resetBuffer(state); + } else if (i > 256) { + buffered.splice(0, i); + state.bufferedIndex = 0; + } else { + state.bufferedIndex = i; } } - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; - Readable.prototype.removeListener = function(ev, fn) { - const res = Stream.prototype.removeListener.call(this, ev, fn); - if (ev === "readable") { - process2.nextTick(updateReadableListening, this); - } - return res; - }; - Readable.prototype.off = Readable.prototype.removeListener; - Readable.prototype.removeAllListeners = function(ev) { - const res = Stream.prototype.removeAllListeners.apply(this, arguments); - if (ev === "readable" || ev === void 0) { - process2.nextTick(updateReadableListening, this); + state.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding, cb) { + if (this._writev) { + this._writev( + [ + { + chunk, + encoding + } + ], + cb + ); + } else { + throw new ERR_METHOD_NOT_IMPLEMENTED("_write()"); } - return res; }; - function updateReadableListening(self2) { - const state = self2._readableState; - state.readableListening = self2.listenerCount("readable") > 0; - if (state.resumeScheduled && state[kPaused] === false) { - state.flowing = true; - } else if (self2.listenerCount("data") > 0) { - self2.resume(); - } else if (!state.readableListening) { - state.flowing = null; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding, cb) { + const state = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === "function") { + cb = encoding; + encoding = null; } - } - function nReadingNextTick(self2) { - debug4("readable nexttick read 0"); - self2.read(0); - } - Readable.prototype.resume = function() { - const state = this._readableState; - if (!state.flowing) { - debug4("resume"); - state.flowing = !state.readableListening; - resume(this, state); + let err; + if (chunk !== null && chunk !== void 0) { + const ret = _write(this, chunk, encoding); + if (ret instanceof Error2) { + err = ret; + } } - state[kPaused] = false; - return this; - }; - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process2.nextTick(resume_, stream, state); + if (state.corked) { + state.corked = 1; + this.uncork(); } - } - function resume_(stream, state) { - debug4("resume", state.reading); - if (!state.reading) { - stream.read(0); + if (err) { + } else if (!state.errored && !state.ending) { + state.ending = true; + finishMaybe(this, state, true); + state.ended = true; + } else if (state.finished) { + err = new ERR_STREAM_ALREADY_FINISHED("end"); + } else if (state.destroyed) { + err = new ERR_STREAM_DESTROYED("end"); } - state.resumeScheduled = false; - stream.emit("resume"); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } - Readable.prototype.pause = function() { - debug4("call pause flowing=%j", this._readableState.flowing); - if (this._readableState.flowing !== false) { - debug4("pause"); - this._readableState.flowing = false; - this.emit("pause"); + if (typeof cb === "function") { + if (err || state.finished) { + process2.nextTick(cb, err); + } else { + state[kOnFinished].push(cb); + } } - this._readableState[kPaused] = true; return this; }; - function flow(stream) { - const state = stream._readableState; - debug4("flow", state.flowing); - while (state.flowing && stream.read() !== null) ; + function needFinish(state) { + return state.ending && !state.destroyed && state.constructed && state.length === 0 && !state.errored && state.buffered.length === 0 && !state.finished && !state.writing && !state.errorEmitted && !state.closeEmitted; } - Readable.prototype.wrap = function(stream) { - let paused = false; - stream.on("data", (chunk) => { - if (!this.push(chunk) && stream.pause) { - paused = true; - stream.pause(); - } - }); - stream.on("end", () => { - this.push(null); - }); - stream.on("error", (err) => { - errorOrDestroy(this, err); - }); - stream.on("close", () => { - this.destroy(); - }); - stream.on("destroy", () => { - this.destroy(); - }); - this._read = () => { - if (paused && stream.resume) { - paused = false; - stream.resume(); + function callFinal(stream, state) { + let called = false; + function onFinish(err) { + if (called) { + errorOrDestroy(stream, err !== null && err !== void 0 ? err : ERR_MULTIPLE_CALLBACK()); + return; } - }; - const streamKeys = ObjectKeys(stream); - for (let j = 1; j < streamKeys.length; j++) { - const i = streamKeys[j]; - if (this[i] === void 0 && typeof stream[i] === "function") { - this[i] = stream[i].bind(stream); + called = true; + state.pendingcb--; + if (err) { + const onfinishCallbacks = state[kOnFinished].splice(0); + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i](err); + } + errorOrDestroy(stream, err, state.sync); + } else if (needFinish(state)) { + state.prefinished = true; + stream.emit("prefinish"); + state.pendingcb++; + process2.nextTick(finish, stream, state); } } - return this; - }; - Readable.prototype[SymbolAsyncIterator] = function() { - return streamToAsyncIterator(this); - }; - Readable.prototype.iterator = function(options) { - if (options !== void 0) { - validateObject(options, "options"); - } - return streamToAsyncIterator(this, options); - }; - function streamToAsyncIterator(stream, options) { - if (typeof stream.read !== "function") { - stream = Readable.wrap(stream, { - objectMode: true - }); + state.sync = true; + state.pendingcb++; + try { + stream._final(onFinish); + } catch (err) { + onFinish(err); } - const iter = createAsyncIterator(stream, options); - iter.stream = stream; - return iter; + state.sync = false; } - async function* createAsyncIterator(stream, options) { - let callback = nop; - function next(resolve2) { - if (this === stream) { - callback(); - callback = nop; + function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === "function" && !state.destroyed) { + state.finalCalled = true; + callFinal(stream, state); } else { - callback = resolve2; + state.prefinished = true; + stream.emit("prefinish"); } } - stream.on("readable", next); - let error4; - const cleanup = eos( - stream, - { - writable: false - }, - (err) => { - error4 = err ? aggregateTwoErrors(error4, err) : null; - callback(); - callback = nop; - } - ); - try { - while (true) { - const chunk = stream.destroyed ? null : stream.read(); - if (chunk !== null) { - yield chunk; - } else if (error4) { - throw error4; - } else if (error4 === null) { - return; - } else { - await new Promise2(next); + } + function finishMaybe(stream, state, sync) { + if (needFinish(state)) { + prefinish(stream, state); + if (state.pendingcb === 0) { + if (sync) { + state.pendingcb++; + process2.nextTick( + (stream2, state2) => { + if (needFinish(state2)) { + finish(stream2, state2); + } else { + state2.pendingcb--; + } + }, + stream, + state + ); + } else if (needFinish(state)) { + state.pendingcb++; + finish(stream, state); } } - } catch (err) { - error4 = aggregateTwoErrors(error4, err); - throw error4; - } finally { - if ((error4 || (options === null || options === void 0 ? void 0 : options.destroyOnReturn) !== false) && (error4 === void 0 || stream._readableState.autoDestroy)) { - destroyImpl.destroyer(stream, null); - } else { - stream.off("readable", next); - cleanup(); + } + } + function finish(stream, state) { + state.pendingcb--; + state.finished = true; + const onfinishCallbacks = state[kOnFinished].splice(0); + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i](); + } + stream.emit("finish"); + if (state.autoDestroy) { + const rState = stream._readableState; + const autoDestroy = !rState || rState.autoDestroy && // We don't expect the readable to ever 'end' + // if readable is explicitly set to false. + (rState.endEmitted || rState.readable === false); + if (autoDestroy) { + stream.destroy(); } } } - ObjectDefineProperties(Readable.prototype, { - readable: { + ObjectDefineProperties(Writable.prototype, { + closed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.closed : false; + } + }, + destroyed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.destroyed : false; + }, + set(value) { + if (this._writableState) { + this._writableState.destroyed = value; + } + } + }, + writable: { __proto__: null, get() { - const r = this._readableState; - return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted; + const w = this._writableState; + return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended; }, set(val2) { - if (this._readableState) { - this._readableState.readable = !!val2; + if (this._writableState) { + this._writableState.writable = !!val2; } } }, - readableDidRead: { + writableFinished: { __proto__: null, - enumerable: false, - get: function() { - return this._readableState.dataEmitted; + get() { + return this._writableState ? this._writableState.finished : false; } }, - readableAborted: { + writableObjectMode: { __proto__: null, - enumerable: false, - get: function() { - return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted); + get() { + return this._writableState ? this._writableState.objectMode : false; } }, - readableHighWaterMark: { + writableBuffer: { __proto__: null, - enumerable: false, - get: function() { - return this._readableState.highWaterMark; + get() { + return this._writableState && this._writableState.getBuffer(); } }, - readableBuffer: { + writableEnded: { + __proto__: null, + get() { + return this._writableState ? this._writableState.ending : false; + } + }, + writableNeedDrain: { + __proto__: null, + get() { + const wState = this._writableState; + if (!wState) return false; + return !wState.destroyed && !wState.ending && wState.needDrain; + } + }, + writableHighWaterMark: { + __proto__: null, + get() { + return this._writableState && this._writableState.highWaterMark; + } + }, + writableCorked: { + __proto__: null, + get() { + return this._writableState ? this._writableState.corked : 0; + } + }, + writableLength: { + __proto__: null, + get() { + return this._writableState && this._writableState.length; + } + }, + errored: { __proto__: null, enumerable: false, - get: function() { - return this._readableState && this._readableState.buffer; + get() { + return this._writableState ? this._writableState.errored : null; } }, - readableFlowing: { + writableAborted: { __proto__: null, enumerable: false, get: function() { - return this._readableState.flowing; + return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished); + } + } + }); + var destroy = destroyImpl.destroy; + Writable.prototype.destroy = function(err, cb) { + const state = this._writableState; + if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) { + process2.nextTick(errorBuffer, state); + } + destroy.call(this, err, cb); + return this; + }; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + Writable.prototype[EE.captureRejectionSymbol] = function(err) { + this.destroy(err); + }; + var webStreamsAdapters; + function lazyWebStreams() { + if (webStreamsAdapters === void 0) webStreamsAdapters = {}; + return webStreamsAdapters; + } + Writable.fromWeb = function(writableStream, options) { + return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options); + }; + Writable.toWeb = function(streamWritable) { + return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable); + }; + } +}); + +// node_modules/readable-stream/lib/internal/streams/duplexify.js +var require_duplexify = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/duplexify.js"(exports2, module2) { + var process2 = require_process(); + var bufferModule = require("buffer"); + var { + isReadable, + isWritable, + isIterable, + isNodeStream, + isReadableNodeStream, + isWritableNodeStream, + isDuplexNodeStream, + isReadableStream, + isWritableStream + } = require_utils6(); + var eos = require_end_of_stream(); + var { + AbortError, + codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_RETURN_VALUE } + } = require_errors3(); + var { destroyer } = require_destroy2(); + var Duplex = require_duplex(); + var Readable = require_readable3(); + var Writable = require_writable(); + var { createDeferredPromise } = require_util12(); + var from = require_from(); + var Blob2 = globalThis.Blob || bufferModule.Blob; + var isBlob = typeof Blob2 !== "undefined" ? function isBlob2(b) { + return b instanceof Blob2; + } : function isBlob2(b) { + return false; + }; + var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; + var { FunctionPrototypeCall } = require_primordials(); + var Duplexify = class extends Duplex { + constructor(options) { + super(options); + if ((options === null || options === void 0 ? void 0 : options.readable) === false) { + this._readableState.readable = false; + this._readableState.ended = true; + this._readableState.endEmitted = true; + } + if ((options === null || options === void 0 ? void 0 : options.writable) === false) { + this._writableState.writable = false; + this._writableState.ending = true; + this._writableState.ended = true; + this._writableState.finished = true; + } + } + }; + module2.exports = function duplexify(body, name) { + if (isDuplexNodeStream(body)) { + return body; + } + if (isReadableNodeStream(body)) { + return _duplexify({ + readable: body + }); + } + if (isWritableNodeStream(body)) { + return _duplexify({ + writable: body + }); + } + if (isNodeStream(body)) { + return _duplexify({ + writable: false, + readable: false + }); + } + if (isReadableStream(body)) { + return _duplexify({ + readable: Readable.fromWeb(body) + }); + } + if (isWritableStream(body)) { + return _duplexify({ + writable: Writable.fromWeb(body) + }); + } + if (typeof body === "function") { + const { value, write, final, destroy } = fromAsyncGen(body); + if (isIterable(value)) { + return from(Duplexify, value, { + // TODO (ronag): highWaterMark? + objectMode: true, + write, + final, + destroy + }); + } + const then2 = value === null || value === void 0 ? void 0 : value.then; + if (typeof then2 === "function") { + let d; + const promise = FunctionPrototypeCall( + then2, + value, + (val2) => { + if (val2 != null) { + throw new ERR_INVALID_RETURN_VALUE("nully", "body", val2); + } + }, + (err) => { + destroyer(d, err); + } + ); + return d = new Duplexify({ + // TODO (ronag): highWaterMark? + objectMode: true, + readable: false, + write, + final(cb) { + final(async () => { + try { + await promise; + process2.nextTick(cb, null); + } catch (err) { + process2.nextTick(cb, err); + } + }); + }, + destroy + }); + } + throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or AsyncFunction", name, value); + } + if (isBlob(body)) { + return duplexify(body.arrayBuffer()); + } + if (isIterable(body)) { + return from(Duplexify, body, { + // TODO (ronag): highWaterMark? + objectMode: true, + writable: false + }); + } + if (isReadableStream(body === null || body === void 0 ? void 0 : body.readable) && isWritableStream(body === null || body === void 0 ? void 0 : body.writable)) { + return Duplexify.fromWeb(body); + } + if (typeof (body === null || body === void 0 ? void 0 : body.writable) === "object" || typeof (body === null || body === void 0 ? void 0 : body.readable) === "object") { + const readable = body !== null && body !== void 0 && body.readable ? isReadableNodeStream(body === null || body === void 0 ? void 0 : body.readable) ? body === null || body === void 0 ? void 0 : body.readable : duplexify(body.readable) : void 0; + const writable = body !== null && body !== void 0 && body.writable ? isWritableNodeStream(body === null || body === void 0 ? void 0 : body.writable) ? body === null || body === void 0 ? void 0 : body.writable : duplexify(body.writable) : void 0; + return _duplexify({ + readable, + writable + }); + } + const then = body === null || body === void 0 ? void 0 : body.then; + if (typeof then === "function") { + let d; + FunctionPrototypeCall( + then, + body, + (val2) => { + if (val2 != null) { + d.push(val2); + } + d.push(null); + }, + (err) => { + destroyer(d, err); + } + ); + return d = new Duplexify({ + objectMode: true, + writable: false, + read() { + } + }); + } + throw new ERR_INVALID_ARG_TYPE2( + name, + [ + "Blob", + "ReadableStream", + "WritableStream", + "Stream", + "Iterable", + "AsyncIterable", + "Function", + "{ readable, writable } pair", + "Promise" + ], + body + ); + }; + function fromAsyncGen(fn) { + let { promise, resolve: resolve2 } = createDeferredPromise(); + const ac = new AbortController2(); + const signal = ac.signal; + const value = fn( + (async function* () { + while (true) { + const _promise = promise; + promise = null; + const { chunk, done, cb } = await _promise; + process2.nextTick(cb); + if (done) return; + if (signal.aborted) + throw new AbortError(void 0, { + cause: signal.reason + }); + ({ promise, resolve: resolve2 } = createDeferredPromise()); + yield chunk; + } + })(), + { + signal + } + ); + return { + value, + write(chunk, encoding, cb) { + const _resolve = resolve2; + resolve2 = null; + _resolve({ + chunk, + done: false, + cb + }); }, - set: function(state) { - if (this._readableState) { - this._readableState.flowing = state; + final(cb) { + const _resolve = resolve2; + resolve2 = null; + _resolve({ + done: true, + cb + }); + }, + destroy(err, cb) { + ac.abort(); + cb(err); + } + }; + } + function _duplexify(pair) { + const r = pair.readable && typeof pair.readable.read !== "function" ? Readable.wrap(pair.readable) : pair.readable; + const w = pair.writable; + let readable = !!isReadable(r); + let writable = !!isWritable(w); + let ondrain; + let onfinish; + let onreadable; + let onclose; + let d; + function onfinished(err) { + const cb = onclose; + onclose = null; + if (cb) { + cb(err); + } else if (err) { + d.destroy(err); + } + } + d = new Duplexify({ + // TODO (ronag): highWaterMark? + readableObjectMode: !!(r !== null && r !== void 0 && r.readableObjectMode), + writableObjectMode: !!(w !== null && w !== void 0 && w.writableObjectMode), + readable, + writable + }); + if (writable) { + eos(w, (err) => { + writable = false; + if (err) { + destroyer(r, err); + } + onfinished(err); + }); + d._write = function(chunk, encoding, callback) { + if (w.write(chunk, encoding)) { + callback(); + } else { + ondrain = callback; + } + }; + d._final = function(callback) { + w.end(); + onfinish = callback; + }; + w.on("drain", function() { + if (ondrain) { + const cb = ondrain; + ondrain = null; + cb(); + } + }); + w.on("finish", function() { + if (onfinish) { + const cb = onfinish; + onfinish = null; + cb(); + } + }); + } + if (readable) { + eos(r, (err) => { + readable = false; + if (err) { + destroyer(r, err); + } + onfinished(err); + }); + r.on("readable", function() { + if (onreadable) { + const cb = onreadable; + onreadable = null; + cb(); + } + }); + r.on("end", function() { + d.push(null); + }); + d._read = function() { + while (true) { + const buf = r.read(); + if (buf === null) { + onreadable = d._read; + return; + } + if (!d.push(buf)) { + return; + } } + }; + } + d._destroy = function(err, callback) { + if (!err && onclose !== null) { + err = new AbortError(); + } + onreadable = null; + ondrain = null; + onfinish = null; + if (onclose === null) { + callback(err); + } else { + onclose = callback; + destroyer(w, err); + destroyer(r, err); + } + }; + return d; + } + } +}); + +// node_modules/readable-stream/lib/internal/streams/duplex.js +var require_duplex = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/duplex.js"(exports2, module2) { + "use strict"; + var { + ObjectDefineProperties, + ObjectGetOwnPropertyDescriptor, + ObjectKeys, + ObjectSetPrototypeOf + } = require_primordials(); + module2.exports = Duplex; + var Readable = require_readable3(); + var Writable = require_writable(); + ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype); + ObjectSetPrototypeOf(Duplex, Readable); + { + const keys = ObjectKeys(Writable.prototype); + for (let i = 0; i < keys.length; i++) { + const method = keys[i]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + if (options) { + this.allowHalfOpen = options.allowHalfOpen !== false; + if (options.readable === false) { + this._readableState.readable = false; + this._readableState.ended = true; + this._readableState.endEmitted = true; + } + if (options.writable === false) { + this._writableState.writable = false; + this._writableState.ending = true; + this._writableState.ended = true; + this._writableState.finished = true; } + } else { + this.allowHalfOpen = true; + } + } + ObjectDefineProperties(Duplex.prototype, { + writable: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writable") }, - readableLength: { + writableHighWaterMark: { __proto__: null, - enumerable: false, - get() { - return this._readableState.length; - } + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableHighWaterMark") }, - readableObjectMode: { + writableObjectMode: { __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.objectMode : false; - } + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableObjectMode") }, - readableEncoding: { + writableBuffer: { __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.encoding : null; - } + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableBuffer") }, - errored: { + writableLength: { __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.errored : null; - } + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableLength") }, - closed: { + writableFinished: { __proto__: null, - get() { - return this._readableState ? this._readableState.closed : false; - } + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableFinished") }, - destroyed: { + writableCorked: { __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.destroyed : false; - }, - set(value) { - if (!this._readableState) { - return; - } - this._readableState.destroyed = value; - } + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableCorked") }, - readableEnded: { + writableEnded: { __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.endEmitted : false; - } - } - }); - ObjectDefineProperties(ReadableState.prototype, { - // Legacy getter for `pipesCount`. - pipesCount: { + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableEnded") + }, + writableNeedDrain: { __proto__: null, - get() { - return this.pipes.length; - } + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableNeedDrain") }, - // Legacy property for `paused`. - paused: { + destroyed: { __proto__: null, get() { - return this[kPaused] !== false; + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; }, set(value) { - this[kPaused] = !!value; - } - } - }); - Readable._fromList = fromList; - function fromList(n, state) { - if (state.length === 0) return null; - let ret; - if (state.objectMode) ret = state.buffer.shift(); - else if (!n || n >= state.length) { - if (state.decoder) ret = state.buffer.join(""); - else if (state.buffer.length === 1) ret = state.buffer.first(); - else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - ret = state.buffer.consume(n, state.decoder); - } - return ret; - } - function endReadable(stream) { - const state = stream._readableState; - debug4("endReadable", state.endEmitted); - if (!state.endEmitted) { - state.ended = true; - process2.nextTick(endReadableNT, state, stream); - } - } - function endReadableNT(state, stream) { - debug4("endReadableNT", state.endEmitted, state.length); - if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.emit("end"); - if (stream.writable && stream.allowHalfOpen === false) { - process2.nextTick(endWritableNT, stream); - } else if (state.autoDestroy) { - const wState = stream._writableState; - const autoDestroy = !wState || wState.autoDestroy && // We don't expect the writable to ever 'finish' - // if writable is explicitly set to false. - (wState.finished || wState.writable === false); - if (autoDestroy) { - stream.destroy(); + if (this._readableState && this._writableState) { + this._readableState.destroyed = value; + this._writableState.destroyed = value; } } } - } - function endWritableNT(stream) { - const writable = stream.writable && !stream.writableEnded && !stream.destroyed; - if (writable) { - stream.end(); - } - } - Readable.from = function(iterable, opts) { - return from(Readable, iterable, opts); - }; + }); var webStreamsAdapters; function lazyWebStreams() { if (webStreamsAdapters === void 0) webStreamsAdapters = {}; return webStreamsAdapters; } - Readable.fromWeb = function(readableStream, options) { - return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options); + Duplex.fromWeb = function(pair, options) { + return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options); }; - Readable.toWeb = function(streamReadable, options) { - return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options); + Duplex.toWeb = function(duplex) { + return lazyWebStreams().newReadableWritablePairFromDuplex(duplex); }; - Readable.wrap = function(src, options) { - var _ref, _src$readableObjectMo; - return new Readable({ - objectMode: (_ref = (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== void 0 ? _src$readableObjectMo : src.objectMode) !== null && _ref !== void 0 ? _ref : true, - ...options, - destroy(err, callback) { - destroyImpl.destroyer(src, err); - callback(err); - } - }).wrap(src); + var duplexify; + Duplex.from = function(body) { + if (!duplexify) { + duplexify = require_duplexify(); + } + return duplexify(body, "body"); }; } }); -// node_modules/readable-stream/lib/internal/streams/writable.js -var require_writable = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/writable.js"(exports2, module2) { - var process2 = require_process(); - var { - ArrayPrototypeSlice, - Error: Error2, - FunctionPrototypeSymbolHasInstance, - ObjectDefineProperty, - ObjectDefineProperties, - ObjectSetPrototypeOf, - StringPrototypeToLowerCase, - Symbol: Symbol2, - SymbolHasInstance - } = require_primordials(); - module2.exports = Writable; - Writable.WritableState = WritableState; - var { EventEmitter: EE } = require("events"); - var Stream = require_legacy().Stream; - var { Buffer: Buffer2 } = require("buffer"); - var destroyImpl = require_destroy2(); - var { addAbortSignal } = require_add_abort_signal(); - var { getHighWaterMark, getDefaultHighWaterMark } = require_state3(); - var { - ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, - ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED, - ERR_STREAM_ALREADY_FINISHED, - ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING - } = require_errors3().codes; - var { errorOrDestroy } = destroyImpl; - ObjectSetPrototypeOf(Writable.prototype, Stream.prototype); - ObjectSetPrototypeOf(Writable, Stream); - function nop() { - } - var kOnFinished = Symbol2("kOnFinished"); - function WritableState(options, stream, isDuplex) { - if (typeof isDuplex !== "boolean") isDuplex = stream instanceof require_duplex(); - this.objectMode = !!(options && options.objectMode); - if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode); - this.highWaterMark = options ? getHighWaterMark(this, options, "writableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false); - this.finalCalled = false; - this.needDrain = false; - this.ending = false; - this.ended = false; - this.finished = false; - this.destroyed = false; - const noDecode = !!(options && options.decodeStrings === false); - this.decodeStrings = !noDecode; - this.defaultEncoding = options && options.defaultEncoding || "utf8"; - this.length = 0; - this.writing = false; - this.corked = 0; - this.sync = true; - this.bufferProcessing = false; - this.onwrite = onwrite.bind(void 0, stream); - this.writecb = null; - this.writelen = 0; - this.afterWriteTickInfo = null; - resetBuffer(this); - this.pendingcb = 0; - this.constructed = true; - this.prefinished = false; - this.errorEmitted = false; - this.emitClose = !options || options.emitClose !== false; - this.autoDestroy = !options || options.autoDestroy !== false; - this.errored = null; - this.closed = false; - this.closeEmitted = false; - this[kOnFinished] = []; - } - function resetBuffer(state) { - state.buffered = []; - state.bufferedIndex = 0; - state.allBuffers = true; - state.allNoop = true; - } - WritableState.prototype.getBuffer = function getBuffer() { - return ArrayPrototypeSlice(this.buffered, this.bufferedIndex); - }; - ObjectDefineProperty(WritableState.prototype, "bufferedRequestCount", { - __proto__: null, - get() { - return this.buffered.length - this.bufferedIndex; +// node_modules/readable-stream/lib/internal/streams/transform.js +var require_transform = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/transform.js"(exports2, module2) { + "use strict"; + var { ObjectSetPrototypeOf, Symbol: Symbol2 } = require_primordials(); + module2.exports = Transform; + var { ERR_METHOD_NOT_IMPLEMENTED } = require_errors3().codes; + var Duplex = require_duplex(); + var { getHighWaterMark } = require_state3(); + ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype); + ObjectSetPrototypeOf(Transform, Duplex); + var kCallback = Symbol2("kCallback"); + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + const readableHighWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", true) : null; + if (readableHighWaterMark === 0) { + options = { + ...options, + highWaterMark: null, + readableHighWaterMark, + // TODO (ronag): 0 is not optimal since we have + // a "bug" where we check needDrain before calling _write and not after. + // Refs: https://github.com/nodejs/node/pull/32887 + // Refs: https://github.com/nodejs/node/pull/35941 + writableHighWaterMark: options.writableHighWaterMark || 0 + }; } - }); - function Writable(options) { - const isDuplex = this instanceof require_duplex(); - if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); + Duplex.call(this, options); + this._readableState.sync = false; + this[kCallback] = null; if (options) { - if (typeof options.write === "function") this._write = options.write; - if (typeof options.writev === "function") this._writev = options.writev; - if (typeof options.destroy === "function") this._destroy = options.destroy; - if (typeof options.final === "function") this._final = options.final; - if (typeof options.construct === "function") this._construct = options.construct; - if (options.signal) addAbortSignal(options.signal, this); + if (typeof options.transform === "function") this._transform = options.transform; + if (typeof options.flush === "function") this._flush = options.flush; } - Stream.call(this, options); - destroyImpl.construct(this, () => { - const state = this._writableState; - if (!state.writing) { - clearBuffer(this, state); - } - finishMaybe(this, state); - }); + this.on("prefinish", prefinish); } - ObjectDefineProperty(Writable, SymbolHasInstance, { - __proto__: null, - value: function(object) { - if (FunctionPrototypeSymbolHasInstance(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); - Writable.prototype.pipe = function() { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); - }; - function _write(stream, chunk, encoding, cb) { - const state = stream._writableState; - if (typeof encoding === "function") { - cb = encoding; - encoding = state.defaultEncoding; - } else { - if (!encoding) encoding = state.defaultEncoding; - else if (encoding !== "buffer" && !Buffer2.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding); - if (typeof cb !== "function") cb = nop; - } - if (chunk === null) { - throw new ERR_STREAM_NULL_VALUES(); - } else if (!state.objectMode) { - if (typeof chunk === "string") { - if (state.decodeStrings !== false) { - chunk = Buffer2.from(chunk, encoding); - encoding = "buffer"; + function final(cb) { + if (typeof this._flush === "function" && !this.destroyed) { + this._flush((er, data) => { + if (er) { + if (cb) { + cb(er); + } else { + this.destroy(er); + } + return; } - } else if (chunk instanceof Buffer2) { - encoding = "buffer"; - } else if (Stream._isUint8Array(chunk)) { - chunk = Stream._uint8ArrayToBuffer(chunk); - encoding = "buffer"; - } else { - throw new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk); + if (data != null) { + this.push(data); + } + this.push(null); + if (cb) { + cb(); + } + }); + } else { + this.push(null); + if (cb) { + cb(); } } - let err; - if (state.ending) { - err = new ERR_STREAM_WRITE_AFTER_END(); - } else if (state.destroyed) { - err = new ERR_STREAM_DESTROYED("write"); - } - if (err) { - process2.nextTick(cb, err); - errorOrDestroy(stream, err, true); - return err; + } + function prefinish() { + if (this._final !== final) { + final.call(this); } - state.pendingcb++; - return writeOrBuffer(stream, state, chunk, encoding, cb); } - Writable.prototype.write = function(chunk, encoding, cb) { - return _write(this, chunk, encoding, cb) === true; + Transform.prototype._final = final; + Transform.prototype._transform = function(chunk, encoding, callback) { + throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()"); }; - Writable.prototype.cork = function() { - this._writableState.corked++; + Transform.prototype._write = function(chunk, encoding, callback) { + const rState = this._readableState; + const wState = this._writableState; + const length = rState.length; + this._transform(chunk, encoding, (err, val2) => { + if (err) { + callback(err); + return; + } + if (val2 != null) { + this.push(val2); + } + if (wState.ended || // Backwards compat. + length === rState.length || // Backwards compat. + rState.length < rState.highWaterMark) { + callback(); + } else { + this[kCallback] = callback; + } + }); }; - Writable.prototype.uncork = function() { - const state = this._writableState; - if (state.corked) { - state.corked--; - if (!state.writing) clearBuffer(this, state); + Transform.prototype._read = function() { + if (this[kCallback]) { + const callback = this[kCallback]; + this[kCallback] = null; + callback(); } }; - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - if (typeof encoding === "string") encoding = StringPrototypeToLowerCase(encoding); - if (!Buffer2.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; + } +}); + +// node_modules/readable-stream/lib/internal/streams/passthrough.js +var require_passthrough2 = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/passthrough.js"(exports2, module2) { + "use strict"; + var { ObjectSetPrototypeOf } = require_primordials(); + module2.exports = PassThrough; + var Transform = require_transform(); + ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype); + ObjectSetPrototypeOf(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); + } + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); }; - function writeOrBuffer(stream, state, chunk, encoding, callback) { - const len = state.objectMode ? 1 : chunk.length; - state.length += len; - const ret = state.length < state.highWaterMark; - if (!ret) state.needDrain = true; - if (state.writing || state.corked || state.errored || !state.constructed) { - state.buffered.push({ - chunk, - encoding, - callback - }); - if (state.allBuffers && encoding !== "buffer") { - state.allBuffers = false; - } - if (state.allNoop && callback !== nop) { - state.allNoop = false; + } +}); + +// node_modules/readable-stream/lib/internal/streams/pipeline.js +var require_pipeline3 = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports2, module2) { + var process2 = require_process(); + var { ArrayIsArray, Promise: Promise2, SymbolAsyncIterator, SymbolDispose } = require_primordials(); + var eos = require_end_of_stream(); + var { once } = require_util12(); + var destroyImpl = require_destroy2(); + var Duplex = require_duplex(); + var { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, + ERR_INVALID_RETURN_VALUE, + ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED, + ERR_STREAM_PREMATURE_CLOSE + }, + AbortError + } = require_errors3(); + var { validateFunction, validateAbortSignal } = require_validators(); + var { + isIterable, + isReadable, + isReadableNodeStream, + isNodeStream, + isTransformStream, + isWebStream, + isReadableStream, + isReadableFinished + } = require_utils6(); + var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; + var PassThrough; + var Readable; + var addAbortListener; + function destroyer(stream, reading, writing) { + let finished = false; + stream.on("close", () => { + finished = true; + }); + const cleanup = eos( + stream, + { + readable: reading, + writable: writing + }, + (err) => { + finished = !err; } - } else { - state.writelen = len; - state.writecb = callback; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } - return ret && !state.errored && !state.destroyed; + ); + return { + destroy: (err) => { + if (finished) return; + finished = true; + destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED("pipe")); + }, + cleanup + }; } - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED("write")); - else if (writev) stream._writev(chunk, state.onwrite); - else stream._write(chunk, encoding, state.onwrite); - state.sync = false; + function popCallback(streams) { + validateFunction(streams[streams.length - 1], "streams[stream.length - 1]"); + return streams.pop(); } - function onwriteError(stream, state, er, cb) { - --state.pendingcb; - cb(er); - errorBuffer(state); - errorOrDestroy(stream, er); + function makeAsyncIterable(val2) { + if (isIterable(val2)) { + return val2; + } else if (isReadableNodeStream(val2)) { + return fromReadable(val2); + } + throw new ERR_INVALID_ARG_TYPE2("val", ["Readable", "Iterable", "AsyncIterable"], val2); } - function onwrite(stream, er) { - const state = stream._writableState; - const sync = state.sync; - const cb = state.writecb; - if (typeof cb !== "function") { - errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK()); - return; + async function* fromReadable(val2) { + if (!Readable) { + Readable = require_readable3(); } - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - if (er) { - er.stack; - if (!state.errored) { - state.errored = er; + yield* Readable.prototype[SymbolAsyncIterator].call(val2); + } + async function pumpToNode(iterable, writable, finish, { end }) { + let error4; + let onresolve = null; + const resume = (err) => { + if (err) { + error4 = err; } - if (stream._readableState && !stream._readableState.errored) { - stream._readableState.errored = er; + if (onresolve) { + const callback = onresolve; + onresolve = null; + callback(); } - if (sync) { - process2.nextTick(onwriteError, stream, state, er, cb); + }; + const wait = () => new Promise2((resolve2, reject) => { + if (error4) { + reject(error4); } else { - onwriteError(stream, state, er, cb); + onresolve = () => { + if (error4) { + reject(error4); + } else { + resolve2(); + } + }; } - } else { - if (state.buffered.length > state.bufferedIndex) { - clearBuffer(stream, state); + }); + writable.on("drain", resume); + const cleanup = eos( + writable, + { + readable: false + }, + resume + ); + try { + if (writable.writableNeedDrain) { + await wait(); } - if (sync) { - if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) { - state.afterWriteTickInfo.count++; - } else { - state.afterWriteTickInfo = { - count: 1, - cb, - stream, - state - }; - process2.nextTick(afterWriteTick, state.afterWriteTickInfo); + for await (const chunk of iterable) { + if (!writable.write(chunk)) { + await wait(); } - } else { - afterWrite(stream, state, 1, cb); } + if (end) { + writable.end(); + await wait(); + } + finish(); + } catch (err) { + finish(error4 !== err ? aggregateTwoErrors(error4, err) : err); + } finally { + cleanup(); + writable.off("drain", resume); } } - function afterWriteTick({ stream, state, count, cb }) { - state.afterWriteTickInfo = null; - return afterWrite(stream, state, count, cb); - } - function afterWrite(stream, state, count, cb) { - const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain; - if (needDrain) { - state.needDrain = false; - stream.emit("drain"); - } - while (count-- > 0) { - state.pendingcb--; - cb(); - } - if (state.destroyed) { - errorBuffer(state); - } - finishMaybe(stream, state); - } - function errorBuffer(state) { - if (state.writing) { - return; - } - for (let n = state.bufferedIndex; n < state.buffered.length; ++n) { - var _state$errored; - const { chunk, callback } = state.buffered[n]; - const len = state.objectMode ? 1 : chunk.length; - state.length -= len; - callback( - (_state$errored = state.errored) !== null && _state$errored !== void 0 ? _state$errored : new ERR_STREAM_DESTROYED("write") - ); - } - const onfinishCallbacks = state[kOnFinished].splice(0); - for (let i = 0; i < onfinishCallbacks.length; i++) { - var _state$errored2; - onfinishCallbacks[i]( - (_state$errored2 = state.errored) !== null && _state$errored2 !== void 0 ? _state$errored2 : new ERR_STREAM_DESTROYED("end") - ); - } - resetBuffer(state); - } - function clearBuffer(stream, state) { - if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) { - return; - } - const { buffered, bufferedIndex, objectMode } = state; - const bufferedLength = buffered.length - bufferedIndex; - if (!bufferedLength) { - return; + async function pumpToWeb(readable, writable, finish, { end }) { + if (isTransformStream(writable)) { + writable = writable.writable; } - let i = bufferedIndex; - state.bufferProcessing = true; - if (bufferedLength > 1 && stream._writev) { - state.pendingcb -= bufferedLength - 1; - const callback = state.allNoop ? nop : (err) => { - for (let n = i; n < buffered.length; ++n) { - buffered[n].callback(err); - } - }; - const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i); - chunks.allBuffers = state.allBuffers; - doWrite(stream, state, true, state.length, chunks, "", callback); - resetBuffer(state); - } else { - do { - const { chunk, encoding, callback } = buffered[i]; - buffered[i++] = null; - const len = objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, callback); - } while (i < buffered.length && !state.writing); - if (i === buffered.length) { - resetBuffer(state); - } else if (i > 256) { - buffered.splice(0, i); - state.bufferedIndex = 0; - } else { - state.bufferedIndex = i; + const writer = writable.getWriter(); + try { + for await (const chunk of readable) { + await writer.ready; + writer.write(chunk).catch(() => { + }); + } + await writer.ready; + if (end) { + await writer.close(); + } + finish(); + } catch (err) { + try { + await writer.abort(err); + finish(err); + } catch (err2) { + finish(err2); } } - state.bufferProcessing = false; } - Writable.prototype._write = function(chunk, encoding, cb) { - if (this._writev) { - this._writev( - [ - { - chunk, - encoding - } - ], - cb - ); - } else { - throw new ERR_METHOD_NOT_IMPLEMENTED("_write()"); + function pipeline(...streams) { + return pipelineImpl(streams, once(popCallback(streams))); + } + function pipelineImpl(streams, callback, opts) { + if (streams.length === 1 && ArrayIsArray(streams[0])) { + streams = streams[0]; } - }; - Writable.prototype._writev = null; - Writable.prototype.end = function(chunk, encoding, cb) { - const state = this._writableState; - if (typeof chunk === "function") { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === "function") { - cb = encoding; - encoding = null; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); } - let err; - if (chunk !== null && chunk !== void 0) { - const ret = _write(this, chunk, encoding); - if (ret instanceof Error2) { - err = ret; - } + const ac = new AbortController2(); + const signal = ac.signal; + const outerSignal = opts === null || opts === void 0 ? void 0 : opts.signal; + const lastStreamCleanup = []; + validateAbortSignal(outerSignal, "options.signal"); + function abort() { + finishImpl(new AbortError()); } - if (state.corked) { - state.corked = 1; - this.uncork(); + addAbortListener = addAbortListener || require_util12().addAbortListener; + let disposable; + if (outerSignal) { + disposable = addAbortListener(outerSignal, abort); } - if (err) { - } else if (!state.errored && !state.ending) { - state.ending = true; - finishMaybe(this, state, true); - state.ended = true; - } else if (state.finished) { - err = new ERR_STREAM_ALREADY_FINISHED("end"); - } else if (state.destroyed) { - err = new ERR_STREAM_DESTROYED("end"); + let error4; + let value; + const destroys = []; + let finishCount = 0; + function finish(err) { + finishImpl(err, --finishCount === 0); } - if (typeof cb === "function") { - if (err || state.finished) { - process2.nextTick(cb, err); - } else { - state[kOnFinished].push(cb); + function finishImpl(err, final) { + var _disposable; + if (err && (!error4 || error4.code === "ERR_STREAM_PREMATURE_CLOSE")) { + error4 = err; } - } - return this; - }; - function needFinish(state) { - return state.ending && !state.destroyed && state.constructed && state.length === 0 && !state.errored && state.buffered.length === 0 && !state.finished && !state.writing && !state.errorEmitted && !state.closeEmitted; - } - function callFinal(stream, state) { - let called = false; - function onFinish(err) { - if (called) { - errorOrDestroy(stream, err !== null && err !== void 0 ? err : ERR_MULTIPLE_CALLBACK()); + if (!error4 && !final) { return; } - called = true; - state.pendingcb--; - if (err) { - const onfinishCallbacks = state[kOnFinished].splice(0); - for (let i = 0; i < onfinishCallbacks.length; i++) { - onfinishCallbacks[i](err); + while (destroys.length) { + destroys.shift()(error4); + } + ; + (_disposable = disposable) === null || _disposable === void 0 ? void 0 : _disposable[SymbolDispose](); + ac.abort(); + if (final) { + if (!error4) { + lastStreamCleanup.forEach((fn) => fn()); } - errorOrDestroy(stream, err, state.sync); - } else if (needFinish(state)) { - state.prefinished = true; - stream.emit("prefinish"); - state.pendingcb++; - process2.nextTick(finish, stream, state); + process2.nextTick(callback, error4, value); } } - state.sync = true; - state.pendingcb++; - try { - stream._final(onFinish); - } catch (err) { - onFinish(err); - } - state.sync = false; - } - function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === "function" && !state.destroyed) { - state.finalCalled = true; - callFinal(stream, state); - } else { - state.prefinished = true; - stream.emit("prefinish"); + let ret; + for (let i = 0; i < streams.length; i++) { + const stream = streams[i]; + const reading = i < streams.length - 1; + const writing = i > 0; + const end = reading || (opts === null || opts === void 0 ? void 0 : opts.end) !== false; + const isLastStream = i === streams.length - 1; + if (isNodeStream(stream)) { + let onError2 = function(err) { + if (err && err.name !== "AbortError" && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + finish(err); + } + }; + var onError = onError2; + if (end) { + const { destroy, cleanup } = destroyer(stream, reading, writing); + destroys.push(destroy); + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(cleanup); + } + } + stream.on("error", onError2); + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(() => { + stream.removeListener("error", onError2); + }); + } } - } - } - function finishMaybe(stream, state, sync) { - if (needFinish(state)) { - prefinish(stream, state); - if (state.pendingcb === 0) { - if (sync) { - state.pendingcb++; - process2.nextTick( - (stream2, state2) => { - if (needFinish(state2)) { - finish(stream2, state2); - } else { - state2.pendingcb--; + if (i === 0) { + if (typeof stream === "function") { + ret = stream({ + signal + }); + if (!isIterable(ret)) { + throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or Stream", "source", ret); + } + } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) { + ret = stream; + } else { + ret = Duplex.from(stream); + } + } else if (typeof stream === "function") { + if (isTransformStream(ret)) { + var _ret; + ret = makeAsyncIterable((_ret = ret) === null || _ret === void 0 ? void 0 : _ret.readable); + } else { + ret = makeAsyncIterable(ret); + } + ret = stream(ret, { + signal + }); + if (reading) { + if (!isIterable(ret, true)) { + throw new ERR_INVALID_RETURN_VALUE("AsyncIterable", `transform[${i - 1}]`, ret); + } + } else { + var _ret2; + if (!PassThrough) { + PassThrough = require_passthrough2(); + } + const pt = new PassThrough({ + objectMode: true + }); + const then = (_ret2 = ret) === null || _ret2 === void 0 ? void 0 : _ret2.then; + if (typeof then === "function") { + finishCount++; + then.call( + ret, + (val2) => { + value = val2; + if (val2 != null) { + pt.write(val2); + } + if (end) { + pt.end(); + } + process2.nextTick(finish); + }, + (err) => { + pt.destroy(err); + process2.nextTick(finish, err); } - }, - stream, - state + ); + } else if (isIterable(ret, true)) { + finishCount++; + pumpToNode(ret, pt, finish, { + end + }); + } else if (isReadableStream(ret) || isTransformStream(ret)) { + const toRead = ret.readable || ret; + finishCount++; + pumpToNode(toRead, pt, finish, { + end + }); + } else { + throw new ERR_INVALID_RETURN_VALUE("AsyncIterable or Promise", "destination", ret); + } + ret = pt; + const { destroy, cleanup } = destroyer(ret, false, true); + destroys.push(destroy); + if (isLastStream) { + lastStreamCleanup.push(cleanup); + } + } + } else if (isNodeStream(stream)) { + if (isReadableNodeStream(ret)) { + finishCount += 2; + const cleanup = pipe(ret, stream, finish, { + end + }); + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(cleanup); + } + } else if (isTransformStream(ret) || isReadableStream(ret)) { + const toRead = ret.readable || ret; + finishCount++; + pumpToNode(toRead, stream, finish, { + end + }); + } else if (isIterable(ret)) { + finishCount++; + pumpToNode(ret, stream, finish, { + end + }); + } else { + throw new ERR_INVALID_ARG_TYPE2( + "val", + ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"], + ret ); - } else if (needFinish(state)) { - state.pendingcb++; - finish(stream, state); } + ret = stream; + } else if (isWebStream(stream)) { + if (isReadableNodeStream(ret)) { + finishCount++; + pumpToWeb(makeAsyncIterable(ret), stream, finish, { + end + }); + } else if (isReadableStream(ret) || isIterable(ret)) { + finishCount++; + pumpToWeb(ret, stream, finish, { + end + }); + } else if (isTransformStream(ret)) { + finishCount++; + pumpToWeb(ret.readable, stream, finish, { + end + }); + } else { + throw new ERR_INVALID_ARG_TYPE2( + "val", + ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"], + ret + ); + } + ret = stream; + } else { + ret = Duplex.from(stream); } } + if (signal !== null && signal !== void 0 && signal.aborted || outerSignal !== null && outerSignal !== void 0 && outerSignal.aborted) { + process2.nextTick(abort); + } + return ret; } - function finish(stream, state) { - state.pendingcb--; - state.finished = true; - const onfinishCallbacks = state[kOnFinished].splice(0); - for (let i = 0; i < onfinishCallbacks.length; i++) { - onfinishCallbacks[i](); - } - stream.emit("finish"); - if (state.autoDestroy) { - const rState = stream._readableState; - const autoDestroy = !rState || rState.autoDestroy && // We don't expect the readable to ever 'end' - // if readable is explicitly set to false. - (rState.endEmitted || rState.readable === false); - if (autoDestroy) { - stream.destroy(); - } - } - } - ObjectDefineProperties(Writable.prototype, { - closed: { - __proto__: null, - get() { - return this._writableState ? this._writableState.closed : false; + function pipe(src, dst, finish, { end }) { + let ended = false; + dst.on("close", () => { + if (!ended) { + finish(new ERR_STREAM_PREMATURE_CLOSE()); } - }, - destroyed: { - __proto__: null, - get() { - return this._writableState ? this._writableState.destroyed : false; - }, - set(value) { - if (this._writableState) { - this._writableState.destroyed = value; - } + }); + src.pipe(dst, { + end: false + }); + if (end) { + let endFn2 = function() { + ended = true; + dst.end(); + }; + var endFn = endFn2; + if (isReadableFinished(src)) { + process2.nextTick(endFn2); + } else { + src.once("end", endFn2); } - }, - writable: { - __proto__: null, - get() { - const w = this._writableState; - return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended; + } else { + finish(); + } + eos( + src, + { + readable: true, + writable: false }, - set(val2) { - if (this._writableState) { - this._writableState.writable = !!val2; + (err) => { + const rState = src._readableState; + if (err && err.code === "ERR_STREAM_PREMATURE_CLOSE" && rState && rState.ended && !rState.errored && !rState.errorEmitted) { + src.once("end", finish).once("error", finish); + } else { + finish(err); } } - }, - writableFinished: { - __proto__: null, - get() { - return this._writableState ? this._writableState.finished : false; - } - }, - writableObjectMode: { - __proto__: null, - get() { - return this._writableState ? this._writableState.objectMode : false; - } - }, - writableBuffer: { - __proto__: null, - get() { - return this._writableState && this._writableState.getBuffer(); - } - }, - writableEnded: { - __proto__: null, - get() { - return this._writableState ? this._writableState.ending : false; - } - }, - writableNeedDrain: { - __proto__: null, - get() { - const wState = this._writableState; - if (!wState) return false; - return !wState.destroyed && !wState.ending && wState.needDrain; - } - }, - writableHighWaterMark: { - __proto__: null, - get() { - return this._writableState && this._writableState.highWaterMark; - } - }, - writableCorked: { - __proto__: null, - get() { - return this._writableState ? this._writableState.corked : 0; - } - }, - writableLength: { - __proto__: null, - get() { - return this._writableState && this._writableState.length; - } - }, - errored: { - __proto__: null, - enumerable: false, - get() { - return this._writableState ? this._writableState.errored : null; - } - }, - writableAborted: { - __proto__: null, - enumerable: false, - get: function() { - return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished); - } - } - }); - var destroy = destroyImpl.destroy; - Writable.prototype.destroy = function(err, cb) { - const state = this._writableState; - if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) { - process2.nextTick(errorBuffer, state); - } - destroy.call(this, err, cb); - return this; - }; - Writable.prototype._undestroy = destroyImpl.undestroy; - Writable.prototype._destroy = function(err, cb) { - cb(err); - }; - Writable.prototype[EE.captureRejectionSymbol] = function(err) { - this.destroy(err); - }; - var webStreamsAdapters; - function lazyWebStreams() { - if (webStreamsAdapters === void 0) webStreamsAdapters = {}; - return webStreamsAdapters; + ); + return eos( + dst, + { + readable: false, + writable: true + }, + finish + ); } - Writable.fromWeb = function(writableStream, options) { - return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options); - }; - Writable.toWeb = function(streamWritable) { - return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable); + module2.exports = { + pipelineImpl, + pipeline }; } }); -// node_modules/readable-stream/lib/internal/streams/duplexify.js -var require_duplexify = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/duplexify.js"(exports2, module2) { - var process2 = require_process(); - var bufferModule = require("buffer"); +// node_modules/readable-stream/lib/internal/streams/compose.js +var require_compose = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/compose.js"(exports2, module2) { + "use strict"; + var { pipeline } = require_pipeline3(); + var Duplex = require_duplex(); + var { destroyer } = require_destroy2(); var { + isNodeStream, isReadable, isWritable, - isIterable, - isNodeStream, - isReadableNodeStream, - isWritableNodeStream, - isDuplexNodeStream, - isReadableStream, - isWritableStream + isWebStream, + isTransformStream, + isWritableStream, + isReadableStream } = require_utils6(); - var eos = require_end_of_stream(); var { AbortError, - codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_RETURN_VALUE } + codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } } = require_errors3(); - var { destroyer } = require_destroy2(); - var Duplex = require_duplex(); - var Readable = require_readable3(); - var Writable = require_writable(); - var { createDeferredPromise } = require_util12(); - var from = require_from(); - var Blob2 = globalThis.Blob || bufferModule.Blob; - var isBlob = typeof Blob2 !== "undefined" ? function isBlob2(b) { - return b instanceof Blob2; - } : function isBlob2(b) { - return false; - }; - var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; - var { FunctionPrototypeCall } = require_primordials(); - var Duplexify = class extends Duplex { - constructor(options) { - super(options); - if ((options === null || options === void 0 ? void 0 : options.readable) === false) { - this._readableState.readable = false; - this._readableState.ended = true; - this._readableState.endEmitted = true; - } - if ((options === null || options === void 0 ? void 0 : options.writable) === false) { - this._writableState.writable = false; - this._writableState.ending = true; - this._writableState.ended = true; - this._writableState.finished = true; - } - } - }; - module2.exports = function duplexify(body, name) { - if (isDuplexNodeStream(body)) { - return body; - } - if (isReadableNodeStream(body)) { - return _duplexify({ - readable: body - }); - } - if (isWritableNodeStream(body)) { - return _duplexify({ - writable: body - }); + var eos = require_end_of_stream(); + module2.exports = function compose(...streams) { + if (streams.length === 0) { + throw new ERR_MISSING_ARGS("streams"); } - if (isNodeStream(body)) { - return _duplexify({ - writable: false, - readable: false - }); + if (streams.length === 1) { + return Duplex.from(streams[0]); } - if (isReadableStream(body)) { - return _duplexify({ - readable: Readable.fromWeb(body) - }); + const orgStreams = [...streams]; + if (typeof streams[0] === "function") { + streams[0] = Duplex.from(streams[0]); } - if (isWritableStream(body)) { - return _duplexify({ - writable: Writable.fromWeb(body) - }); + if (typeof streams[streams.length - 1] === "function") { + const idx = streams.length - 1; + streams[idx] = Duplex.from(streams[idx]); } - if (typeof body === "function") { - const { value, write, final, destroy } = fromAsyncGen(body); - if (isIterable(value)) { - return from(Duplexify, value, { - // TODO (ronag): highWaterMark? - objectMode: true, - write, - final, - destroy - }); - } - const then2 = value === null || value === void 0 ? void 0 : value.then; - if (typeof then2 === "function") { - let d; - const promise = FunctionPrototypeCall( - then2, - value, - (val2) => { - if (val2 != null) { - throw new ERR_INVALID_RETURN_VALUE("nully", "body", val2); - } - }, - (err) => { - destroyer(d, err); - } - ); - return d = new Duplexify({ - // TODO (ronag): highWaterMark? - objectMode: true, - readable: false, - write, - final(cb) { - final(async () => { - try { - await promise; - process2.nextTick(cb, null); - } catch (err) { - process2.nextTick(cb, err); - } - }); - }, - destroy - }); + for (let n = 0; n < streams.length; ++n) { + if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { + continue; } - throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or AsyncFunction", name, value); - } - if (isBlob(body)) { - return duplexify(body.arrayBuffer()); - } - if (isIterable(body)) { - return from(Duplexify, body, { - // TODO (ronag): highWaterMark? - objectMode: true, - writable: false - }); - } - if (isReadableStream(body === null || body === void 0 ? void 0 : body.readable) && isWritableStream(body === null || body === void 0 ? void 0 : body.writable)) { - return Duplexify.fromWeb(body); - } - if (typeof (body === null || body === void 0 ? void 0 : body.writable) === "object" || typeof (body === null || body === void 0 ? void 0 : body.readable) === "object") { - const readable = body !== null && body !== void 0 && body.readable ? isReadableNodeStream(body === null || body === void 0 ? void 0 : body.readable) ? body === null || body === void 0 ? void 0 : body.readable : duplexify(body.readable) : void 0; - const writable = body !== null && body !== void 0 && body.writable ? isWritableNodeStream(body === null || body === void 0 ? void 0 : body.writable) ? body === null || body === void 0 ? void 0 : body.writable : duplexify(body.writable) : void 0; - return _duplexify({ - readable, - writable - }); - } - const then = body === null || body === void 0 ? void 0 : body.then; - if (typeof then === "function") { - let d; - FunctionPrototypeCall( - then, - body, - (val2) => { - if (val2 != null) { - d.push(val2); - } - d.push(null); - }, - (err) => { - destroyer(d, err); - } - ); - return d = new Duplexify({ - objectMode: true, - writable: false, - read() { - } - }); - } - throw new ERR_INVALID_ARG_TYPE2( - name, - [ - "Blob", - "ReadableStream", - "WritableStream", - "Stream", - "Iterable", - "AsyncIterable", - "Function", - "{ readable, writable } pair", - "Promise" - ], - body - ); - }; - function fromAsyncGen(fn) { - let { promise, resolve: resolve2 } = createDeferredPromise(); - const ac = new AbortController2(); - const signal = ac.signal; - const value = fn( - (async function* () { - while (true) { - const _promise = promise; - promise = null; - const { chunk, done, cb } = await _promise; - process2.nextTick(cb); - if (done) return; - if (signal.aborted) - throw new AbortError(void 0, { - cause: signal.reason - }); - ({ promise, resolve: resolve2 } = createDeferredPromise()); - yield chunk; - } - })(), - { - signal + if (n < streams.length - 1 && !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], "must be readable"); } - ); - return { - value, - write(chunk, encoding, cb) { - const _resolve = resolve2; - resolve2 = null; - _resolve({ - chunk, - done: false, - cb - }); - }, - final(cb) { - const _resolve = resolve2; - resolve2 = null; - _resolve({ - done: true, - cb - }); - }, - destroy(err, cb) { - ac.abort(); - cb(err); + if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], "must be writable"); } - }; - } - function _duplexify(pair) { - const r = pair.readable && typeof pair.readable.read !== "function" ? Readable.wrap(pair.readable) : pair.readable; - const w = pair.writable; - let readable = !!isReadable(r); - let writable = !!isWritable(w); + } let ondrain; let onfinish; let onreadable; @@ -81341,42 +83666,67 @@ var require_duplexify = __commonJS({ cb(err); } else if (err) { d.destroy(err); + } else if (!readable && !writable) { + d.destroy(); } } - d = new Duplexify({ + const head = streams[0]; + const tail = pipeline(streams, onfinished); + const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)); + const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)); + d = new Duplex({ // TODO (ronag): highWaterMark? - readableObjectMode: !!(r !== null && r !== void 0 && r.readableObjectMode), - writableObjectMode: !!(w !== null && w !== void 0 && w.writableObjectMode), - readable, - writable + writableObjectMode: !!(head !== null && head !== void 0 && head.writableObjectMode), + readableObjectMode: !!(tail !== null && tail !== void 0 && tail.readableObjectMode), + writable, + readable }); if (writable) { - eos(w, (err) => { - writable = false; - if (err) { - destroyer(r, err); - } - onfinished(err); - }); - d._write = function(chunk, encoding, callback) { - if (w.write(chunk, encoding)) { - callback(); - } else { - ondrain = callback; - } - }; - d._final = function(callback) { - w.end(); - onfinish = callback; - }; - w.on("drain", function() { - if (ondrain) { - const cb = ondrain; - ondrain = null; - cb(); - } - }); - w.on("finish", function() { + if (isNodeStream(head)) { + d._write = function(chunk, encoding, callback) { + if (head.write(chunk, encoding)) { + callback(); + } else { + ondrain = callback; + } + }; + d._final = function(callback) { + head.end(); + onfinish = callback; + }; + head.on("drain", function() { + if (ondrain) { + const cb = ondrain; + ondrain = null; + cb(); + } + }); + } else if (isWebStream(head)) { + const writable2 = isTransformStream(head) ? head.writable : head; + const writer = writable2.getWriter(); + d._write = async function(chunk, encoding, callback) { + try { + await writer.ready; + writer.write(chunk).catch(() => { + }); + callback(); + } catch (err) { + callback(err); + } + }; + d._final = async function(callback) { + try { + await writer.ready; + writer.close().catch(() => { + }); + onfinish = callback; + } catch (err) { + callback(err); + } + }; + } + const toRead = isTransformStream(tail) ? tail.readable : tail; + eos(toRead, () => { if (onfinish) { const cb = onfinish; onfinish = null; @@ -81385,35 +83735,49 @@ var require_duplexify = __commonJS({ }); } if (readable) { - eos(r, (err) => { - readable = false; - if (err) { - destroyer(r, err); - } - onfinished(err); - }); - r.on("readable", function() { - if (onreadable) { - const cb = onreadable; - onreadable = null; - cb(); - } - }); - r.on("end", function() { - d.push(null); - }); - d._read = function() { - while (true) { - const buf = r.read(); - if (buf === null) { - onreadable = d._read; - return; + if (isNodeStream(tail)) { + tail.on("readable", function() { + if (onreadable) { + const cb = onreadable; + onreadable = null; + cb(); } - if (!d.push(buf)) { - return; + }); + tail.on("end", function() { + d.push(null); + }); + d._read = function() { + while (true) { + const buf = tail.read(); + if (buf === null) { + onreadable = d._read; + return; + } + if (!d.push(buf)) { + return; + } } - } - }; + }; + } else if (isWebStream(tail)) { + const readable2 = isTransformStream(tail) ? tail.readable : tail; + const reader = readable2.getReader(); + d._read = async function() { + while (true) { + try { + const { value, done } = await reader.read(); + if (!d.push(value)) { + return; + } + if (done) { + d.push(null); + return; + } + } catch { + return; + } + } + }; + } } d._destroy = function(err, callback) { if (!err && onclose !== null) { @@ -81426,13827 +83790,16121 @@ var require_duplexify = __commonJS({ callback(err); } else { onclose = callback; - destroyer(w, err); - destroyer(r, err); + if (isNodeStream(tail)) { + destroyer(tail, err); + } } }; return d; - } + }; } }); -// node_modules/readable-stream/lib/internal/streams/duplex.js -var require_duplex = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/duplex.js"(exports2, module2) { +// node_modules/readable-stream/lib/internal/streams/operators.js +var require_operators = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/operators.js"(exports2, module2) { "use strict"; + var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; var { - ObjectDefineProperties, - ObjectGetOwnPropertyDescriptor, - ObjectKeys, - ObjectSetPrototypeOf + codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, + AbortError + } = require_errors3(); + var { validateAbortSignal, validateInteger, validateObject } = require_validators(); + var kWeakHandler = require_primordials().Symbol("kWeak"); + var kResistStopPropagation = require_primordials().Symbol("kResistStopPropagation"); + var { finished } = require_end_of_stream(); + var staticCompose = require_compose(); + var { addAbortSignalNoValidate } = require_add_abort_signal(); + var { isWritable, isNodeStream } = require_utils6(); + var { deprecate } = require_util12(); + var { + ArrayPrototypePush, + Boolean: Boolean2, + MathFloor, + Number: Number2, + NumberIsNaN, + Promise: Promise2, + PromiseReject, + PromiseResolve, + PromisePrototypeThen, + Symbol: Symbol2 } = require_primordials(); - module2.exports = Duplex; - var Readable = require_readable3(); - var Writable = require_writable(); - ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype); - ObjectSetPrototypeOf(Duplex, Readable); - { - const keys = ObjectKeys(Writable.prototype); - for (let i = 0; i < keys.length; i++) { - const method = keys[i]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + var kEmpty = Symbol2("kEmpty"); + var kEof = Symbol2("kEof"); + function compose(stream, options) { + if (options != null) { + validateObject(options, "options"); } - } - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - if (options) { - this.allowHalfOpen = options.allowHalfOpen !== false; - if (options.readable === false) { - this._readableState.readable = false; - this._readableState.ended = true; - this._readableState.endEmitted = true; - } - if (options.writable === false) { - this._writableState.writable = false; - this._writableState.ending = true; - this._writableState.ended = true; - this._writableState.finished = true; - } - } else { - this.allowHalfOpen = true; + if ((options === null || options === void 0 ? void 0 : options.signal) != null) { + validateAbortSignal(options.signal, "options.signal"); } - } - ObjectDefineProperties(Duplex.prototype, { - writable: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writable") - }, - writableHighWaterMark: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableHighWaterMark") - }, - writableObjectMode: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableObjectMode") - }, - writableBuffer: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableBuffer") - }, - writableLength: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableLength") - }, - writableFinished: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableFinished") - }, - writableCorked: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableCorked") - }, - writableEnded: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableEnded") - }, - writableNeedDrain: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableNeedDrain") - }, - destroyed: { - __proto__: null, - get() { - if (this._readableState === void 0 || this._writableState === void 0) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set(value) { - if (this._readableState && this._writableState) { - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - } + if (isNodeStream(stream) && !isWritable(stream)) { + throw new ERR_INVALID_ARG_VALUE("stream", stream, "must be writable"); } - }); - var webStreamsAdapters; - function lazyWebStreams() { - if (webStreamsAdapters === void 0) webStreamsAdapters = {}; - return webStreamsAdapters; + const composedStream = staticCompose(this, stream); + if (options !== null && options !== void 0 && options.signal) { + addAbortSignalNoValidate(options.signal, composedStream); + } + return composedStream; } - Duplex.fromWeb = function(pair, options) { - return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options); - }; - Duplex.toWeb = function(duplex) { - return lazyWebStreams().newReadableWritablePairFromDuplex(duplex); - }; - var duplexify; - Duplex.from = function(body) { - if (!duplexify) { - duplexify = require_duplexify(); + function map2(fn, options) { + if (typeof fn !== "function") { + throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); } - return duplexify(body, "body"); - }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/transform.js -var require_transform = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/transform.js"(exports2, module2) { - "use strict"; - var { ObjectSetPrototypeOf, Symbol: Symbol2 } = require_primordials(); - module2.exports = Transform; - var { ERR_METHOD_NOT_IMPLEMENTED } = require_errors3().codes; - var Duplex = require_duplex(); - var { getHighWaterMark } = require_state3(); - ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype); - ObjectSetPrototypeOf(Transform, Duplex); - var kCallback = Symbol2("kCallback"); - function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - const readableHighWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", true) : null; - if (readableHighWaterMark === 0) { - options = { - ...options, - highWaterMark: null, - readableHighWaterMark, - // TODO (ronag): 0 is not optimal since we have - // a "bug" where we check needDrain before calling _write and not after. - // Refs: https://github.com/nodejs/node/pull/32887 - // Refs: https://github.com/nodejs/node/pull/35941 - writableHighWaterMark: options.writableHighWaterMark || 0 - }; + if (options != null) { + validateObject(options, "options"); } - Duplex.call(this, options); - this._readableState.sync = false; - this[kCallback] = null; - if (options) { - if (typeof options.transform === "function") this._transform = options.transform; - if (typeof options.flush === "function") this._flush = options.flush; + if ((options === null || options === void 0 ? void 0 : options.signal) != null) { + validateAbortSignal(options.signal, "options.signal"); } - this.on("prefinish", prefinish); - } - function final(cb) { - if (typeof this._flush === "function" && !this.destroyed) { - this._flush((er, data) => { - if (er) { - if (cb) { - cb(er); - } else { - this.destroy(er); + let concurrency = 1; + if ((options === null || options === void 0 ? void 0 : options.concurrency) != null) { + concurrency = MathFloor(options.concurrency); + } + let highWaterMark = concurrency - 1; + if ((options === null || options === void 0 ? void 0 : options.highWaterMark) != null) { + highWaterMark = MathFloor(options.highWaterMark); + } + validateInteger(concurrency, "options.concurrency", 1); + validateInteger(highWaterMark, "options.highWaterMark", 0); + highWaterMark += concurrency; + return async function* map3() { + const signal = require_util12().AbortSignalAny( + [options === null || options === void 0 ? void 0 : options.signal].filter(Boolean2) + ); + const stream = this; + const queue = []; + const signalOpt = { + signal + }; + let next; + let resume; + let done = false; + let cnt = 0; + function onCatch() { + done = true; + afterItemProcessed(); + } + function afterItemProcessed() { + cnt -= 1; + maybeResume(); + } + function maybeResume() { + if (resume && !done && cnt < concurrency && queue.length < highWaterMark) { + resume(); + resume = null; + } + } + async function pump() { + try { + for await (let val2 of stream) { + if (done) { + return; + } + if (signal.aborted) { + throw new AbortError(); + } + try { + val2 = fn(val2, signalOpt); + if (val2 === kEmpty) { + continue; + } + val2 = PromiseResolve(val2); + } catch (err) { + val2 = PromiseReject(err); + } + cnt += 1; + PromisePrototypeThen(val2, afterItemProcessed, onCatch); + queue.push(val2); + if (next) { + next(); + next = null; + } + if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) { + await new Promise2((resolve2) => { + resume = resolve2; + }); + } + } + queue.push(kEof); + } catch (err) { + const val2 = PromiseReject(err); + PromisePrototypeThen(val2, afterItemProcessed, onCatch); + queue.push(val2); + } finally { + done = true; + if (next) { + next(); + next = null; } - return; } - if (data != null) { - this.push(data); + } + pump(); + try { + while (true) { + while (queue.length > 0) { + const val2 = await queue[0]; + if (val2 === kEof) { + return; + } + if (signal.aborted) { + throw new AbortError(); + } + if (val2 !== kEmpty) { + yield val2; + } + queue.shift(); + maybeResume(); + } + await new Promise2((resolve2) => { + next = resolve2; + }); } - this.push(null); - if (cb) { - cb(); + } finally { + done = true; + if (resume) { + resume(); + resume = null; } - }); - } else { - this.push(null); - if (cb) { - cb(); } - } + }.call(this); } - function prefinish() { - if (this._final !== final) { - final.call(this); + function asIndexedPairs(options = void 0) { + if (options != null) { + validateObject(options, "options"); } - } - Transform.prototype._final = final; - Transform.prototype._transform = function(chunk, encoding, callback) { - throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()"); - }; - Transform.prototype._write = function(chunk, encoding, callback) { - const rState = this._readableState; - const wState = this._writableState; - const length = rState.length; - this._transform(chunk, encoding, (err, val2) => { - if (err) { - callback(err); - return; - } - if (val2 != null) { - this.push(val2); - } - if (wState.ended || // Backwards compat. - length === rState.length || // Backwards compat. - rState.length < rState.highWaterMark) { - callback(); - } else { - this[kCallback] = callback; - } - }); - }; - Transform.prototype._read = function() { - if (this[kCallback]) { - const callback = this[kCallback]; - this[kCallback] = null; - callback(); + if ((options === null || options === void 0 ? void 0 : options.signal) != null) { + validateAbortSignal(options.signal, "options.signal"); } - }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/passthrough.js -var require_passthrough2 = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/passthrough.js"(exports2, module2) { - "use strict"; - var { ObjectSetPrototypeOf } = require_primordials(); - module2.exports = PassThrough; - var Transform = require_transform(); - ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype); - ObjectSetPrototypeOf(PassThrough, Transform); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); - } - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); - }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/pipeline.js -var require_pipeline3 = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports2, module2) { - var process2 = require_process(); - var { ArrayIsArray, Promise: Promise2, SymbolAsyncIterator, SymbolDispose } = require_primordials(); - var eos = require_end_of_stream(); - var { once } = require_util12(); - var destroyImpl = require_destroy2(); - var Duplex = require_duplex(); - var { - aggregateTwoErrors, - codes: { - ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, - ERR_INVALID_RETURN_VALUE, - ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED, - ERR_STREAM_PREMATURE_CLOSE - }, - AbortError - } = require_errors3(); - var { validateFunction, validateAbortSignal } = require_validators(); - var { - isIterable, - isReadable, - isReadableNodeStream, - isNodeStream, - isTransformStream, - isWebStream, - isReadableStream, - isReadableFinished - } = require_utils6(); - var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; - var PassThrough; - var Readable; - var addAbortListener; - function destroyer(stream, reading, writing) { - let finished = false; - stream.on("close", () => { - finished = true; - }); - const cleanup = eos( - stream, - { - readable: reading, - writable: writing - }, - (err) => { - finished = !err; + return async function* asIndexedPairs2() { + let index = 0; + for await (const val2 of this) { + var _options$signal; + if (options !== null && options !== void 0 && (_options$signal = options.signal) !== null && _options$signal !== void 0 && _options$signal.aborted) { + throw new AbortError({ + cause: options.signal.reason + }); + } + yield [index++, val2]; } - ); - return { - destroy: (err) => { - if (finished) return; - finished = true; - destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED("pipe")); - }, - cleanup - }; + }.call(this); } - function popCallback(streams) { - validateFunction(streams[streams.length - 1], "streams[stream.length - 1]"); - return streams.pop(); + async function some(fn, options = void 0) { + for await (const unused of filter.call(this, fn, options)) { + return true; + } + return false; } - function makeAsyncIterable(val2) { - if (isIterable(val2)) { - return val2; - } else if (isReadableNodeStream(val2)) { - return fromReadable(val2); + async function every(fn, options = void 0) { + if (typeof fn !== "function") { + throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); } - throw new ERR_INVALID_ARG_TYPE2("val", ["Readable", "Iterable", "AsyncIterable"], val2); + return !await some.call( + this, + async (...args) => { + return !await fn(...args); + }, + options + ); } - async function* fromReadable(val2) { - if (!Readable) { - Readable = require_readable3(); + async function find2(fn, options) { + for await (const result of filter.call(this, fn, options)) { + return result; } - yield* Readable.prototype[SymbolAsyncIterator].call(val2); + return void 0; } - async function pumpToNode(iterable, writable, finish, { end }) { - let error4; - let onresolve = null; - const resume = (err) => { - if (err) { - error4 = err; - } - if (onresolve) { - const callback = onresolve; - onresolve = null; - callback(); - } - }; - const wait = () => new Promise2((resolve2, reject) => { - if (error4) { - reject(error4); - } else { - onresolve = () => { - if (error4) { - reject(error4); - } else { - resolve2(); - } - }; + async function forEach(fn, options) { + if (typeof fn !== "function") { + throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); + } + async function forEachFn(value, options2) { + await fn(value, options2); + return kEmpty; + } + for await (const unused of map2.call(this, forEachFn, options)) ; + } + function filter(fn, options) { + if (typeof fn !== "function") { + throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); + } + async function filterFn(value, options2) { + if (await fn(value, options2)) { + return value; } - }); - writable.on("drain", resume); - const cleanup = eos( - writable, - { - readable: false - }, - resume - ); + return kEmpty; + } + return map2.call(this, filterFn, options); + } + var ReduceAwareErrMissingArgs = class extends ERR_MISSING_ARGS { + constructor() { + super("reduce"); + this.message = "Reduce of an empty stream requires an initial value"; + } + }; + async function reduce(reducer, initialValue, options) { + var _options$signal2; + if (typeof reducer !== "function") { + throw new ERR_INVALID_ARG_TYPE2("reducer", ["Function", "AsyncFunction"], reducer); + } + if (options != null) { + validateObject(options, "options"); + } + if ((options === null || options === void 0 ? void 0 : options.signal) != null) { + validateAbortSignal(options.signal, "options.signal"); + } + let hasInitialValue = arguments.length > 1; + if (options !== null && options !== void 0 && (_options$signal2 = options.signal) !== null && _options$signal2 !== void 0 && _options$signal2.aborted) { + const err = new AbortError(void 0, { + cause: options.signal.reason + }); + this.once("error", () => { + }); + await finished(this.destroy(err)); + throw err; + } + const ac = new AbortController2(); + const signal = ac.signal; + if (options !== null && options !== void 0 && options.signal) { + const opts = { + once: true, + [kWeakHandler]: this, + [kResistStopPropagation]: true + }; + options.signal.addEventListener("abort", () => ac.abort(), opts); + } + let gotAnyItemFromStream = false; try { - if (writable.writableNeedDrain) { - await wait(); - } - for await (const chunk of iterable) { - if (!writable.write(chunk)) { - await wait(); + for await (const value of this) { + var _options$signal3; + gotAnyItemFromStream = true; + if (options !== null && options !== void 0 && (_options$signal3 = options.signal) !== null && _options$signal3 !== void 0 && _options$signal3.aborted) { + throw new AbortError(); + } + if (!hasInitialValue) { + initialValue = value; + hasInitialValue = true; + } else { + initialValue = await reducer(initialValue, value, { + signal + }); } } - if (end) { - writable.end(); - await wait(); + if (!gotAnyItemFromStream && !hasInitialValue) { + throw new ReduceAwareErrMissingArgs(); } - finish(); - } catch (err) { - finish(error4 !== err ? aggregateTwoErrors(error4, err) : err); } finally { - cleanup(); - writable.off("drain", resume); + ac.abort(); } + return initialValue; } - async function pumpToWeb(readable, writable, finish, { end }) { - if (isTransformStream(writable)) { - writable = writable.writable; + async function toArray2(options) { + if (options != null) { + validateObject(options, "options"); } - const writer = writable.getWriter(); - try { - for await (const chunk of readable) { - await writer.ready; - writer.write(chunk).catch(() => { + if ((options === null || options === void 0 ? void 0 : options.signal) != null) { + validateAbortSignal(options.signal, "options.signal"); + } + const result = []; + for await (const val2 of this) { + var _options$signal4; + if (options !== null && options !== void 0 && (_options$signal4 = options.signal) !== null && _options$signal4 !== void 0 && _options$signal4.aborted) { + throw new AbortError(void 0, { + cause: options.signal.reason }); } - await writer.ready; - if (end) { - await writer.close(); - } - finish(); - } catch (err) { - try { - await writer.abort(err); - finish(err); - } catch (err2) { - finish(err2); - } + ArrayPrototypePush(result, val2); } + return result; } - function pipeline(...streams) { - return pipelineImpl(streams, once(popCallback(streams))); + function flatMap(fn, options) { + const values = map2.call(this, fn, options); + return async function* flatMap2() { + for await (const val2 of values) { + yield* val2; + } + }.call(this); } - function pipelineImpl(streams, callback, opts) { - if (streams.length === 1 && ArrayIsArray(streams[0])) { - streams = streams[0]; - } - if (streams.length < 2) { - throw new ERR_MISSING_ARGS("streams"); + function toIntegerOrInfinity(number) { + number = Number2(number); + if (NumberIsNaN(number)) { + return 0; } - const ac = new AbortController2(); - const signal = ac.signal; - const outerSignal = opts === null || opts === void 0 ? void 0 : opts.signal; - const lastStreamCleanup = []; - validateAbortSignal(outerSignal, "options.signal"); - function abort() { - finishImpl(new AbortError()); + if (number < 0) { + throw new ERR_OUT_OF_RANGE("number", ">= 0", number); } - addAbortListener = addAbortListener || require_util12().addAbortListener; - let disposable; - if (outerSignal) { - disposable = addAbortListener(outerSignal, abort); + return number; + } + function drop(number, options = void 0) { + if (options != null) { + validateObject(options, "options"); } - let error4; - let value; - const destroys = []; - let finishCount = 0; - function finish(err) { - finishImpl(err, --finishCount === 0); + if ((options === null || options === void 0 ? void 0 : options.signal) != null) { + validateAbortSignal(options.signal, "options.signal"); } - function finishImpl(err, final) { - var _disposable; - if (err && (!error4 || error4.code === "ERR_STREAM_PREMATURE_CLOSE")) { - error4 = err; - } - if (!error4 && !final) { - return; - } - while (destroys.length) { - destroys.shift()(error4); + number = toIntegerOrInfinity(number); + return async function* drop2() { + var _options$signal5; + if (options !== null && options !== void 0 && (_options$signal5 = options.signal) !== null && _options$signal5 !== void 0 && _options$signal5.aborted) { + throw new AbortError(); } - ; - (_disposable = disposable) === null || _disposable === void 0 ? void 0 : _disposable[SymbolDispose](); - ac.abort(); - if (final) { - if (!error4) { - lastStreamCleanup.forEach((fn) => fn()); + for await (const val2 of this) { + var _options$signal6; + if (options !== null && options !== void 0 && (_options$signal6 = options.signal) !== null && _options$signal6 !== void 0 && _options$signal6.aborted) { + throw new AbortError(); + } + if (number-- <= 0) { + yield val2; } - process2.nextTick(callback, error4, value); } + }.call(this); + } + function take(number, options = void 0) { + if (options != null) { + validateObject(options, "options"); } - let ret; - for (let i = 0; i < streams.length; i++) { - const stream = streams[i]; - const reading = i < streams.length - 1; - const writing = i > 0; - const end = reading || (opts === null || opts === void 0 ? void 0 : opts.end) !== false; - const isLastStream = i === streams.length - 1; - if (isNodeStream(stream)) { - let onError2 = function(err) { - if (err && err.name !== "AbortError" && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { - finish(err); - } - }; - var onError = onError2; - if (end) { - const { destroy, cleanup } = destroyer(stream, reading, writing); - destroys.push(destroy); - if (isReadable(stream) && isLastStream) { - lastStreamCleanup.push(cleanup); - } - } - stream.on("error", onError2); - if (isReadable(stream) && isLastStream) { - lastStreamCleanup.push(() => { - stream.removeListener("error", onError2); - }); - } + if ((options === null || options === void 0 ? void 0 : options.signal) != null) { + validateAbortSignal(options.signal, "options.signal"); + } + number = toIntegerOrInfinity(number); + return async function* take2() { + var _options$signal7; + if (options !== null && options !== void 0 && (_options$signal7 = options.signal) !== null && _options$signal7 !== void 0 && _options$signal7.aborted) { + throw new AbortError(); } - if (i === 0) { - if (typeof stream === "function") { - ret = stream({ - signal - }); - if (!isIterable(ret)) { - throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or Stream", "source", ret); - } - } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) { - ret = stream; - } else { - ret = Duplex.from(stream); - } - } else if (typeof stream === "function") { - if (isTransformStream(ret)) { - var _ret; - ret = makeAsyncIterable((_ret = ret) === null || _ret === void 0 ? void 0 : _ret.readable); - } else { - ret = makeAsyncIterable(ret); - } - ret = stream(ret, { - signal - }); - if (reading) { - if (!isIterable(ret, true)) { - throw new ERR_INVALID_RETURN_VALUE("AsyncIterable", `transform[${i - 1}]`, ret); - } - } else { - var _ret2; - if (!PassThrough) { - PassThrough = require_passthrough2(); - } - const pt = new PassThrough({ - objectMode: true - }); - const then = (_ret2 = ret) === null || _ret2 === void 0 ? void 0 : _ret2.then; - if (typeof then === "function") { - finishCount++; - then.call( - ret, - (val2) => { - value = val2; - if (val2 != null) { - pt.write(val2); - } - if (end) { - pt.end(); - } - process2.nextTick(finish); - }, - (err) => { - pt.destroy(err); - process2.nextTick(finish, err); - } - ); - } else if (isIterable(ret, true)) { - finishCount++; - pumpToNode(ret, pt, finish, { - end - }); - } else if (isReadableStream(ret) || isTransformStream(ret)) { - const toRead = ret.readable || ret; - finishCount++; - pumpToNode(toRead, pt, finish, { - end - }); - } else { - throw new ERR_INVALID_RETURN_VALUE("AsyncIterable or Promise", "destination", ret); - } - ret = pt; - const { destroy, cleanup } = destroyer(ret, false, true); - destroys.push(destroy); - if (isLastStream) { - lastStreamCleanup.push(cleanup); - } + for await (const val2 of this) { + var _options$signal8; + if (options !== null && options !== void 0 && (_options$signal8 = options.signal) !== null && _options$signal8 !== void 0 && _options$signal8.aborted) { + throw new AbortError(); } - } else if (isNodeStream(stream)) { - if (isReadableNodeStream(ret)) { - finishCount += 2; - const cleanup = pipe(ret, stream, finish, { - end - }); - if (isReadable(stream) && isLastStream) { - lastStreamCleanup.push(cleanup); - } - } else if (isTransformStream(ret) || isReadableStream(ret)) { - const toRead = ret.readable || ret; - finishCount++; - pumpToNode(toRead, stream, finish, { - end - }); - } else if (isIterable(ret)) { - finishCount++; - pumpToNode(ret, stream, finish, { - end - }); - } else { - throw new ERR_INVALID_ARG_TYPE2( - "val", - ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"], - ret - ); + if (number-- > 0) { + yield val2; } - ret = stream; - } else if (isWebStream(stream)) { - if (isReadableNodeStream(ret)) { - finishCount++; - pumpToWeb(makeAsyncIterable(ret), stream, finish, { - end - }); - } else if (isReadableStream(ret) || isIterable(ret)) { - finishCount++; - pumpToWeb(ret, stream, finish, { - end - }); - } else if (isTransformStream(ret)) { - finishCount++; - pumpToWeb(ret.readable, stream, finish, { - end - }); - } else { - throw new ERR_INVALID_ARG_TYPE2( - "val", - ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"], - ret - ); + if (number <= 0) { + return; } - ret = stream; - } else { - ret = Duplex.from(stream); } - } - if (signal !== null && signal !== void 0 && signal.aborted || outerSignal !== null && outerSignal !== void 0 && outerSignal.aborted) { - process2.nextTick(abort); - } - return ret; + }.call(this); } - function pipe(src, dst, finish, { end }) { - let ended = false; - dst.on("close", () => { - if (!ended) { - finish(new ERR_STREAM_PREMATURE_CLOSE()); - } - }); - src.pipe(dst, { - end: false - }); - if (end) { - let endFn2 = function() { - ended = true; - dst.end(); - }; - var endFn = endFn2; - if (isReadableFinished(src)) { - process2.nextTick(endFn2); - } else { - src.once("end", endFn2); + module2.exports.streamReturningOperators = { + asIndexedPairs: deprecate(asIndexedPairs, "readable.asIndexedPairs will be removed in a future version."), + drop, + filter, + flatMap, + map: map2, + take, + compose + }; + module2.exports.promiseReturningOperators = { + every, + forEach, + reduce, + toArray: toArray2, + some, + find: find2 + }; + } +}); + +// node_modules/readable-stream/lib/stream/promises.js +var require_promises = __commonJS({ + "node_modules/readable-stream/lib/stream/promises.js"(exports2, module2) { + "use strict"; + var { ArrayPrototypePop, Promise: Promise2 } = require_primordials(); + var { isIterable, isNodeStream, isWebStream } = require_utils6(); + var { pipelineImpl: pl } = require_pipeline3(); + var { finished } = require_end_of_stream(); + require_stream2(); + function pipeline(...streams) { + return new Promise2((resolve2, reject) => { + let signal; + let end; + const lastArg = streams[streams.length - 1]; + if (lastArg && typeof lastArg === "object" && !isNodeStream(lastArg) && !isIterable(lastArg) && !isWebStream(lastArg)) { + const options = ArrayPrototypePop(streams); + signal = options.signal; + end = options.end; } - } else { - finish(); - } - eos( - src, - { - readable: true, - writable: false - }, - (err) => { - const rState = src._readableState; - if (err && err.code === "ERR_STREAM_PREMATURE_CLOSE" && rState && rState.ended && !rState.errored && !rState.errorEmitted) { - src.once("end", finish).once("error", finish); - } else { - finish(err); + pl( + streams, + (err, value) => { + if (err) { + reject(err); + } else { + resolve2(value); + } + }, + { + signal, + end } - } - ); - return eos( - dst, - { - readable: false, - writable: true - }, - finish - ); + ); + }); } module2.exports = { - pipelineImpl, + finished, pipeline }; } }); -// node_modules/readable-stream/lib/internal/streams/compose.js -var require_compose = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/compose.js"(exports2, module2) { - "use strict"; - var { pipeline } = require_pipeline3(); - var Duplex = require_duplex(); - var { destroyer } = require_destroy2(); +// node_modules/readable-stream/lib/stream.js +var require_stream2 = __commonJS({ + "node_modules/readable-stream/lib/stream.js"(exports2, module2) { + var { Buffer: Buffer2 } = require("buffer"); + var { ObjectDefineProperty, ObjectKeys, ReflectApply } = require_primordials(); var { - isNodeStream, - isReadable, - isWritable, - isWebStream, - isTransformStream, - isWritableStream, - isReadableStream - } = require_utils6(); + promisify: { custom: customPromisify } + } = require_util12(); + var { streamReturningOperators, promiseReturningOperators } = require_operators(); var { - AbortError, - codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } + codes: { ERR_ILLEGAL_CONSTRUCTOR } } = require_errors3(); + var compose = require_compose(); + var { setDefaultHighWaterMark, getDefaultHighWaterMark } = require_state3(); + var { pipeline } = require_pipeline3(); + var { destroyer } = require_destroy2(); var eos = require_end_of_stream(); - module2.exports = function compose(...streams) { - if (streams.length === 0) { - throw new ERR_MISSING_ARGS("streams"); - } - if (streams.length === 1) { - return Duplex.from(streams[0]); - } - const orgStreams = [...streams]; - if (typeof streams[0] === "function") { - streams[0] = Duplex.from(streams[0]); - } - if (typeof streams[streams.length - 1] === "function") { - const idx = streams.length - 1; - streams[idx] = Duplex.from(streams[idx]); - } - for (let n = 0; n < streams.length; ++n) { - if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { - continue; - } - if (n < streams.length - 1 && !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))) { - throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], "must be readable"); + var promises2 = require_promises(); + var utils = require_utils6(); + var Stream = module2.exports = require_legacy().Stream; + Stream.isDestroyed = utils.isDestroyed; + Stream.isDisturbed = utils.isDisturbed; + Stream.isErrored = utils.isErrored; + Stream.isReadable = utils.isReadable; + Stream.isWritable = utils.isWritable; + Stream.Readable = require_readable3(); + for (const key of ObjectKeys(streamReturningOperators)) { + let fn2 = function(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR(); } - if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { - throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], "must be writable"); + return Stream.Readable.from(ReflectApply(op, this, args)); + }; + fn = fn2; + const op = streamReturningOperators[key]; + ObjectDefineProperty(fn2, "name", { + __proto__: null, + value: op.name + }); + ObjectDefineProperty(fn2, "length", { + __proto__: null, + value: op.length + }); + ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, + value: fn2, + enumerable: false, + configurable: true, + writable: true + }); + } + var fn; + for (const key of ObjectKeys(promiseReturningOperators)) { + let fn2 = function(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR(); } + return ReflectApply(op, this, args); + }; + fn = fn2; + const op = promiseReturningOperators[key]; + ObjectDefineProperty(fn2, "name", { + __proto__: null, + value: op.name + }); + ObjectDefineProperty(fn2, "length", { + __proto__: null, + value: op.length + }); + ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, + value: fn2, + enumerable: false, + configurable: true, + writable: true + }); + } + var fn; + Stream.Writable = require_writable(); + Stream.Duplex = require_duplex(); + Stream.Transform = require_transform(); + Stream.PassThrough = require_passthrough2(); + Stream.pipeline = pipeline; + var { addAbortSignal } = require_add_abort_signal(); + Stream.addAbortSignal = addAbortSignal; + Stream.finished = eos; + Stream.destroy = destroyer; + Stream.compose = compose; + Stream.setDefaultHighWaterMark = setDefaultHighWaterMark; + Stream.getDefaultHighWaterMark = getDefaultHighWaterMark; + ObjectDefineProperty(Stream, "promises", { + __proto__: null, + configurable: true, + enumerable: true, + get() { + return promises2; } - let ondrain; - let onfinish; - let onreadable; - let onclose; - let d; - function onfinished(err) { - const cb = onclose; - onclose = null; - if (cb) { - cb(err); - } else if (err) { - d.destroy(err); - } else if (!readable && !writable) { - d.destroy(); - } + }); + ObjectDefineProperty(pipeline, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises2.pipeline; } - const head = streams[0]; - const tail = pipeline(streams, onfinished); - const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)); - const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)); - d = new Duplex({ - // TODO (ronag): highWaterMark? - writableObjectMode: !!(head !== null && head !== void 0 && head.writableObjectMode), - readableObjectMode: !!(tail !== null && tail !== void 0 && tail.readableObjectMode), - writable, - readable - }); - if (writable) { - if (isNodeStream(head)) { - d._write = function(chunk, encoding, callback) { - if (head.write(chunk, encoding)) { - callback(); - } else { - ondrain = callback; - } - }; - d._final = function(callback) { - head.end(); - onfinish = callback; - }; - head.on("drain", function() { - if (ondrain) { - const cb = ondrain; - ondrain = null; - cb(); - } - }); - } else if (isWebStream(head)) { - const writable2 = isTransformStream(head) ? head.writable : head; - const writer = writable2.getWriter(); - d._write = async function(chunk, encoding, callback) { - try { - await writer.ready; - writer.write(chunk).catch(() => { - }); - callback(); - } catch (err) { - callback(err); - } - }; - d._final = async function(callback) { - try { - await writer.ready; - writer.close().catch(() => { - }); - onfinish = callback; - } catch (err) { - callback(err); - } - }; - } - const toRead = isTransformStream(tail) ? tail.readable : tail; - eos(toRead, () => { - if (onfinish) { - const cb = onfinish; - onfinish = null; - cb(); - } - }); + }); + ObjectDefineProperty(eos, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises2.finished; } - if (readable) { - if (isNodeStream(tail)) { - tail.on("readable", function() { - if (onreadable) { - const cb = onreadable; - onreadable = null; - cb(); - } - }); - tail.on("end", function() { - d.push(null); - }); - d._read = function() { - while (true) { - const buf = tail.read(); - if (buf === null) { - onreadable = d._read; - return; - } - if (!d.push(buf)) { - return; - } - } - }; - } else if (isWebStream(tail)) { - const readable2 = isTransformStream(tail) ? tail.readable : tail; - const reader = readable2.getReader(); - d._read = async function() { - while (true) { - try { - const { value, done } = await reader.read(); - if (!d.push(value)) { - return; - } - if (done) { - d.push(null); - return; - } - } catch { - return; - } - } - }; + }); + Stream.Stream = Stream; + Stream._isUint8Array = function isUint8Array(value) { + return value instanceof Uint8Array; + }; + Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); + }; + } +}); + +// node_modules/readable-stream/lib/ours/index.js +var require_ours = __commonJS({ + "node_modules/readable-stream/lib/ours/index.js"(exports2, module2) { + "use strict"; + var Stream = require("stream"); + if (Stream && process.env.READABLE_STREAM === "disable") { + const promises2 = Stream.promises; + module2.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer; + module2.exports._isUint8Array = Stream._isUint8Array; + module2.exports.isDisturbed = Stream.isDisturbed; + module2.exports.isErrored = Stream.isErrored; + module2.exports.isReadable = Stream.isReadable; + module2.exports.Readable = Stream.Readable; + module2.exports.Writable = Stream.Writable; + module2.exports.Duplex = Stream.Duplex; + module2.exports.Transform = Stream.Transform; + module2.exports.PassThrough = Stream.PassThrough; + module2.exports.addAbortSignal = Stream.addAbortSignal; + module2.exports.finished = Stream.finished; + module2.exports.destroy = Stream.destroy; + module2.exports.pipeline = Stream.pipeline; + module2.exports.compose = Stream.compose; + Object.defineProperty(Stream, "promises", { + configurable: true, + enumerable: true, + get() { + return promises2; } - } - d._destroy = function(err, callback) { - if (!err && onclose !== null) { - err = new AbortError(); + }); + module2.exports.Stream = Stream.Stream; + } else { + const CustomStream = require_stream2(); + const promises2 = require_promises(); + const originalDestroy = CustomStream.Readable.destroy; + module2.exports = CustomStream.Readable; + module2.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer; + module2.exports._isUint8Array = CustomStream._isUint8Array; + module2.exports.isDisturbed = CustomStream.isDisturbed; + module2.exports.isErrored = CustomStream.isErrored; + module2.exports.isReadable = CustomStream.isReadable; + module2.exports.Readable = CustomStream.Readable; + module2.exports.Writable = CustomStream.Writable; + module2.exports.Duplex = CustomStream.Duplex; + module2.exports.Transform = CustomStream.Transform; + module2.exports.PassThrough = CustomStream.PassThrough; + module2.exports.addAbortSignal = CustomStream.addAbortSignal; + module2.exports.finished = CustomStream.finished; + module2.exports.destroy = CustomStream.destroy; + module2.exports.destroy = originalDestroy; + module2.exports.pipeline = CustomStream.pipeline; + module2.exports.compose = CustomStream.compose; + Object.defineProperty(CustomStream, "promises", { + configurable: true, + enumerable: true, + get() { + return promises2; } - onreadable = null; - ondrain = null; - onfinish = null; - if (onclose === null) { - callback(err); - } else { - onclose = callback; - if (isNodeStream(tail)) { - destroyer(tail, err); + }); + module2.exports.Stream = CustomStream.Stream; + } + module2.exports.default = module2.exports; + } +}); + +// node_modules/lodash/_arrayPush.js +var require_arrayPush = __commonJS({ + "node_modules/lodash/_arrayPush.js"(exports2, module2) { + function arrayPush(array, values) { + var index = -1, length = values.length, offset = array.length; + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + module2.exports = arrayPush; + } +}); + +// node_modules/lodash/_isFlattenable.js +var require_isFlattenable = __commonJS({ + "node_modules/lodash/_isFlattenable.js"(exports2, module2) { + var Symbol2 = require_Symbol(); + var isArguments = require_isArguments(); + var isArray = require_isArray(); + var spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : void 0; + function isFlattenable(value) { + return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); + } + module2.exports = isFlattenable; + } +}); + +// node_modules/lodash/_baseFlatten.js +var require_baseFlatten = __commonJS({ + "node_modules/lodash/_baseFlatten.js"(exports2, module2) { + var arrayPush = require_arrayPush(); + var isFlattenable = require_isFlattenable(); + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, length = array.length; + predicate || (predicate = isFlattenable); + 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(result, value); } + } else if (!isStrict) { + result[result.length] = value; } - }; - return d; - }; + } + return result; + } + module2.exports = baseFlatten; + } +}); + +// node_modules/lodash/flatten.js +var require_flatten = __commonJS({ + "node_modules/lodash/flatten.js"(exports2, module2) { + var baseFlatten = require_baseFlatten(); + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + module2.exports = flatten; + } +}); + +// node_modules/lodash/_nativeCreate.js +var require_nativeCreate = __commonJS({ + "node_modules/lodash/_nativeCreate.js"(exports2, module2) { + var getNative = require_getNative(); + var nativeCreate = getNative(Object, "create"); + module2.exports = nativeCreate; + } +}); + +// node_modules/lodash/_hashClear.js +var require_hashClear = __commonJS({ + "node_modules/lodash/_hashClear.js"(exports2, module2) { + var nativeCreate = require_nativeCreate(); + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + module2.exports = hashClear; + } +}); + +// node_modules/lodash/_hashDelete.js +var require_hashDelete = __commonJS({ + "node_modules/lodash/_hashDelete.js"(exports2, module2) { + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + module2.exports = hashDelete; + } +}); + +// node_modules/lodash/_hashGet.js +var require_hashGet = __commonJS({ + "node_modules/lodash/_hashGet.js"(exports2, module2) { + var nativeCreate = require_nativeCreate(); + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? void 0 : result; + } + return hasOwnProperty.call(data, key) ? data[key] : void 0; + } + module2.exports = hashGet; + } +}); + +// node_modules/lodash/_hashHas.js +var require_hashHas = __commonJS({ + "node_modules/lodash/_hashHas.js"(exports2, module2) { + var nativeCreate = require_nativeCreate(); + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key); + } + module2.exports = hashHas; } }); -// node_modules/readable-stream/lib/internal/streams/operators.js -var require_operators = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/operators.js"(exports2, module2) { - "use strict"; - var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController; - var { - codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, - AbortError - } = require_errors3(); - var { validateAbortSignal, validateInteger, validateObject } = require_validators(); - var kWeakHandler = require_primordials().Symbol("kWeak"); - var kResistStopPropagation = require_primordials().Symbol("kResistStopPropagation"); - var { finished } = require_end_of_stream(); - var staticCompose = require_compose(); - var { addAbortSignalNoValidate } = require_add_abort_signal(); - var { isWritable, isNodeStream } = require_utils6(); - var { deprecate } = require_util12(); - var { - ArrayPrototypePush, - Boolean: Boolean2, - MathFloor, - Number: Number2, - NumberIsNaN, - Promise: Promise2, - PromiseReject, - PromiseResolve, - PromisePrototypeThen, - Symbol: Symbol2 - } = require_primordials(); - var kEmpty = Symbol2("kEmpty"); - var kEof = Symbol2("kEof"); - function compose(stream, options) { - if (options != null) { - validateObject(options, "options"); - } - if ((options === null || options === void 0 ? void 0 : options.signal) != null) { - validateAbortSignal(options.signal, "options.signal"); - } - if (isNodeStream(stream) && !isWritable(stream)) { - throw new ERR_INVALID_ARG_VALUE("stream", stream, "must be writable"); - } - const composedStream = staticCompose(this, stream); - if (options !== null && options !== void 0 && options.signal) { - addAbortSignalNoValidate(options.signal, composedStream); - } - return composedStream; +// node_modules/lodash/_hashSet.js +var require_hashSet = __commonJS({ + "node_modules/lodash/_hashSet.js"(exports2, module2) { + var nativeCreate = require_nativeCreate(); + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; + return this; } - function map2(fn, options) { - if (typeof fn !== "function") { - throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); - } - if (options != null) { - validateObject(options, "options"); - } - if ((options === null || options === void 0 ? void 0 : options.signal) != null) { - validateAbortSignal(options.signal, "options.signal"); - } - let concurrency = 1; - if ((options === null || options === void 0 ? void 0 : options.concurrency) != null) { - concurrency = MathFloor(options.concurrency); - } - let highWaterMark = concurrency - 1; - if ((options === null || options === void 0 ? void 0 : options.highWaterMark) != null) { - highWaterMark = MathFloor(options.highWaterMark); + module2.exports = hashSet; + } +}); + +// node_modules/lodash/_Hash.js +var require_Hash = __commonJS({ + "node_modules/lodash/_Hash.js"(exports2, module2) { + var hashClear = require_hashClear(); + var hashDelete = require_hashDelete(); + var hashGet = require_hashGet(); + var hashHas = require_hashHas(); + var hashSet = require_hashSet(); + 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]); } - validateInteger(concurrency, "options.concurrency", 1); - validateInteger(highWaterMark, "options.highWaterMark", 0); - highWaterMark += concurrency; - return async function* map3() { - const signal = require_util12().AbortSignalAny( - [options === null || options === void 0 ? void 0 : options.signal].filter(Boolean2) - ); - const stream = this; - const queue = []; - const signalOpt = { - signal - }; - let next; - let resume; - let done = false; - let cnt = 0; - function onCatch() { - done = true; - afterItemProcessed(); - } - function afterItemProcessed() { - cnt -= 1; - maybeResume(); - } - function maybeResume() { - if (resume && !done && cnt < concurrency && queue.length < highWaterMark) { - resume(); - resume = null; - } - } - async function pump() { - try { - for await (let val2 of stream) { - if (done) { - return; - } - if (signal.aborted) { - throw new AbortError(); - } - try { - val2 = fn(val2, signalOpt); - if (val2 === kEmpty) { - continue; - } - val2 = PromiseResolve(val2); - } catch (err) { - val2 = PromiseReject(err); - } - cnt += 1; - PromisePrototypeThen(val2, afterItemProcessed, onCatch); - queue.push(val2); - if (next) { - next(); - next = null; - } - if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) { - await new Promise2((resolve2) => { - resume = resolve2; - }); - } - } - queue.push(kEof); - } catch (err) { - const val2 = PromiseReject(err); - PromisePrototypeThen(val2, afterItemProcessed, onCatch); - queue.push(val2); - } finally { - done = true; - if (next) { - next(); - next = null; - } - } - } - pump(); - try { - while (true) { - while (queue.length > 0) { - const val2 = await queue[0]; - if (val2 === kEof) { - return; - } - if (signal.aborted) { - throw new AbortError(); - } - if (val2 !== kEmpty) { - yield val2; - } - queue.shift(); - maybeResume(); - } - await new Promise2((resolve2) => { - next = resolve2; - }); - } - } finally { - done = true; - if (resume) { - resume(); - resume = null; - } + } + Hash.prototype.clear = hashClear; + Hash.prototype["delete"] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + module2.exports = Hash; + } +}); + +// node_modules/lodash/_listCacheClear.js +var require_listCacheClear = __commonJS({ + "node_modules/lodash/_listCacheClear.js"(exports2, module2) { + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + module2.exports = listCacheClear; + } +}); + +// node_modules/lodash/_assocIndexOf.js +var require_assocIndexOf = __commonJS({ + "node_modules/lodash/_assocIndexOf.js"(exports2, module2) { + var eq = require_eq2(); + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; } - }.call(this); + } + return -1; } - function asIndexedPairs(options = void 0) { - if (options != null) { - validateObject(options, "options"); + module2.exports = assocIndexOf; + } +}); + +// node_modules/lodash/_listCacheDelete.js +var require_listCacheDelete = __commonJS({ + "node_modules/lodash/_listCacheDelete.js"(exports2, module2) { + var assocIndexOf = require_assocIndexOf(); + var arrayProto = Array.prototype; + var splice = arrayProto.splice; + function listCacheDelete(key) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + return false; } - if ((options === null || options === void 0 ? void 0 : options.signal) != null) { - validateAbortSignal(options.signal, "options.signal"); + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); } - return async function* asIndexedPairs2() { - let index = 0; - for await (const val2 of this) { - var _options$signal; - if (options !== null && options !== void 0 && (_options$signal = options.signal) !== null && _options$signal !== void 0 && _options$signal.aborted) { - throw new AbortError({ - cause: options.signal.reason - }); - } - yield [index++, val2]; - } - }.call(this); + --this.size; + return true; } - async function some(fn, options = void 0) { - for await (const unused of filter.call(this, fn, options)) { - return true; - } - return false; + module2.exports = listCacheDelete; + } +}); + +// node_modules/lodash/_listCacheGet.js +var require_listCacheGet = __commonJS({ + "node_modules/lodash/_listCacheGet.js"(exports2, module2) { + var assocIndexOf = require_assocIndexOf(); + function listCacheGet(key) { + var data = this.__data__, index = assocIndexOf(data, key); + return index < 0 ? void 0 : data[index][1]; } - async function every(fn, options = void 0) { - if (typeof fn !== "function") { - throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); + module2.exports = listCacheGet; + } +}); + +// node_modules/lodash/_listCacheHas.js +var require_listCacheHas = __commonJS({ + "node_modules/lodash/_listCacheHas.js"(exports2, module2) { + var assocIndexOf = require_assocIndexOf(); + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + module2.exports = listCacheHas; + } +}); + +// node_modules/lodash/_listCacheSet.js +var require_listCacheSet = __commonJS({ + "node_modules/lodash/_listCacheSet.js"(exports2, module2) { + var assocIndexOf = require_assocIndexOf(); + function listCacheSet(key, value) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; } - return !await some.call( - this, - async (...args) => { - return !await fn(...args); - }, - options - ); + return this; } - async function find2(fn, options) { - for await (const result of filter.call(this, fn, options)) { - return result; + module2.exports = listCacheSet; + } +}); + +// node_modules/lodash/_ListCache.js +var require_ListCache = __commonJS({ + "node_modules/lodash/_ListCache.js"(exports2, module2) { + var listCacheClear = require_listCacheClear(); + var listCacheDelete = require_listCacheDelete(); + var listCacheGet = require_listCacheGet(); + var listCacheHas = require_listCacheHas(); + var listCacheSet = require_listCacheSet(); + 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]); } - return void 0; } - async function forEach(fn, options) { - if (typeof fn !== "function") { - throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); + ListCache.prototype.clear = listCacheClear; + ListCache.prototype["delete"] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + module2.exports = ListCache; + } +}); + +// node_modules/lodash/_Map.js +var require_Map = __commonJS({ + "node_modules/lodash/_Map.js"(exports2, module2) { + var getNative = require_getNative(); + var root = require_root(); + var Map2 = getNative(root, "Map"); + module2.exports = Map2; + } +}); + +// node_modules/lodash/_mapCacheClear.js +var require_mapCacheClear = __commonJS({ + "node_modules/lodash/_mapCacheClear.js"(exports2, module2) { + var Hash = require_Hash(); + var ListCache = require_ListCache(); + var Map2 = require_Map(); + function mapCacheClear() { + this.size = 0; + this.__data__ = { + "hash": new Hash(), + "map": new (Map2 || ListCache)(), + "string": new Hash() + }; + } + module2.exports = mapCacheClear; + } +}); + +// node_modules/lodash/_isKeyable.js +var require_isKeyable = __commonJS({ + "node_modules/lodash/_isKeyable.js"(exports2, module2) { + function isKeyable(value) { + var type2 = typeof value; + return type2 == "string" || type2 == "number" || type2 == "symbol" || type2 == "boolean" ? value !== "__proto__" : value === null; + } + module2.exports = isKeyable; + } +}); + +// node_modules/lodash/_getMapData.js +var require_getMapData = __commonJS({ + "node_modules/lodash/_getMapData.js"(exports2, module2) { + var isKeyable = require_isKeyable(); + function getMapData(map2, key) { + var data = map2.__data__; + return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; + } + module2.exports = getMapData; + } +}); + +// node_modules/lodash/_mapCacheDelete.js +var require_mapCacheDelete = __commonJS({ + "node_modules/lodash/_mapCacheDelete.js"(exports2, module2) { + var getMapData = require_getMapData(); + function mapCacheDelete(key) { + var result = getMapData(this, key)["delete"](key); + this.size -= result ? 1 : 0; + return result; + } + module2.exports = mapCacheDelete; + } +}); + +// node_modules/lodash/_mapCacheGet.js +var require_mapCacheGet = __commonJS({ + "node_modules/lodash/_mapCacheGet.js"(exports2, module2) { + var getMapData = require_getMapData(); + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + module2.exports = mapCacheGet; + } +}); + +// node_modules/lodash/_mapCacheHas.js +var require_mapCacheHas = __commonJS({ + "node_modules/lodash/_mapCacheHas.js"(exports2, module2) { + var getMapData = require_getMapData(); + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + module2.exports = mapCacheHas; + } +}); + +// node_modules/lodash/_mapCacheSet.js +var require_mapCacheSet = __commonJS({ + "node_modules/lodash/_mapCacheSet.js"(exports2, module2) { + var getMapData = require_getMapData(); + function mapCacheSet(key, value) { + var data = getMapData(this, key), size = data.size; + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + module2.exports = mapCacheSet; + } +}); + +// node_modules/lodash/_MapCache.js +var require_MapCache = __commonJS({ + "node_modules/lodash/_MapCache.js"(exports2, module2) { + var mapCacheClear = require_mapCacheClear(); + var mapCacheDelete = require_mapCacheDelete(); + var mapCacheGet = require_mapCacheGet(); + var mapCacheHas = require_mapCacheHas(); + var mapCacheSet = require_mapCacheSet(); + 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]); } - async function forEachFn(value, options2) { - await fn(value, options2); - return kEmpty; + } + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype["delete"] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + module2.exports = MapCache; + } +}); + +// node_modules/lodash/_setCacheAdd.js +var require_setCacheAdd = __commonJS({ + "node_modules/lodash/_setCacheAdd.js"(exports2, module2) { + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + module2.exports = setCacheAdd; + } +}); + +// node_modules/lodash/_setCacheHas.js +var require_setCacheHas = __commonJS({ + "node_modules/lodash/_setCacheHas.js"(exports2, module2) { + function setCacheHas(value) { + return this.__data__.has(value); + } + module2.exports = setCacheHas; + } +}); + +// node_modules/lodash/_SetCache.js +var require_SetCache = __commonJS({ + "node_modules/lodash/_SetCache.js"(exports2, module2) { + var MapCache = require_MapCache(); + var setCacheAdd = require_setCacheAdd(); + var setCacheHas = require_setCacheHas(); + function SetCache(values) { + var index = -1, length = values == null ? 0 : values.length; + this.__data__ = new MapCache(); + while (++index < length) { + this.add(values[index]); } - for await (const unused of map2.call(this, forEachFn, options)) ; } - function filter(fn, options) { - if (typeof fn !== "function") { - throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); - } - async function filterFn(value, options2) { - if (await fn(value, options2)) { - return value; + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + module2.exports = SetCache; + } +}); + +// node_modules/lodash/_baseFindIndex.js +var require_baseFindIndex = __commonJS({ + "node_modules/lodash/_baseFindIndex.js"(exports2, module2) { + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, index = fromIndex + (fromRight ? 1 : -1); + while (fromRight ? index-- : ++index < length) { + if (predicate(array[index], index, array)) { + return index; } - return kEmpty; } - return map2.call(this, filterFn, options); + return -1; } - var ReduceAwareErrMissingArgs = class extends ERR_MISSING_ARGS { - constructor() { - super("reduce"); - this.message = "Reduce of an empty stream requires an initial value"; - } - }; - async function reduce(reducer, initialValue, options) { - var _options$signal2; - if (typeof reducer !== "function") { - throw new ERR_INVALID_ARG_TYPE2("reducer", ["Function", "AsyncFunction"], reducer); - } - if (options != null) { - validateObject(options, "options"); - } - if ((options === null || options === void 0 ? void 0 : options.signal) != null) { - validateAbortSignal(options.signal, "options.signal"); - } - let hasInitialValue = arguments.length > 1; - if (options !== null && options !== void 0 && (_options$signal2 = options.signal) !== null && _options$signal2 !== void 0 && _options$signal2.aborted) { - const err = new AbortError(void 0, { - cause: options.signal.reason - }); - this.once("error", () => { - }); - await finished(this.destroy(err)); - throw err; - } - const ac = new AbortController2(); - const signal = ac.signal; - if (options !== null && options !== void 0 && options.signal) { - const opts = { - once: true, - [kWeakHandler]: this, - [kResistStopPropagation]: true - }; - options.signal.addEventListener("abort", () => ac.abort(), opts); - } - let gotAnyItemFromStream = false; - try { - for await (const value of this) { - var _options$signal3; - gotAnyItemFromStream = true; - if (options !== null && options !== void 0 && (_options$signal3 = options.signal) !== null && _options$signal3 !== void 0 && _options$signal3.aborted) { - throw new AbortError(); - } - if (!hasInitialValue) { - initialValue = value; - hasInitialValue = true; - } else { - initialValue = await reducer(initialValue, value, { - signal - }); - } - } - if (!gotAnyItemFromStream && !hasInitialValue) { - throw new ReduceAwareErrMissingArgs(); - } - } finally { - ac.abort(); - } - return initialValue; + module2.exports = baseFindIndex; + } +}); + +// node_modules/lodash/_baseIsNaN.js +var require_baseIsNaN = __commonJS({ + "node_modules/lodash/_baseIsNaN.js"(exports2, module2) { + function baseIsNaN(value) { + return value !== value; } - async function toArray2(options) { - if (options != null) { - validateObject(options, "options"); - } - if ((options === null || options === void 0 ? void 0 : options.signal) != null) { - validateAbortSignal(options.signal, "options.signal"); - } - const result = []; - for await (const val2 of this) { - var _options$signal4; - if (options !== null && options !== void 0 && (_options$signal4 = options.signal) !== null && _options$signal4 !== void 0 && _options$signal4.aborted) { - throw new AbortError(void 0, { - cause: options.signal.reason - }); + module2.exports = baseIsNaN; + } +}); + +// node_modules/lodash/_strictIndexOf.js +var require_strictIndexOf = __commonJS({ + "node_modules/lodash/_strictIndexOf.js"(exports2, module2) { + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (array[index] === value) { + return index; } - ArrayPrototypePush(result, val2); } - return result; + return -1; } - function flatMap(fn, options) { - const values = map2.call(this, fn, options); - return async function* flatMap2() { - for await (const val2 of values) { - yield* val2; - } - }.call(this); + module2.exports = strictIndexOf; + } +}); + +// node_modules/lodash/_baseIndexOf.js +var require_baseIndexOf = __commonJS({ + "node_modules/lodash/_baseIndexOf.js"(exports2, module2) { + var baseFindIndex = require_baseFindIndex(); + var baseIsNaN = require_baseIsNaN(); + var strictIndexOf = require_strictIndexOf(); + function baseIndexOf(array, value, fromIndex) { + return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } - function toIntegerOrInfinity(number) { - number = Number2(number); - if (NumberIsNaN(number)) { - return 0; - } - if (number < 0) { - throw new ERR_OUT_OF_RANGE("number", ">= 0", number); - } - return number; + module2.exports = baseIndexOf; + } +}); + +// node_modules/lodash/_arrayIncludes.js +var require_arrayIncludes = __commonJS({ + "node_modules/lodash/_arrayIncludes.js"(exports2, module2) { + var baseIndexOf = require_baseIndexOf(); + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; } - function drop(number, options = void 0) { - if (options != null) { - validateObject(options, "options"); - } - if ((options === null || options === void 0 ? void 0 : options.signal) != null) { - validateAbortSignal(options.signal, "options.signal"); - } - number = toIntegerOrInfinity(number); - return async function* drop2() { - var _options$signal5; - if (options !== null && options !== void 0 && (_options$signal5 = options.signal) !== null && _options$signal5 !== void 0 && _options$signal5.aborted) { - throw new AbortError(); - } - for await (const val2 of this) { - var _options$signal6; - if (options !== null && options !== void 0 && (_options$signal6 = options.signal) !== null && _options$signal6 !== void 0 && _options$signal6.aborted) { - throw new AbortError(); - } - if (number-- <= 0) { - yield val2; - } + module2.exports = arrayIncludes; + } +}); + +// node_modules/lodash/_arrayIncludesWith.js +var require_arrayIncludesWith = __commonJS({ + "node_modules/lodash/_arrayIncludesWith.js"(exports2, module2) { + function arrayIncludesWith(array, value, comparator) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (comparator(value, array[index])) { + return true; } - }.call(this); - } - function take(number, options = void 0) { - if (options != null) { - validateObject(options, "options"); - } - if ((options === null || options === void 0 ? void 0 : options.signal) != null) { - validateAbortSignal(options.signal, "options.signal"); } - number = toIntegerOrInfinity(number); - return async function* take2() { - var _options$signal7; - if (options !== null && options !== void 0 && (_options$signal7 = options.signal) !== null && _options$signal7 !== void 0 && _options$signal7.aborted) { - throw new AbortError(); - } - for await (const val2 of this) { - var _options$signal8; - if (options !== null && options !== void 0 && (_options$signal8 = options.signal) !== null && _options$signal8 !== void 0 && _options$signal8.aborted) { - throw new AbortError(); - } - if (number-- > 0) { - yield val2; - } - if (number <= 0) { - return; - } - } - }.call(this); + return false; } - module2.exports.streamReturningOperators = { - asIndexedPairs: deprecate(asIndexedPairs, "readable.asIndexedPairs will be removed in a future version."), - drop, - filter, - flatMap, - map: map2, - take, - compose - }; - module2.exports.promiseReturningOperators = { - every, - forEach, - reduce, - toArray: toArray2, - some, - find: find2 - }; + module2.exports = arrayIncludesWith; } }); -// node_modules/readable-stream/lib/stream/promises.js -var require_promises = __commonJS({ - "node_modules/readable-stream/lib/stream/promises.js"(exports2, module2) { - "use strict"; - var { ArrayPrototypePop, Promise: Promise2 } = require_primordials(); - var { isIterable, isNodeStream, isWebStream } = require_utils6(); - var { pipelineImpl: pl } = require_pipeline3(); - var { finished } = require_end_of_stream(); - require_stream2(); - function pipeline(...streams) { - return new Promise2((resolve2, reject) => { - let signal; - let end; - const lastArg = streams[streams.length - 1]; - if (lastArg && typeof lastArg === "object" && !isNodeStream(lastArg) && !isIterable(lastArg) && !isWebStream(lastArg)) { - const options = ArrayPrototypePop(streams); - signal = options.signal; - end = options.end; - } - pl( - streams, - (err, value) => { - if (err) { - reject(err); - } else { - resolve2(value); - } - }, - { - signal, - end - } - ); - }); +// node_modules/lodash/_arrayMap.js +var require_arrayMap = __commonJS({ + "node_modules/lodash/_arrayMap.js"(exports2, module2) { + 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; } - module2.exports = { - finished, - pipeline - }; + module2.exports = arrayMap; } }); -// node_modules/readable-stream/lib/stream.js -var require_stream2 = __commonJS({ - "node_modules/readable-stream/lib/stream.js"(exports2, module2) { - var { Buffer: Buffer2 } = require("buffer"); - var { ObjectDefineProperty, ObjectKeys, ReflectApply } = require_primordials(); - var { - promisify: { custom: customPromisify } - } = require_util12(); - var { streamReturningOperators, promiseReturningOperators } = require_operators(); - var { - codes: { ERR_ILLEGAL_CONSTRUCTOR } - } = require_errors3(); - var compose = require_compose(); - var { setDefaultHighWaterMark, getDefaultHighWaterMark } = require_state3(); - var { pipeline } = require_pipeline3(); - var { destroyer } = require_destroy2(); - var eos = require_end_of_stream(); - var promises2 = require_promises(); - var utils = require_utils6(); - var Stream = module2.exports = require_legacy().Stream; - Stream.isDestroyed = utils.isDestroyed; - Stream.isDisturbed = utils.isDisturbed; - Stream.isErrored = utils.isErrored; - Stream.isReadable = utils.isReadable; - Stream.isWritable = utils.isWritable; - Stream.Readable = require_readable3(); - for (const key of ObjectKeys(streamReturningOperators)) { - let fn2 = function(...args) { - if (new.target) { - throw ERR_ILLEGAL_CONSTRUCTOR(); - } - return Stream.Readable.from(ReflectApply(op, this, args)); - }; - fn = fn2; - const op = streamReturningOperators[key]; - ObjectDefineProperty(fn2, "name", { - __proto__: null, - value: op.name - }); - ObjectDefineProperty(fn2, "length", { - __proto__: null, - value: op.length - }); - ObjectDefineProperty(Stream.Readable.prototype, key, { - __proto__: null, - value: fn2, - enumerable: false, - configurable: true, - writable: true - }); - } - var fn; - for (const key of ObjectKeys(promiseReturningOperators)) { - let fn2 = function(...args) { - if (new.target) { - throw ERR_ILLEGAL_CONSTRUCTOR(); - } - return ReflectApply(op, this, args); - }; - fn = fn2; - const op = promiseReturningOperators[key]; - ObjectDefineProperty(fn2, "name", { - __proto__: null, - value: op.name - }); - ObjectDefineProperty(fn2, "length", { - __proto__: null, - value: op.length - }); - ObjectDefineProperty(Stream.Readable.prototype, key, { - __proto__: null, - value: fn2, - enumerable: false, - configurable: true, - writable: true - }); +// node_modules/lodash/_cacheHas.js +var require_cacheHas = __commonJS({ + "node_modules/lodash/_cacheHas.js"(exports2, module2) { + function cacheHas(cache, key) { + return cache.has(key); } - var fn; - Stream.Writable = require_writable(); - Stream.Duplex = require_duplex(); - Stream.Transform = require_transform(); - Stream.PassThrough = require_passthrough2(); - Stream.pipeline = pipeline; - var { addAbortSignal } = require_add_abort_signal(); - Stream.addAbortSignal = addAbortSignal; - Stream.finished = eos; - Stream.destroy = destroyer; - Stream.compose = compose; - Stream.setDefaultHighWaterMark = setDefaultHighWaterMark; - Stream.getDefaultHighWaterMark = getDefaultHighWaterMark; - ObjectDefineProperty(Stream, "promises", { - __proto__: null, - configurable: true, - enumerable: true, - get() { - return promises2; - } - }); - ObjectDefineProperty(pipeline, customPromisify, { - __proto__: null, - enumerable: true, - get() { - return promises2.pipeline; - } - }); - ObjectDefineProperty(eos, customPromisify, { - __proto__: null, - enumerable: true, - get() { - return promises2.finished; - } - }); - Stream.Stream = Stream; - Stream._isUint8Array = function isUint8Array(value) { - return value instanceof Uint8Array; - }; - Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); - }; + module2.exports = cacheHas; } }); -// node_modules/readable-stream/lib/ours/index.js -var require_ours = __commonJS({ - "node_modules/readable-stream/lib/ours/index.js"(exports2, module2) { - "use strict"; - var Stream = require("stream"); - if (Stream && process.env.READABLE_STREAM === "disable") { - const promises2 = Stream.promises; - module2.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer; - module2.exports._isUint8Array = Stream._isUint8Array; - module2.exports.isDisturbed = Stream.isDisturbed; - module2.exports.isErrored = Stream.isErrored; - module2.exports.isReadable = Stream.isReadable; - module2.exports.Readable = Stream.Readable; - module2.exports.Writable = Stream.Writable; - module2.exports.Duplex = Stream.Duplex; - module2.exports.Transform = Stream.Transform; - module2.exports.PassThrough = Stream.PassThrough; - module2.exports.addAbortSignal = Stream.addAbortSignal; - module2.exports.finished = Stream.finished; - module2.exports.destroy = Stream.destroy; - module2.exports.pipeline = Stream.pipeline; - module2.exports.compose = Stream.compose; - Object.defineProperty(Stream, "promises", { - configurable: true, - enumerable: true, - get() { - return promises2; - } - }); - module2.exports.Stream = Stream.Stream; - } else { - const CustomStream = require_stream2(); - const promises2 = require_promises(); - const originalDestroy = CustomStream.Readable.destroy; - module2.exports = CustomStream.Readable; - module2.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer; - module2.exports._isUint8Array = CustomStream._isUint8Array; - module2.exports.isDisturbed = CustomStream.isDisturbed; - module2.exports.isErrored = CustomStream.isErrored; - module2.exports.isReadable = CustomStream.isReadable; - module2.exports.Readable = CustomStream.Readable; - module2.exports.Writable = CustomStream.Writable; - module2.exports.Duplex = CustomStream.Duplex; - module2.exports.Transform = CustomStream.Transform; - module2.exports.PassThrough = CustomStream.PassThrough; - module2.exports.addAbortSignal = CustomStream.addAbortSignal; - module2.exports.finished = CustomStream.finished; - module2.exports.destroy = CustomStream.destroy; - module2.exports.destroy = originalDestroy; - module2.exports.pipeline = CustomStream.pipeline; - module2.exports.compose = CustomStream.compose; - Object.defineProperty(CustomStream, "promises", { - configurable: true, - enumerable: true, - get() { - return promises2; +// node_modules/lodash/_baseDifference.js +var require_baseDifference = __commonJS({ + "node_modules/lodash/_baseDifference.js"(exports2, module2) { + var SetCache = require_SetCache(); + var arrayIncludes = require_arrayIncludes(); + var arrayIncludesWith = require_arrayIncludesWith(); + var arrayMap = require_arrayMap(); + var baseUnary = require_baseUnary(); + var cacheHas = require_cacheHas(); + var LARGE_ARRAY_SIZE = 200; + function baseDifference(array, values, iteratee, comparator) { + var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], computed = iteratee == null ? value : iteratee(value); + value = comparator || value !== 0 ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } else if (!includes(values, computed, comparator)) { + result.push(value); + } } - }); - module2.exports.Stream = CustomStream.Stream; + return result; } - module2.exports.default = module2.exports; + module2.exports = baseDifference; } }); -// node_modules/lodash/_arrayPush.js -var require_arrayPush = __commonJS({ - "node_modules/lodash/_arrayPush.js"(exports2, module2) { - function arrayPush(array, values) { - var index = -1, length = values.length, offset = array.length; - while (++index < length) { - array[offset + index] = values[index]; - } - return array; +// node_modules/lodash/isArrayLikeObject.js +var require_isArrayLikeObject = __commonJS({ + "node_modules/lodash/isArrayLikeObject.js"(exports2, module2) { + var isArrayLike = require_isArrayLike(); + var isObjectLike = require_isObjectLike(); + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); } - module2.exports = arrayPush; + module2.exports = isArrayLikeObject; } }); -// node_modules/lodash/_isFlattenable.js -var require_isFlattenable = __commonJS({ - "node_modules/lodash/_isFlattenable.js"(exports2, module2) { - var Symbol2 = require_Symbol(); - var isArguments = require_isArguments(); - var isArray = require_isArray(); - var spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : void 0; - function isFlattenable(value) { - return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); +// node_modules/lodash/difference.js +var require_difference = __commonJS({ + "node_modules/lodash/difference.js"(exports2, module2) { + var baseDifference = require_baseDifference(); + var baseFlatten = require_baseFlatten(); + var baseRest = require_baseRest(); + var isArrayLikeObject = require_isArrayLikeObject(); + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; + }); + module2.exports = difference; + } +}); + +// node_modules/lodash/_Set.js +var require_Set = __commonJS({ + "node_modules/lodash/_Set.js"(exports2, module2) { + var getNative = require_getNative(); + var root = require_root(); + var Set2 = getNative(root, "Set"); + module2.exports = Set2; + } +}); + +// node_modules/lodash/noop.js +var require_noop = __commonJS({ + "node_modules/lodash/noop.js"(exports2, module2) { + function noop() { } - module2.exports = isFlattenable; + module2.exports = noop; } }); -// node_modules/lodash/_baseFlatten.js -var require_baseFlatten = __commonJS({ - "node_modules/lodash/_baseFlatten.js"(exports2, module2) { - var arrayPush = require_arrayPush(); - var isFlattenable = require_isFlattenable(); - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, length = array.length; - predicate || (predicate = isFlattenable); - 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(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } +// node_modules/lodash/_setToArray.js +var require_setToArray = __commonJS({ + "node_modules/lodash/_setToArray.js"(exports2, module2) { + function setToArray(set2) { + var index = -1, result = Array(set2.size); + set2.forEach(function(value) { + result[++index] = value; + }); return result; } - module2.exports = baseFlatten; + module2.exports = setToArray; } }); -// node_modules/lodash/flatten.js -var require_flatten = __commonJS({ - "node_modules/lodash/flatten.js"(exports2, module2) { - var baseFlatten = require_baseFlatten(); - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; +// node_modules/lodash/_createSet.js +var require_createSet = __commonJS({ + "node_modules/lodash/_createSet.js"(exports2, module2) { + var Set2 = require_Set(); + var noop = require_noop(); + var setToArray = require_setToArray(); + var INFINITY = 1 / 0; + var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop : function(values) { + return new Set2(values); + }; + module2.exports = createSet; + } +}); + +// node_modules/lodash/_baseUniq.js +var require_baseUniq = __commonJS({ + "node_modules/lodash/_baseUniq.js"(exports2, module2) { + var SetCache = require_SetCache(); + var arrayIncludes = require_arrayIncludes(); + var arrayIncludesWith = require_arrayIncludesWith(); + var cacheHas = require_cacheHas(); + var createSet = require_createSet(); + var setToArray = require_setToArray(); + var LARGE_ARRAY_SIZE = 200; + function baseUniq(array, iteratee, comparator) { + var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } else if (length >= LARGE_ARRAY_SIZE) { + var set2 = iteratee ? null : createSet(array); + if (set2) { + return setToArray(set2); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache(); + } else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], computed = iteratee ? iteratee(value) : value; + value = comparator || value !== 0 ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; } - module2.exports = flatten; + module2.exports = baseUniq; } }); -// node_modules/lodash/_nativeCreate.js -var require_nativeCreate = __commonJS({ - "node_modules/lodash/_nativeCreate.js"(exports2, module2) { - var getNative = require_getNative(); - var nativeCreate = getNative(Object, "create"); - module2.exports = nativeCreate; +// node_modules/lodash/union.js +var require_union = __commonJS({ + "node_modules/lodash/union.js"(exports2, module2) { + var baseFlatten = require_baseFlatten(); + var baseRest = require_baseRest(); + var baseUniq = require_baseUniq(); + var isArrayLikeObject = require_isArrayLikeObject(); + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + module2.exports = union; } }); -// node_modules/lodash/_hashClear.js -var require_hashClear = __commonJS({ - "node_modules/lodash/_hashClear.js"(exports2, module2) { - var nativeCreate = require_nativeCreate(); - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; +// node_modules/lodash/_overArg.js +var require_overArg = __commonJS({ + "node_modules/lodash/_overArg.js"(exports2, module2) { + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; } - module2.exports = hashClear; + module2.exports = overArg; } }); -// node_modules/lodash/_hashDelete.js -var require_hashDelete = __commonJS({ - "node_modules/lodash/_hashDelete.js"(exports2, module2) { - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - module2.exports = hashDelete; +// node_modules/lodash/_getPrototype.js +var require_getPrototype = __commonJS({ + "node_modules/lodash/_getPrototype.js"(exports2, module2) { + var overArg = require_overArg(); + var getPrototype = overArg(Object.getPrototypeOf, Object); + module2.exports = getPrototype; } }); -// node_modules/lodash/_hashGet.js -var require_hashGet = __commonJS({ - "node_modules/lodash/_hashGet.js"(exports2, module2) { - var nativeCreate = require_nativeCreate(); - var HASH_UNDEFINED = "__lodash_hash_undefined__"; +// node_modules/lodash/isPlainObject.js +var require_isPlainObject = __commonJS({ + "node_modules/lodash/isPlainObject.js"(exports2, module2) { + var baseGetTag = require_baseGetTag(); + var getPrototype = require_getPrototype(); + var isObjectLike = require_isObjectLike(); + var objectTag = "[object Object]"; + var funcProto = Function.prototype; var objectProto = Object.prototype; + var funcToString = funcProto.toString; var hasOwnProperty = objectProto.hasOwnProperty; - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? void 0 : result; + var objectCtorString = funcToString.call(Object); + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; } - return hasOwnProperty.call(data, key) ? data[key] : void 0; + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } - module2.exports = hashGet; + module2.exports = isPlainObject; } }); -// node_modules/lodash/_hashHas.js -var require_hashHas = __commonJS({ - "node_modules/lodash/_hashHas.js"(exports2, module2) { - var nativeCreate = require_nativeCreate(); - var objectProto = Object.prototype; - var hasOwnProperty = objectProto.hasOwnProperty; - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key); +// node_modules/archiver-utils/node_modules/brace-expansion/index.js +var require_brace_expansion2 = __commonJS({ + "node_modules/archiver-utils/node_modules/brace-expansion/index.js"(exports2, module2) { + var balanced = require_balanced_match(); + module2.exports = expandTop; + var escSlash = "\0SLASH" + Math.random() + "\0"; + var escOpen = "\0OPEN" + Math.random() + "\0"; + var escClose = "\0CLOSE" + Math.random() + "\0"; + var escComma = "\0COMMA" + Math.random() + "\0"; + var escPeriod = "\0PERIOD" + Math.random() + "\0"; + function numeric(str2) { + return parseInt(str2, 10) == str2 ? parseInt(str2, 10) : str2.charCodeAt(0); + } + function escapeBraces(str2) { + return str2.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod); + } + function unescapeBraces(str2) { + return str2.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join("."); + } + function parseCommaParts(str2) { + if (!str2) + return [""]; + var parts = []; + var m = balanced("{", "}", str2); + if (!m) + return str2.split(","); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(","); + p[p.length - 1] += "{" + body + "}"; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; + } + function expandTop(str2) { + if (!str2) + return []; + if (str2.substr(0, 2) === "{}") { + str2 = "\\{\\}" + str2.substr(2); + } + return expand(escapeBraces(str2), true).map(unescapeBraces); + } + function embrace(str2) { + return "{" + str2 + "}"; + } + function isPadded(el) { + return /^-?0\d/.test(el); + } + function lte(i, y) { + return i <= y; + } + function gte5(i, y) { + return i >= y; + } + function expand(str2, isTop) { + var expansions = []; + var m = balanced("{", "}", str2); + if (!m) return [str2]; + var pre = m.pre; + var post = m.post.length ? expand(m.post, false) : [""]; + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + "{" + m.body + "}" + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(",") >= 0; + if (!isSequence && !isOptions) { + if (m.post.match(/,(?!,).*\}/)) { + str2 = m.pre + "{" + m.body + escClose + m.post; + return expand(str2); + } + return [str2]; + } + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + var N; + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte5; + } + var pad = n.some(isPadded); + N = []; + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === "\\") + c = ""; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join("0"); + if (i < 0) + c = "-" + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } + } + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } + return expansions; } - module2.exports = hashHas; } }); -// node_modules/lodash/_hashSet.js -var require_hashSet = __commonJS({ - "node_modules/lodash/_hashSet.js"(exports2, module2) { - var nativeCreate = require_nativeCreate(); - var HASH_UNDEFINED = "__lodash_hash_undefined__"; - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; - return this; - } - module2.exports = hashSet; +// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js +var require_assert_valid_pattern = __commonJS({ + "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.assertValidPattern = void 0; + var MAX_PATTERN_LENGTH = 1024 * 64; + var assertValidPattern = (pattern) => { + if (typeof pattern !== "string") { + throw new TypeError("invalid pattern"); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError("pattern is too long"); + } + }; + exports2.assertValidPattern = assertValidPattern; } }); -// node_modules/lodash/_Hash.js -var require_Hash = __commonJS({ - "node_modules/lodash/_Hash.js"(exports2, module2) { - var hashClear = require_hashClear(); - var hashDelete = require_hashDelete(); - var hashGet = require_hashGet(); - var hashHas = require_hashHas(); - var hashSet = require_hashSet(); - 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]); +// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/brace-expressions.js +var require_brace_expressions = __commonJS({ + "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/brace-expressions.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.parseClass = void 0; + var posixClasses = { + "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true], + "[:alpha:]": ["\\p{L}\\p{Nl}", true], + "[:ascii:]": ["\\x00-\\x7f", false], + "[:blank:]": ["\\p{Zs}\\t", true], + "[:cntrl:]": ["\\p{Cc}", true], + "[:digit:]": ["\\p{Nd}", true], + "[:graph:]": ["\\p{Z}\\p{C}", true, true], + "[:lower:]": ["\\p{Ll}", true], + "[:print:]": ["\\p{C}", true], + "[:punct:]": ["\\p{P}", true], + "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true], + "[:upper:]": ["\\p{Lu}", true], + "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true], + "[:xdigit:]": ["A-Fa-f0-9", false] + }; + var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&"); + var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + var rangesToString = (ranges) => ranges.join(""); + var parseClass = (glob2, position) => { + const pos = position; + if (glob2.charAt(pos) !== "[") { + throw new Error("not in a brace expression"); + } + const ranges = []; + const negs = []; + let i = pos + 1; + let sawStart = false; + let uflag = false; + let escaping = false; + let negate = false; + let endPos = pos; + let rangeStart = ""; + WHILE: while (i < glob2.length) { + const c = glob2.charAt(i); + if ((c === "!" || c === "^") && i === pos + 1) { + negate = true; + i++; + continue; + } + if (c === "]" && sawStart && !escaping) { + endPos = i + 1; + break; + } + sawStart = true; + if (c === "\\") { + if (!escaping) { + escaping = true; + i++; + continue; + } + } + if (c === "[" && !escaping) { + for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { + if (glob2.startsWith(cls, i)) { + if (rangeStart) { + return ["$.", false, glob2.length - pos, true]; + } + i += cls.length; + if (neg) + negs.push(unip); + else + ranges.push(unip); + uflag = uflag || u; + continue WHILE; + } + } + } + escaping = false; + if (rangeStart) { + if (c > rangeStart) { + ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c)); + } else if (c === rangeStart) { + ranges.push(braceEscape(c)); + } + rangeStart = ""; + i++; + continue; + } + if (glob2.startsWith("-]", i + 1)) { + ranges.push(braceEscape(c + "-")); + i += 2; + continue; + } + if (glob2.startsWith("-", i + 1)) { + rangeStart = c; + i += 2; + continue; + } + ranges.push(braceEscape(c)); + i++; } - } - Hash.prototype.clear = hashClear; - Hash.prototype["delete"] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - module2.exports = Hash; + if (endPos < i) { + return ["", false, 0, false]; + } + if (!ranges.length && !negs.length) { + return ["$.", false, glob2.length - pos, true]; + } + if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) { + const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; + return [regexpEscape(r), false, endPos - pos, false]; + } + const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]"; + const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]"; + const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs; + return [comb, uflag, endPos - pos, true]; + }; + exports2.parseClass = parseClass; } }); -// node_modules/lodash/_listCacheClear.js -var require_listCacheClear = __commonJS({ - "node_modules/lodash/_listCacheClear.js"(exports2, module2) { - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - module2.exports = listCacheClear; +// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/unescape.js +var require_unescape = __commonJS({ + "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/unescape.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.unescape = void 0; + var unescape = (s, { windowsPathsNoEscape = false } = {}) => { + return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1"); + }; + exports2.unescape = unescape; } }); -// node_modules/lodash/_assocIndexOf.js -var require_assocIndexOf = __commonJS({ - "node_modules/lodash/_assocIndexOf.js"(exports2, module2) { - var eq = require_eq2(); - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; +// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/ast.js +var require_ast = __commonJS({ + "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/ast.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AST = void 0; + var brace_expressions_js_1 = require_brace_expressions(); + var unescape_js_1 = require_unescape(); + var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]); + var isExtglobType = (c) => types.has(c); + var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))"; + var startNoDot = "(?!\\.)"; + var addPatternStart = /* @__PURE__ */ new Set(["[", "."]); + var justDots = /* @__PURE__ */ new Set(["..", "."]); + var reSpecials = new Set("().*{}+?[]^$\\!"); + var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + var qmark = "[^/]"; + var star = qmark + "*?"; + var starNoEmpty = qmark + "+?"; + var AST = class _AST { + type; + #root; + #hasMagic; + #uflag = false; + #parts = []; + #parent; + #parentIndex; + #negs; + #filledNegs = false; + #options; + #toString; + // set to true if it's an extglob with no children + // (which really means one child of '') + #emptyExt = false; + constructor(type2, parent, options = {}) { + this.type = type2; + if (type2) + this.#hasMagic = true; + this.#parent = parent; + this.#root = this.#parent ? this.#parent.#root : this; + this.#options = this.#root === this ? options : this.#root.#options; + this.#negs = this.#root === this ? [] : this.#root.#negs; + if (type2 === "!" && !this.#root.#filledNegs) + this.#negs.push(this); + this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0; + } + get hasMagic() { + if (this.#hasMagic !== void 0) + return this.#hasMagic; + for (const p of this.#parts) { + if (typeof p === "string") + continue; + if (p.type || p.hasMagic) + return this.#hasMagic = true; + } + return this.#hasMagic; + } + // reconstructs the pattern + toString() { + if (this.#toString !== void 0) + return this.#toString; + if (!this.type) { + return this.#toString = this.#parts.map((p) => String(p)).join(""); + } else { + return this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")"; + } + } + #fillNegs() { + if (this !== this.#root) + throw new Error("should only call on root"); + if (this.#filledNegs) + return this; + this.toString(); + this.#filledNegs = true; + let n; + while (n = this.#negs.pop()) { + if (n.type !== "!") + continue; + let p = n; + let pp = p.#parent; + while (pp) { + for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) { + for (const part of n.#parts) { + if (typeof part === "string") { + throw new Error("string part in extglob AST??"); + } + part.copyIn(pp.#parts[i]); + } + } + p = pp; + pp = p.#parent; + } + } + return this; + } + push(...parts) { + for (const p of parts) { + if (p === "") + continue; + if (typeof p !== "string" && !(p instanceof _AST && p.#parent === this)) { + throw new Error("invalid part: " + p); + } + this.#parts.push(p); + } + } + toJSON() { + const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())]; + if (this.isStart() && !this.type) + ret.unshift([]); + if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) { + ret.push({}); + } + return ret; + } + isStart() { + if (this.#root === this) + return true; + if (!this.#parent?.isStart()) + return false; + if (this.#parentIndex === 0) + return true; + const p = this.#parent; + for (let i = 0; i < this.#parentIndex; i++) { + const pp = p.#parts[i]; + if (!(pp instanceof _AST && pp.type === "!")) { + return false; + } + } + return true; + } + isEnd() { + if (this.#root === this) + return true; + if (this.#parent?.type === "!") + return true; + if (!this.#parent?.isEnd()) + return false; + if (!this.type) + return this.#parent?.isEnd(); + const pl = this.#parent ? this.#parent.#parts.length : 0; + return this.#parentIndex === pl - 1; + } + copyIn(part) { + if (typeof part === "string") + this.push(part); + else + this.push(part.clone(this)); + } + clone(parent) { + const c = new _AST(this.type, parent); + for (const p of this.#parts) { + c.copyIn(p); + } + return c; + } + static #parseAST(str2, ast, pos, opt) { + let escaping = false; + let inBrace = false; + let braceStart = -1; + let braceNeg = false; + if (ast.type === null) { + let i2 = pos; + let acc2 = ""; + while (i2 < str2.length) { + const c = str2.charAt(i2++); + if (escaping || c === "\\") { + escaping = !escaping; + acc2 += c; + continue; + } + if (inBrace) { + if (i2 === braceStart + 1) { + if (c === "^" || c === "!") { + braceNeg = true; + } + } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc2 += c; + continue; + } else if (c === "[") { + inBrace = true; + braceStart = i2; + braceNeg = false; + acc2 += c; + continue; + } + if (!opt.noext && isExtglobType(c) && str2.charAt(i2) === "(") { + ast.push(acc2); + acc2 = ""; + const ext = new _AST(c, ast); + i2 = _AST.#parseAST(str2, ext, i2, opt); + ast.push(ext); + continue; + } + acc2 += c; + } + ast.push(acc2); + return i2; + } + let i = pos + 1; + let part = new _AST(null, ast); + const parts = []; + let acc = ""; + while (i < str2.length) { + const c = str2.charAt(i++); + if (escaping || c === "\\") { + escaping = !escaping; + acc += c; + continue; + } + if (inBrace) { + if (i === braceStart + 1) { + if (c === "^" || c === "!") { + braceNeg = true; + } + } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc += c; + continue; + } else if (c === "[") { + inBrace = true; + braceStart = i; + braceNeg = false; + acc += c; + continue; + } + if (isExtglobType(c) && str2.charAt(i) === "(") { + part.push(acc); + acc = ""; + const ext = new _AST(c, part); + part.push(ext); + i = _AST.#parseAST(str2, ext, i, opt); + continue; + } + if (c === "|") { + part.push(acc); + acc = ""; + parts.push(part); + part = new _AST(null, ast); + continue; + } + if (c === ")") { + if (acc === "" && ast.#parts.length === 0) { + ast.#emptyExt = true; + } + part.push(acc); + acc = ""; + ast.push(...parts, part); + return i; + } + acc += c; + } + ast.type = null; + ast.#hasMagic = void 0; + ast.#parts = [str2.substring(pos - 1)]; + return i; + } + static fromGlob(pattern, options = {}) { + const ast = new _AST(null, void 0, options); + _AST.#parseAST(pattern, ast, 0, options); + return ast; + } + // returns the regular expression if there's magic, or the unescaped + // string if not. + toMMPattern() { + if (this !== this.#root) + return this.#root.toMMPattern(); + const glob2 = this.toString(); + const [re, body, hasMagic, uflag] = this.toRegExpSource(); + const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob2.toUpperCase() !== glob2.toLowerCase(); + if (!anyMagic) { + return body; + } + const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : ""); + return Object.assign(new RegExp(`^${re}$`, flags), { + _src: re, + _glob: glob2 + }); + } + get options() { + return this.#options; + } + // returns the string match, the regexp source, whether there's magic + // in the regexp (so a regular expression is required) and whether or + // not the uflag is needed for the regular expression (for posix classes) + // TODO: instead of injecting the start/end at this point, just return + // the BODY of the regexp, along with the start/end portions suitable + // for binding the start/end in either a joined full-path makeRe context + // (where we bind to (^|/), or a standalone matchPart context (where + // we bind to ^, and not /). Otherwise slashes get duped! + // + // In part-matching mode, the start is: + // - if not isStart: nothing + // - if traversal possible, but not allowed: ^(?!\.\.?$) + // - if dots allowed or not possible: ^ + // - if dots possible and not allowed: ^(?!\.) + // end is: + // - if not isEnd(): nothing + // - else: $ + // + // In full-path matching mode, we put the slash at the START of the + // pattern, so start is: + // - if first pattern: same as part-matching mode + // - if not isStart(): nothing + // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) + // - if dots allowed or not possible: / + // - if dots possible and not allowed: /(?!\.) + // end is: + // - if last pattern, same as part-matching mode + // - else nothing + // + // Always put the (?:$|/) on negated tails, though, because that has to be + // there to bind the end of the negated pattern portion, and it's easier to + // just stick it in now rather than try to inject it later in the middle of + // the pattern. + // + // We can just always return the same end, and leave it up to the caller + // to know whether it's going to be used joined or in parts. + // And, if the start is adjusted slightly, can do the same there: + // - if not isStart: nothing + // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) + // - if dots allowed or not possible: (?:/|^) + // - if dots possible and not allowed: (?:/|^)(?!\.) + // + // But it's better to have a simpler binding without a conditional, for + // performance, so probably better to return both start options. + // + // Then the caller just ignores the end if it's not the first pattern, + // and the start always gets applied. + // + // But that's always going to be $ if it's the ending pattern, or nothing, + // so the caller can just attach $ at the end of the pattern when building. + // + // So the todo is: + // - better detect what kind of start is needed + // - return both flavors of starting pattern + // - attach $ at the end of the pattern when creating the actual RegExp + // + // Ah, but wait, no, that all only applies to the root when the first pattern + // is not an extglob. If the first pattern IS an extglob, then we need all + // that dot prevention biz to live in the extglob portions, because eg + // +(*|.x*) can match .xy but not .yx. + // + // So, return the two flavors if it's #root and the first child is not an + // AST, otherwise leave it to the child AST to handle it, and there, + // use the (?:^|/) style of start binding. + // + // Even simplified further: + // - Since the start for a join is eg /(?!\.) and the start for a part + // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root + // or start or whatever) and prepend ^ or / at the Regexp construction. + toRegExpSource(allowDot) { + const dot = allowDot ?? !!this.#options.dot; + if (this.#root === this) + this.#fillNegs(); + if (!this.type) { + const noEmpty = this.isStart() && this.isEnd(); + const src = this.#parts.map((p) => { + const [re, _2, hasMagic, uflag] = typeof p === "string" ? _AST.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot); + this.#hasMagic = this.#hasMagic || hasMagic; + this.#uflag = this.#uflag || uflag; + return re; + }).join(""); + let start2 = ""; + if (this.isStart()) { + if (typeof this.#parts[0] === "string") { + const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]); + if (!dotTravAllowed) { + const aps = addPatternStart; + const needNoTrav = ( + // dots are allowed, and the pattern starts with [ or . + dot && aps.has(src.charAt(0)) || // the pattern starts with \., and then [ or . + src.startsWith("\\.") && aps.has(src.charAt(2)) || // the pattern starts with \.\., and then [ or . + src.startsWith("\\.\\.") && aps.has(src.charAt(4)) + ); + const needNoDot = !dot && !allowDot && aps.has(src.charAt(0)); + start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ""; + } + } + } + let end = ""; + if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") { + end = "(?:$|\\/)"; + } + const final2 = start2 + src + end; + return [ + final2, + (0, unescape_js_1.unescape)(src), + this.#hasMagic = !!this.#hasMagic, + this.#uflag + ]; + } + const repeated = this.type === "*" || this.type === "+"; + const start = this.type === "!" ? "(?:(?!(?:" : "(?:"; + let body = this.#partsToRegExp(dot); + if (this.isStart() && this.isEnd() && !body && this.type !== "!") { + const s = this.toString(); + this.#parts = [s]; + this.type = null; + this.#hasMagic = void 0; + return [s, (0, unescape_js_1.unescape)(this.toString()), false, false]; + } + let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true); + if (bodyDotAllowed === body) { + bodyDotAllowed = ""; + } + if (bodyDotAllowed) { + body = `(?:${body})(?:${bodyDotAllowed})*?`; } + let final = ""; + if (this.type === "!" && this.#emptyExt) { + final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty; + } else { + const close = this.type === "!" ? ( + // !() must match something,but !(x) can match '' + "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")" + ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`; + final = start + body + close; + } + return [ + final, + (0, unescape_js_1.unescape)(body), + this.#hasMagic = !!this.#hasMagic, + this.#uflag + ]; } - return -1; - } - module2.exports = assocIndexOf; - } -}); - -// node_modules/lodash/_listCacheDelete.js -var require_listCacheDelete = __commonJS({ - "node_modules/lodash/_listCacheDelete.js"(exports2, module2) { - var assocIndexOf = require_assocIndexOf(); - var arrayProto = Array.prototype; - var splice = arrayProto.splice; - function listCacheDelete(key) { - var data = this.__data__, index = assocIndexOf(data, key); - if (index < 0) { - return false; + #partsToRegExp(dot) { + return this.#parts.map((p) => { + if (typeof p === "string") { + throw new Error("string type in extglob ast??"); + } + const [re, _2, _hasMagic, uflag] = p.toRegExpSource(dot); + this.#uflag = this.#uflag || uflag; + return re; + }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|"); } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); + static #parseGlob(glob2, hasMagic, noEmpty = false) { + let escaping = false; + let re = ""; + let uflag = false; + for (let i = 0; i < glob2.length; i++) { + const c = glob2.charAt(i); + if (escaping) { + escaping = false; + re += (reSpecials.has(c) ? "\\" : "") + c; + continue; + } + if (c === "\\") { + if (i === glob2.length - 1) { + re += "\\\\"; + } else { + escaping = true; + } + continue; + } + if (c === "[") { + const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob2, i); + if (consumed) { + re += src; + uflag = uflag || needUflag; + i += consumed - 1; + hasMagic = hasMagic || magic; + continue; + } + } + if (c === "*") { + if (noEmpty && glob2 === "*") + re += starNoEmpty; + else + re += star; + hasMagic = true; + continue; + } + if (c === "?") { + re += qmark; + hasMagic = true; + continue; + } + re += regExpEscape(c); + } + return [re, (0, unescape_js_1.unescape)(glob2), !!hasMagic, uflag]; } - --this.size; - return true; - } - module2.exports = listCacheDelete; - } -}); - -// node_modules/lodash/_listCacheGet.js -var require_listCacheGet = __commonJS({ - "node_modules/lodash/_listCacheGet.js"(exports2, module2) { - var assocIndexOf = require_assocIndexOf(); - function listCacheGet(key) { - var data = this.__data__, index = assocIndexOf(data, key); - return index < 0 ? void 0 : data[index][1]; - } - module2.exports = listCacheGet; - } -}); - -// node_modules/lodash/_listCacheHas.js -var require_listCacheHas = __commonJS({ - "node_modules/lodash/_listCacheHas.js"(exports2, module2) { - var assocIndexOf = require_assocIndexOf(); - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - module2.exports = listCacheHas; + }; + exports2.AST = AST; } }); -// node_modules/lodash/_listCacheSet.js -var require_listCacheSet = __commonJS({ - "node_modules/lodash/_listCacheSet.js"(exports2, module2) { - var assocIndexOf = require_assocIndexOf(); - function listCacheSet(key, value) { - var data = this.__data__, index = assocIndexOf(data, key); - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - module2.exports = listCacheSet; +// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/escape.js +var require_escape = __commonJS({ + "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/escape.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.escape = void 0; + var escape = (s, { windowsPathsNoEscape = false } = {}) => { + return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&"); + }; + exports2.escape = escape; } }); -// node_modules/lodash/_ListCache.js -var require_ListCache = __commonJS({ - "node_modules/lodash/_ListCache.js"(exports2, module2) { - var listCacheClear = require_listCacheClear(); - var listCacheDelete = require_listCacheDelete(); - var listCacheGet = require_listCacheGet(); - var listCacheHas = require_listCacheHas(); - var listCacheSet = require_listCacheSet(); - 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]); +// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/index.js +var require_commonjs13 = __commonJS({ + "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/index.js"(exports2) { + "use strict"; + var __importDefault4 = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.unescape = exports2.escape = exports2.AST = exports2.Minimatch = exports2.match = exports2.makeRe = exports2.braceExpand = exports2.defaults = exports2.filter = exports2.GLOBSTAR = exports2.sep = exports2.minimatch = void 0; + var brace_expansion_1 = __importDefault4(require_brace_expansion2()); + var assert_valid_pattern_js_1 = require_assert_valid_pattern(); + var ast_js_1 = require_ast(); + var escape_js_1 = require_escape(); + var unescape_js_1 = require_unescape(); + var minimatch = (p, pattern, options = {}) => { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + if (!options.nocomment && pattern.charAt(0) === "#") { + return false; } - } - ListCache.prototype.clear = listCacheClear; - ListCache.prototype["delete"] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - module2.exports = ListCache; - } -}); - -// node_modules/lodash/_Map.js -var require_Map = __commonJS({ - "node_modules/lodash/_Map.js"(exports2, module2) { - var getNative = require_getNative(); - var root = require_root(); - var Map2 = getNative(root, "Map"); - module2.exports = Map2; - } -}); - -// node_modules/lodash/_mapCacheClear.js -var require_mapCacheClear = __commonJS({ - "node_modules/lodash/_mapCacheClear.js"(exports2, module2) { - var Hash = require_Hash(); - var ListCache = require_ListCache(); - var Map2 = require_Map(); - function mapCacheClear() { - this.size = 0; - this.__data__ = { - "hash": new Hash(), - "map": new (Map2 || ListCache)(), - "string": new Hash() - }; - } - module2.exports = mapCacheClear; - } -}); - -// node_modules/lodash/_isKeyable.js -var require_isKeyable = __commonJS({ - "node_modules/lodash/_isKeyable.js"(exports2, module2) { - function isKeyable(value) { - var type2 = typeof value; - return type2 == "string" || type2 == "number" || type2 == "symbol" || type2 == "boolean" ? value !== "__proto__" : value === null; - } - module2.exports = isKeyable; - } -}); - -// node_modules/lodash/_getMapData.js -var require_getMapData = __commonJS({ - "node_modules/lodash/_getMapData.js"(exports2, module2) { - var isKeyable = require_isKeyable(); - function getMapData(map2, key) { - var data = map2.__data__; - return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; - } - module2.exports = getMapData; - } -}); - -// node_modules/lodash/_mapCacheDelete.js -var require_mapCacheDelete = __commonJS({ - "node_modules/lodash/_mapCacheDelete.js"(exports2, module2) { - var getMapData = require_getMapData(); - function mapCacheDelete(key) { - var result = getMapData(this, key)["delete"](key); - this.size -= result ? 1 : 0; - return result; - } - module2.exports = mapCacheDelete; - } -}); - -// node_modules/lodash/_mapCacheGet.js -var require_mapCacheGet = __commonJS({ - "node_modules/lodash/_mapCacheGet.js"(exports2, module2) { - var getMapData = require_getMapData(); - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - module2.exports = mapCacheGet; - } -}); - -// node_modules/lodash/_mapCacheHas.js -var require_mapCacheHas = __commonJS({ - "node_modules/lodash/_mapCacheHas.js"(exports2, module2) { - var getMapData = require_getMapData(); - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - module2.exports = mapCacheHas; - } -}); - -// node_modules/lodash/_mapCacheSet.js -var require_mapCacheSet = __commonJS({ - "node_modules/lodash/_mapCacheSet.js"(exports2, module2) { - var getMapData = require_getMapData(); - function mapCacheSet(key, value) { - var data = getMapData(this, key), size = data.size; - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - module2.exports = mapCacheSet; - } -}); - -// node_modules/lodash/_MapCache.js -var require_MapCache = __commonJS({ - "node_modules/lodash/_MapCache.js"(exports2, module2) { - var mapCacheClear = require_mapCacheClear(); - var mapCacheDelete = require_mapCacheDelete(); - var mapCacheGet = require_mapCacheGet(); - var mapCacheHas = require_mapCacheHas(); - var mapCacheSet = require_mapCacheSet(); - 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]); + return new Minimatch(pattern, options).match(p); + }; + exports2.minimatch = minimatch; + var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; + var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2); + var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2); + var starDotExtTestNocase = (ext2) => { + ext2 = ext2.toLowerCase(); + return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2); + }; + var starDotExtTestNocaseDot = (ext2) => { + ext2 = ext2.toLowerCase(); + return (f) => f.toLowerCase().endsWith(ext2); + }; + var starDotStarRE = /^\*+\.\*+$/; + var starDotStarTest = (f) => !f.startsWith(".") && f.includes("."); + var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes("."); + var dotStarRE = /^\.\*+$/; + var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith("."); + var starRE = /^\*+$/; + var starTest = (f) => f.length !== 0 && !f.startsWith("."); + var starTestDot = (f) => f.length !== 0 && f !== "." && f !== ".."; + var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; + var qmarksTestNocase = ([$0, ext2 = ""]) => { + const noext = qmarksTestNoExt([$0]); + if (!ext2) + return noext; + ext2 = ext2.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext2); + }; + var qmarksTestNocaseDot = ([$0, ext2 = ""]) => { + const noext = qmarksTestNoExtDot([$0]); + if (!ext2) + return noext; + ext2 = ext2.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext2); + }; + var qmarksTestDot = ([$0, ext2 = ""]) => { + const noext = qmarksTestNoExtDot([$0]); + return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2); + }; + var qmarksTest = ([$0, ext2 = ""]) => { + const noext = qmarksTestNoExt([$0]); + return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2); + }; + var qmarksTestNoExt = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && !f.startsWith("."); + }; + var qmarksTestNoExtDot = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && f !== "." && f !== ".."; + }; + var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix"; + var path2 = { + win32: { sep: "\\" }, + posix: { sep: "/" } + }; + exports2.sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep; + exports2.minimatch.sep = exports2.sep; + exports2.GLOBSTAR = Symbol("globstar **"); + exports2.minimatch.GLOBSTAR = exports2.GLOBSTAR; + var qmark = "[^/]"; + var star = qmark + "*?"; + var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?"; + var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; + var filter = (pattern, options = {}) => (p) => (0, exports2.minimatch)(p, pattern, options); + exports2.filter = filter; + exports2.minimatch.filter = exports2.filter; + var ext = (a, b = {}) => Object.assign({}, a, b); + var defaults = (def) => { + if (!def || typeof def !== "object" || !Object.keys(def).length) { + return exports2.minimatch; } - } - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype["delete"] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - module2.exports = MapCache; - } -}); - -// node_modules/lodash/_setCacheAdd.js -var require_setCacheAdd = __commonJS({ - "node_modules/lodash/_setCacheAdd.js"(exports2, module2) { - var HASH_UNDEFINED = "__lodash_hash_undefined__"; - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } - module2.exports = setCacheAdd; - } -}); - -// node_modules/lodash/_setCacheHas.js -var require_setCacheHas = __commonJS({ - "node_modules/lodash/_setCacheHas.js"(exports2, module2) { - function setCacheHas(value) { - return this.__data__.has(value); - } - module2.exports = setCacheHas; - } -}); - -// node_modules/lodash/_SetCache.js -var require_SetCache = __commonJS({ - "node_modules/lodash/_SetCache.js"(exports2, module2) { - var MapCache = require_MapCache(); - var setCacheAdd = require_setCacheAdd(); - var setCacheHas = require_setCacheHas(); - function SetCache(values) { - var index = -1, length = values == null ? 0 : values.length; - this.__data__ = new MapCache(); - while (++index < length) { - this.add(values[index]); + const orig = exports2.minimatch; + const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); + return Object.assign(m, { + Minimatch: class Minimatch extends orig.Minimatch { + constructor(pattern, options = {}) { + super(pattern, ext(def, options)); + } + static defaults(options) { + return orig.defaults(ext(def, options)).Minimatch; + } + }, + AST: class AST extends orig.AST { + /* c8 ignore start */ + constructor(type2, parent, options = {}) { + super(type2, parent, ext(def, options)); + } + /* c8 ignore stop */ + static fromGlob(pattern, options = {}) { + return orig.AST.fromGlob(pattern, ext(def, options)); + } + }, + unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), + escape: (s, options = {}) => orig.escape(s, ext(def, options)), + filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), + defaults: (options) => orig.defaults(ext(def, options)), + makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), + braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), + match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), + sep: orig.sep, + GLOBSTAR: exports2.GLOBSTAR + }); + }; + exports2.defaults = defaults; + exports2.minimatch.defaults = exports2.defaults; + var braceExpand = (pattern, options = {}) => { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + return [pattern]; } - } - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - module2.exports = SetCache; - } -}); - -// node_modules/lodash/_baseFindIndex.js -var require_baseFindIndex = __commonJS({ - "node_modules/lodash/_baseFindIndex.js"(exports2, module2) { - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, index = fromIndex + (fromRight ? 1 : -1); - while (fromRight ? index-- : ++index < length) { - if (predicate(array[index], index, array)) { - return index; - } + return (0, brace_expansion_1.default)(pattern); + }; + exports2.braceExpand = braceExpand; + exports2.minimatch.braceExpand = exports2.braceExpand; + var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); + exports2.makeRe = makeRe; + exports2.minimatch.makeRe = exports2.makeRe; + var match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options); + list = list.filter((f) => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); } - return -1; - } - module2.exports = baseFindIndex; - } -}); - -// node_modules/lodash/_baseIsNaN.js -var require_baseIsNaN = __commonJS({ - "node_modules/lodash/_baseIsNaN.js"(exports2, module2) { - function baseIsNaN(value) { - return value !== value; - } - module2.exports = baseIsNaN; - } -}); - -// node_modules/lodash/_strictIndexOf.js -var require_strictIndexOf = __commonJS({ - "node_modules/lodash/_strictIndexOf.js"(exports2, module2) { - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; + return list; + }; + exports2.match = match; + exports2.minimatch.match = exports2.match; + var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; + var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + var Minimatch = class { + options; + set; + pattern; + windowsPathsNoEscape; + nonegate; + negate; + comment; + empty; + preserveMultipleSlashes; + partial; + globSet; + globParts; + nocase; + isWindows; + platform; + windowsNoMagicRoot; + regexp; + constructor(pattern, options = {}) { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + options = options || {}; + this.options = options; + this.pattern = pattern; + this.platform = options.platform || defaultPlatform; + this.isWindows = this.platform === "win32"; + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, "/"); } + this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; + this.regexp = null; + this.negate = false; + this.nonegate = !!options.nonegate; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + this.nocase = !!this.options.nocase; + this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase); + this.globSet = []; + this.globParts = []; + this.set = []; + this.make(); } - return -1; - } - module2.exports = strictIndexOf; - } -}); - -// node_modules/lodash/_baseIndexOf.js -var require_baseIndexOf = __commonJS({ - "node_modules/lodash/_baseIndexOf.js"(exports2, module2) { - var baseFindIndex = require_baseFindIndex(); - var baseIsNaN = require_baseIsNaN(); - var strictIndexOf = require_strictIndexOf(); - function baseIndexOf(array, value, fromIndex) { - return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); - } - module2.exports = baseIndexOf; - } -}); - -// node_modules/lodash/_arrayIncludes.js -var require_arrayIncludes = __commonJS({ - "node_modules/lodash/_arrayIncludes.js"(exports2, module2) { - var baseIndexOf = require_baseIndexOf(); - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } - module2.exports = arrayIncludes; - } -}); - -// node_modules/lodash/_arrayIncludesWith.js -var require_arrayIncludesWith = __commonJS({ - "node_modules/lodash/_arrayIncludesWith.js"(exports2, module2) { - function arrayIncludesWith(array, value, comparator) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (comparator(value, array[index])) { + hasMagic() { + if (this.options.magicalBraces && this.set.length > 1) { return true; } + for (const pattern of this.set) { + for (const part of pattern) { + if (typeof part !== "string") + return true; + } + } + return false; } - return false; - } - module2.exports = arrayIncludesWith; - } -}); - -// node_modules/lodash/_arrayMap.js -var require_arrayMap = __commonJS({ - "node_modules/lodash/_arrayMap.js"(exports2, module2) { - 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); + debug(..._2) { } - return result; - } - module2.exports = arrayMap; - } -}); - -// node_modules/lodash/_cacheHas.js -var require_cacheHas = __commonJS({ - "node_modules/lodash/_cacheHas.js"(exports2, module2) { - function cacheHas(cache, key) { - return cache.has(key); - } - module2.exports = cacheHas; - } -}); - -// node_modules/lodash/_baseDifference.js -var require_baseDifference = __commonJS({ - "node_modules/lodash/_baseDifference.js"(exports2, module2) { - var SetCache = require_SetCache(); - var arrayIncludes = require_arrayIncludes(); - var arrayIncludesWith = require_arrayIncludesWith(); - var arrayMap = require_arrayMap(); - var baseUnary = require_baseUnary(); - var cacheHas = require_cacheHas(); - var LARGE_ARRAY_SIZE = 200; - function baseDifference(array, values, iteratee, comparator) { - var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; - if (!length) { - return result; + make() { + const pattern = this.pattern; + const options = this.options; + if (!options.nocomment && pattern.charAt(0) === "#") { + this.comment = true; + return; + } + if (!pattern) { + this.empty = true; + return; + } + this.parseNegate(); + this.globSet = [...new Set(this.braceExpand())]; + if (options.debug) { + this.debug = (...args) => console.error(...args); + } + this.debug(this.pattern, this.globSet); + const rawGlobParts = this.globSet.map((s) => this.slashSplit(s)); + this.globParts = this.preprocess(rawGlobParts); + this.debug(this.pattern, this.globParts); + let set2 = this.globParts.map((s, _2, __) => { + if (this.isWindows && this.windowsNoMagicRoot) { + const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]); + const isDrive = /^[a-z]:/i.test(s[0]); + if (isUNC) { + return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))]; + } else if (isDrive) { + return [s[0], ...s.slice(1).map((ss) => this.parse(ss))]; + } + } + return s.map((ss) => this.parse(ss)); + }); + this.debug(this.pattern, set2); + this.set = set2.filter((s) => s.indexOf(false) === -1); + if (this.isWindows) { + for (let i = 0; i < this.set.length; i++) { + const p = this.set[i]; + if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) { + p[2] = "?"; + } + } + } + this.debug(this.pattern, this.set); } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); + // various transforms to equivalent pattern sets that are + // faster to process in a filesystem walk. The goal is to + // eliminate what we can, and push all ** patterns as far + // to the right as possible, even if it increases the number + // of patterns that we have to process. + preprocess(globParts) { + if (this.options.noglobstar) { + for (let i = 0; i < globParts.length; i++) { + for (let j = 0; j < globParts[i].length; j++) { + if (globParts[i][j] === "**") { + globParts[i][j] = "*"; + } + } + } + } + const { optimizationLevel = 1 } = this.options; + if (optimizationLevel >= 2) { + globParts = this.firstPhasePreProcess(globParts); + globParts = this.secondPhasePreProcess(globParts); + } else if (optimizationLevel >= 1) { + globParts = this.levelOneOptimize(globParts); + } else { + globParts = this.adjascentGlobstarOptimize(globParts); + } + return globParts; } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); + // just get rid of adjascent ** portions + adjascentGlobstarOptimize(globParts) { + return globParts.map((parts) => { + let gs = -1; + while (-1 !== (gs = parts.indexOf("**", gs + 1))) { + let i = gs; + while (parts[i + 1] === "**") { + i++; + } + if (i !== gs) { + parts.splice(gs, i - gs); + } + } + return parts; + }); } - outer: - while (++index < length) { - var value = array[index], computed = iteratee == null ? value : iteratee(value); - value = comparator || value !== 0 ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; + // get rid of adjascent ** and resolve .. portions + levelOneOptimize(globParts) { + return globParts.map((parts) => { + parts = parts.reduce((set2, part) => { + const prev = set2[set2.length - 1]; + if (part === "**" && prev === "**") { + return set2; + } + if (part === "..") { + if (prev && prev !== ".." && prev !== "." && prev !== "**") { + set2.pop(); + return set2; } } - result.push(value); - } else if (!includes(values, computed, comparator)) { - result.push(value); + set2.push(part); + return set2; + }, []); + return parts.length === 0 ? [""] : parts; + }); + } + levelTwoFileOptimize(parts) { + if (!Array.isArray(parts)) { + parts = this.slashSplit(parts); + } + let didSomething = false; + do { + didSomething = false; + if (!this.preserveMultipleSlashes) { + for (let i = 1; i < parts.length - 1; i++) { + const p = parts[i]; + if (i === 1 && p === "" && parts[0] === "") + continue; + if (p === "." || p === "") { + didSomething = true; + parts.splice(i, 1); + i--; + } + } + if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) { + didSomething = true; + parts.pop(); + } + } + let dd = 0; + while (-1 !== (dd = parts.indexOf("..", dd + 1))) { + const p = parts[dd - 1]; + if (p && p !== "." && p !== ".." && p !== "**") { + didSomething = true; + parts.splice(dd - 1, 2); + dd -= 2; + } + } + } while (didSomething); + return parts.length === 0 ? [""] : parts; + } + // First phase: single-pattern processing + //
 is 1 or more portions
+      //  is 1 or more portions
+      // 

is any portion other than ., .., '', or ** + // is . or '' + // + // **/.. is *brutal* for filesystem walking performance, because + // it effectively resets the recursive walk each time it occurs, + // and ** cannot be reduced out by a .. pattern part like a regexp + // or most strings (other than .., ., and '') can be. + // + //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + //

// -> 
/
+      // 
/

/../ ->

/
+      // **/**/ -> **/
+      //
+      // **/*/ -> */**/ <== not valid because ** doesn't follow
+      // this WOULD be allowed if ** did follow symlinks, or * didn't
+      firstPhasePreProcess(globParts) {
+        let didSomething = false;
+        do {
+          didSomething = false;
+          for (let parts of globParts) {
+            let gs = -1;
+            while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
+              let gss = gs;
+              while (parts[gss + 1] === "**") {
+                gss++;
+              }
+              if (gss > gs) {
+                parts.splice(gs + 1, gss - gs);
+              }
+              let next = parts[gs + 1];
+              const p = parts[gs + 2];
+              const p2 = parts[gs + 3];
+              if (next !== "..")
+                continue;
+              if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
+                continue;
+              }
+              didSomething = true;
+              parts.splice(gs, 1);
+              const other = parts.slice(0);
+              other[gs] = "**";
+              globParts.push(other);
+              gs--;
+            }
+            if (!this.preserveMultipleSlashes) {
+              for (let i = 1; i < parts.length - 1; i++) {
+                const p = parts[i];
+                if (i === 1 && p === "" && parts[0] === "")
+                  continue;
+                if (p === "." || p === "") {
+                  didSomething = true;
+                  parts.splice(i, 1);
+                  i--;
+                }
+              }
+              if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
+                didSomething = true;
+                parts.pop();
+              }
+            }
+            let dd = 0;
+            while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
+              const p = parts[dd - 1];
+              if (p && p !== "." && p !== ".." && p !== "**") {
+                didSomething = true;
+                const needDot = dd === 1 && parts[dd + 1] === "**";
+                const splin = needDot ? ["."] : [];
+                parts.splice(dd - 1, 2, ...splin);
+                if (parts.length === 0)
+                  parts.push("");
+                dd -= 2;
+              }
+            }
+          }
+        } while (didSomething);
+        return globParts;
+      }
+      // second phase: multi-pattern dedupes
+      // {
/*/,
/

/} ->

/*/
+      // {
/,
/} -> 
/
+      // {
/**/,
/} -> 
/**/
+      //
+      // {
/**/,
/**/

/} ->

/**/
+      // ^-- not valid because ** doens't follow symlinks
+      secondPhasePreProcess(globParts) {
+        for (let i = 0; i < globParts.length - 1; i++) {
+          for (let j = i + 1; j < globParts.length; j++) {
+            const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
+            if (matched) {
+              globParts[i] = [];
+              globParts[j] = matched;
+              break;
+            }
           }
         }
-      return result;
-    }
-    module2.exports = baseDifference;
-  }
-});
-
-// node_modules/lodash/isArrayLikeObject.js
-var require_isArrayLikeObject = __commonJS({
-  "node_modules/lodash/isArrayLikeObject.js"(exports2, module2) {
-    var isArrayLike = require_isArrayLike();
-    var isObjectLike = require_isObjectLike();
-    function isArrayLikeObject(value) {
-      return isObjectLike(value) && isArrayLike(value);
-    }
-    module2.exports = isArrayLikeObject;
-  }
-});
-
-// node_modules/lodash/difference.js
-var require_difference = __commonJS({
-  "node_modules/lodash/difference.js"(exports2, module2) {
-    var baseDifference = require_baseDifference();
-    var baseFlatten = require_baseFlatten();
-    var baseRest = require_baseRest();
-    var isArrayLikeObject = require_isArrayLikeObject();
-    var difference = baseRest(function(array, values) {
-      return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : [];
-    });
-    module2.exports = difference;
-  }
-});
-
-// node_modules/lodash/_Set.js
-var require_Set = __commonJS({
-  "node_modules/lodash/_Set.js"(exports2, module2) {
-    var getNative = require_getNative();
-    var root = require_root();
-    var Set2 = getNative(root, "Set");
-    module2.exports = Set2;
-  }
-});
-
-// node_modules/lodash/noop.js
-var require_noop = __commonJS({
-  "node_modules/lodash/noop.js"(exports2, module2) {
-    function noop() {
-    }
-    module2.exports = noop;
-  }
-});
-
-// node_modules/lodash/_setToArray.js
-var require_setToArray = __commonJS({
-  "node_modules/lodash/_setToArray.js"(exports2, module2) {
-    function setToArray(set2) {
-      var index = -1, result = Array(set2.size);
-      set2.forEach(function(value) {
-        result[++index] = value;
-      });
-      return result;
-    }
-    module2.exports = setToArray;
-  }
-});
-
-// node_modules/lodash/_createSet.js
-var require_createSet = __commonJS({
-  "node_modules/lodash/_createSet.js"(exports2, module2) {
-    var Set2 = require_Set();
-    var noop = require_noop();
-    var setToArray = require_setToArray();
-    var INFINITY = 1 / 0;
-    var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop : function(values) {
-      return new Set2(values);
-    };
-    module2.exports = createSet;
-  }
-});
-
-// node_modules/lodash/_baseUniq.js
-var require_baseUniq = __commonJS({
-  "node_modules/lodash/_baseUniq.js"(exports2, module2) {
-    var SetCache = require_SetCache();
-    var arrayIncludes = require_arrayIncludes();
-    var arrayIncludesWith = require_arrayIncludesWith();
-    var cacheHas = require_cacheHas();
-    var createSet = require_createSet();
-    var setToArray = require_setToArray();
-    var LARGE_ARRAY_SIZE = 200;
-    function baseUniq(array, iteratee, comparator) {
-      var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result;
-      if (comparator) {
-        isCommon = false;
-        includes = arrayIncludesWith;
-      } else if (length >= LARGE_ARRAY_SIZE) {
-        var set2 = iteratee ? null : createSet(array);
-        if (set2) {
-          return setToArray(set2);
+        return globParts.filter((gs) => gs.length);
+      }
+      partsMatch(a, b, emptyGSMatch = false) {
+        let ai = 0;
+        let bi = 0;
+        let result = [];
+        let which6 = "";
+        while (ai < a.length && bi < b.length) {
+          if (a[ai] === b[bi]) {
+            result.push(which6 === "b" ? b[bi] : a[ai]);
+            ai++;
+            bi++;
+          } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
+            result.push(a[ai]);
+            ai++;
+          } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
+            result.push(b[bi]);
+            bi++;
+          } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
+            if (which6 === "b")
+              return false;
+            which6 = "a";
+            result.push(a[ai]);
+            ai++;
+            bi++;
+          } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
+            if (which6 === "a")
+              return false;
+            which6 = "b";
+            result.push(b[bi]);
+            ai++;
+            bi++;
+          } else {
+            return false;
+          }
+        }
+        return a.length === b.length && result;
+      }
+      parseNegate() {
+        if (this.nonegate)
+          return;
+        const pattern = this.pattern;
+        let negate = false;
+        let negateOffset = 0;
+        for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
+          negate = !negate;
+          negateOffset++;
         }
-        isCommon = false;
-        includes = cacheHas;
-        seen = new SetCache();
-      } else {
-        seen = iteratee ? [] : result;
+        if (negateOffset)
+          this.pattern = pattern.slice(negateOffset);
+        this.negate = negate;
       }
-      outer:
-        while (++index < length) {
-          var value = array[index], computed = iteratee ? iteratee(value) : value;
-          value = comparator || value !== 0 ? value : 0;
-          if (isCommon && computed === computed) {
-            var seenIndex = seen.length;
-            while (seenIndex--) {
-              if (seen[seenIndex] === computed) {
-                continue outer;
+      // set partial to true to test if, for example,
+      // "/a/b" matches the start of "/*/b/*/d"
+      // Partial means, if you run out of file before you run
+      // out of pattern, then that's fine, as long as all
+      // the parts match.
+      matchOne(file, pattern, partial = false) {
+        const options = this.options;
+        if (this.isWindows) {
+          const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
+          const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
+          const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
+          const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
+          const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
+          const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
+          if (typeof fdi === "number" && typeof pdi === "number") {
+            const [fd, pd] = [file[fdi], pattern[pdi]];
+            if (fd.toLowerCase() === pd.toLowerCase()) {
+              pattern[pdi] = fd;
+              if (pdi > fdi) {
+                pattern = pattern.slice(pdi);
+              } else if (fdi > pdi) {
+                file = file.slice(fdi);
               }
             }
-            if (iteratee) {
-              seen.push(computed);
-            }
-            result.push(value);
-          } else if (!includes(seen, computed, comparator)) {
-            if (seen !== result) {
-              seen.push(computed);
-            }
-            result.push(value);
           }
         }
-      return result;
-    }
-    module2.exports = baseUniq;
-  }
-});
-
-// node_modules/lodash/union.js
-var require_union = __commonJS({
-  "node_modules/lodash/union.js"(exports2, module2) {
-    var baseFlatten = require_baseFlatten();
-    var baseRest = require_baseRest();
-    var baseUniq = require_baseUniq();
-    var isArrayLikeObject = require_isArrayLikeObject();
-    var union = baseRest(function(arrays) {
-      return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
-    });
-    module2.exports = union;
-  }
-});
-
-// node_modules/lodash/_overArg.js
-var require_overArg = __commonJS({
-  "node_modules/lodash/_overArg.js"(exports2, module2) {
-    function overArg(func, transform) {
-      return function(arg) {
-        return func(transform(arg));
-      };
-    }
-    module2.exports = overArg;
-  }
-});
-
-// node_modules/lodash/_getPrototype.js
-var require_getPrototype = __commonJS({
-  "node_modules/lodash/_getPrototype.js"(exports2, module2) {
-    var overArg = require_overArg();
-    var getPrototype = overArg(Object.getPrototypeOf, Object);
-    module2.exports = getPrototype;
-  }
-});
-
-// node_modules/lodash/isPlainObject.js
-var require_isPlainObject = __commonJS({
-  "node_modules/lodash/isPlainObject.js"(exports2, module2) {
-    var baseGetTag = require_baseGetTag();
-    var getPrototype = require_getPrototype();
-    var isObjectLike = require_isObjectLike();
-    var objectTag = "[object Object]";
-    var funcProto = Function.prototype;
-    var objectProto = Object.prototype;
-    var funcToString = funcProto.toString;
-    var hasOwnProperty = objectProto.hasOwnProperty;
-    var objectCtorString = funcToString.call(Object);
-    function isPlainObject(value) {
-      if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
-        return false;
-      }
-      var proto = getPrototype(value);
-      if (proto === null) {
-        return true;
-      }
-      var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
-      return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
-    }
-    module2.exports = isPlainObject;
-  }
-});
-
-// node_modules/archiver-utils/node_modules/brace-expansion/index.js
-var require_brace_expansion2 = __commonJS({
-  "node_modules/archiver-utils/node_modules/brace-expansion/index.js"(exports2, module2) {
-    var balanced = require_balanced_match();
-    module2.exports = expandTop;
-    var escSlash = "\0SLASH" + Math.random() + "\0";
-    var escOpen = "\0OPEN" + Math.random() + "\0";
-    var escClose = "\0CLOSE" + Math.random() + "\0";
-    var escComma = "\0COMMA" + Math.random() + "\0";
-    var escPeriod = "\0PERIOD" + Math.random() + "\0";
-    function numeric(str2) {
-      return parseInt(str2, 10) == str2 ? parseInt(str2, 10) : str2.charCodeAt(0);
-    }
-    function escapeBraces(str2) {
-      return str2.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
-    }
-    function unescapeBraces(str2) {
-      return str2.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
-    }
-    function parseCommaParts(str2) {
-      if (!str2)
-        return [""];
-      var parts = [];
-      var m = balanced("{", "}", str2);
-      if (!m)
-        return str2.split(",");
-      var pre = m.pre;
-      var body = m.body;
-      var post = m.post;
-      var p = pre.split(",");
-      p[p.length - 1] += "{" + body + "}";
-      var postParts = parseCommaParts(post);
-      if (post.length) {
-        p[p.length - 1] += postParts.shift();
-        p.push.apply(p, postParts);
-      }
-      parts.push.apply(parts, p);
-      return parts;
-    }
-    function expandTop(str2) {
-      if (!str2)
-        return [];
-      if (str2.substr(0, 2) === "{}") {
-        str2 = "\\{\\}" + str2.substr(2);
-      }
-      return expand(escapeBraces(str2), true).map(unescapeBraces);
-    }
-    function embrace(str2) {
-      return "{" + str2 + "}";
-    }
-    function isPadded(el) {
-      return /^-?0\d/.test(el);
-    }
-    function lte(i, y) {
-      return i <= y;
-    }
-    function gte5(i, y) {
-      return i >= y;
-    }
-    function expand(str2, isTop) {
-      var expansions = [];
-      var m = balanced("{", "}", str2);
-      if (!m) return [str2];
-      var pre = m.pre;
-      var post = m.post.length ? expand(m.post, false) : [""];
-      if (/\$$/.test(m.pre)) {
-        for (var k = 0; k < post.length; k++) {
-          var expansion = pre + "{" + m.body + "}" + post[k];
-          expansions.push(expansion);
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+          file = this.levelTwoFileOptimize(file);
         }
-      } else {
-        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
-        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
-        var isSequence = isNumericSequence || isAlphaSequence;
-        var isOptions = m.body.indexOf(",") >= 0;
-        if (!isSequence && !isOptions) {
-          if (m.post.match(/,(?!,).*\}/)) {
-            str2 = m.pre + "{" + m.body + escClose + m.post;
-            return expand(str2);
+        this.debug("matchOne", this, { file, pattern });
+        this.debug("matchOne", file.length, pattern.length);
+        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
+          this.debug("matchOne loop");
+          var p = pattern[pi];
+          var f = file[fi];
+          this.debug(pattern, p, f);
+          if (p === false) {
+            return false;
           }
-          return [str2];
-        }
-        var n;
-        if (isSequence) {
-          n = m.body.split(/\.\./);
-        } else {
-          n = parseCommaParts(m.body);
-          if (n.length === 1) {
-            n = expand(n[0], false).map(embrace);
-            if (n.length === 1) {
-              return post.map(function(p) {
-                return m.pre + n[0] + p;
-              });
+          if (p === exports2.GLOBSTAR) {
+            this.debug("GLOBSTAR", [pattern, p, f]);
+            var fr = fi;
+            var pr = pi + 1;
+            if (pr === pl) {
+              this.debug("** at the end");
+              for (; fi < fl; fi++) {
+                if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
+                  return false;
+              }
+              return true;
             }
-          }
-        }
-        var N;
-        if (isSequence) {
-          var x = numeric(n[0]);
-          var y = numeric(n[1]);
-          var width = Math.max(n[0].length, n[1].length);
-          var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
-          var test = lte;
-          var reverse = y < x;
-          if (reverse) {
-            incr *= -1;
-            test = gte5;
-          }
-          var pad = n.some(isPadded);
-          N = [];
-          for (var i = x; test(i, y); i += incr) {
-            var c;
-            if (isAlphaSequence) {
-              c = String.fromCharCode(i);
-              if (c === "\\")
-                c = "";
-            } else {
-              c = String(i);
-              if (pad) {
-                var need = width - c.length;
-                if (need > 0) {
-                  var z = new Array(need + 1).join("0");
-                  if (i < 0)
-                    c = "-" + z + c.slice(1);
-                  else
-                    c = z + c;
+            while (fr < fl) {
+              var swallowee = file[fr];
+              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
+              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+                this.debug("globstar found match!", fr, fl, swallowee);
+                return true;
+              } else {
+                if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
+                  this.debug("dot detected!", file, fr, pattern, pr);
+                  break;
                 }
+                this.debug("globstar swallow a segment, and continue");
+                fr++;
               }
             }
-            N.push(c);
+            if (partial) {
+              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
+              if (fr === fl) {
+                return true;
+              }
+            }
+            return false;
           }
-        } else {
-          N = [];
-          for (var j = 0; j < n.length; j++) {
-            N.push.apply(N, expand(n[j], false));
+          let hit;
+          if (typeof p === "string") {
+            hit = f === p;
+            this.debug("string match", p, f, hit);
+          } else {
+            hit = p.test(f);
+            this.debug("pattern match", p, f, hit);
           }
+          if (!hit)
+            return false;
         }
-        for (var j = 0; j < N.length; j++) {
-          for (var k = 0; k < post.length; k++) {
-            var expansion = pre + N[j] + post[k];
-            if (!isTop || isSequence || expansion)
-              expansions.push(expansion);
-          }
+        if (fi === fl && pi === pl) {
+          return true;
+        } else if (fi === fl) {
+          return partial;
+        } else if (pi === pl) {
+          return fi === fl - 1 && file[fi] === "";
+        } else {
+          throw new Error("wtf?");
         }
       }
-      return expansions;
-    }
-  }
-});
-
-// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js
-var require_assert_valid_pattern = __commonJS({
-  "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.assertValidPattern = void 0;
-    var MAX_PATTERN_LENGTH = 1024 * 64;
-    var assertValidPattern = (pattern) => {
-      if (typeof pattern !== "string") {
-        throw new TypeError("invalid pattern");
-      }
-      if (pattern.length > MAX_PATTERN_LENGTH) {
-        throw new TypeError("pattern is too long");
-      }
-    };
-    exports2.assertValidPattern = assertValidPattern;
-  }
-});
-
-// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/brace-expressions.js
-var require_brace_expressions = __commonJS({
-  "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/brace-expressions.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.parseClass = void 0;
-    var posixClasses = {
-      "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
-      "[:alpha:]": ["\\p{L}\\p{Nl}", true],
-      "[:ascii:]": ["\\x00-\\x7f", false],
-      "[:blank:]": ["\\p{Zs}\\t", true],
-      "[:cntrl:]": ["\\p{Cc}", true],
-      "[:digit:]": ["\\p{Nd}", true],
-      "[:graph:]": ["\\p{Z}\\p{C}", true, true],
-      "[:lower:]": ["\\p{Ll}", true],
-      "[:print:]": ["\\p{C}", true],
-      "[:punct:]": ["\\p{P}", true],
-      "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
-      "[:upper:]": ["\\p{Lu}", true],
-      "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
-      "[:xdigit:]": ["A-Fa-f0-9", false]
-    };
-    var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
-    var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
-    var rangesToString = (ranges) => ranges.join("");
-    var parseClass = (glob2, position) => {
-      const pos = position;
-      if (glob2.charAt(pos) !== "[") {
-        throw new Error("not in a brace expression");
+      braceExpand() {
+        return (0, exports2.braceExpand)(this.pattern, this.options);
       }
-      const ranges = [];
-      const negs = [];
-      let i = pos + 1;
-      let sawStart = false;
-      let uflag = false;
-      let escaping = false;
-      let negate = false;
-      let endPos = pos;
-      let rangeStart = "";
-      WHILE: while (i < glob2.length) {
-        const c = glob2.charAt(i);
-        if ((c === "!" || c === "^") && i === pos + 1) {
-          negate = true;
-          i++;
-          continue;
+      parse(pattern) {
+        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
+        const options = this.options;
+        if (pattern === "**")
+          return exports2.GLOBSTAR;
+        if (pattern === "")
+          return "";
+        let m;
+        let fastTest = null;
+        if (m = pattern.match(starRE)) {
+          fastTest = options.dot ? starTestDot : starTest;
+        } else if (m = pattern.match(starDotExtRE)) {
+          fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
+        } else if (m = pattern.match(qmarksRE)) {
+          fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
+        } else if (m = pattern.match(starDotStarRE)) {
+          fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
+        } else if (m = pattern.match(dotStarRE)) {
+          fastTest = dotStarTest;
         }
-        if (c === "]" && sawStart && !escaping) {
-          endPos = i + 1;
-          break;
+        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
+        if (fastTest && typeof re === "object") {
+          Reflect.defineProperty(re, "test", { value: fastTest });
         }
-        sawStart = true;
-        if (c === "\\") {
-          if (!escaping) {
-            escaping = true;
-            i++;
-            continue;
-          }
+        return re;
+      }
+      makeRe() {
+        if (this.regexp || this.regexp === false)
+          return this.regexp;
+        const set2 = this.set;
+        if (!set2.length) {
+          this.regexp = false;
+          return this.regexp;
         }
-        if (c === "[" && !escaping) {
-          for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
-            if (glob2.startsWith(cls, i)) {
-              if (rangeStart) {
-                return ["$.", false, glob2.length - pos, true];
+        const options = this.options;
+        const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
+        const flags = new Set(options.nocase ? ["i"] : []);
+        let re = set2.map((pattern) => {
+          const pp = pattern.map((p) => {
+            if (p instanceof RegExp) {
+              for (const f of p.flags.split(""))
+                flags.add(f);
+            }
+            return typeof p === "string" ? regExpEscape(p) : p === exports2.GLOBSTAR ? exports2.GLOBSTAR : p._src;
+          });
+          pp.forEach((p, i) => {
+            const next = pp[i + 1];
+            const prev = pp[i - 1];
+            if (p !== exports2.GLOBSTAR || prev === exports2.GLOBSTAR) {
+              return;
+            }
+            if (prev === void 0) {
+              if (next !== void 0 && next !== exports2.GLOBSTAR) {
+                pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
+              } else {
+                pp[i] = twoStar;
               }
-              i += cls.length;
-              if (neg)
-                negs.push(unip);
-              else
-                ranges.push(unip);
-              uflag = uflag || u;
-              continue WHILE;
+            } else if (next === void 0) {
+              pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
+            } else if (next !== exports2.GLOBSTAR) {
+              pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
+              pp[i + 1] = exports2.GLOBSTAR;
             }
-          }
+          });
+          return pp.filter((p) => p !== exports2.GLOBSTAR).join("/");
+        }).join("|");
+        const [open, close] = set2.length > 1 ? ["(?:", ")"] : ["", ""];
+        re = "^" + open + re + close + "$";
+        if (this.negate)
+          re = "^(?!" + re + ").+$";
+        try {
+          this.regexp = new RegExp(re, [...flags].join(""));
+        } catch (ex) {
+          this.regexp = false;
         }
-        escaping = false;
-        if (rangeStart) {
-          if (c > rangeStart) {
-            ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
-          } else if (c === rangeStart) {
-            ranges.push(braceEscape(c));
+        return this.regexp;
+      }
+      slashSplit(p) {
+        if (this.preserveMultipleSlashes) {
+          return p.split("/");
+        } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
+          return ["", ...p.split(/\/+/)];
+        } else {
+          return p.split(/\/+/);
+        }
+      }
+      match(f, partial = this.partial) {
+        this.debug("match", f, this.pattern);
+        if (this.comment) {
+          return false;
+        }
+        if (this.empty) {
+          return f === "";
+        }
+        if (f === "/" && partial) {
+          return true;
+        }
+        const options = this.options;
+        if (this.isWindows) {
+          f = f.split("\\").join("/");
+        }
+        const ff = this.slashSplit(f);
+        this.debug(this.pattern, "split", ff);
+        const set2 = this.set;
+        this.debug(this.pattern, "set", set2);
+        let filename = ff[ff.length - 1];
+        if (!filename) {
+          for (let i = ff.length - 2; !filename && i >= 0; i--) {
+            filename = ff[i];
           }
-          rangeStart = "";
-          i++;
-          continue;
         }
-        if (glob2.startsWith("-]", i + 1)) {
-          ranges.push(braceEscape(c + "-"));
-          i += 2;
-          continue;
+        for (let i = 0; i < set2.length; i++) {
+          const pattern = set2[i];
+          let file = ff;
+          if (options.matchBase && pattern.length === 1) {
+            file = [filename];
+          }
+          const hit = this.matchOne(file, pattern, partial);
+          if (hit) {
+            if (options.flipNegate) {
+              return true;
+            }
+            return !this.negate;
+          }
         }
-        if (glob2.startsWith("-", i + 1)) {
-          rangeStart = c;
-          i += 2;
-          continue;
+        if (options.flipNegate) {
+          return false;
         }
-        ranges.push(braceEscape(c));
-        i++;
-      }
-      if (endPos < i) {
-        return ["", false, 0, false];
-      }
-      if (!ranges.length && !negs.length) {
-        return ["$.", false, glob2.length - pos, true];
+        return this.negate;
       }
-      if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
-        const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
-        return [regexpEscape(r), false, endPos - pos, false];
+      static defaults(def) {
+        return exports2.minimatch.defaults(def).Minimatch;
       }
-      const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
-      const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
-      const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
-      return [comb, uflag, endPos - pos, true];
     };
-    exports2.parseClass = parseClass;
+    exports2.Minimatch = Minimatch;
+    var ast_js_2 = require_ast();
+    Object.defineProperty(exports2, "AST", { enumerable: true, get: function() {
+      return ast_js_2.AST;
+    } });
+    var escape_js_2 = require_escape();
+    Object.defineProperty(exports2, "escape", { enumerable: true, get: function() {
+      return escape_js_2.escape;
+    } });
+    var unescape_js_2 = require_unescape();
+    Object.defineProperty(exports2, "unescape", { enumerable: true, get: function() {
+      return unescape_js_2.unescape;
+    } });
+    exports2.minimatch.AST = ast_js_1.AST;
+    exports2.minimatch.Minimatch = Minimatch;
+    exports2.minimatch.escape = escape_js_1.escape;
+    exports2.minimatch.unescape = unescape_js_1.unescape;
   }
 });
 
-// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/unescape.js
-var require_unescape = __commonJS({
-  "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/unescape.js"(exports2) {
+// node_modules/archiver-utils/node_modules/lru-cache/dist/commonjs/index.js
+var require_commonjs14 = __commonJS({
+  "node_modules/archiver-utils/node_modules/lru-cache/dist/commonjs/index.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.unescape = void 0;
-    var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
-      return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
+    exports2.LRUCache = void 0;
+    var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
+    var warned = /* @__PURE__ */ new Set();
+    var PROCESS = typeof process === "object" && !!process ? process : {};
+    var emitWarning = (msg, type2, code, fn) => {
+      typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type2, code, fn) : console.error(`[${code}] ${type2}: ${msg}`);
     };
-    exports2.unescape = unescape;
-  }
-});
-
-// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/ast.js
-var require_ast = __commonJS({
-  "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/ast.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.AST = void 0;
-    var brace_expressions_js_1 = require_brace_expressions();
-    var unescape_js_1 = require_unescape();
-    var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
-    var isExtglobType = (c) => types.has(c);
-    var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
-    var startNoDot = "(?!\\.)";
-    var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
-    var justDots = /* @__PURE__ */ new Set(["..", "."]);
-    var reSpecials = new Set("().*{}+?[]^$\\!");
-    var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
-    var qmark = "[^/]";
-    var star = qmark + "*?";
-    var starNoEmpty = qmark + "+?";
-    var AST = class _AST {
-      type;
-      #root;
-      #hasMagic;
-      #uflag = false;
-      #parts = [];
-      #parent;
-      #parentIndex;
-      #negs;
-      #filledNegs = false;
-      #options;
-      #toString;
-      // set to true if it's an extglob with no children
-      // (which really means one child of '')
-      #emptyExt = false;
-      constructor(type2, parent, options = {}) {
-        this.type = type2;
-        if (type2)
-          this.#hasMagic = true;
-        this.#parent = parent;
-        this.#root = this.#parent ? this.#parent.#root : this;
-        this.#options = this.#root === this ? options : this.#root.#options;
-        this.#negs = this.#root === this ? [] : this.#root.#negs;
-        if (type2 === "!" && !this.#root.#filledNegs)
-          this.#negs.push(this);
-        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
+    var AC = globalThis.AbortController;
+    var AS = globalThis.AbortSignal;
+    if (typeof AC === "undefined") {
+      AS = class AbortSignal {
+        onabort;
+        _onabort = [];
+        reason;
+        aborted = false;
+        addEventListener(_2, fn) {
+          this._onabort.push(fn);
+        }
+      };
+      AC = class AbortController {
+        constructor() {
+          warnACPolyfill();
+        }
+        signal = new AS();
+        abort(reason) {
+          if (this.signal.aborted)
+            return;
+          this.signal.reason = reason;
+          this.signal.aborted = true;
+          for (const fn of this.signal._onabort) {
+            fn(reason);
+          }
+          this.signal.onabort?.(reason);
+        }
+      };
+      let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
+      const warnACPolyfill = () => {
+        if (!printACPolyfillWarning)
+          return;
+        printACPolyfillWarning = false;
+        emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
+      };
+    }
+    var shouldWarn = (code) => !warned.has(code);
+    var TYPE = Symbol("type");
+    var isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
+    var getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;
+    var ZeroArray = class extends Array {
+      constructor(size) {
+        super(size);
+        this.fill(0);
       }
-      get hasMagic() {
-        if (this.#hasMagic !== void 0)
-          return this.#hasMagic;
-        for (const p of this.#parts) {
-          if (typeof p === "string")
-            continue;
-          if (p.type || p.hasMagic)
-            return this.#hasMagic = true;
+    };
+    var Stack = class _Stack {
+      heap;
+      length;
+      // private constructor
+      static #constructing = false;
+      static create(max) {
+        const HeapCls = getUintArray(max);
+        if (!HeapCls)
+          return [];
+        _Stack.#constructing = true;
+        const s = new _Stack(max, HeapCls);
+        _Stack.#constructing = false;
+        return s;
+      }
+      constructor(max, HeapCls) {
+        if (!_Stack.#constructing) {
+          throw new TypeError("instantiate Stack using Stack.create(n)");
         }
-        return this.#hasMagic;
+        this.heap = new HeapCls(max);
+        this.length = 0;
       }
-      // reconstructs the pattern
-      toString() {
-        if (this.#toString !== void 0)
-          return this.#toString;
-        if (!this.type) {
-          return this.#toString = this.#parts.map((p) => String(p)).join("");
+      push(n) {
+        this.heap[this.length++] = n;
+      }
+      pop() {
+        return this.heap[--this.length];
+      }
+    };
+    var LRUCache = class _LRUCache {
+      // options that cannot be changed without disaster
+      #max;
+      #maxSize;
+      #dispose;
+      #disposeAfter;
+      #fetchMethod;
+      #memoMethod;
+      /**
+       * {@link LRUCache.OptionsBase.ttl}
+       */
+      ttl;
+      /**
+       * {@link LRUCache.OptionsBase.ttlResolution}
+       */
+      ttlResolution;
+      /**
+       * {@link LRUCache.OptionsBase.ttlAutopurge}
+       */
+      ttlAutopurge;
+      /**
+       * {@link LRUCache.OptionsBase.updateAgeOnGet}
+       */
+      updateAgeOnGet;
+      /**
+       * {@link LRUCache.OptionsBase.updateAgeOnHas}
+       */
+      updateAgeOnHas;
+      /**
+       * {@link LRUCache.OptionsBase.allowStale}
+       */
+      allowStale;
+      /**
+       * {@link LRUCache.OptionsBase.noDisposeOnSet}
+       */
+      noDisposeOnSet;
+      /**
+       * {@link LRUCache.OptionsBase.noUpdateTTL}
+       */
+      noUpdateTTL;
+      /**
+       * {@link LRUCache.OptionsBase.maxEntrySize}
+       */
+      maxEntrySize;
+      /**
+       * {@link LRUCache.OptionsBase.sizeCalculation}
+       */
+      sizeCalculation;
+      /**
+       * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
+       */
+      noDeleteOnFetchRejection;
+      /**
+       * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
+       */
+      noDeleteOnStaleGet;
+      /**
+       * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
+       */
+      allowStaleOnFetchAbort;
+      /**
+       * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
+       */
+      allowStaleOnFetchRejection;
+      /**
+       * {@link LRUCache.OptionsBase.ignoreFetchAbort}
+       */
+      ignoreFetchAbort;
+      // computed properties
+      #size;
+      #calculatedSize;
+      #keyMap;
+      #keyList;
+      #valList;
+      #next;
+      #prev;
+      #head;
+      #tail;
+      #free;
+      #disposed;
+      #sizes;
+      #starts;
+      #ttls;
+      #hasDispose;
+      #hasFetchMethod;
+      #hasDisposeAfter;
+      /**
+       * Do not call this method unless you need to inspect the
+       * inner workings of the cache.  If anything returned by this
+       * object is modified in any way, strange breakage may occur.
+       *
+       * These fields are private for a reason!
+       *
+       * @internal
+       */
+      static unsafeExposeInternals(c) {
+        return {
+          // properties
+          starts: c.#starts,
+          ttls: c.#ttls,
+          sizes: c.#sizes,
+          keyMap: c.#keyMap,
+          keyList: c.#keyList,
+          valList: c.#valList,
+          next: c.#next,
+          prev: c.#prev,
+          get head() {
+            return c.#head;
+          },
+          get tail() {
+            return c.#tail;
+          },
+          free: c.#free,
+          // methods
+          isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
+          backgroundFetch: (k, index, options, context2) => c.#backgroundFetch(k, index, options, context2),
+          moveToTail: (index) => c.#moveToTail(index),
+          indexes: (options) => c.#indexes(options),
+          rindexes: (options) => c.#rindexes(options),
+          isStale: (index) => c.#isStale(index)
+        };
+      }
+      // Protected read-only members
+      /**
+       * {@link LRUCache.OptionsBase.max} (read-only)
+       */
+      get max() {
+        return this.#max;
+      }
+      /**
+       * {@link LRUCache.OptionsBase.maxSize} (read-only)
+       */
+      get maxSize() {
+        return this.#maxSize;
+      }
+      /**
+       * The total computed size of items in the cache (read-only)
+       */
+      get calculatedSize() {
+        return this.#calculatedSize;
+      }
+      /**
+       * The number of items stored in the cache (read-only)
+       */
+      get size() {
+        return this.#size;
+      }
+      /**
+       * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
+       */
+      get fetchMethod() {
+        return this.#fetchMethod;
+      }
+      get memoMethod() {
+        return this.#memoMethod;
+      }
+      /**
+       * {@link LRUCache.OptionsBase.dispose} (read-only)
+       */
+      get dispose() {
+        return this.#dispose;
+      }
+      /**
+       * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
+       */
+      get disposeAfter() {
+        return this.#disposeAfter;
+      }
+      constructor(options) {
+        const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options;
+        if (max !== 0 && !isPosInt(max)) {
+          throw new TypeError("max option must be a nonnegative integer");
+        }
+        const UintArray = max ? getUintArray(max) : Array;
+        if (!UintArray) {
+          throw new Error("invalid max value: " + max);
+        }
+        this.#max = max;
+        this.#maxSize = maxSize;
+        this.maxEntrySize = maxEntrySize || this.#maxSize;
+        this.sizeCalculation = sizeCalculation;
+        if (this.sizeCalculation) {
+          if (!this.#maxSize && !this.maxEntrySize) {
+            throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
+          }
+          if (typeof this.sizeCalculation !== "function") {
+            throw new TypeError("sizeCalculation set to non-function");
+          }
+        }
+        if (memoMethod !== void 0 && typeof memoMethod !== "function") {
+          throw new TypeError("memoMethod must be a function if defined");
+        }
+        this.#memoMethod = memoMethod;
+        if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
+          throw new TypeError("fetchMethod must be a function if specified");
+        }
+        this.#fetchMethod = fetchMethod;
+        this.#hasFetchMethod = !!fetchMethod;
+        this.#keyMap = /* @__PURE__ */ new Map();
+        this.#keyList = new Array(max).fill(void 0);
+        this.#valList = new Array(max).fill(void 0);
+        this.#next = new UintArray(max);
+        this.#prev = new UintArray(max);
+        this.#head = 0;
+        this.#tail = 0;
+        this.#free = Stack.create(max);
+        this.#size = 0;
+        this.#calculatedSize = 0;
+        if (typeof dispose === "function") {
+          this.#dispose = dispose;
+        }
+        if (typeof disposeAfter === "function") {
+          this.#disposeAfter = disposeAfter;
+          this.#disposed = [];
         } else {
-          return this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";
+          this.#disposeAfter = void 0;
+          this.#disposed = void 0;
         }
-      }
-      #fillNegs() {
-        if (this !== this.#root)
-          throw new Error("should only call on root");
-        if (this.#filledNegs)
-          return this;
-        this.toString();
-        this.#filledNegs = true;
-        let n;
-        while (n = this.#negs.pop()) {
-          if (n.type !== "!")
-            continue;
-          let p = n;
-          let pp = p.#parent;
-          while (pp) {
-            for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
-              for (const part of n.#parts) {
-                if (typeof part === "string") {
-                  throw new Error("string part in extglob AST??");
-                }
-                part.copyIn(pp.#parts[i]);
-              }
+        this.#hasDispose = !!this.#dispose;
+        this.#hasDisposeAfter = !!this.#disposeAfter;
+        this.noDisposeOnSet = !!noDisposeOnSet;
+        this.noUpdateTTL = !!noUpdateTTL;
+        this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
+        this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
+        this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
+        this.ignoreFetchAbort = !!ignoreFetchAbort;
+        if (this.maxEntrySize !== 0) {
+          if (this.#maxSize !== 0) {
+            if (!isPosInt(this.#maxSize)) {
+              throw new TypeError("maxSize must be a positive integer if specified");
             }
-            p = pp;
-            pp = p.#parent;
           }
-        }
-        return this;
-      }
-      push(...parts) {
-        for (const p of parts) {
-          if (p === "")
-            continue;
-          if (typeof p !== "string" && !(p instanceof _AST && p.#parent === this)) {
-            throw new Error("invalid part: " + p);
+          if (!isPosInt(this.maxEntrySize)) {
+            throw new TypeError("maxEntrySize must be a positive integer if specified");
           }
-          this.#parts.push(p);
-        }
-      }
-      toJSON() {
-        const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];
-        if (this.isStart() && !this.type)
-          ret.unshift([]);
-        if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) {
-          ret.push({});
+          this.#initializeSizeTracking();
         }
-        return ret;
-      }
-      isStart() {
-        if (this.#root === this)
-          return true;
-        if (!this.#parent?.isStart())
-          return false;
-        if (this.#parentIndex === 0)
-          return true;
-        const p = this.#parent;
-        for (let i = 0; i < this.#parentIndex; i++) {
-          const pp = p.#parts[i];
-          if (!(pp instanceof _AST && pp.type === "!")) {
-            return false;
+        this.allowStale = !!allowStale;
+        this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
+        this.updateAgeOnGet = !!updateAgeOnGet;
+        this.updateAgeOnHas = !!updateAgeOnHas;
+        this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
+        this.ttlAutopurge = !!ttlAutopurge;
+        this.ttl = ttl || 0;
+        if (this.ttl) {
+          if (!isPosInt(this.ttl)) {
+            throw new TypeError("ttl must be a positive integer if specified");
           }
+          this.#initializeTTLTracking();
         }
-        return true;
-      }
-      isEnd() {
-        if (this.#root === this)
-          return true;
-        if (this.#parent?.type === "!")
-          return true;
-        if (!this.#parent?.isEnd())
-          return false;
-        if (!this.type)
-          return this.#parent?.isEnd();
-        const pl = this.#parent ? this.#parent.#parts.length : 0;
-        return this.#parentIndex === pl - 1;
-      }
-      copyIn(part) {
-        if (typeof part === "string")
-          this.push(part);
-        else
-          this.push(part.clone(this));
-      }
-      clone(parent) {
-        const c = new _AST(this.type, parent);
-        for (const p of this.#parts) {
-          c.copyIn(p);
+        if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
+          throw new TypeError("At least one of max, maxSize, or ttl is required");
+        }
+        if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
+          const code = "LRU_CACHE_UNBOUNDED";
+          if (shouldWarn(code)) {
+            warned.add(code);
+            const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
+            emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
+          }
         }
-        return c;
       }
-      static #parseAST(str2, ast, pos, opt) {
-        let escaping = false;
-        let inBrace = false;
-        let braceStart = -1;
-        let braceNeg = false;
-        if (ast.type === null) {
-          let i2 = pos;
-          let acc2 = "";
-          while (i2 < str2.length) {
-            const c = str2.charAt(i2++);
-            if (escaping || c === "\\") {
-              escaping = !escaping;
-              acc2 += c;
-              continue;
-            }
-            if (inBrace) {
-              if (i2 === braceStart + 1) {
-                if (c === "^" || c === "!") {
-                  braceNeg = true;
-                }
-              } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {
-                inBrace = false;
+      /**
+       * Return the number of ms left in the item's TTL. If item is not in cache,
+       * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
+       */
+      getRemainingTTL(key) {
+        return this.#keyMap.has(key) ? Infinity : 0;
+      }
+      #initializeTTLTracking() {
+        const ttls = new ZeroArray(this.#max);
+        const starts = new ZeroArray(this.#max);
+        this.#ttls = ttls;
+        this.#starts = starts;
+        this.#setItemTTL = (index, ttl, start = perf.now()) => {
+          starts[index] = ttl !== 0 ? start : 0;
+          ttls[index] = ttl;
+          if (ttl !== 0 && this.ttlAutopurge) {
+            const t = setTimeout(() => {
+              if (this.#isStale(index)) {
+                this.#delete(this.#keyList[index], "expire");
               }
-              acc2 += c;
-              continue;
-            } else if (c === "[") {
-              inBrace = true;
-              braceStart = i2;
-              braceNeg = false;
-              acc2 += c;
-              continue;
+            }, ttl + 1);
+            if (t.unref) {
+              t.unref();
             }
-            if (!opt.noext && isExtglobType(c) && str2.charAt(i2) === "(") {
-              ast.push(acc2);
-              acc2 = "";
-              const ext = new _AST(c, ast);
-              i2 = _AST.#parseAST(str2, ext, i2, opt);
-              ast.push(ext);
-              continue;
+          }
+        };
+        this.#updateItemAge = (index) => {
+          starts[index] = ttls[index] !== 0 ? perf.now() : 0;
+        };
+        this.#statusTTL = (status, index) => {
+          if (ttls[index]) {
+            const ttl = ttls[index];
+            const start = starts[index];
+            if (!ttl || !start)
+              return;
+            status.ttl = ttl;
+            status.start = start;
+            status.now = cachedNow || getNow();
+            const age = status.now - start;
+            status.remainingTTL = ttl - age;
+          }
+        };
+        let cachedNow = 0;
+        const getNow = () => {
+          const n = perf.now();
+          if (this.ttlResolution > 0) {
+            cachedNow = n;
+            const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
+            if (t.unref) {
+              t.unref();
             }
-            acc2 += c;
           }
-          ast.push(acc2);
-          return i2;
-        }
-        let i = pos + 1;
-        let part = new _AST(null, ast);
-        const parts = [];
-        let acc = "";
-        while (i < str2.length) {
-          const c = str2.charAt(i++);
-          if (escaping || c === "\\") {
-            escaping = !escaping;
-            acc += c;
-            continue;
+          return n;
+        };
+        this.getRemainingTTL = (key) => {
+          const index = this.#keyMap.get(key);
+          if (index === void 0) {
+            return 0;
           }
-          if (inBrace) {
-            if (i === braceStart + 1) {
-              if (c === "^" || c === "!") {
-                braceNeg = true;
+          const ttl = ttls[index];
+          const start = starts[index];
+          if (!ttl || !start) {
+            return Infinity;
+          }
+          const age = (cachedNow || getNow()) - start;
+          return ttl - age;
+        };
+        this.#isStale = (index) => {
+          const s = starts[index];
+          const t = ttls[index];
+          return !!t && !!s && (cachedNow || getNow()) - s > t;
+        };
+      }
+      // conditionally set private methods related to TTL
+      #updateItemAge = () => {
+      };
+      #statusTTL = () => {
+      };
+      #setItemTTL = () => {
+      };
+      /* c8 ignore stop */
+      #isStale = () => false;
+      #initializeSizeTracking() {
+        const sizes = new ZeroArray(this.#max);
+        this.#calculatedSize = 0;
+        this.#sizes = sizes;
+        this.#removeItemSize = (index) => {
+          this.#calculatedSize -= sizes[index];
+          sizes[index] = 0;
+        };
+        this.#requireSize = (k, v, size, sizeCalculation) => {
+          if (this.#isBackgroundFetch(v)) {
+            return 0;
+          }
+          if (!isPosInt(size)) {
+            if (sizeCalculation) {
+              if (typeof sizeCalculation !== "function") {
+                throw new TypeError("sizeCalculation must be a function");
               }
-            } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {
-              inBrace = false;
+              size = sizeCalculation(v, k);
+              if (!isPosInt(size)) {
+                throw new TypeError("sizeCalculation return invalid (expect positive integer)");
+              }
+            } else {
+              throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
             }
-            acc += c;
-            continue;
-          } else if (c === "[") {
-            inBrace = true;
-            braceStart = i;
-            braceNeg = false;
-            acc += c;
-            continue;
           }
-          if (isExtglobType(c) && str2.charAt(i) === "(") {
-            part.push(acc);
-            acc = "";
-            const ext = new _AST(c, part);
-            part.push(ext);
-            i = _AST.#parseAST(str2, ext, i, opt);
-            continue;
+          return size;
+        };
+        this.#addItemSize = (index, size, status) => {
+          sizes[index] = size;
+          if (this.#maxSize) {
+            const maxSize = this.#maxSize - sizes[index];
+            while (this.#calculatedSize > maxSize) {
+              this.#evict(true);
+            }
           }
-          if (c === "|") {
-            part.push(acc);
-            acc = "";
-            parts.push(part);
-            part = new _AST(null, ast);
-            continue;
+          this.#calculatedSize += sizes[index];
+          if (status) {
+            status.entrySize = size;
+            status.totalCalculatedSize = this.#calculatedSize;
           }
-          if (c === ")") {
-            if (acc === "" && ast.#parts.length === 0) {
-              ast.#emptyExt = true;
+        };
+      }
+      #removeItemSize = (_i) => {
+      };
+      #addItemSize = (_i, _s, _st) => {
+      };
+      #requireSize = (_k, _v, size, sizeCalculation) => {
+        if (size || sizeCalculation) {
+          throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
+        }
+        return 0;
+      };
+      *#indexes({ allowStale = this.allowStale } = {}) {
+        if (this.#size) {
+          for (let i = this.#tail; true; ) {
+            if (!this.#isValidIndex(i)) {
+              break;
+            }
+            if (allowStale || !this.#isStale(i)) {
+              yield i;
+            }
+            if (i === this.#head) {
+              break;
+            } else {
+              i = this.#prev[i];
             }
-            part.push(acc);
-            acc = "";
-            ast.push(...parts, part);
-            return i;
           }
-          acc += c;
         }
-        ast.type = null;
-        ast.#hasMagic = void 0;
-        ast.#parts = [str2.substring(pos - 1)];
-        return i;
-      }
-      static fromGlob(pattern, options = {}) {
-        const ast = new _AST(null, void 0, options);
-        _AST.#parseAST(pattern, ast, 0, options);
-        return ast;
       }
-      // returns the regular expression if there's magic, or the unescaped
-      // string if not.
-      toMMPattern() {
-        if (this !== this.#root)
-          return this.#root.toMMPattern();
-        const glob2 = this.toString();
-        const [re, body, hasMagic, uflag] = this.toRegExpSource();
-        const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob2.toUpperCase() !== glob2.toLowerCase();
-        if (!anyMagic) {
-          return body;
+      *#rindexes({ allowStale = this.allowStale } = {}) {
+        if (this.#size) {
+          for (let i = this.#head; true; ) {
+            if (!this.#isValidIndex(i)) {
+              break;
+            }
+            if (allowStale || !this.#isStale(i)) {
+              yield i;
+            }
+            if (i === this.#tail) {
+              break;
+            } else {
+              i = this.#next[i];
+            }
+          }
         }
-        const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");
-        return Object.assign(new RegExp(`^${re}$`, flags), {
-          _src: re,
-          _glob: glob2
-        });
       }
-      get options() {
-        return this.#options;
+      #isValidIndex(index) {
+        return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index;
       }
-      // returns the string match, the regexp source, whether there's magic
-      // in the regexp (so a regular expression is required) and whether or
-      // not the uflag is needed for the regular expression (for posix classes)
-      // TODO: instead of injecting the start/end at this point, just return
-      // the BODY of the regexp, along with the start/end portions suitable
-      // for binding the start/end in either a joined full-path makeRe context
-      // (where we bind to (^|/), or a standalone matchPart context (where
-      // we bind to ^, and not /).  Otherwise slashes get duped!
-      //
-      // In part-matching mode, the start is:
-      // - if not isStart: nothing
-      // - if traversal possible, but not allowed: ^(?!\.\.?$)
-      // - if dots allowed or not possible: ^
-      // - if dots possible and not allowed: ^(?!\.)
-      // end is:
-      // - if not isEnd(): nothing
-      // - else: $
-      //
-      // In full-path matching mode, we put the slash at the START of the
-      // pattern, so start is:
-      // - if first pattern: same as part-matching mode
-      // - if not isStart(): nothing
-      // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
-      // - if dots allowed or not possible: /
-      // - if dots possible and not allowed: /(?!\.)
-      // end is:
-      // - if last pattern, same as part-matching mode
-      // - else nothing
-      //
-      // Always put the (?:$|/) on negated tails, though, because that has to be
-      // there to bind the end of the negated pattern portion, and it's easier to
-      // just stick it in now rather than try to inject it later in the middle of
-      // the pattern.
-      //
-      // We can just always return the same end, and leave it up to the caller
-      // to know whether it's going to be used joined or in parts.
-      // And, if the start is adjusted slightly, can do the same there:
-      // - if not isStart: nothing
-      // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
-      // - if dots allowed or not possible: (?:/|^)
-      // - if dots possible and not allowed: (?:/|^)(?!\.)
-      //
-      // But it's better to have a simpler binding without a conditional, for
-      // performance, so probably better to return both start options.
-      //
-      // Then the caller just ignores the end if it's not the first pattern,
-      // and the start always gets applied.
-      //
-      // But that's always going to be $ if it's the ending pattern, or nothing,
-      // so the caller can just attach $ at the end of the pattern when building.
-      //
-      // So the todo is:
-      // - better detect what kind of start is needed
-      // - return both flavors of starting pattern
-      // - attach $ at the end of the pattern when creating the actual RegExp
-      //
-      // Ah, but wait, no, that all only applies to the root when the first pattern
-      // is not an extglob. If the first pattern IS an extglob, then we need all
-      // that dot prevention biz to live in the extglob portions, because eg
-      // +(*|.x*) can match .xy but not .yx.
-      //
-      // So, return the two flavors if it's #root and the first child is not an
-      // AST, otherwise leave it to the child AST to handle it, and there,
-      // use the (?:^|/) style of start binding.
-      //
-      // Even simplified further:
-      // - Since the start for a join is eg /(?!\.) and the start for a part
-      // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
-      // or start or whatever) and prepend ^ or / at the Regexp construction.
-      toRegExpSource(allowDot) {
-        const dot = allowDot ?? !!this.#options.dot;
-        if (this.#root === this)
-          this.#fillNegs();
-        if (!this.type) {
-          const noEmpty = this.isStart() && this.isEnd();
-          const src = this.#parts.map((p) => {
-            const [re, _2, hasMagic, uflag] = typeof p === "string" ? _AST.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);
-            this.#hasMagic = this.#hasMagic || hasMagic;
-            this.#uflag = this.#uflag || uflag;
-            return re;
-          }).join("");
-          let start2 = "";
-          if (this.isStart()) {
-            if (typeof this.#parts[0] === "string") {
-              const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
-              if (!dotTravAllowed) {
-                const aps = addPatternStart;
-                const needNoTrav = (
-                  // dots are allowed, and the pattern starts with [ or .
-                  dot && aps.has(src.charAt(0)) || // the pattern starts with \., and then [ or .
-                  src.startsWith("\\.") && aps.has(src.charAt(2)) || // the pattern starts with \.\., and then [ or .
-                  src.startsWith("\\.\\.") && aps.has(src.charAt(4))
-                );
-                const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
-                start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
-              }
-            }
+      /**
+       * Return a generator yielding `[key, value]` pairs,
+       * in order from most recently used to least recently used.
+       */
+      *entries() {
+        for (const i of this.#indexes()) {
+          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
+            yield [this.#keyList[i], this.#valList[i]];
           }
-          let end = "";
-          if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {
-            end = "(?:$|\\/)";
+        }
+      }
+      /**
+       * Inverse order version of {@link LRUCache.entries}
+       *
+       * Return a generator yielding `[key, value]` pairs,
+       * in order from least recently used to most recently used.
+       */
+      *rentries() {
+        for (const i of this.#rindexes()) {
+          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
+            yield [this.#keyList[i], this.#valList[i]];
           }
-          const final2 = start2 + src + end;
-          return [
-            final2,
-            (0, unescape_js_1.unescape)(src),
-            this.#hasMagic = !!this.#hasMagic,
-            this.#uflag
-          ];
         }
-        const repeated = this.type === "*" || this.type === "+";
-        const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
-        let body = this.#partsToRegExp(dot);
-        if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
-          const s = this.toString();
-          this.#parts = [s];
-          this.type = null;
-          this.#hasMagic = void 0;
-          return [s, (0, unescape_js_1.unescape)(this.toString()), false, false];
+      }
+      /**
+       * Return a generator yielding the keys in the cache,
+       * in order from most recently used to least recently used.
+       */
+      *keys() {
+        for (const i of this.#indexes()) {
+          const k = this.#keyList[i];
+          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
+            yield k;
+          }
         }
-        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true);
-        if (bodyDotAllowed === body) {
-          bodyDotAllowed = "";
+      }
+      /**
+       * Inverse order version of {@link LRUCache.keys}
+       *
+       * Return a generator yielding the keys in the cache,
+       * in order from least recently used to most recently used.
+       */
+      *rkeys() {
+        for (const i of this.#rindexes()) {
+          const k = this.#keyList[i];
+          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
+            yield k;
+          }
         }
-        if (bodyDotAllowed) {
-          body = `(?:${body})(?:${bodyDotAllowed})*?`;
+      }
+      /**
+       * Return a generator yielding the values in the cache,
+       * in order from most recently used to least recently used.
+       */
+      *values() {
+        for (const i of this.#indexes()) {
+          const v = this.#valList[i];
+          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
+            yield this.#valList[i];
+          }
         }
-        let final = "";
-        if (this.type === "!" && this.#emptyExt) {
-          final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
-        } else {
-          const close = this.type === "!" ? (
-            // !() must match something,but !(x) can match ''
-            "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")"
-          ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
-          final = start + body + close;
+      }
+      /**
+       * Inverse order version of {@link LRUCache.values}
+       *
+       * Return a generator yielding the values in the cache,
+       * in order from least recently used to most recently used.
+       */
+      *rvalues() {
+        for (const i of this.#rindexes()) {
+          const v = this.#valList[i];
+          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
+            yield this.#valList[i];
+          }
         }
-        return [
-          final,
-          (0, unescape_js_1.unescape)(body),
-          this.#hasMagic = !!this.#hasMagic,
-          this.#uflag
-        ];
       }
-      #partsToRegExp(dot) {
-        return this.#parts.map((p) => {
-          if (typeof p === "string") {
-            throw new Error("string type in extglob ast??");
+      /**
+       * Iterating over the cache itself yields the same results as
+       * {@link LRUCache.entries}
+       */
+      [Symbol.iterator]() {
+        return this.entries();
+      }
+      /**
+       * A String value that is used in the creation of the default string
+       * description of an object. Called by the built-in method
+       * `Object.prototype.toString`.
+       */
+      [Symbol.toStringTag] = "LRUCache";
+      /**
+       * Find a value for which the supplied fn method returns a truthy value,
+       * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
+       */
+      find(fn, getOptions = {}) {
+        for (const i of this.#indexes()) {
+          const v = this.#valList[i];
+          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
+          if (value === void 0)
+            continue;
+          if (fn(value, this.#keyList[i], this)) {
+            return this.get(this.#keyList[i], getOptions);
           }
-          const [re, _2, _hasMagic, uflag] = p.toRegExpSource(dot);
-          this.#uflag = this.#uflag || uflag;
-          return re;
-        }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
+        }
       }
-      static #parseGlob(glob2, hasMagic, noEmpty = false) {
-        let escaping = false;
-        let re = "";
-        let uflag = false;
-        for (let i = 0; i < glob2.length; i++) {
-          const c = glob2.charAt(i);
-          if (escaping) {
-            escaping = false;
-            re += (reSpecials.has(c) ? "\\" : "") + c;
+      /**
+       * Call the supplied function on each item in the cache, in order from most
+       * recently used to least recently used.
+       *
+       * `fn` is called as `fn(value, key, cache)`.
+       *
+       * If `thisp` is provided, function will be called in the `this`-context of
+       * the provided object, or the cache if no `thisp` object is provided.
+       *
+       * Does not update age or recenty of use, or iterate over stale values.
+       */
+      forEach(fn, thisp = this) {
+        for (const i of this.#indexes()) {
+          const v = this.#valList[i];
+          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
+          if (value === void 0)
             continue;
-          }
-          if (c === "\\") {
-            if (i === glob2.length - 1) {
-              re += "\\\\";
-            } else {
-              escaping = true;
-            }
+          fn.call(thisp, value, this.#keyList[i], this);
+        }
+      }
+      /**
+       * The same as {@link LRUCache.forEach} but items are iterated over in
+       * reverse order.  (ie, less recently used items are iterated over first.)
+       */
+      rforEach(fn, thisp = this) {
+        for (const i of this.#rindexes()) {
+          const v = this.#valList[i];
+          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
+          if (value === void 0)
             continue;
+          fn.call(thisp, value, this.#keyList[i], this);
+        }
+      }
+      /**
+       * Delete any stale entries. Returns true if anything was removed,
+       * false otherwise.
+       */
+      purgeStale() {
+        let deleted = false;
+        for (const i of this.#rindexes({ allowStale: true })) {
+          if (this.#isStale(i)) {
+            this.#delete(this.#keyList[i], "expire");
+            deleted = true;
           }
-          if (c === "[") {
-            const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob2, i);
-            if (consumed) {
-              re += src;
-              uflag = uflag || needUflag;
-              i += consumed - 1;
-              hasMagic = hasMagic || magic;
-              continue;
-            }
+        }
+        return deleted;
+      }
+      /**
+       * Get the extended info about a given entry, to get its value, size, and
+       * TTL info simultaneously. Returns `undefined` if the key is not present.
+       *
+       * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
+       * serialization, the `start` value is always the current timestamp, and the
+       * `ttl` is a calculated remaining time to live (negative if expired).
+       *
+       * Always returns stale values, if their info is found in the cache, so be
+       * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
+       * if relevant.
+       */
+      info(key) {
+        const i = this.#keyMap.get(key);
+        if (i === void 0)
+          return void 0;
+        const v = this.#valList[i];
+        const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
+        if (value === void 0)
+          return void 0;
+        const entry = { value };
+        if (this.#ttls && this.#starts) {
+          const ttl = this.#ttls[i];
+          const start = this.#starts[i];
+          if (ttl && start) {
+            const remain = ttl - (perf.now() - start);
+            entry.ttl = remain;
+            entry.start = Date.now();
           }
-          if (c === "*") {
-            if (noEmpty && glob2 === "*")
-              re += starNoEmpty;
-            else
-              re += star;
-            hasMagic = true;
+        }
+        if (this.#sizes) {
+          entry.size = this.#sizes[i];
+        }
+        return entry;
+      }
+      /**
+       * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
+       * passed to {@link LRLUCache#load}.
+       *
+       * The `start` fields are calculated relative to a portable `Date.now()`
+       * timestamp, even if `performance.now()` is available.
+       *
+       * Stale entries are always included in the `dump`, even if
+       * {@link LRUCache.OptionsBase.allowStale} is false.
+       *
+       * Note: this returns an actual array, not a generator, so it can be more
+       * easily passed around.
+       */
+      dump() {
+        const arr = [];
+        for (const i of this.#indexes({ allowStale: true })) {
+          const key = this.#keyList[i];
+          const v = this.#valList[i];
+          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
+          if (value === void 0 || key === void 0)
             continue;
+          const entry = { value };
+          if (this.#ttls && this.#starts) {
+            entry.ttl = this.#ttls[i];
+            const age = perf.now() - this.#starts[i];
+            entry.start = Math.floor(Date.now() - age);
           }
-          if (c === "?") {
-            re += qmark;
-            hasMagic = true;
-            continue;
+          if (this.#sizes) {
+            entry.size = this.#sizes[i];
           }
-          re += regExpEscape(c);
+          arr.unshift([key, entry]);
         }
-        return [re, (0, unescape_js_1.unescape)(glob2), !!hasMagic, uflag];
-      }
-    };
-    exports2.AST = AST;
-  }
-});
-
-// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/escape.js
-var require_escape = __commonJS({
-  "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/escape.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.escape = void 0;
-    var escape = (s, { windowsPathsNoEscape = false } = {}) => {
-      return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
-    };
-    exports2.escape = escape;
-  }
-});
-
-// node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/index.js
-var require_commonjs13 = __commonJS({
-  "node_modules/archiver-utils/node_modules/minimatch/dist/commonjs/index.js"(exports2) {
-    "use strict";
-    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
-      return mod && mod.__esModule ? mod : { "default": mod };
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.unescape = exports2.escape = exports2.AST = exports2.Minimatch = exports2.match = exports2.makeRe = exports2.braceExpand = exports2.defaults = exports2.filter = exports2.GLOBSTAR = exports2.sep = exports2.minimatch = void 0;
-    var brace_expansion_1 = __importDefault4(require_brace_expansion2());
-    var assert_valid_pattern_js_1 = require_assert_valid_pattern();
-    var ast_js_1 = require_ast();
-    var escape_js_1 = require_escape();
-    var unescape_js_1 = require_unescape();
-    var minimatch = (p, pattern, options = {}) => {
-      (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-      if (!options.nocomment && pattern.charAt(0) === "#") {
-        return false;
-      }
-      return new Minimatch(pattern, options).match(p);
-    };
-    exports2.minimatch = minimatch;
-    var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
-    var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);
-    var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);
-    var starDotExtTestNocase = (ext2) => {
-      ext2 = ext2.toLowerCase();
-      return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
-    };
-    var starDotExtTestNocaseDot = (ext2) => {
-      ext2 = ext2.toLowerCase();
-      return (f) => f.toLowerCase().endsWith(ext2);
-    };
-    var starDotStarRE = /^\*+\.\*+$/;
-    var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
-    var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
-    var dotStarRE = /^\.\*+$/;
-    var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
-    var starRE = /^\*+$/;
-    var starTest = (f) => f.length !== 0 && !f.startsWith(".");
-    var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
-    var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
-    var qmarksTestNocase = ([$0, ext2 = ""]) => {
-      const noext = qmarksTestNoExt([$0]);
-      if (!ext2)
-        return noext;
-      ext2 = ext2.toLowerCase();
-      return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
-    };
-    var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
-      const noext = qmarksTestNoExtDot([$0]);
-      if (!ext2)
-        return noext;
-      ext2 = ext2.toLowerCase();
-      return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
-    };
-    var qmarksTestDot = ([$0, ext2 = ""]) => {
-      const noext = qmarksTestNoExtDot([$0]);
-      return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
-    };
-    var qmarksTest = ([$0, ext2 = ""]) => {
-      const noext = qmarksTestNoExt([$0]);
-      return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
-    };
-    var qmarksTestNoExt = ([$0]) => {
-      const len = $0.length;
-      return (f) => f.length === len && !f.startsWith(".");
-    };
-    var qmarksTestNoExtDot = ([$0]) => {
-      const len = $0.length;
-      return (f) => f.length === len && f !== "." && f !== "..";
-    };
-    var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
-    var path2 = {
-      win32: { sep: "\\" },
-      posix: { sep: "/" }
-    };
-    exports2.sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
-    exports2.minimatch.sep = exports2.sep;
-    exports2.GLOBSTAR = Symbol("globstar **");
-    exports2.minimatch.GLOBSTAR = exports2.GLOBSTAR;
-    var qmark = "[^/]";
-    var star = qmark + "*?";
-    var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
-    var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
-    var filter = (pattern, options = {}) => (p) => (0, exports2.minimatch)(p, pattern, options);
-    exports2.filter = filter;
-    exports2.minimatch.filter = exports2.filter;
-    var ext = (a, b = {}) => Object.assign({}, a, b);
-    var defaults = (def) => {
-      if (!def || typeof def !== "object" || !Object.keys(def).length) {
-        return exports2.minimatch;
+        return arr;
       }
-      const orig = exports2.minimatch;
-      const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
-      return Object.assign(m, {
-        Minimatch: class Minimatch extends orig.Minimatch {
-          constructor(pattern, options = {}) {
-            super(pattern, ext(def, options));
-          }
-          static defaults(options) {
-            return orig.defaults(ext(def, options)).Minimatch;
+      /**
+       * Reset the cache and load in the items in entries in the order listed.
+       *
+       * The shape of the resulting cache may be different if the same options are
+       * not used in both caches.
+       *
+       * The `start` fields are assumed to be calculated relative to a portable
+       * `Date.now()` timestamp, even if `performance.now()` is available.
+       */
+      load(arr) {
+        this.clear();
+        for (const [key, entry] of arr) {
+          if (entry.start) {
+            const age = Date.now() - entry.start;
+            entry.start = perf.now() - age;
           }
-        },
-        AST: class AST extends orig.AST {
-          /* c8 ignore start */
-          constructor(type2, parent, options = {}) {
-            super(type2, parent, ext(def, options));
+          this.set(key, entry.value, entry);
+        }
+      }
+      /**
+       * Add a value to the cache.
+       *
+       * Note: if `undefined` is specified as a value, this is an alias for
+       * {@link LRUCache#delete}
+       *
+       * Fields on the {@link LRUCache.SetOptions} options param will override
+       * their corresponding values in the constructor options for the scope
+       * of this single `set()` operation.
+       *
+       * If `start` is provided, then that will set the effective start
+       * time for the TTL calculation. Note that this must be a previous
+       * value of `performance.now()` if supported, or a previous value of
+       * `Date.now()` if not.
+       *
+       * Options object may also include `size`, which will prevent
+       * calling the `sizeCalculation` function and just use the specified
+       * number if it is a positive integer, and `noDisposeOnSet` which
+       * will prevent calling a `dispose` function in the case of
+       * overwrites.
+       *
+       * If the `size` (or return value of `sizeCalculation`) for a given
+       * entry is greater than `maxEntrySize`, then the item will not be
+       * added to the cache.
+       *
+       * Will update the recency of the entry.
+       *
+       * If the value is `undefined`, then this is an alias for
+       * `cache.delete(key)`. `undefined` is never stored in the cache.
+       */
+      set(k, v, setOptions = {}) {
+        if (v === void 0) {
+          this.delete(k);
+          return this;
+        }
+        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
+        let { noUpdateTTL = this.noUpdateTTL } = setOptions;
+        const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
+        if (this.maxEntrySize && size > this.maxEntrySize) {
+          if (status) {
+            status.set = "miss";
+            status.maxEntrySizeExceeded = true;
           }
-          /* c8 ignore stop */
-          static fromGlob(pattern, options = {}) {
-            return orig.AST.fromGlob(pattern, ext(def, options));
+          this.#delete(k, "set");
+          return this;
+        }
+        let index = this.#size === 0 ? void 0 : this.#keyMap.get(k);
+        if (index === void 0) {
+          index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
+          this.#keyList[index] = k;
+          this.#valList[index] = v;
+          this.#keyMap.set(k, index);
+          this.#next[this.#tail] = index;
+          this.#prev[index] = this.#tail;
+          this.#tail = index;
+          this.#size++;
+          this.#addItemSize(index, size, status);
+          if (status)
+            status.set = "add";
+          noUpdateTTL = false;
+        } else {
+          this.#moveToTail(index);
+          const oldVal = this.#valList[index];
+          if (v !== oldVal) {
+            if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
+              oldVal.__abortController.abort(new Error("replaced"));
+              const { __staleWhileFetching: s } = oldVal;
+              if (s !== void 0 && !noDisposeOnSet) {
+                if (this.#hasDispose) {
+                  this.#dispose?.(s, k, "set");
+                }
+                if (this.#hasDisposeAfter) {
+                  this.#disposed?.push([s, k, "set"]);
+                }
+              }
+            } else if (!noDisposeOnSet) {
+              if (this.#hasDispose) {
+                this.#dispose?.(oldVal, k, "set");
+              }
+              if (this.#hasDisposeAfter) {
+                this.#disposed?.push([oldVal, k, "set"]);
+              }
+            }
+            this.#removeItemSize(index);
+            this.#addItemSize(index, size, status);
+            this.#valList[index] = v;
+            if (status) {
+              status.set = "replace";
+              const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
+              if (oldValue !== void 0)
+                status.oldValue = oldValue;
+            }
+          } else if (status) {
+            status.set = "update";
           }
-        },
-        unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
-        escape: (s, options = {}) => orig.escape(s, ext(def, options)),
-        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
-        defaults: (options) => orig.defaults(ext(def, options)),
-        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
-        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
-        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
-        sep: orig.sep,
-        GLOBSTAR: exports2.GLOBSTAR
-      });
-    };
-    exports2.defaults = defaults;
-    exports2.minimatch.defaults = exports2.defaults;
-    var braceExpand = (pattern, options = {}) => {
-      (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
-        return [pattern];
-      }
-      return (0, brace_expansion_1.default)(pattern);
-    };
-    exports2.braceExpand = braceExpand;
-    exports2.minimatch.braceExpand = exports2.braceExpand;
-    var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
-    exports2.makeRe = makeRe;
-    exports2.minimatch.makeRe = exports2.makeRe;
-    var match = (list, pattern, options = {}) => {
-      const mm = new Minimatch(pattern, options);
-      list = list.filter((f) => mm.match(f));
-      if (mm.options.nonull && !list.length) {
-        list.push(pattern);
-      }
-      return list;
-    };
-    exports2.match = match;
-    exports2.minimatch.match = exports2.match;
-    var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
-    var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
-    var Minimatch = class {
-      options;
-      set;
-      pattern;
-      windowsPathsNoEscape;
-      nonegate;
-      negate;
-      comment;
-      empty;
-      preserveMultipleSlashes;
-      partial;
-      globSet;
-      globParts;
-      nocase;
-      isWindows;
-      platform;
-      windowsNoMagicRoot;
-      regexp;
-      constructor(pattern, options = {}) {
-        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-        options = options || {};
-        this.options = options;
-        this.pattern = pattern;
-        this.platform = options.platform || defaultPlatform;
-        this.isWindows = this.platform === "win32";
-        this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
-        if (this.windowsPathsNoEscape) {
-          this.pattern = this.pattern.replace(/\\/g, "/");
         }
-        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
-        this.regexp = null;
-        this.negate = false;
-        this.nonegate = !!options.nonegate;
-        this.comment = false;
-        this.empty = false;
-        this.partial = !!options.partial;
-        this.nocase = !!this.options.nocase;
-        this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
-        this.globSet = [];
-        this.globParts = [];
-        this.set = [];
-        this.make();
-      }
-      hasMagic() {
-        if (this.options.magicalBraces && this.set.length > 1) {
-          return true;
+        if (ttl !== 0 && !this.#ttls) {
+          this.#initializeTTLTracking();
         }
-        for (const pattern of this.set) {
-          for (const part of pattern) {
-            if (typeof part !== "string")
-              return true;
+        if (this.#ttls) {
+          if (!noUpdateTTL) {
+            this.#setItemTTL(index, ttl, start);
+          }
+          if (status)
+            this.#statusTTL(status, index);
+        }
+        if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
+          const dt = this.#disposed;
+          let task;
+          while (task = dt?.shift()) {
+            this.#disposeAfter?.(...task);
           }
         }
-        return false;
-      }
-      debug(..._2) {
+        return this;
       }
-      make() {
-        const pattern = this.pattern;
-        const options = this.options;
-        if (!options.nocomment && pattern.charAt(0) === "#") {
-          this.comment = true;
-          return;
-        }
-        if (!pattern) {
-          this.empty = true;
-          return;
-        }
-        this.parseNegate();
-        this.globSet = [...new Set(this.braceExpand())];
-        if (options.debug) {
-          this.debug = (...args) => console.error(...args);
-        }
-        this.debug(this.pattern, this.globSet);
-        const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
-        this.globParts = this.preprocess(rawGlobParts);
-        this.debug(this.pattern, this.globParts);
-        let set2 = this.globParts.map((s, _2, __) => {
-          if (this.isWindows && this.windowsNoMagicRoot) {
-            const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
-            const isDrive = /^[a-z]:/i.test(s[0]);
-            if (isUNC) {
-              return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))];
-            } else if (isDrive) {
-              return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
+      /**
+       * Evict the least recently used item, returning its value or
+       * `undefined` if cache is empty.
+       */
+      pop() {
+        try {
+          while (this.#size) {
+            const val2 = this.#valList[this.#head];
+            this.#evict(true);
+            if (this.#isBackgroundFetch(val2)) {
+              if (val2.__staleWhileFetching) {
+                return val2.__staleWhileFetching;
+              }
+            } else if (val2 !== void 0) {
+              return val2;
             }
           }
-          return s.map((ss) => this.parse(ss));
-        });
-        this.debug(this.pattern, set2);
-        this.set = set2.filter((s) => s.indexOf(false) === -1);
-        if (this.isWindows) {
-          for (let i = 0; i < this.set.length; i++) {
-            const p = this.set[i];
-            if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
-              p[2] = "?";
+        } finally {
+          if (this.#hasDisposeAfter && this.#disposed) {
+            const dt = this.#disposed;
+            let task;
+            while (task = dt?.shift()) {
+              this.#disposeAfter?.(...task);
             }
           }
         }
-        this.debug(this.pattern, this.set);
       }
-      // various transforms to equivalent pattern sets that are
-      // faster to process in a filesystem walk.  The goal is to
-      // eliminate what we can, and push all ** patterns as far
-      // to the right as possible, even if it increases the number
-      // of patterns that we have to process.
-      preprocess(globParts) {
-        if (this.options.noglobstar) {
-          for (let i = 0; i < globParts.length; i++) {
-            for (let j = 0; j < globParts[i].length; j++) {
-              if (globParts[i][j] === "**") {
-                globParts[i][j] = "*";
-              }
-            }
+      #evict(free) {
+        const head = this.#head;
+        const k = this.#keyList[head];
+        const v = this.#valList[head];
+        if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
+          v.__abortController.abort(new Error("evicted"));
+        } else if (this.#hasDispose || this.#hasDisposeAfter) {
+          if (this.#hasDispose) {
+            this.#dispose?.(v, k, "evict");
+          }
+          if (this.#hasDisposeAfter) {
+            this.#disposed?.push([v, k, "evict"]);
           }
         }
-        const { optimizationLevel = 1 } = this.options;
-        if (optimizationLevel >= 2) {
-          globParts = this.firstPhasePreProcess(globParts);
-          globParts = this.secondPhasePreProcess(globParts);
-        } else if (optimizationLevel >= 1) {
-          globParts = this.levelOneOptimize(globParts);
+        this.#removeItemSize(head);
+        if (free) {
+          this.#keyList[head] = void 0;
+          this.#valList[head] = void 0;
+          this.#free.push(head);
+        }
+        if (this.#size === 1) {
+          this.#head = this.#tail = 0;
+          this.#free.length = 0;
         } else {
-          globParts = this.adjascentGlobstarOptimize(globParts);
+          this.#head = this.#next[head];
         }
-        return globParts;
+        this.#keyMap.delete(k);
+        this.#size--;
+        return head;
       }
-      // just get rid of adjascent ** portions
-      adjascentGlobstarOptimize(globParts) {
-        return globParts.map((parts) => {
-          let gs = -1;
-          while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
-            let i = gs;
-            while (parts[i + 1] === "**") {
-              i++;
+      /**
+       * Check if a key is in the cache, without updating the recency of use.
+       * Will return false if the item is stale, even though it is technically
+       * in the cache.
+       *
+       * Check if a key is in the cache, without updating the recency of
+       * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
+       * to `true` in either the options or the constructor.
+       *
+       * Will return `false` if the item is stale, even though it is technically in
+       * the cache. The difference can be determined (if it matters) by using a
+       * `status` argument, and inspecting the `has` field.
+       *
+       * Will not update item age unless
+       * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
+       */
+      has(k, hasOptions = {}) {
+        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
+        const index = this.#keyMap.get(k);
+        if (index !== void 0) {
+          const v = this.#valList[index];
+          if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) {
+            return false;
+          }
+          if (!this.#isStale(index)) {
+            if (updateAgeOnHas) {
+              this.#updateItemAge(index);
             }
-            if (i !== gs) {
-              parts.splice(gs, i - gs);
+            if (status) {
+              status.has = "hit";
+              this.#statusTTL(status, index);
             }
+            return true;
+          } else if (status) {
+            status.has = "stale";
+            this.#statusTTL(status, index);
           }
-          return parts;
-        });
+        } else if (status) {
+          status.has = "miss";
+        }
+        return false;
       }
-      // get rid of adjascent ** and resolve .. portions
-      levelOneOptimize(globParts) {
-        return globParts.map((parts) => {
-          parts = parts.reduce((set2, part) => {
-            const prev = set2[set2.length - 1];
-            if (part === "**" && prev === "**") {
-              return set2;
+      /**
+       * Like {@link LRUCache#get} but doesn't update recency or delete stale
+       * items.
+       *
+       * Returns `undefined` if the item is stale, unless
+       * {@link LRUCache.OptionsBase.allowStale} is set.
+       */
+      peek(k, peekOptions = {}) {
+        const { allowStale = this.allowStale } = peekOptions;
+        const index = this.#keyMap.get(k);
+        if (index === void 0 || !allowStale && this.#isStale(index)) {
+          return;
+        }
+        const v = this.#valList[index];
+        return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
+      }
+      #backgroundFetch(k, index, options, context2) {
+        const v = index === void 0 ? void 0 : this.#valList[index];
+        if (this.#isBackgroundFetch(v)) {
+          return v;
+        }
+        const ac = new AC();
+        const { signal } = options;
+        signal?.addEventListener("abort", () => ac.abort(signal.reason), {
+          signal: ac.signal
+        });
+        const fetchOpts = {
+          signal: ac.signal,
+          options,
+          context: context2
+        };
+        const cb = (v2, updateCache = false) => {
+          const { aborted } = ac.signal;
+          const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;
+          if (options.status) {
+            if (aborted && !updateCache) {
+              options.status.fetchAborted = true;
+              options.status.fetchError = ac.signal.reason;
+              if (ignoreAbort)
+                options.status.fetchAbortIgnored = true;
+            } else {
+              options.status.fetchResolved = true;
             }
-            if (part === "..") {
-              if (prev && prev !== ".." && prev !== "." && prev !== "**") {
-                set2.pop();
-                return set2;
+          }
+          if (aborted && !ignoreAbort && !updateCache) {
+            return fetchFail(ac.signal.reason);
+          }
+          const bf2 = p;
+          if (this.#valList[index] === p) {
+            if (v2 === void 0) {
+              if (bf2.__staleWhileFetching) {
+                this.#valList[index] = bf2.__staleWhileFetching;
+              } else {
+                this.#delete(k, "fetch");
               }
+            } else {
+              if (options.status)
+                options.status.fetchUpdated = true;
+              this.set(k, v2, fetchOpts.options);
             }
-            set2.push(part);
-            return set2;
-          }, []);
-          return parts.length === 0 ? [""] : parts;
+          }
+          return v2;
+        };
+        const eb = (er) => {
+          if (options.status) {
+            options.status.fetchRejected = true;
+            options.status.fetchError = er;
+          }
+          return fetchFail(er);
+        };
+        const fetchFail = (er) => {
+          const { aborted } = ac.signal;
+          const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
+          const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
+          const noDelete = allowStale || options.noDeleteOnFetchRejection;
+          const bf2 = p;
+          if (this.#valList[index] === p) {
+            const del = !noDelete || bf2.__staleWhileFetching === void 0;
+            if (del) {
+              this.#delete(k, "fetch");
+            } else if (!allowStaleAborted) {
+              this.#valList[index] = bf2.__staleWhileFetching;
+            }
+          }
+          if (allowStale) {
+            if (options.status && bf2.__staleWhileFetching !== void 0) {
+              options.status.returnedStale = true;
+            }
+            return bf2.__staleWhileFetching;
+          } else if (bf2.__returned === bf2) {
+            throw er;
+          }
+        };
+        const pcall = (res, rej) => {
+          const fmp = this.#fetchMethod?.(k, v, fetchOpts);
+          if (fmp && fmp instanceof Promise) {
+            fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
+          }
+          ac.signal.addEventListener("abort", () => {
+            if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
+              res(void 0);
+              if (options.allowStaleOnFetchAbort) {
+                res = (v2) => cb(v2, true);
+              }
+            }
+          });
+        };
+        if (options.status)
+          options.status.fetchDispatched = true;
+        const p = new Promise(pcall).then(cb, eb);
+        const bf = Object.assign(p, {
+          __abortController: ac,
+          __staleWhileFetching: v,
+          __returned: void 0
         });
+        if (index === void 0) {
+          this.set(k, bf, { ...fetchOpts.options, status: void 0 });
+          index = this.#keyMap.get(k);
+        } else {
+          this.#valList[index] = bf;
+        }
+        return bf;
       }
-      levelTwoFileOptimize(parts) {
-        if (!Array.isArray(parts)) {
-          parts = this.slashSplit(parts);
+      #isBackgroundFetch(p) {
+        if (!this.#hasFetchMethod)
+          return false;
+        const b = p;
+        return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
+      }
+      async fetch(k, fetchOptions = {}) {
+        const {
+          // get options
+          allowStale = this.allowStale,
+          updateAgeOnGet = this.updateAgeOnGet,
+          noDeleteOnStaleGet = this.noDeleteOnStaleGet,
+          // set options
+          ttl = this.ttl,
+          noDisposeOnSet = this.noDisposeOnSet,
+          size = 0,
+          sizeCalculation = this.sizeCalculation,
+          noUpdateTTL = this.noUpdateTTL,
+          // fetch exclusive options
+          noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
+          allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
+          ignoreFetchAbort = this.ignoreFetchAbort,
+          allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
+          context: context2,
+          forceRefresh = false,
+          status,
+          signal
+        } = fetchOptions;
+        if (!this.#hasFetchMethod) {
+          if (status)
+            status.fetch = "get";
+          return this.get(k, {
+            allowStale,
+            updateAgeOnGet,
+            noDeleteOnStaleGet,
+            status
+          });
         }
-        let didSomething = false;
-        do {
-          didSomething = false;
-          if (!this.preserveMultipleSlashes) {
-            for (let i = 1; i < parts.length - 1; i++) {
-              const p = parts[i];
-              if (i === 1 && p === "" && parts[0] === "")
-                continue;
-              if (p === "." || p === "") {
-                didSomething = true;
-                parts.splice(i, 1);
-                i--;
-              }
-            }
-            if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
-              didSomething = true;
-              parts.pop();
+        const options = {
+          allowStale,
+          updateAgeOnGet,
+          noDeleteOnStaleGet,
+          ttl,
+          noDisposeOnSet,
+          size,
+          sizeCalculation,
+          noUpdateTTL,
+          noDeleteOnFetchRejection,
+          allowStaleOnFetchRejection,
+          allowStaleOnFetchAbort,
+          ignoreFetchAbort,
+          status,
+          signal
+        };
+        let index = this.#keyMap.get(k);
+        if (index === void 0) {
+          if (status)
+            status.fetch = "miss";
+          const p = this.#backgroundFetch(k, index, options, context2);
+          return p.__returned = p;
+        } else {
+          const v = this.#valList[index];
+          if (this.#isBackgroundFetch(v)) {
+            const stale = allowStale && v.__staleWhileFetching !== void 0;
+            if (status) {
+              status.fetch = "inflight";
+              if (stale)
+                status.returnedStale = true;
             }
+            return stale ? v.__staleWhileFetching : v.__returned = v;
           }
-          let dd = 0;
-          while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
-            const p = parts[dd - 1];
-            if (p && p !== "." && p !== ".." && p !== "**") {
-              didSomething = true;
-              parts.splice(dd - 1, 2);
-              dd -= 2;
+          const isStale = this.#isStale(index);
+          if (!forceRefresh && !isStale) {
+            if (status)
+              status.fetch = "hit";
+            this.#moveToTail(index);
+            if (updateAgeOnGet) {
+              this.#updateItemAge(index);
             }
+            if (status)
+              this.#statusTTL(status, index);
+            return v;
           }
-        } while (didSomething);
-        return parts.length === 0 ? [""] : parts;
+          const p = this.#backgroundFetch(k, index, options, context2);
+          const hasStale = p.__staleWhileFetching !== void 0;
+          const staleVal = hasStale && allowStale;
+          if (status) {
+            status.fetch = isStale ? "stale" : "refresh";
+            if (staleVal && isStale)
+              status.returnedStale = true;
+          }
+          return staleVal ? p.__staleWhileFetching : p.__returned = p;
+        }
       }
-      // First phase: single-pattern processing
-      // 
 is 1 or more portions
-      //  is 1 or more portions
-      // 

is any portion other than ., .., '', or ** - // is . or '' - // - // **/.. is *brutal* for filesystem walking performance, because - // it effectively resets the recursive walk each time it occurs, - // and ** cannot be reduced out by a .. pattern part like a regexp - // or most strings (other than .., ., and '') can be. - // - //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} - //

// -> 
/
-      // 
/

/../ ->

/
-      // **/**/ -> **/
-      //
-      // **/*/ -> */**/ <== not valid because ** doesn't follow
-      // this WOULD be allowed if ** did follow symlinks, or * didn't
-      firstPhasePreProcess(globParts) {
-        let didSomething = false;
-        do {
-          didSomething = false;
-          for (let parts of globParts) {
-            let gs = -1;
-            while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
-              let gss = gs;
-              while (parts[gss + 1] === "**") {
-                gss++;
-              }
-              if (gss > gs) {
-                parts.splice(gs + 1, gss - gs);
-              }
-              let next = parts[gs + 1];
-              const p = parts[gs + 2];
-              const p2 = parts[gs + 3];
-              if (next !== "..")
-                continue;
-              if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
-                continue;
-              }
-              didSomething = true;
-              parts.splice(gs, 1);
-              const other = parts.slice(0);
-              other[gs] = "**";
-              globParts.push(other);
-              gs--;
-            }
-            if (!this.preserveMultipleSlashes) {
-              for (let i = 1; i < parts.length - 1; i++) {
-                const p = parts[i];
-                if (i === 1 && p === "" && parts[0] === "")
-                  continue;
-                if (p === "." || p === "") {
-                  didSomething = true;
-                  parts.splice(i, 1);
-                  i--;
-                }
-              }
-              if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
-                didSomething = true;
-                parts.pop();
+      async forceFetch(k, fetchOptions = {}) {
+        const v = await this.fetch(k, fetchOptions);
+        if (v === void 0)
+          throw new Error("fetch() returned undefined");
+        return v;
+      }
+      memo(k, memoOptions = {}) {
+        const memoMethod = this.#memoMethod;
+        if (!memoMethod) {
+          throw new Error("no memoMethod provided to constructor");
+        }
+        const { context: context2, forceRefresh, ...options } = memoOptions;
+        const v = this.get(k, options);
+        if (!forceRefresh && v !== void 0)
+          return v;
+        const vv = memoMethod(k, v, {
+          options,
+          context: context2
+        });
+        this.set(k, vv, options);
+        return vv;
+      }
+      /**
+       * Return a value from the cache. Will update the recency of the cache
+       * entry found.
+       *
+       * If the key is not found, get() will return `undefined`.
+       */
+      get(k, getOptions = {}) {
+        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
+        const index = this.#keyMap.get(k);
+        if (index !== void 0) {
+          const value = this.#valList[index];
+          const fetching = this.#isBackgroundFetch(value);
+          if (status)
+            this.#statusTTL(status, index);
+          if (this.#isStale(index)) {
+            if (status)
+              status.get = "stale";
+            if (!fetching) {
+              if (!noDeleteOnStaleGet) {
+                this.#delete(k, "expire");
               }
-            }
-            let dd = 0;
-            while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
-              const p = parts[dd - 1];
-              if (p && p !== "." && p !== ".." && p !== "**") {
-                didSomething = true;
-                const needDot = dd === 1 && parts[dd + 1] === "**";
-                const splin = needDot ? ["."] : [];
-                parts.splice(dd - 1, 2, ...splin);
-                if (parts.length === 0)
-                  parts.push("");
-                dd -= 2;
+              if (status && allowStale)
+                status.returnedStale = true;
+              return allowStale ? value : void 0;
+            } else {
+              if (status && allowStale && value.__staleWhileFetching !== void 0) {
+                status.returnedStale = true;
               }
+              return allowStale ? value.__staleWhileFetching : void 0;
             }
-          }
-        } while (didSomething);
-        return globParts;
-      }
-      // second phase: multi-pattern dedupes
-      // {
/*/,
/

/} ->

/*/
-      // {
/,
/} -> 
/
-      // {
/**/,
/} -> 
/**/
-      //
-      // {
/**/,
/**/

/} ->

/**/
-      // ^-- not valid because ** doens't follow symlinks
-      secondPhasePreProcess(globParts) {
-        for (let i = 0; i < globParts.length - 1; i++) {
-          for (let j = i + 1; j < globParts.length; j++) {
-            const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
-            if (matched) {
-              globParts[i] = [];
-              globParts[j] = matched;
-              break;
+          } else {
+            if (status)
+              status.get = "hit";
+            if (fetching) {
+              return value.__staleWhileFetching;
+            }
+            this.#moveToTail(index);
+            if (updateAgeOnGet) {
+              this.#updateItemAge(index);
             }
+            return value;
           }
+        } else if (status) {
+          status.get = "miss";
         }
-        return globParts.filter((gs) => gs.length);
       }
-      partsMatch(a, b, emptyGSMatch = false) {
-        let ai = 0;
-        let bi = 0;
-        let result = [];
-        let which6 = "";
-        while (ai < a.length && bi < b.length) {
-          if (a[ai] === b[bi]) {
-            result.push(which6 === "b" ? b[bi] : a[ai]);
-            ai++;
-            bi++;
-          } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
-            result.push(a[ai]);
-            ai++;
-          } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
-            result.push(b[bi]);
-            bi++;
-          } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
-            if (which6 === "b")
-              return false;
-            which6 = "a";
-            result.push(a[ai]);
-            ai++;
-            bi++;
-          } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
-            if (which6 === "a")
-              return false;
-            which6 = "b";
-            result.push(b[bi]);
-            ai++;
-            bi++;
+      #connect(p, n) {
+        this.#prev[n] = p;
+        this.#next[p] = n;
+      }
+      #moveToTail(index) {
+        if (index !== this.#tail) {
+          if (index === this.#head) {
+            this.#head = this.#next[index];
           } else {
-            return false;
+            this.#connect(this.#prev[index], this.#next[index]);
           }
+          this.#connect(this.#tail, index);
+          this.#tail = index;
         }
-        return a.length === b.length && result;
       }
-      parseNegate() {
-        if (this.nonegate)
-          return;
-        const pattern = this.pattern;
-        let negate = false;
-        let negateOffset = 0;
-        for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
-          negate = !negate;
-          negateOffset++;
-        }
-        if (negateOffset)
-          this.pattern = pattern.slice(negateOffset);
-        this.negate = negate;
+      /**
+       * Deletes a key out of the cache.
+       *
+       * Returns true if the key was deleted, false otherwise.
+       */
+      delete(k) {
+        return this.#delete(k, "delete");
       }
-      // set partial to true to test if, for example,
-      // "/a/b" matches the start of "/*/b/*/d"
-      // Partial means, if you run out of file before you run
-      // out of pattern, then that's fine, as long as all
-      // the parts match.
-      matchOne(file, pattern, partial = false) {
-        const options = this.options;
-        if (this.isWindows) {
-          const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
-          const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
-          const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
-          const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
-          const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
-          const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
-          if (typeof fdi === "number" && typeof pdi === "number") {
-            const [fd, pd] = [file[fdi], pattern[pdi]];
-            if (fd.toLowerCase() === pd.toLowerCase()) {
-              pattern[pdi] = fd;
-              if (pdi > fdi) {
-                pattern = pattern.slice(pdi);
-              } else if (fdi > pdi) {
-                file = file.slice(fdi);
+      #delete(k, reason) {
+        let deleted = false;
+        if (this.#size !== 0) {
+          const index = this.#keyMap.get(k);
+          if (index !== void 0) {
+            deleted = true;
+            if (this.#size === 1) {
+              this.#clear(reason);
+            } else {
+              this.#removeItemSize(index);
+              const v = this.#valList[index];
+              if (this.#isBackgroundFetch(v)) {
+                v.__abortController.abort(new Error("deleted"));
+              } else if (this.#hasDispose || this.#hasDisposeAfter) {
+                if (this.#hasDispose) {
+                  this.#dispose?.(v, k, reason);
+                }
+                if (this.#hasDisposeAfter) {
+                  this.#disposed?.push([v, k, reason]);
+                }
+              }
+              this.#keyMap.delete(k);
+              this.#keyList[index] = void 0;
+              this.#valList[index] = void 0;
+              if (index === this.#tail) {
+                this.#tail = this.#prev[index];
+              } else if (index === this.#head) {
+                this.#head = this.#next[index];
+              } else {
+                const pi = this.#prev[index];
+                this.#next[pi] = this.#next[index];
+                const ni = this.#next[index];
+                this.#prev[ni] = this.#prev[index];
               }
+              this.#size--;
+              this.#free.push(index);
             }
           }
         }
-        const { optimizationLevel = 1 } = this.options;
-        if (optimizationLevel >= 2) {
-          file = this.levelTwoFileOptimize(file);
-        }
-        this.debug("matchOne", this, { file, pattern });
-        this.debug("matchOne", file.length, pattern.length);
-        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
-          this.debug("matchOne loop");
-          var p = pattern[pi];
-          var f = file[fi];
-          this.debug(pattern, p, f);
-          if (p === false) {
-            return false;
+        if (this.#hasDisposeAfter && this.#disposed?.length) {
+          const dt = this.#disposed;
+          let task;
+          while (task = dt?.shift()) {
+            this.#disposeAfter?.(...task);
           }
-          if (p === exports2.GLOBSTAR) {
-            this.debug("GLOBSTAR", [pattern, p, f]);
-            var fr = fi;
-            var pr = pi + 1;
-            if (pr === pl) {
-              this.debug("** at the end");
-              for (; fi < fl; fi++) {
-                if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
-                  return false;
-              }
-              return true;
-            }
-            while (fr < fl) {
-              var swallowee = file[fr];
-              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
-              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
-                this.debug("globstar found match!", fr, fl, swallowee);
-                return true;
-              } else {
-                if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
-                  this.debug("dot detected!", file, fr, pattern, pr);
-                  break;
-                }
-                this.debug("globstar swallow a segment, and continue");
-                fr++;
-              }
+        }
+        return deleted;
+      }
+      /**
+       * Clear the cache entirely, throwing away all values.
+       */
+      clear() {
+        return this.#clear("delete");
+      }
+      #clear(reason) {
+        for (const index of this.#rindexes({ allowStale: true })) {
+          const v = this.#valList[index];
+          if (this.#isBackgroundFetch(v)) {
+            v.__abortController.abort(new Error("deleted"));
+          } else {
+            const k = this.#keyList[index];
+            if (this.#hasDispose) {
+              this.#dispose?.(v, k, reason);
             }
-            if (partial) {
-              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
-              if (fr === fl) {
-                return true;
-              }
+            if (this.#hasDisposeAfter) {
+              this.#disposed?.push([v, k, reason]);
             }
-            return false;
-          }
-          let hit;
-          if (typeof p === "string") {
-            hit = f === p;
-            this.debug("string match", p, f, hit);
-          } else {
-            hit = p.test(f);
-            this.debug("pattern match", p, f, hit);
           }
-          if (!hit)
-            return false;
         }
-        if (fi === fl && pi === pl) {
-          return true;
-        } else if (fi === fl) {
-          return partial;
-        } else if (pi === pl) {
-          return fi === fl - 1 && file[fi] === "";
-        } else {
-          throw new Error("wtf?");
+        this.#keyMap.clear();
+        this.#valList.fill(void 0);
+        this.#keyList.fill(void 0);
+        if (this.#ttls && this.#starts) {
+          this.#ttls.fill(0);
+          this.#starts.fill(0);
+        }
+        if (this.#sizes) {
+          this.#sizes.fill(0);
+        }
+        this.#head = 0;
+        this.#tail = 0;
+        this.#free.length = 0;
+        this.#calculatedSize = 0;
+        this.#size = 0;
+        if (this.#hasDisposeAfter && this.#disposed) {
+          const dt = this.#disposed;
+          let task;
+          while (task = dt?.shift()) {
+            this.#disposeAfter?.(...task);
+          }
         }
       }
-      braceExpand() {
-        return (0, exports2.braceExpand)(this.pattern, this.options);
+    };
+    exports2.LRUCache = LRUCache;
+  }
+});
+
+// node_modules/minipass/dist/commonjs/index.js
+var require_commonjs15 = __commonJS({
+  "node_modules/minipass/dist/commonjs/index.js"(exports2) {
+    "use strict";
+    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
+      return mod && mod.__esModule ? mod : { "default": mod };
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.Minipass = exports2.isWritable = exports2.isReadable = exports2.isStream = void 0;
+    var proc = typeof process === "object" && process ? process : {
+      stdout: null,
+      stderr: null
+    };
+    var node_events_1 = require("node:events");
+    var node_stream_1 = __importDefault4(require("node:stream"));
+    var node_string_decoder_1 = require("node:string_decoder");
+    var isStream = (s) => !!s && typeof s === "object" && (s instanceof Minipass || s instanceof node_stream_1.default || (0, exports2.isReadable)(s) || (0, exports2.isWritable)(s));
+    exports2.isStream = isStream;
+    var isReadable = (s) => !!s && typeof s === "object" && s instanceof node_events_1.EventEmitter && typeof s.pipe === "function" && // node core Writable streams have a pipe() method, but it throws
+    s.pipe !== node_stream_1.default.Writable.prototype.pipe;
+    exports2.isReadable = isReadable;
+    var isWritable = (s) => !!s && typeof s === "object" && s instanceof node_events_1.EventEmitter && typeof s.write === "function" && typeof s.end === "function";
+    exports2.isWritable = isWritable;
+    var EOF = Symbol("EOF");
+    var MAYBE_EMIT_END = Symbol("maybeEmitEnd");
+    var EMITTED_END = Symbol("emittedEnd");
+    var EMITTING_END = Symbol("emittingEnd");
+    var EMITTED_ERROR = Symbol("emittedError");
+    var CLOSED = Symbol("closed");
+    var READ = Symbol("read");
+    var FLUSH = Symbol("flush");
+    var FLUSHCHUNK = Symbol("flushChunk");
+    var ENCODING = Symbol("encoding");
+    var DECODER = Symbol("decoder");
+    var FLOWING = Symbol("flowing");
+    var PAUSED = Symbol("paused");
+    var RESUME = Symbol("resume");
+    var BUFFER = Symbol("buffer");
+    var PIPES = Symbol("pipes");
+    var BUFFERLENGTH = Symbol("bufferLength");
+    var BUFFERPUSH = Symbol("bufferPush");
+    var BUFFERSHIFT = Symbol("bufferShift");
+    var OBJECTMODE = Symbol("objectMode");
+    var DESTROYED = Symbol("destroyed");
+    var ERROR = Symbol("error");
+    var EMITDATA = Symbol("emitData");
+    var EMITEND = Symbol("emitEnd");
+    var EMITEND2 = Symbol("emitEnd2");
+    var ASYNC = Symbol("async");
+    var ABORT = Symbol("abort");
+    var ABORTED = Symbol("aborted");
+    var SIGNAL = Symbol("signal");
+    var DATALISTENERS = Symbol("dataListeners");
+    var DISCARDED = Symbol("discarded");
+    var defer = (fn) => Promise.resolve().then(fn);
+    var nodefer = (fn) => fn();
+    var isEndish = (ev) => ev === "end" || ev === "finish" || ev === "prefinish";
+    var isArrayBufferLike = (b) => b instanceof ArrayBuffer || !!b && typeof b === "object" && b.constructor && b.constructor.name === "ArrayBuffer" && b.byteLength >= 0;
+    var isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
+    var Pipe = class {
+      src;
+      dest;
+      opts;
+      ondrain;
+      constructor(src, dest, opts) {
+        this.src = src;
+        this.dest = dest;
+        this.opts = opts;
+        this.ondrain = () => src[RESUME]();
+        this.dest.on("drain", this.ondrain);
       }
-      parse(pattern) {
-        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-        const options = this.options;
-        if (pattern === "**")
-          return exports2.GLOBSTAR;
-        if (pattern === "")
-          return "";
-        let m;
-        let fastTest = null;
-        if (m = pattern.match(starRE)) {
-          fastTest = options.dot ? starTestDot : starTest;
-        } else if (m = pattern.match(starDotExtRE)) {
-          fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
-        } else if (m = pattern.match(qmarksRE)) {
-          fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
-        } else if (m = pattern.match(starDotStarRE)) {
-          fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
-        } else if (m = pattern.match(dotStarRE)) {
-          fastTest = dotStarTest;
+      unpipe() {
+        this.dest.removeListener("drain", this.ondrain);
+      }
+      // only here for the prototype
+      /* c8 ignore start */
+      proxyErrors(_er) {
+      }
+      /* c8 ignore stop */
+      end() {
+        this.unpipe();
+        if (this.opts.end)
+          this.dest.end();
+      }
+    };
+    var PipeProxyErrors = class extends Pipe {
+      unpipe() {
+        this.src.removeListener("error", this.proxyErrors);
+        super.unpipe();
+      }
+      constructor(src, dest, opts) {
+        super(src, dest, opts);
+        this.proxyErrors = (er) => dest.emit("error", er);
+        src.on("error", this.proxyErrors);
+      }
+    };
+    var isObjectModeOptions = (o) => !!o.objectMode;
+    var isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== "buffer";
+    var Minipass = class extends node_events_1.EventEmitter {
+      [FLOWING] = false;
+      [PAUSED] = false;
+      [PIPES] = [];
+      [BUFFER] = [];
+      [OBJECTMODE];
+      [ENCODING];
+      [ASYNC];
+      [DECODER];
+      [EOF] = false;
+      [EMITTED_END] = false;
+      [EMITTING_END] = false;
+      [CLOSED] = false;
+      [EMITTED_ERROR] = null;
+      [BUFFERLENGTH] = 0;
+      [DESTROYED] = false;
+      [SIGNAL];
+      [ABORTED] = false;
+      [DATALISTENERS] = 0;
+      [DISCARDED] = false;
+      /**
+       * true if the stream can be written
+       */
+      writable = true;
+      /**
+       * true if the stream can be read
+       */
+      readable = true;
+      /**
+       * If `RType` is Buffer, then options do not need to be provided.
+       * Otherwise, an options object must be provided to specify either
+       * {@link Minipass.SharedOptions.objectMode} or
+       * {@link Minipass.SharedOptions.encoding}, as appropriate.
+       */
+      constructor(...args) {
+        const options = args[0] || {};
+        super();
+        if (options.objectMode && typeof options.encoding === "string") {
+          throw new TypeError("Encoding and objectMode may not be used together");
         }
-        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
-        if (fastTest && typeof re === "object") {
-          Reflect.defineProperty(re, "test", { value: fastTest });
+        if (isObjectModeOptions(options)) {
+          this[OBJECTMODE] = true;
+          this[ENCODING] = null;
+        } else if (isEncodingOptions(options)) {
+          this[ENCODING] = options.encoding;
+          this[OBJECTMODE] = false;
+        } else {
+          this[OBJECTMODE] = false;
+          this[ENCODING] = null;
         }
-        return re;
-      }
-      makeRe() {
-        if (this.regexp || this.regexp === false)
-          return this.regexp;
-        const set2 = this.set;
-        if (!set2.length) {
-          this.regexp = false;
-          return this.regexp;
+        this[ASYNC] = !!options.async;
+        this[DECODER] = this[ENCODING] ? new node_string_decoder_1.StringDecoder(this[ENCODING]) : null;
+        if (options && options.debugExposeBuffer === true) {
+          Object.defineProperty(this, "buffer", { get: () => this[BUFFER] });
         }
-        const options = this.options;
-        const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
-        const flags = new Set(options.nocase ? ["i"] : []);
-        let re = set2.map((pattern) => {
-          const pp = pattern.map((p) => {
-            if (p instanceof RegExp) {
-              for (const f of p.flags.split(""))
-                flags.add(f);
-            }
-            return typeof p === "string" ? regExpEscape(p) : p === exports2.GLOBSTAR ? exports2.GLOBSTAR : p._src;
-          });
-          pp.forEach((p, i) => {
-            const next = pp[i + 1];
-            const prev = pp[i - 1];
-            if (p !== exports2.GLOBSTAR || prev === exports2.GLOBSTAR) {
-              return;
-            }
-            if (prev === void 0) {
-              if (next !== void 0 && next !== exports2.GLOBSTAR) {
-                pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
-              } else {
-                pp[i] = twoStar;
-              }
-            } else if (next === void 0) {
-              pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
-            } else if (next !== exports2.GLOBSTAR) {
-              pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
-              pp[i + 1] = exports2.GLOBSTAR;
-            }
-          });
-          return pp.filter((p) => p !== exports2.GLOBSTAR).join("/");
-        }).join("|");
-        const [open, close] = set2.length > 1 ? ["(?:", ")"] : ["", ""];
-        re = "^" + open + re + close + "$";
-        if (this.negate)
-          re = "^(?!" + re + ").+$";
-        try {
-          this.regexp = new RegExp(re, [...flags].join(""));
-        } catch (ex) {
-          this.regexp = false;
+        if (options && options.debugExposePipes === true) {
+          Object.defineProperty(this, "pipes", { get: () => this[PIPES] });
+        }
+        const { signal } = options;
+        if (signal) {
+          this[SIGNAL] = signal;
+          if (signal.aborted) {
+            this[ABORT]();
+          } else {
+            signal.addEventListener("abort", () => this[ABORT]());
+          }
         }
-        return this.regexp;
       }
-      slashSplit(p) {
-        if (this.preserveMultipleSlashes) {
-          return p.split("/");
-        } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
-          return ["", ...p.split(/\/+/)];
-        } else {
-          return p.split(/\/+/);
-        }
+      /**
+       * The amount of data stored in the buffer waiting to be read.
+       *
+       * For Buffer strings, this will be the total byte length.
+       * For string encoding streams, this will be the string character length,
+       * according to JavaScript's `string.length` logic.
+       * For objectMode streams, this is a count of the items waiting to be
+       * emitted.
+       */
+      get bufferLength() {
+        return this[BUFFERLENGTH];
       }
-      match(f, partial = this.partial) {
-        this.debug("match", f, this.pattern);
-        if (this.comment) {
+      /**
+       * The `BufferEncoding` currently in use, or `null`
+       */
+      get encoding() {
+        return this[ENCODING];
+      }
+      /**
+       * @deprecated - This is a read only property
+       */
+      set encoding(_enc) {
+        throw new Error("Encoding must be set at instantiation time");
+      }
+      /**
+       * @deprecated - Encoding may only be set at instantiation time
+       */
+      setEncoding(_enc) {
+        throw new Error("Encoding must be set at instantiation time");
+      }
+      /**
+       * True if this is an objectMode stream
+       */
+      get objectMode() {
+        return this[OBJECTMODE];
+      }
+      /**
+       * @deprecated - This is a read-only property
+       */
+      set objectMode(_om) {
+        throw new Error("objectMode must be set at instantiation time");
+      }
+      /**
+       * true if this is an async stream
+       */
+      get ["async"]() {
+        return this[ASYNC];
+      }
+      /**
+       * Set to true to make this stream async.
+       *
+       * Once set, it cannot be unset, as this would potentially cause incorrect
+       * behavior.  Ie, a sync stream can be made async, but an async stream
+       * cannot be safely made sync.
+       */
+      set ["async"](a) {
+        this[ASYNC] = this[ASYNC] || !!a;
+      }
+      // drop everything and get out of the flow completely
+      [ABORT]() {
+        this[ABORTED] = true;
+        this.emit("abort", this[SIGNAL]?.reason);
+        this.destroy(this[SIGNAL]?.reason);
+      }
+      /**
+       * True if the stream has been aborted.
+       */
+      get aborted() {
+        return this[ABORTED];
+      }
+      /**
+       * No-op setter. Stream aborted status is set via the AbortSignal provided
+       * in the constructor options.
+       */
+      set aborted(_2) {
+      }
+      write(chunk, encoding, cb) {
+        if (this[ABORTED])
           return false;
-        }
-        if (this.empty) {
-          return f === "";
-        }
-        if (f === "/" && partial) {
+        if (this[EOF])
+          throw new Error("write after end");
+        if (this[DESTROYED]) {
+          this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" }));
           return true;
         }
-        const options = this.options;
-        if (this.isWindows) {
-          f = f.split("\\").join("/");
+        if (typeof encoding === "function") {
+          cb = encoding;
+          encoding = "utf8";
         }
-        const ff = this.slashSplit(f);
-        this.debug(this.pattern, "split", ff);
-        const set2 = this.set;
-        this.debug(this.pattern, "set", set2);
-        let filename = ff[ff.length - 1];
-        if (!filename) {
-          for (let i = ff.length - 2; !filename && i >= 0; i--) {
-            filename = ff[i];
+        if (!encoding)
+          encoding = "utf8";
+        const fn = this[ASYNC] ? defer : nodefer;
+        if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
+          if (isArrayBufferView(chunk)) {
+            chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
+          } else if (isArrayBufferLike(chunk)) {
+            chunk = Buffer.from(chunk);
+          } else if (typeof chunk !== "string") {
+            throw new Error("Non-contiguous data written to non-objectMode stream");
           }
         }
-        for (let i = 0; i < set2.length; i++) {
-          const pattern = set2[i];
-          let file = ff;
-          if (options.matchBase && pattern.length === 1) {
-            file = [filename];
-          }
-          const hit = this.matchOne(file, pattern, partial);
-          if (hit) {
-            if (options.flipNegate) {
-              return true;
-            }
-            return !this.negate;
-          }
+        if (this[OBJECTMODE]) {
+          if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
+            this[FLUSH](true);
+          if (this[FLOWING])
+            this.emit("data", chunk);
+          else
+            this[BUFFERPUSH](chunk);
+          if (this[BUFFERLENGTH] !== 0)
+            this.emit("readable");
+          if (cb)
+            fn(cb);
+          return this[FLOWING];
         }
-        if (options.flipNegate) {
-          return false;
+        if (!chunk.length) {
+          if (this[BUFFERLENGTH] !== 0)
+            this.emit("readable");
+          if (cb)
+            fn(cb);
+          return this[FLOWING];
         }
-        return this.negate;
-      }
-      static defaults(def) {
-        return exports2.minimatch.defaults(def).Minimatch;
+        if (typeof chunk === "string" && // unless it is a string already ready for us to use
+        !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
+          chunk = Buffer.from(chunk, encoding);
+        }
+        if (Buffer.isBuffer(chunk) && this[ENCODING]) {
+          chunk = this[DECODER].write(chunk);
+        }
+        if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
+          this[FLUSH](true);
+        if (this[FLOWING])
+          this.emit("data", chunk);
+        else
+          this[BUFFERPUSH](chunk);
+        if (this[BUFFERLENGTH] !== 0)
+          this.emit("readable");
+        if (cb)
+          fn(cb);
+        return this[FLOWING];
       }
-    };
-    exports2.Minimatch = Minimatch;
-    var ast_js_2 = require_ast();
-    Object.defineProperty(exports2, "AST", { enumerable: true, get: function() {
-      return ast_js_2.AST;
-    } });
-    var escape_js_2 = require_escape();
-    Object.defineProperty(exports2, "escape", { enumerable: true, get: function() {
-      return escape_js_2.escape;
-    } });
-    var unescape_js_2 = require_unescape();
-    Object.defineProperty(exports2, "unescape", { enumerable: true, get: function() {
-      return unescape_js_2.unescape;
-    } });
-    exports2.minimatch.AST = ast_js_1.AST;
-    exports2.minimatch.Minimatch = Minimatch;
-    exports2.minimatch.escape = escape_js_1.escape;
-    exports2.minimatch.unescape = unescape_js_1.unescape;
-  }
-});
-
-// node_modules/archiver-utils/node_modules/lru-cache/dist/commonjs/index.js
-var require_commonjs14 = __commonJS({
-  "node_modules/archiver-utils/node_modules/lru-cache/dist/commonjs/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.LRUCache = void 0;
-    var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
-    var warned = /* @__PURE__ */ new Set();
-    var PROCESS = typeof process === "object" && !!process ? process : {};
-    var emitWarning = (msg, type2, code, fn) => {
-      typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type2, code, fn) : console.error(`[${code}] ${type2}: ${msg}`);
-    };
-    var AC = globalThis.AbortController;
-    var AS = globalThis.AbortSignal;
-    if (typeof AC === "undefined") {
-      AS = class AbortSignal {
-        onabort;
-        _onabort = [];
-        reason;
-        aborted = false;
-        addEventListener(_2, fn) {
-          this._onabort.push(fn);
+      /**
+       * Low-level explicit read method.
+       *
+       * In objectMode, the argument is ignored, and one item is returned if
+       * available.
+       *
+       * `n` is the number of bytes (or in the case of encoding streams,
+       * characters) to consume. If `n` is not provided, then the entire buffer
+       * is returned, or `null` is returned if no data is available.
+       *
+       * If `n` is greater that the amount of data in the internal buffer,
+       * then `null` is returned.
+       */
+      read(n) {
+        if (this[DESTROYED])
+          return null;
+        this[DISCARDED] = false;
+        if (this[BUFFERLENGTH] === 0 || n === 0 || n && n > this[BUFFERLENGTH]) {
+          this[MAYBE_EMIT_END]();
+          return null;
         }
-      };
-      AC = class AbortController {
-        constructor() {
-          warnACPolyfill();
+        if (this[OBJECTMODE])
+          n = null;
+        if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
+          this[BUFFER] = [
+            this[ENCODING] ? this[BUFFER].join("") : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])
+          ];
         }
-        signal = new AS();
-        abort(reason) {
-          if (this.signal.aborted)
-            return;
-          this.signal.reason = reason;
-          this.signal.aborted = true;
-          for (const fn of this.signal._onabort) {
-            fn(reason);
+        const ret = this[READ](n || null, this[BUFFER][0]);
+        this[MAYBE_EMIT_END]();
+        return ret;
+      }
+      [READ](n, chunk) {
+        if (this[OBJECTMODE])
+          this[BUFFERSHIFT]();
+        else {
+          const c = chunk;
+          if (n === c.length || n === null)
+            this[BUFFERSHIFT]();
+          else if (typeof c === "string") {
+            this[BUFFER][0] = c.slice(n);
+            chunk = c.slice(0, n);
+            this[BUFFERLENGTH] -= n;
+          } else {
+            this[BUFFER][0] = c.subarray(n);
+            chunk = c.subarray(0, n);
+            this[BUFFERLENGTH] -= n;
           }
-          this.signal.onabort?.(reason);
         }
-      };
-      let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
-      const warnACPolyfill = () => {
-        if (!printACPolyfillWarning)
+        this.emit("data", chunk);
+        if (!this[BUFFER].length && !this[EOF])
+          this.emit("drain");
+        return chunk;
+      }
+      end(chunk, encoding, cb) {
+        if (typeof chunk === "function") {
+          cb = chunk;
+          chunk = void 0;
+        }
+        if (typeof encoding === "function") {
+          cb = encoding;
+          encoding = "utf8";
+        }
+        if (chunk !== void 0)
+          this.write(chunk, encoding);
+        if (cb)
+          this.once("end", cb);
+        this[EOF] = true;
+        this.writable = false;
+        if (this[FLOWING] || !this[PAUSED])
+          this[MAYBE_EMIT_END]();
+        return this;
+      }
+      // don't let the internal resume be overwritten
+      [RESUME]() {
+        if (this[DESTROYED])
           return;
-        printACPolyfillWarning = false;
-        emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
-      };
-    }
-    var shouldWarn = (code) => !warned.has(code);
-    var TYPE = Symbol("type");
-    var isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
-    var getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;
-    var ZeroArray = class extends Array {
-      constructor(size) {
-        super(size);
-        this.fill(0);
+        if (!this[DATALISTENERS] && !this[PIPES].length) {
+          this[DISCARDED] = true;
+        }
+        this[PAUSED] = false;
+        this[FLOWING] = true;
+        this.emit("resume");
+        if (this[BUFFER].length)
+          this[FLUSH]();
+        else if (this[EOF])
+          this[MAYBE_EMIT_END]();
+        else
+          this.emit("drain");
       }
-    };
-    var Stack = class _Stack {
-      heap;
-      length;
-      // private constructor
-      static #constructing = false;
-      static create(max) {
-        const HeapCls = getUintArray(max);
-        if (!HeapCls)
-          return [];
-        _Stack.#constructing = true;
-        const s = new _Stack(max, HeapCls);
-        _Stack.#constructing = false;
-        return s;
+      /**
+       * Resume the stream if it is currently in a paused state
+       *
+       * If called when there are no pipe destinations or `data` event listeners,
+       * this will place the stream in a "discarded" state, where all data will
+       * be thrown away. The discarded state is removed if a pipe destination or
+       * data handler is added, if pause() is called, or if any synchronous or
+       * asynchronous iteration is started.
+       */
+      resume() {
+        return this[RESUME]();
       }
-      constructor(max, HeapCls) {
-        if (!_Stack.#constructing) {
-          throw new TypeError("instantiate Stack using Stack.create(n)");
+      /**
+       * Pause the stream
+       */
+      pause() {
+        this[FLOWING] = false;
+        this[PAUSED] = true;
+        this[DISCARDED] = false;
+      }
+      /**
+       * true if the stream has been forcibly destroyed
+       */
+      get destroyed() {
+        return this[DESTROYED];
+      }
+      /**
+       * true if the stream is currently in a flowing state, meaning that
+       * any writes will be immediately emitted.
+       */
+      get flowing() {
+        return this[FLOWING];
+      }
+      /**
+       * true if the stream is currently in a paused state
+       */
+      get paused() {
+        return this[PAUSED];
+      }
+      [BUFFERPUSH](chunk) {
+        if (this[OBJECTMODE])
+          this[BUFFERLENGTH] += 1;
+        else
+          this[BUFFERLENGTH] += chunk.length;
+        this[BUFFER].push(chunk);
+      }
+      [BUFFERSHIFT]() {
+        if (this[OBJECTMODE])
+          this[BUFFERLENGTH] -= 1;
+        else
+          this[BUFFERLENGTH] -= this[BUFFER][0].length;
+        return this[BUFFER].shift();
+      }
+      [FLUSH](noDrain = false) {
+        do {
+        } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length);
+        if (!noDrain && !this[BUFFER].length && !this[EOF])
+          this.emit("drain");
+      }
+      [FLUSHCHUNK](chunk) {
+        this.emit("data", chunk);
+        return this[FLOWING];
+      }
+      /**
+       * Pipe all data emitted by this stream into the destination provided.
+       *
+       * Triggers the flow of data.
+       */
+      pipe(dest, opts) {
+        if (this[DESTROYED])
+          return dest;
+        this[DISCARDED] = false;
+        const ended = this[EMITTED_END];
+        opts = opts || {};
+        if (dest === proc.stdout || dest === proc.stderr)
+          opts.end = false;
+        else
+          opts.end = opts.end !== false;
+        opts.proxyErrors = !!opts.proxyErrors;
+        if (ended) {
+          if (opts.end)
+            dest.end();
+        } else {
+          this[PIPES].push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts));
+          if (this[ASYNC])
+            defer(() => this[RESUME]());
+          else
+            this[RESUME]();
         }
-        this.heap = new HeapCls(max);
-        this.length = 0;
+        return dest;
       }
-      push(n) {
-        this.heap[this.length++] = n;
+      /**
+       * Fully unhook a piped destination stream.
+       *
+       * If the destination stream was the only consumer of this stream (ie,
+       * there are no other piped destinations or `'data'` event listeners)
+       * then the flow of data will stop until there is another consumer or
+       * {@link Minipass#resume} is explicitly called.
+       */
+      unpipe(dest) {
+        const p = this[PIPES].find((p2) => p2.dest === dest);
+        if (p) {
+          if (this[PIPES].length === 1) {
+            if (this[FLOWING] && this[DATALISTENERS] === 0) {
+              this[FLOWING] = false;
+            }
+            this[PIPES] = [];
+          } else
+            this[PIPES].splice(this[PIPES].indexOf(p), 1);
+          p.unpipe();
+        }
       }
-      pop() {
-        return this.heap[--this.length];
+      /**
+       * Alias for {@link Minipass#on}
+       */
+      addListener(ev, handler) {
+        return this.on(ev, handler);
+      }
+      /**
+       * Mostly identical to `EventEmitter.on`, with the following
+       * behavior differences to prevent data loss and unnecessary hangs:
+       *
+       * - Adding a 'data' event handler will trigger the flow of data
+       *
+       * - Adding a 'readable' event handler when there is data waiting to be read
+       *   will cause 'readable' to be emitted immediately.
+       *
+       * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
+       *   already passed will cause the event to be emitted immediately and all
+       *   handlers removed.
+       *
+       * - Adding an 'error' event handler after an error has been emitted will
+       *   cause the event to be re-emitted immediately with the error previously
+       *   raised.
+       */
+      on(ev, handler) {
+        const ret = super.on(ev, handler);
+        if (ev === "data") {
+          this[DISCARDED] = false;
+          this[DATALISTENERS]++;
+          if (!this[PIPES].length && !this[FLOWING]) {
+            this[RESUME]();
+          }
+        } else if (ev === "readable" && this[BUFFERLENGTH] !== 0) {
+          super.emit("readable");
+        } else if (isEndish(ev) && this[EMITTED_END]) {
+          super.emit(ev);
+          this.removeAllListeners(ev);
+        } else if (ev === "error" && this[EMITTED_ERROR]) {
+          const h = handler;
+          if (this[ASYNC])
+            defer(() => h.call(this, this[EMITTED_ERROR]));
+          else
+            h.call(this, this[EMITTED_ERROR]);
+        }
+        return ret;
       }
-    };
-    var LRUCache = class _LRUCache {
-      // options that cannot be changed without disaster
-      #max;
-      #maxSize;
-      #dispose;
-      #disposeAfter;
-      #fetchMethod;
-      #memoMethod;
-      /**
-       * {@link LRUCache.OptionsBase.ttl}
-       */
-      ttl;
-      /**
-       * {@link LRUCache.OptionsBase.ttlResolution}
-       */
-      ttlResolution;
       /**
-       * {@link LRUCache.OptionsBase.ttlAutopurge}
+       * Alias for {@link Minipass#off}
        */
-      ttlAutopurge;
+      removeListener(ev, handler) {
+        return this.off(ev, handler);
+      }
       /**
-       * {@link LRUCache.OptionsBase.updateAgeOnGet}
+       * Mostly identical to `EventEmitter.off`
+       *
+       * If a 'data' event handler is removed, and it was the last consumer
+       * (ie, there are no pipe destinations or other 'data' event listeners),
+       * then the flow of data will stop until there is another consumer or
+       * {@link Minipass#resume} is explicitly called.
        */
-      updateAgeOnGet;
+      off(ev, handler) {
+        const ret = super.off(ev, handler);
+        if (ev === "data") {
+          this[DATALISTENERS] = this.listeners("data").length;
+          if (this[DATALISTENERS] === 0 && !this[DISCARDED] && !this[PIPES].length) {
+            this[FLOWING] = false;
+          }
+        }
+        return ret;
+      }
       /**
-       * {@link LRUCache.OptionsBase.updateAgeOnHas}
+       * Mostly identical to `EventEmitter.removeAllListeners`
+       *
+       * If all 'data' event handlers are removed, and they were the last consumer
+       * (ie, there are no pipe destinations), then the flow of data will stop
+       * until there is another consumer or {@link Minipass#resume} is explicitly
+       * called.
        */
-      updateAgeOnHas;
+      removeAllListeners(ev) {
+        const ret = super.removeAllListeners(ev);
+        if (ev === "data" || ev === void 0) {
+          this[DATALISTENERS] = 0;
+          if (!this[DISCARDED] && !this[PIPES].length) {
+            this[FLOWING] = false;
+          }
+        }
+        return ret;
+      }
       /**
-       * {@link LRUCache.OptionsBase.allowStale}
+       * true if the 'end' event has been emitted
        */
-      allowStale;
+      get emittedEnd() {
+        return this[EMITTED_END];
+      }
+      [MAYBE_EMIT_END]() {
+        if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF]) {
+          this[EMITTING_END] = true;
+          this.emit("end");
+          this.emit("prefinish");
+          this.emit("finish");
+          if (this[CLOSED])
+            this.emit("close");
+          this[EMITTING_END] = false;
+        }
+      }
       /**
-       * {@link LRUCache.OptionsBase.noDisposeOnSet}
+       * Mostly identical to `EventEmitter.emit`, with the following
+       * behavior differences to prevent data loss and unnecessary hangs:
+       *
+       * If the stream has been destroyed, and the event is something other
+       * than 'close' or 'error', then `false` is returned and no handlers
+       * are called.
+       *
+       * If the event is 'end', and has already been emitted, then the event
+       * is ignored. If the stream is in a paused or non-flowing state, then
+       * the event will be deferred until data flow resumes. If the stream is
+       * async, then handlers will be called on the next tick rather than
+       * immediately.
+       *
+       * If the event is 'close', and 'end' has not yet been emitted, then
+       * the event will be deferred until after 'end' is emitted.
+       *
+       * If the event is 'error', and an AbortSignal was provided for the stream,
+       * and there are no listeners, then the event is ignored, matching the
+       * behavior of node core streams in the presense of an AbortSignal.
+       *
+       * If the event is 'finish' or 'prefinish', then all listeners will be
+       * removed after emitting the event, to prevent double-firing.
        */
-      noDisposeOnSet;
+      emit(ev, ...args) {
+        const data = args[0];
+        if (ev !== "error" && ev !== "close" && ev !== DESTROYED && this[DESTROYED]) {
+          return false;
+        } else if (ev === "data") {
+          return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? (defer(() => this[EMITDATA](data)), true) : this[EMITDATA](data);
+        } else if (ev === "end") {
+          return this[EMITEND]();
+        } else if (ev === "close") {
+          this[CLOSED] = true;
+          if (!this[EMITTED_END] && !this[DESTROYED])
+            return false;
+          const ret2 = super.emit("close");
+          this.removeAllListeners("close");
+          return ret2;
+        } else if (ev === "error") {
+          this[EMITTED_ERROR] = data;
+          super.emit(ERROR, data);
+          const ret2 = !this[SIGNAL] || this.listeners("error").length ? super.emit("error", data) : false;
+          this[MAYBE_EMIT_END]();
+          return ret2;
+        } else if (ev === "resume") {
+          const ret2 = super.emit("resume");
+          this[MAYBE_EMIT_END]();
+          return ret2;
+        } else if (ev === "finish" || ev === "prefinish") {
+          const ret2 = super.emit(ev);
+          this.removeAllListeners(ev);
+          return ret2;
+        }
+        const ret = super.emit(ev, ...args);
+        this[MAYBE_EMIT_END]();
+        return ret;
+      }
+      [EMITDATA](data) {
+        for (const p of this[PIPES]) {
+          if (p.dest.write(data) === false)
+            this.pause();
+        }
+        const ret = this[DISCARDED] ? false : super.emit("data", data);
+        this[MAYBE_EMIT_END]();
+        return ret;
+      }
+      [EMITEND]() {
+        if (this[EMITTED_END])
+          return false;
+        this[EMITTED_END] = true;
+        this.readable = false;
+        return this[ASYNC] ? (defer(() => this[EMITEND2]()), true) : this[EMITEND2]();
+      }
+      [EMITEND2]() {
+        if (this[DECODER]) {
+          const data = this[DECODER].end();
+          if (data) {
+            for (const p of this[PIPES]) {
+              p.dest.write(data);
+            }
+            if (!this[DISCARDED])
+              super.emit("data", data);
+          }
+        }
+        for (const p of this[PIPES]) {
+          p.end();
+        }
+        const ret = super.emit("end");
+        this.removeAllListeners("end");
+        return ret;
+      }
       /**
-       * {@link LRUCache.OptionsBase.noUpdateTTL}
+       * Return a Promise that resolves to an array of all emitted data once
+       * the stream ends.
        */
-      noUpdateTTL;
+      async collect() {
+        const buf = Object.assign([], {
+          dataLength: 0
+        });
+        if (!this[OBJECTMODE])
+          buf.dataLength = 0;
+        const p = this.promise();
+        this.on("data", (c) => {
+          buf.push(c);
+          if (!this[OBJECTMODE])
+            buf.dataLength += c.length;
+        });
+        await p;
+        return buf;
+      }
       /**
-       * {@link LRUCache.OptionsBase.maxEntrySize}
+       * Return a Promise that resolves to the concatenation of all emitted data
+       * once the stream ends.
+       *
+       * Not allowed on objectMode streams.
        */
-      maxEntrySize;
+      async concat() {
+        if (this[OBJECTMODE]) {
+          throw new Error("cannot concat in objectMode");
+        }
+        const buf = await this.collect();
+        return this[ENCODING] ? buf.join("") : Buffer.concat(buf, buf.dataLength);
+      }
       /**
-       * {@link LRUCache.OptionsBase.sizeCalculation}
+       * Return a void Promise that resolves once the stream ends.
        */
-      sizeCalculation;
+      async promise() {
+        return new Promise((resolve2, reject) => {
+          this.on(DESTROYED, () => reject(new Error("stream destroyed")));
+          this.on("error", (er) => reject(er));
+          this.on("end", () => resolve2());
+        });
+      }
       /**
-       * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
+       * Asynchronous `for await of` iteration.
+       *
+       * This will continue emitting all chunks until the stream terminates.
        */
-      noDeleteOnFetchRejection;
+      [Symbol.asyncIterator]() {
+        this[DISCARDED] = false;
+        let stopped = false;
+        const stop = async () => {
+          this.pause();
+          stopped = true;
+          return { value: void 0, done: true };
+        };
+        const next = () => {
+          if (stopped)
+            return stop();
+          const res = this.read();
+          if (res !== null)
+            return Promise.resolve({ done: false, value: res });
+          if (this[EOF])
+            return stop();
+          let resolve2;
+          let reject;
+          const onerr = (er) => {
+            this.off("data", ondata);
+            this.off("end", onend);
+            this.off(DESTROYED, ondestroy);
+            stop();
+            reject(er);
+          };
+          const ondata = (value) => {
+            this.off("error", onerr);
+            this.off("end", onend);
+            this.off(DESTROYED, ondestroy);
+            this.pause();
+            resolve2({ value, done: !!this[EOF] });
+          };
+          const onend = () => {
+            this.off("error", onerr);
+            this.off("data", ondata);
+            this.off(DESTROYED, ondestroy);
+            stop();
+            resolve2({ done: true, value: void 0 });
+          };
+          const ondestroy = () => onerr(new Error("stream destroyed"));
+          return new Promise((res2, rej) => {
+            reject = rej;
+            resolve2 = res2;
+            this.once(DESTROYED, ondestroy);
+            this.once("error", onerr);
+            this.once("end", onend);
+            this.once("data", ondata);
+          });
+        };
+        return {
+          next,
+          throw: stop,
+          return: stop,
+          [Symbol.asyncIterator]() {
+            return this;
+          }
+        };
+      }
       /**
-       * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
+       * Synchronous `for of` iteration.
+       *
+       * The iteration will terminate when the internal buffer runs out, even
+       * if the stream has not yet terminated.
        */
-      noDeleteOnStaleGet;
+      [Symbol.iterator]() {
+        this[DISCARDED] = false;
+        let stopped = false;
+        const stop = () => {
+          this.pause();
+          this.off(ERROR, stop);
+          this.off(DESTROYED, stop);
+          this.off("end", stop);
+          stopped = true;
+          return { done: true, value: void 0 };
+        };
+        const next = () => {
+          if (stopped)
+            return stop();
+          const value = this.read();
+          return value === null ? stop() : { done: false, value };
+        };
+        this.once("end", stop);
+        this.once(ERROR, stop);
+        this.once(DESTROYED, stop);
+        return {
+          next,
+          throw: stop,
+          return: stop,
+          [Symbol.iterator]() {
+            return this;
+          }
+        };
+      }
       /**
-       * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
+       * Destroy a stream, preventing it from being used for any further purpose.
+       *
+       * If the stream has a `close()` method, then it will be called on
+       * destruction.
+       *
+       * After destruction, any attempt to write data, read data, or emit most
+       * events will be ignored.
+       *
+       * If an error argument is provided, then it will be emitted in an
+       * 'error' event.
        */
-      allowStaleOnFetchAbort;
+      destroy(er) {
+        if (this[DESTROYED]) {
+          if (er)
+            this.emit("error", er);
+          else
+            this.emit(DESTROYED);
+          return this;
+        }
+        this[DESTROYED] = true;
+        this[DISCARDED] = true;
+        this[BUFFER].length = 0;
+        this[BUFFERLENGTH] = 0;
+        const wc = this;
+        if (typeof wc.close === "function" && !this[CLOSED])
+          wc.close();
+        if (er)
+          this.emit("error", er);
+        else
+          this.emit(DESTROYED);
+        return this;
+      }
       /**
-       * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
+       * Alias for {@link isStream}
+       *
+       * Former export location, maintained for backwards compatibility.
+       *
+       * @deprecated
        */
-      allowStaleOnFetchRejection;
+      static get isStream() {
+        return exports2.isStream;
+      }
+    };
+    exports2.Minipass = Minipass;
+  }
+});
+
+// node_modules/archiver-utils/node_modules/path-scurry/dist/commonjs/index.js
+var require_commonjs16 = __commonJS({
+  "node_modules/archiver-utils/node_modules/path-scurry/dist/commonjs/index.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.PathScurry = exports2.Path = exports2.PathScurryDarwin = exports2.PathScurryPosix = exports2.PathScurryWin32 = exports2.PathScurryBase = exports2.PathPosix = exports2.PathWin32 = exports2.PathBase = exports2.ChildrenCache = exports2.ResolveCache = void 0;
+    var lru_cache_1 = require_commonjs14();
+    var node_path_1 = require("node:path");
+    var node_url_1 = require("node:url");
+    var fs_1 = require("fs");
+    var actualFS = __importStar4(require("node:fs"));
+    var realpathSync = fs_1.realpathSync.native;
+    var promises_1 = require("node:fs/promises");
+    var minipass_1 = require_commonjs15();
+    var defaultFS = {
+      lstatSync: fs_1.lstatSync,
+      readdir: fs_1.readdir,
+      readdirSync: fs_1.readdirSync,
+      readlinkSync: fs_1.readlinkSync,
+      realpathSync,
+      promises: {
+        lstat: promises_1.lstat,
+        readdir: promises_1.readdir,
+        readlink: promises_1.readlink,
+        realpath: promises_1.realpath
+      }
+    };
+    var fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ? defaultFS : {
+      ...defaultFS,
+      ...fsOption,
+      promises: {
+        ...defaultFS.promises,
+        ...fsOption.promises || {}
+      }
+    };
+    var uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
+    var uncToDrive = (rootPath) => rootPath.replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
+    var eitherSep = /[\\\/]/;
+    var UNKNOWN = 0;
+    var IFIFO = 1;
+    var IFCHR = 2;
+    var IFDIR = 4;
+    var IFBLK = 6;
+    var IFREG = 8;
+    var IFLNK = 10;
+    var IFSOCK = 12;
+    var IFMT = 15;
+    var IFMT_UNKNOWN = ~IFMT;
+    var READDIR_CALLED = 16;
+    var LSTAT_CALLED = 32;
+    var ENOTDIR = 64;
+    var ENOENT = 128;
+    var ENOREADLINK = 256;
+    var ENOREALPATH = 512;
+    var ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
+    var TYPEMASK = 1023;
+    var entToType = (s) => s.isFile() ? IFREG : s.isDirectory() ? IFDIR : s.isSymbolicLink() ? IFLNK : s.isCharacterDevice() ? IFCHR : s.isBlockDevice() ? IFBLK : s.isSocket() ? IFSOCK : s.isFIFO() ? IFIFO : UNKNOWN;
+    var normalizeCache = /* @__PURE__ */ new Map();
+    var normalize2 = (s) => {
+      const c = normalizeCache.get(s);
+      if (c)
+        return c;
+      const n = s.normalize("NFKD");
+      normalizeCache.set(s, n);
+      return n;
+    };
+    var normalizeNocaseCache = /* @__PURE__ */ new Map();
+    var normalizeNocase = (s) => {
+      const c = normalizeNocaseCache.get(s);
+      if (c)
+        return c;
+      const n = normalize2(s.toLowerCase());
+      normalizeNocaseCache.set(s, n);
+      return n;
+    };
+    var ResolveCache = class extends lru_cache_1.LRUCache {
+      constructor() {
+        super({ max: 256 });
+      }
+    };
+    exports2.ResolveCache = ResolveCache;
+    var ChildrenCache = class extends lru_cache_1.LRUCache {
+      constructor(maxSize = 16 * 1024) {
+        super({
+          maxSize,
+          // parent + children
+          sizeCalculation: (a) => a.length + 1
+        });
+      }
+    };
+    exports2.ChildrenCache = ChildrenCache;
+    var setAsCwd = Symbol("PathScurry setAsCwd");
+    var PathBase = class {
       /**
-       * {@link LRUCache.OptionsBase.ignoreFetchAbort}
+       * the basename of this path
+       *
+       * **Important**: *always* test the path name against any test string
+       * usingthe {@link isNamed} method, and not by directly comparing this
+       * string. Otherwise, unicode path strings that the system sees as identical
+       * will not be properly treated as the same path, leading to incorrect
+       * behavior and possible security issues.
        */
-      ignoreFetchAbort;
-      // computed properties
-      #size;
-      #calculatedSize;
-      #keyMap;
-      #keyList;
-      #valList;
-      #next;
-      #prev;
-      #head;
-      #tail;
-      #free;
-      #disposed;
-      #sizes;
-      #starts;
-      #ttls;
-      #hasDispose;
-      #hasFetchMethod;
-      #hasDisposeAfter;
+      name;
       /**
-       * Do not call this method unless you need to inspect the
-       * inner workings of the cache.  If anything returned by this
-       * object is modified in any way, strange breakage may occur.
-       *
-       * These fields are private for a reason!
+       * the Path entry corresponding to the path root.
        *
        * @internal
        */
-      static unsafeExposeInternals(c) {
-        return {
-          // properties
-          starts: c.#starts,
-          ttls: c.#ttls,
-          sizes: c.#sizes,
-          keyMap: c.#keyMap,
-          keyList: c.#keyList,
-          valList: c.#valList,
-          next: c.#next,
-          prev: c.#prev,
-          get head() {
-            return c.#head;
-          },
-          get tail() {
-            return c.#tail;
-          },
-          free: c.#free,
-          // methods
-          isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
-          backgroundFetch: (k, index, options, context2) => c.#backgroundFetch(k, index, options, context2),
-          moveToTail: (index) => c.#moveToTail(index),
-          indexes: (options) => c.#indexes(options),
-          rindexes: (options) => c.#rindexes(options),
-          isStale: (index) => c.#isStale(index)
-        };
-      }
-      // Protected read-only members
+      root;
       /**
-       * {@link LRUCache.OptionsBase.max} (read-only)
+       * All roots found within the current PathScurry family
+       *
+       * @internal
        */
-      get max() {
-        return this.#max;
-      }
+      roots;
       /**
-       * {@link LRUCache.OptionsBase.maxSize} (read-only)
+       * a reference to the parent path, or undefined in the case of root entries
+       *
+       * @internal
        */
-      get maxSize() {
-        return this.#maxSize;
-      }
+      parent;
       /**
-       * The total computed size of items in the cache (read-only)
+       * boolean indicating whether paths are compared case-insensitively
+       * @internal
        */
-      get calculatedSize() {
-        return this.#calculatedSize;
-      }
+      nocase;
       /**
-       * The number of items stored in the cache (read-only)
+       * boolean indicating that this path is the current working directory
+       * of the PathScurry collection that contains it.
        */
+      isCWD = false;
+      // potential default fs override
+      #fs;
+      // Stats fields
+      #dev;
+      get dev() {
+        return this.#dev;
+      }
+      #mode;
+      get mode() {
+        return this.#mode;
+      }
+      #nlink;
+      get nlink() {
+        return this.#nlink;
+      }
+      #uid;
+      get uid() {
+        return this.#uid;
+      }
+      #gid;
+      get gid() {
+        return this.#gid;
+      }
+      #rdev;
+      get rdev() {
+        return this.#rdev;
+      }
+      #blksize;
+      get blksize() {
+        return this.#blksize;
+      }
+      #ino;
+      get ino() {
+        return this.#ino;
+      }
+      #size;
       get size() {
         return this.#size;
       }
-      /**
-       * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
-       */
-      get fetchMethod() {
-        return this.#fetchMethod;
+      #blocks;
+      get blocks() {
+        return this.#blocks;
       }
-      get memoMethod() {
-        return this.#memoMethod;
+      #atimeMs;
+      get atimeMs() {
+        return this.#atimeMs;
+      }
+      #mtimeMs;
+      get mtimeMs() {
+        return this.#mtimeMs;
+      }
+      #ctimeMs;
+      get ctimeMs() {
+        return this.#ctimeMs;
+      }
+      #birthtimeMs;
+      get birthtimeMs() {
+        return this.#birthtimeMs;
+      }
+      #atime;
+      get atime() {
+        return this.#atime;
+      }
+      #mtime;
+      get mtime() {
+        return this.#mtime;
+      }
+      #ctime;
+      get ctime() {
+        return this.#ctime;
+      }
+      #birthtime;
+      get birthtime() {
+        return this.#birthtime;
       }
+      #matchName;
+      #depth;
+      #fullpath;
+      #fullpathPosix;
+      #relative;
+      #relativePosix;
+      #type;
+      #children;
+      #linkTarget;
+      #realpath;
       /**
-       * {@link LRUCache.OptionsBase.dispose} (read-only)
+       * This property is for compatibility with the Dirent class as of
+       * Node v20, where Dirent['parentPath'] refers to the path of the
+       * directory that was passed to readdir. For root entries, it's the path
+       * to the entry itself.
        */
-      get dispose() {
-        return this.#dispose;
+      get parentPath() {
+        return (this.parent || this).fullpath();
       }
       /**
-       * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
+       * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
+       * this property refers to the *parent* path, not the path object itself.
        */
-      get disposeAfter() {
-        return this.#disposeAfter;
+      get path() {
+        return this.parentPath;
       }
-      constructor(options) {
-        const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options;
-        if (max !== 0 && !isPosInt(max)) {
-          throw new TypeError("max option must be a nonnegative integer");
-        }
-        const UintArray = max ? getUintArray(max) : Array;
-        if (!UintArray) {
-          throw new Error("invalid max value: " + max);
-        }
-        this.#max = max;
-        this.#maxSize = maxSize;
-        this.maxEntrySize = maxEntrySize || this.#maxSize;
-        this.sizeCalculation = sizeCalculation;
-        if (this.sizeCalculation) {
-          if (!this.#maxSize && !this.maxEntrySize) {
-            throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
-          }
-          if (typeof this.sizeCalculation !== "function") {
-            throw new TypeError("sizeCalculation set to non-function");
-          }
-        }
-        if (memoMethod !== void 0 && typeof memoMethod !== "function") {
-          throw new TypeError("memoMethod must be a function if defined");
-        }
-        this.#memoMethod = memoMethod;
-        if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
-          throw new TypeError("fetchMethod must be a function if specified");
-        }
-        this.#fetchMethod = fetchMethod;
-        this.#hasFetchMethod = !!fetchMethod;
-        this.#keyMap = /* @__PURE__ */ new Map();
-        this.#keyList = new Array(max).fill(void 0);
-        this.#valList = new Array(max).fill(void 0);
-        this.#next = new UintArray(max);
-        this.#prev = new UintArray(max);
-        this.#head = 0;
-        this.#tail = 0;
-        this.#free = Stack.create(max);
-        this.#size = 0;
-        this.#calculatedSize = 0;
-        if (typeof dispose === "function") {
-          this.#dispose = dispose;
-        }
-        if (typeof disposeAfter === "function") {
-          this.#disposeAfter = disposeAfter;
-          this.#disposed = [];
+      /**
+       * Do not create new Path objects directly.  They should always be accessed
+       * via the PathScurry class or other methods on the Path class.
+       *
+       * @internal
+       */
+      constructor(name, type2 = UNKNOWN, root, roots, nocase, children, opts) {
+        this.name = name;
+        this.#matchName = nocase ? normalizeNocase(name) : normalize2(name);
+        this.#type = type2 & TYPEMASK;
+        this.nocase = nocase;
+        this.roots = roots;
+        this.root = root || this;
+        this.#children = children;
+        this.#fullpath = opts.fullpath;
+        this.#relative = opts.relative;
+        this.#relativePosix = opts.relativePosix;
+        this.parent = opts.parent;
+        if (this.parent) {
+          this.#fs = this.parent.#fs;
         } else {
-          this.#disposeAfter = void 0;
-          this.#disposed = void 0;
-        }
-        this.#hasDispose = !!this.#dispose;
-        this.#hasDisposeAfter = !!this.#disposeAfter;
-        this.noDisposeOnSet = !!noDisposeOnSet;
-        this.noUpdateTTL = !!noUpdateTTL;
-        this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
-        this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
-        this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
-        this.ignoreFetchAbort = !!ignoreFetchAbort;
-        if (this.maxEntrySize !== 0) {
-          if (this.#maxSize !== 0) {
-            if (!isPosInt(this.#maxSize)) {
-              throw new TypeError("maxSize must be a positive integer if specified");
-            }
-          }
-          if (!isPosInt(this.maxEntrySize)) {
-            throw new TypeError("maxEntrySize must be a positive integer if specified");
-          }
-          this.#initializeSizeTracking();
-        }
-        this.allowStale = !!allowStale;
-        this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
-        this.updateAgeOnGet = !!updateAgeOnGet;
-        this.updateAgeOnHas = !!updateAgeOnHas;
-        this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
-        this.ttlAutopurge = !!ttlAutopurge;
-        this.ttl = ttl || 0;
-        if (this.ttl) {
-          if (!isPosInt(this.ttl)) {
-            throw new TypeError("ttl must be a positive integer if specified");
-          }
-          this.#initializeTTLTracking();
-        }
-        if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
-          throw new TypeError("At least one of max, maxSize, or ttl is required");
-        }
-        if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
-          const code = "LRU_CACHE_UNBOUNDED";
-          if (shouldWarn(code)) {
-            warned.add(code);
-            const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
-            emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
-          }
+          this.#fs = fsFromOption(opts.fs);
         }
       }
       /**
-       * Return the number of ms left in the item's TTL. If item is not in cache,
-       * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
+       * Returns the depth of the Path object from its root.
+       *
+       * For example, a path at `/foo/bar` would have a depth of 2.
        */
-      getRemainingTTL(key) {
-        return this.#keyMap.has(key) ? Infinity : 0;
+      depth() {
+        if (this.#depth !== void 0)
+          return this.#depth;
+        if (!this.parent)
+          return this.#depth = 0;
+        return this.#depth = this.parent.depth() + 1;
       }
-      #initializeTTLTracking() {
-        const ttls = new ZeroArray(this.#max);
-        const starts = new ZeroArray(this.#max);
-        this.#ttls = ttls;
-        this.#starts = starts;
-        this.#setItemTTL = (index, ttl, start = perf.now()) => {
-          starts[index] = ttl !== 0 ? start : 0;
-          ttls[index] = ttl;
-          if (ttl !== 0 && this.ttlAutopurge) {
-            const t = setTimeout(() => {
-              if (this.#isStale(index)) {
-                this.#delete(this.#keyList[index], "expire");
-              }
-            }, ttl + 1);
-            if (t.unref) {
-              t.unref();
-            }
-          }
-        };
-        this.#updateItemAge = (index) => {
-          starts[index] = ttls[index] !== 0 ? perf.now() : 0;
-        };
-        this.#statusTTL = (status, index) => {
-          if (ttls[index]) {
-            const ttl = ttls[index];
-            const start = starts[index];
-            if (!ttl || !start)
-              return;
-            status.ttl = ttl;
-            status.start = start;
-            status.now = cachedNow || getNow();
-            const age = status.now - start;
-            status.remainingTTL = ttl - age;
-          }
-        };
-        let cachedNow = 0;
-        const getNow = () => {
-          const n = perf.now();
-          if (this.ttlResolution > 0) {
-            cachedNow = n;
-            const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
-            if (t.unref) {
-              t.unref();
-            }
-          }
-          return n;
-        };
-        this.getRemainingTTL = (key) => {
-          const index = this.#keyMap.get(key);
-          if (index === void 0) {
-            return 0;
-          }
-          const ttl = ttls[index];
-          const start = starts[index];
-          if (!ttl || !start) {
-            return Infinity;
-          }
-          const age = (cachedNow || getNow()) - start;
-          return ttl - age;
-        };
-        this.#isStale = (index) => {
-          const s = starts[index];
-          const t = ttls[index];
-          return !!t && !!s && (cachedNow || getNow()) - s > t;
-        };
+      /**
+       * @internal
+       */
+      childrenCache() {
+        return this.#children;
       }
-      // conditionally set private methods related to TTL
-      #updateItemAge = () => {
-      };
-      #statusTTL = () => {
-      };
-      #setItemTTL = () => {
-      };
-      /* c8 ignore stop */
-      #isStale = () => false;
-      #initializeSizeTracking() {
-        const sizes = new ZeroArray(this.#max);
-        this.#calculatedSize = 0;
-        this.#sizes = sizes;
-        this.#removeItemSize = (index) => {
-          this.#calculatedSize -= sizes[index];
-          sizes[index] = 0;
-        };
-        this.#requireSize = (k, v, size, sizeCalculation) => {
-          if (this.#isBackgroundFetch(v)) {
-            return 0;
-          }
-          if (!isPosInt(size)) {
-            if (sizeCalculation) {
-              if (typeof sizeCalculation !== "function") {
-                throw new TypeError("sizeCalculation must be a function");
-              }
-              size = sizeCalculation(v, k);
-              if (!isPosInt(size)) {
-                throw new TypeError("sizeCalculation return invalid (expect positive integer)");
-              }
-            } else {
-              throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
-            }
-          }
-          return size;
-        };
-        this.#addItemSize = (index, size, status) => {
-          sizes[index] = size;
-          if (this.#maxSize) {
-            const maxSize = this.#maxSize - sizes[index];
-            while (this.#calculatedSize > maxSize) {
-              this.#evict(true);
-            }
-          }
-          this.#calculatedSize += sizes[index];
-          if (status) {
-            status.entrySize = size;
-            status.totalCalculatedSize = this.#calculatedSize;
-          }
-        };
+      /**
+       * Get the Path object referenced by the string path, resolved from this Path
+       */
+      resolve(path2) {
+        if (!path2) {
+          return this;
+        }
+        const rootPath = this.getRootString(path2);
+        const dir = path2.substring(rootPath.length);
+        const dirParts = dir.split(this.splitSep);
+        const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
+        return result;
       }
-      #removeItemSize = (_i) => {
-      };
-      #addItemSize = (_i, _s, _st) => {
-      };
-      #requireSize = (_k, _v, size, sizeCalculation) => {
-        if (size || sizeCalculation) {
-          throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
+      #resolveParts(dirParts) {
+        let p = this;
+        for (const part of dirParts) {
+          p = p.child(part);
         }
-        return 0;
-      };
-      *#indexes({ allowStale = this.allowStale } = {}) {
-        if (this.#size) {
-          for (let i = this.#tail; true; ) {
-            if (!this.#isValidIndex(i)) {
-              break;
-            }
-            if (allowStale || !this.#isStale(i)) {
-              yield i;
-            }
-            if (i === this.#head) {
-              break;
-            } else {
-              i = this.#prev[i];
-            }
-          }
+        return p;
+      }
+      /**
+       * Returns the cached children Path objects, if still available.  If they
+       * have fallen out of the cache, then returns an empty array, and resets the
+       * READDIR_CALLED bit, so that future calls to readdir() will require an fs
+       * lookup.
+       *
+       * @internal
+       */
+      children() {
+        const cached = this.#children.get(this);
+        if (cached) {
+          return cached;
         }
+        const children = Object.assign([], { provisional: 0 });
+        this.#children.set(this, children);
+        this.#type &= ~READDIR_CALLED;
+        return children;
       }
-      *#rindexes({ allowStale = this.allowStale } = {}) {
-        if (this.#size) {
-          for (let i = this.#head; true; ) {
-            if (!this.#isValidIndex(i)) {
-              break;
-            }
-            if (allowStale || !this.#isStale(i)) {
-              yield i;
-            }
-            if (i === this.#tail) {
-              break;
-            } else {
-              i = this.#next[i];
-            }
+      /**
+       * Resolves a path portion and returns or creates the child Path.
+       *
+       * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
+       * `'..'`.
+       *
+       * This should not be called directly.  If `pathPart` contains any path
+       * separators, it will lead to unsafe undefined behavior.
+       *
+       * Use `Path.resolve()` instead.
+       *
+       * @internal
+       */
+      child(pathPart, opts) {
+        if (pathPart === "" || pathPart === ".") {
+          return this;
+        }
+        if (pathPart === "..") {
+          return this.parent || this;
+        }
+        const children = this.children();
+        const name = this.nocase ? normalizeNocase(pathPart) : normalize2(pathPart);
+        for (const p of children) {
+          if (p.#matchName === name) {
+            return p;
           }
         }
-      }
-      #isValidIndex(index) {
-        return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index;
+        const s = this.parent ? this.sep : "";
+        const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : void 0;
+        const pchild = this.newChild(pathPart, UNKNOWN, {
+          ...opts,
+          parent: this,
+          fullpath
+        });
+        if (!this.canReaddir()) {
+          pchild.#type |= ENOENT;
+        }
+        children.push(pchild);
+        return pchild;
       }
       /**
-       * Return a generator yielding `[key, value]` pairs,
-       * in order from most recently used to least recently used.
+       * The relative path from the cwd. If it does not share an ancestor with
+       * the cwd, then this ends up being equivalent to the fullpath()
        */
-      *entries() {
-        for (const i of this.#indexes()) {
-          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
-            yield [this.#keyList[i], this.#valList[i]];
-          }
+      relative() {
+        if (this.isCWD)
+          return "";
+        if (this.#relative !== void 0) {
+          return this.#relative;
+        }
+        const name = this.name;
+        const p = this.parent;
+        if (!p) {
+          return this.#relative = this.name;
         }
+        const pv = p.relative();
+        return pv + (!pv || !p.parent ? "" : this.sep) + name;
       }
       /**
-       * Inverse order version of {@link LRUCache.entries}
-       *
-       * Return a generator yielding `[key, value]` pairs,
-       * in order from least recently used to most recently used.
+       * The relative path from the cwd, using / as the path separator.
+       * If it does not share an ancestor with
+       * the cwd, then this ends up being equivalent to the fullpathPosix()
+       * On posix systems, this is identical to relative().
        */
-      *rentries() {
-        for (const i of this.#rindexes()) {
-          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
-            yield [this.#keyList[i], this.#valList[i]];
-          }
+      relativePosix() {
+        if (this.sep === "/")
+          return this.relative();
+        if (this.isCWD)
+          return "";
+        if (this.#relativePosix !== void 0)
+          return this.#relativePosix;
+        const name = this.name;
+        const p = this.parent;
+        if (!p) {
+          return this.#relativePosix = this.fullpathPosix();
         }
+        const pv = p.relativePosix();
+        return pv + (!pv || !p.parent ? "" : "/") + name;
       }
       /**
-       * Return a generator yielding the keys in the cache,
-       * in order from most recently used to least recently used.
+       * The fully resolved path string for this Path entry
        */
-      *keys() {
-        for (const i of this.#indexes()) {
-          const k = this.#keyList[i];
-          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
-            yield k;
-          }
+      fullpath() {
+        if (this.#fullpath !== void 0) {
+          return this.#fullpath;
+        }
+        const name = this.name;
+        const p = this.parent;
+        if (!p) {
+          return this.#fullpath = this.name;
         }
+        const pv = p.fullpath();
+        const fp = pv + (!p.parent ? "" : this.sep) + name;
+        return this.#fullpath = fp;
       }
       /**
-       * Inverse order version of {@link LRUCache.keys}
+       * On platforms other than windows, this is identical to fullpath.
        *
-       * Return a generator yielding the keys in the cache,
-       * in order from least recently used to most recently used.
+       * On windows, this is overridden to return the forward-slash form of the
+       * full UNC path.
        */
-      *rkeys() {
-        for (const i of this.#rindexes()) {
-          const k = this.#keyList[i];
-          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
-            yield k;
+      fullpathPosix() {
+        if (this.#fullpathPosix !== void 0)
+          return this.#fullpathPosix;
+        if (this.sep === "/")
+          return this.#fullpathPosix = this.fullpath();
+        if (!this.parent) {
+          const p2 = this.fullpath().replace(/\\/g, "/");
+          if (/^[a-z]:\//i.test(p2)) {
+            return this.#fullpathPosix = `//?/${p2}`;
+          } else {
+            return this.#fullpathPosix = p2;
           }
         }
+        const p = this.parent;
+        const pfpp = p.fullpathPosix();
+        const fpp = pfpp + (!pfpp || !p.parent ? "" : "/") + this.name;
+        return this.#fullpathPosix = fpp;
       }
       /**
-       * Return a generator yielding the values in the cache,
-       * in order from most recently used to least recently used.
+       * Is the Path of an unknown type?
+       *
+       * Note that we might know *something* about it if there has been a previous
+       * filesystem operation, for example that it does not exist, or is not a
+       * link, or whether it has child entries.
        */
-      *values() {
-        for (const i of this.#indexes()) {
-          const v = this.#valList[i];
-          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
-            yield this.#valList[i];
-          }
-        }
+      isUnknown() {
+        return (this.#type & IFMT) === UNKNOWN;
+      }
+      isType(type2) {
+        return this[`is${type2}`]();
+      }
+      getType() {
+        return this.isUnknown() ? "Unknown" : this.isDirectory() ? "Directory" : this.isFile() ? "File" : this.isSymbolicLink() ? "SymbolicLink" : this.isFIFO() ? "FIFO" : this.isCharacterDevice() ? "CharacterDevice" : this.isBlockDevice() ? "BlockDevice" : (
+          /* c8 ignore start */
+          this.isSocket() ? "Socket" : "Unknown"
+        );
       }
       /**
-       * Inverse order version of {@link LRUCache.values}
-       *
-       * Return a generator yielding the values in the cache,
-       * in order from least recently used to most recently used.
+       * Is the Path a regular file?
        */
-      *rvalues() {
-        for (const i of this.#rindexes()) {
-          const v = this.#valList[i];
-          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
-            yield this.#valList[i];
-          }
-        }
+      isFile() {
+        return (this.#type & IFMT) === IFREG;
       }
       /**
-       * Iterating over the cache itself yields the same results as
-       * {@link LRUCache.entries}
+       * Is the Path a directory?
        */
-      [Symbol.iterator]() {
-        return this.entries();
+      isDirectory() {
+        return (this.#type & IFMT) === IFDIR;
       }
       /**
-       * A String value that is used in the creation of the default string
-       * description of an object. Called by the built-in method
-       * `Object.prototype.toString`.
+       * Is the path a character device?
        */
-      [Symbol.toStringTag] = "LRUCache";
+      isCharacterDevice() {
+        return (this.#type & IFMT) === IFCHR;
+      }
       /**
-       * Find a value for which the supplied fn method returns a truthy value,
-       * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
+       * Is the path a block device?
        */
-      find(fn, getOptions = {}) {
-        for (const i of this.#indexes()) {
-          const v = this.#valList[i];
-          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
-          if (value === void 0)
-            continue;
-          if (fn(value, this.#keyList[i], this)) {
-            return this.get(this.#keyList[i], getOptions);
-          }
-        }
+      isBlockDevice() {
+        return (this.#type & IFMT) === IFBLK;
       }
       /**
-       * Call the supplied function on each item in the cache, in order from most
-       * recently used to least recently used.
-       *
-       * `fn` is called as `fn(value, key, cache)`.
-       *
-       * If `thisp` is provided, function will be called in the `this`-context of
-       * the provided object, or the cache if no `thisp` object is provided.
-       *
-       * Does not update age or recenty of use, or iterate over stale values.
+       * Is the path a FIFO pipe?
        */
-      forEach(fn, thisp = this) {
-        for (const i of this.#indexes()) {
-          const v = this.#valList[i];
-          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
-          if (value === void 0)
-            continue;
-          fn.call(thisp, value, this.#keyList[i], this);
-        }
+      isFIFO() {
+        return (this.#type & IFMT) === IFIFO;
       }
       /**
-       * The same as {@link LRUCache.forEach} but items are iterated over in
-       * reverse order.  (ie, less recently used items are iterated over first.)
+       * Is the path a socket?
        */
-      rforEach(fn, thisp = this) {
-        for (const i of this.#rindexes()) {
-          const v = this.#valList[i];
-          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
-          if (value === void 0)
-            continue;
-          fn.call(thisp, value, this.#keyList[i], this);
-        }
+      isSocket() {
+        return (this.#type & IFMT) === IFSOCK;
       }
       /**
-       * Delete any stale entries. Returns true if anything was removed,
-       * false otherwise.
+       * Is the path a symbolic link?
        */
-      purgeStale() {
-        let deleted = false;
-        for (const i of this.#rindexes({ allowStale: true })) {
-          if (this.#isStale(i)) {
-            this.#delete(this.#keyList[i], "expire");
-            deleted = true;
-          }
-        }
-        return deleted;
+      isSymbolicLink() {
+        return (this.#type & IFLNK) === IFLNK;
       }
       /**
-       * Get the extended info about a given entry, to get its value, size, and
-       * TTL info simultaneously. Returns `undefined` if the key is not present.
-       *
-       * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
-       * serialization, the `start` value is always the current timestamp, and the
-       * `ttl` is a calculated remaining time to live (negative if expired).
+       * Return the entry if it has been subject of a successful lstat, or
+       * undefined otherwise.
        *
-       * Always returns stale values, if their info is found in the cache, so be
-       * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
-       * if relevant.
+       * Does not read the filesystem, so an undefined result *could* simply
+       * mean that we haven't called lstat on it.
        */
-      info(key) {
-        const i = this.#keyMap.get(key);
-        if (i === void 0)
-          return void 0;
-        const v = this.#valList[i];
-        const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
-        if (value === void 0)
-          return void 0;
-        const entry = { value };
-        if (this.#ttls && this.#starts) {
-          const ttl = this.#ttls[i];
-          const start = this.#starts[i];
-          if (ttl && start) {
-            const remain = ttl - (perf.now() - start);
-            entry.ttl = remain;
-            entry.start = Date.now();
-          }
-        }
-        if (this.#sizes) {
-          entry.size = this.#sizes[i];
-        }
-        return entry;
+      lstatCached() {
+        return this.#type & LSTAT_CALLED ? this : void 0;
       }
       /**
-       * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
-       * passed to {@link LRLUCache#load}.
-       *
-       * The `start` fields are calculated relative to a portable `Date.now()`
-       * timestamp, even if `performance.now()` is available.
-       *
-       * Stale entries are always included in the `dump`, even if
-       * {@link LRUCache.OptionsBase.allowStale} is false.
+       * Return the cached link target if the entry has been the subject of a
+       * successful readlink, or undefined otherwise.
        *
-       * Note: this returns an actual array, not a generator, so it can be more
-       * easily passed around.
+       * Does not read the filesystem, so an undefined result *could* just mean we
+       * don't have any cached data. Only use it if you are very sure that a
+       * readlink() has been called at some point.
        */
-      dump() {
-        const arr = [];
-        for (const i of this.#indexes({ allowStale: true })) {
-          const key = this.#keyList[i];
-          const v = this.#valList[i];
-          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
-          if (value === void 0 || key === void 0)
-            continue;
-          const entry = { value };
-          if (this.#ttls && this.#starts) {
-            entry.ttl = this.#ttls[i];
-            const age = perf.now() - this.#starts[i];
-            entry.start = Math.floor(Date.now() - age);
-          }
-          if (this.#sizes) {
-            entry.size = this.#sizes[i];
-          }
-          arr.unshift([key, entry]);
-        }
-        return arr;
+      readlinkCached() {
+        return this.#linkTarget;
       }
       /**
-       * Reset the cache and load in the items in entries in the order listed.
-       *
-       * The shape of the resulting cache may be different if the same options are
-       * not used in both caches.
+       * Returns the cached realpath target if the entry has been the subject
+       * of a successful realpath, or undefined otherwise.
        *
-       * The `start` fields are assumed to be calculated relative to a portable
-       * `Date.now()` timestamp, even if `performance.now()` is available.
+       * Does not read the filesystem, so an undefined result *could* just mean we
+       * don't have any cached data. Only use it if you are very sure that a
+       * realpath() has been called at some point.
        */
-      load(arr) {
-        this.clear();
-        for (const [key, entry] of arr) {
-          if (entry.start) {
-            const age = Date.now() - entry.start;
-            entry.start = perf.now() - age;
-          }
-          this.set(key, entry.value, entry);
-        }
+      realpathCached() {
+        return this.#realpath;
       }
       /**
-       * Add a value to the cache.
-       *
-       * Note: if `undefined` is specified as a value, this is an alias for
-       * {@link LRUCache#delete}
+       * Returns the cached child Path entries array if the entry has been the
+       * subject of a successful readdir(), or [] otherwise.
        *
-       * Fields on the {@link LRUCache.SetOptions} options param will override
-       * their corresponding values in the constructor options for the scope
-       * of this single `set()` operation.
+       * Does not read the filesystem, so an empty array *could* just mean we
+       * don't have any cached data. Only use it if you are very sure that a
+       * readdir() has been called recently enough to still be valid.
+       */
+      readdirCached() {
+        const children = this.children();
+        return children.slice(0, children.provisional);
+      }
+      /**
+       * Return true if it's worth trying to readlink.  Ie, we don't (yet) have
+       * any indication that readlink will definitely fail.
        *
-       * If `start` is provided, then that will set the effective start
-       * time for the TTL calculation. Note that this must be a previous
-       * value of `performance.now()` if supported, or a previous value of
-       * `Date.now()` if not.
+       * Returns false if the path is known to not be a symlink, if a previous
+       * readlink failed, or if the entry does not exist.
+       */
+      canReadlink() {
+        if (this.#linkTarget)
+          return true;
+        if (!this.parent)
+          return false;
+        const ifmt = this.#type & IFMT;
+        return !(ifmt !== UNKNOWN && ifmt !== IFLNK || this.#type & ENOREADLINK || this.#type & ENOENT);
+      }
+      /**
+       * Return true if readdir has previously been successfully called on this
+       * path, indicating that cachedReaddir() is likely valid.
+       */
+      calledReaddir() {
+        return !!(this.#type & READDIR_CALLED);
+      }
+      /**
+       * Returns true if the path is known to not exist. That is, a previous lstat
+       * or readdir failed to verify its existence when that would have been
+       * expected, or a parent entry was marked either enoent or enotdir.
+       */
+      isENOENT() {
+        return !!(this.#type & ENOENT);
+      }
+      /**
+       * Return true if the path is a match for the given path name.  This handles
+       * case sensitivity and unicode normalization.
        *
-       * Options object may also include `size`, which will prevent
-       * calling the `sizeCalculation` function and just use the specified
-       * number if it is a positive integer, and `noDisposeOnSet` which
-       * will prevent calling a `dispose` function in the case of
-       * overwrites.
+       * Note: even on case-sensitive systems, it is **not** safe to test the
+       * equality of the `.name` property to determine whether a given pathname
+       * matches, due to unicode normalization mismatches.
        *
-       * If the `size` (or return value of `sizeCalculation`) for a given
-       * entry is greater than `maxEntrySize`, then the item will not be
-       * added to the cache.
+       * Always use this method instead of testing the `path.name` property
+       * directly.
+       */
+      isNamed(n) {
+        return !this.nocase ? this.#matchName === normalize2(n) : this.#matchName === normalizeNocase(n);
+      }
+      /**
+       * Return the Path object corresponding to the target of a symbolic link.
        *
-       * Will update the recency of the entry.
+       * If the Path is not a symbolic link, or if the readlink call fails for any
+       * reason, `undefined` is returned.
        *
-       * If the value is `undefined`, then this is an alias for
-       * `cache.delete(key)`. `undefined` is never stored in the cache.
+       * Result is cached, and thus may be outdated if the filesystem is mutated.
        */
-      set(k, v, setOptions = {}) {
-        if (v === void 0) {
-          this.delete(k);
-          return this;
+      async readlink() {
+        const target = this.#linkTarget;
+        if (target) {
+          return target;
         }
-        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
-        let { noUpdateTTL = this.noUpdateTTL } = setOptions;
-        const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
-        if (this.maxEntrySize && size > this.maxEntrySize) {
-          if (status) {
-            status.set = "miss";
-            status.maxEntrySizeExceeded = true;
+        if (!this.canReadlink()) {
+          return void 0;
+        }
+        if (!this.parent) {
+          return void 0;
+        }
+        try {
+          const read = await this.#fs.promises.readlink(this.fullpath());
+          const linkTarget = (await this.parent.realpath())?.resolve(read);
+          if (linkTarget) {
+            return this.#linkTarget = linkTarget;
           }
-          this.#delete(k, "set");
-          return this;
+        } catch (er) {
+          this.#readlinkFail(er.code);
+          return void 0;
         }
-        let index = this.#size === 0 ? void 0 : this.#keyMap.get(k);
-        if (index === void 0) {
-          index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
-          this.#keyList[index] = k;
-          this.#valList[index] = v;
-          this.#keyMap.set(k, index);
-          this.#next[this.#tail] = index;
-          this.#prev[index] = this.#tail;
-          this.#tail = index;
-          this.#size++;
-          this.#addItemSize(index, size, status);
-          if (status)
-            status.set = "add";
-          noUpdateTTL = false;
-        } else {
-          this.#moveToTail(index);
-          const oldVal = this.#valList[index];
-          if (v !== oldVal) {
-            if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
-              oldVal.__abortController.abort(new Error("replaced"));
-              const { __staleWhileFetching: s } = oldVal;
-              if (s !== void 0 && !noDisposeOnSet) {
-                if (this.#hasDispose) {
-                  this.#dispose?.(s, k, "set");
-                }
-                if (this.#hasDisposeAfter) {
-                  this.#disposed?.push([s, k, "set"]);
-                }
-              }
-            } else if (!noDisposeOnSet) {
-              if (this.#hasDispose) {
-                this.#dispose?.(oldVal, k, "set");
-              }
-              if (this.#hasDisposeAfter) {
-                this.#disposed?.push([oldVal, k, "set"]);
-              }
-            }
-            this.#removeItemSize(index);
-            this.#addItemSize(index, size, status);
-            this.#valList[index] = v;
-            if (status) {
-              status.set = "replace";
-              const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
-              if (oldValue !== void 0)
-                status.oldValue = oldValue;
-            }
-          } else if (status) {
-            status.set = "update";
+      }
+      /**
+       * Synchronous {@link PathBase.readlink}
+       */
+      readlinkSync() {
+        const target = this.#linkTarget;
+        if (target) {
+          return target;
+        }
+        if (!this.canReadlink()) {
+          return void 0;
+        }
+        if (!this.parent) {
+          return void 0;
+        }
+        try {
+          const read = this.#fs.readlinkSync(this.fullpath());
+          const linkTarget = this.parent.realpathSync()?.resolve(read);
+          if (linkTarget) {
+            return this.#linkTarget = linkTarget;
           }
+        } catch (er) {
+          this.#readlinkFail(er.code);
+          return void 0;
+        }
+      }
+      #readdirSuccess(children) {
+        this.#type |= READDIR_CALLED;
+        for (let p = children.provisional; p < children.length; p++) {
+          const c = children[p];
+          if (c)
+            c.#markENOENT();
+        }
+      }
+      #markENOENT() {
+        if (this.#type & ENOENT)
+          return;
+        this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN;
+        this.#markChildrenENOENT();
+      }
+      #markChildrenENOENT() {
+        const children = this.children();
+        children.provisional = 0;
+        for (const p of children) {
+          p.#markENOENT();
+        }
+      }
+      #markENOREALPATH() {
+        this.#type |= ENOREALPATH;
+        this.#markENOTDIR();
+      }
+      // save the information when we know the entry is not a dir
+      #markENOTDIR() {
+        if (this.#type & ENOTDIR)
+          return;
+        let t = this.#type;
+        if ((t & IFMT) === IFDIR)
+          t &= IFMT_UNKNOWN;
+        this.#type = t | ENOTDIR;
+        this.#markChildrenENOENT();
+      }
+      #readdirFail(code = "") {
+        if (code === "ENOTDIR" || code === "EPERM") {
+          this.#markENOTDIR();
+        } else if (code === "ENOENT") {
+          this.#markENOENT();
+        } else {
+          this.children().provisional = 0;
         }
-        if (ttl !== 0 && !this.#ttls) {
-          this.#initializeTTLTracking();
+      }
+      #lstatFail(code = "") {
+        if (code === "ENOTDIR") {
+          const p = this.parent;
+          p.#markENOTDIR();
+        } else if (code === "ENOENT") {
+          this.#markENOENT();
         }
-        if (this.#ttls) {
-          if (!noUpdateTTL) {
-            this.#setItemTTL(index, ttl, start);
-          }
-          if (status)
-            this.#statusTTL(status, index);
+      }
+      #readlinkFail(code = "") {
+        let ter = this.#type;
+        ter |= ENOREADLINK;
+        if (code === "ENOENT")
+          ter |= ENOENT;
+        if (code === "EINVAL" || code === "UNKNOWN") {
+          ter &= IFMT_UNKNOWN;
         }
-        if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
-          const dt = this.#disposed;
-          let task;
-          while (task = dt?.shift()) {
-            this.#disposeAfter?.(...task);
-          }
+        this.#type = ter;
+        if (code === "ENOTDIR" && this.parent) {
+          this.parent.#markENOTDIR();
         }
-        return this;
       }
-      /**
-       * Evict the least recently used item, returning its value or
-       * `undefined` if cache is empty.
-       */
-      pop() {
-        try {
-          while (this.#size) {
-            const val2 = this.#valList[this.#head];
-            this.#evict(true);
-            if (this.#isBackgroundFetch(val2)) {
-              if (val2.__staleWhileFetching) {
-                return val2.__staleWhileFetching;
-              }
-            } else if (val2 !== void 0) {
-              return val2;
-            }
-          }
-        } finally {
-          if (this.#hasDisposeAfter && this.#disposed) {
-            const dt = this.#disposed;
-            let task;
-            while (task = dt?.shift()) {
-              this.#disposeAfter?.(...task);
-            }
-          }
+      #readdirAddChild(e, c) {
+        return this.#readdirMaybePromoteChild(e, c) || this.#readdirAddNewChild(e, c);
+      }
+      #readdirAddNewChild(e, c) {
+        const type2 = entToType(e);
+        const child = this.newChild(e.name, type2, { parent: this });
+        const ifmt = child.#type & IFMT;
+        if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
+          child.#type |= ENOTDIR;
         }
+        c.unshift(child);
+        c.provisional++;
+        return child;
       }
-      #evict(free) {
-        const head = this.#head;
-        const k = this.#keyList[head];
-        const v = this.#valList[head];
-        if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
-          v.__abortController.abort(new Error("evicted"));
-        } else if (this.#hasDispose || this.#hasDisposeAfter) {
-          if (this.#hasDispose) {
-            this.#dispose?.(v, k, "evict");
-          }
-          if (this.#hasDisposeAfter) {
-            this.#disposed?.push([v, k, "evict"]);
+      #readdirMaybePromoteChild(e, c) {
+        for (let p = c.provisional; p < c.length; p++) {
+          const pchild = c[p];
+          const name = this.nocase ? normalizeNocase(e.name) : normalize2(e.name);
+          if (name !== pchild.#matchName) {
+            continue;
           }
+          return this.#readdirPromoteChild(e, pchild, p, c);
         }
-        this.#removeItemSize(head);
-        if (free) {
-          this.#keyList[head] = void 0;
-          this.#valList[head] = void 0;
-          this.#free.push(head);
-        }
-        if (this.#size === 1) {
-          this.#head = this.#tail = 0;
-          this.#free.length = 0;
-        } else {
-          this.#head = this.#next[head];
+      }
+      #readdirPromoteChild(e, p, index, c) {
+        const v = p.name;
+        p.#type = p.#type & IFMT_UNKNOWN | entToType(e);
+        if (v !== e.name)
+          p.name = e.name;
+        if (index !== c.provisional) {
+          if (index === c.length - 1)
+            c.pop();
+          else
+            c.splice(index, 1);
+          c.unshift(p);
         }
-        this.#keyMap.delete(k);
-        this.#size--;
-        return head;
+        c.provisional++;
+        return p;
       }
       /**
-       * Check if a key is in the cache, without updating the recency of use.
-       * Will return false if the item is stale, even though it is technically
-       * in the cache.
+       * Call lstat() on this Path, and update all known information that can be
+       * determined.
        *
-       * Check if a key is in the cache, without updating the recency of
-       * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
-       * to `true` in either the options or the constructor.
+       * Note that unlike `fs.lstat()`, the returned value does not contain some
+       * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
+       * information is required, you will need to call `fs.lstat` yourself.
        *
-       * Will return `false` if the item is stale, even though it is technically in
-       * the cache. The difference can be determined (if it matters) by using a
-       * `status` argument, and inspecting the `has` field.
+       * If the Path refers to a nonexistent file, or if the lstat call fails for
+       * any reason, `undefined` is returned.  Otherwise the updated Path object is
+       * returned.
        *
-       * Will not update item age unless
-       * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
+       * Results are cached, and thus may be out of date if the filesystem is
+       * mutated.
        */
-      has(k, hasOptions = {}) {
-        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
-        const index = this.#keyMap.get(k);
-        if (index !== void 0) {
-          const v = this.#valList[index];
-          if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) {
-            return false;
+      async lstat() {
+        if ((this.#type & ENOENT) === 0) {
+          try {
+            this.#applyStat(await this.#fs.promises.lstat(this.fullpath()));
+            return this;
+          } catch (er) {
+            this.#lstatFail(er.code);
           }
-          if (!this.#isStale(index)) {
-            if (updateAgeOnHas) {
-              this.#updateItemAge(index);
-            }
-            if (status) {
-              status.has = "hit";
-              this.#statusTTL(status, index);
-            }
-            return true;
-          } else if (status) {
-            status.has = "stale";
-            this.#statusTTL(status, index);
+        }
+      }
+      /**
+       * synchronous {@link PathBase.lstat}
+       */
+      lstatSync() {
+        if ((this.#type & ENOENT) === 0) {
+          try {
+            this.#applyStat(this.#fs.lstatSync(this.fullpath()));
+            return this;
+          } catch (er) {
+            this.#lstatFail(er.code);
           }
-        } else if (status) {
-          status.has = "miss";
         }
-        return false;
+      }
+      #applyStat(st) {
+        const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid } = st;
+        this.#atime = atime;
+        this.#atimeMs = atimeMs;
+        this.#birthtime = birthtime;
+        this.#birthtimeMs = birthtimeMs;
+        this.#blksize = blksize;
+        this.#blocks = blocks;
+        this.#ctime = ctime;
+        this.#ctimeMs = ctimeMs;
+        this.#dev = dev;
+        this.#gid = gid;
+        this.#ino = ino;
+        this.#mode = mode;
+        this.#mtime = mtime;
+        this.#mtimeMs = mtimeMs;
+        this.#nlink = nlink;
+        this.#rdev = rdev;
+        this.#size = size;
+        this.#uid = uid;
+        const ifmt = entToType(st);
+        this.#type = this.#type & IFMT_UNKNOWN | ifmt | LSTAT_CALLED;
+        if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
+          this.#type |= ENOTDIR;
+        }
+      }
+      #onReaddirCB = [];
+      #readdirCBInFlight = false;
+      #callOnReaddirCB(children) {
+        this.#readdirCBInFlight = false;
+        const cbs = this.#onReaddirCB.slice();
+        this.#onReaddirCB.length = 0;
+        cbs.forEach((cb) => cb(null, children));
       }
       /**
-       * Like {@link LRUCache#get} but doesn't update recency or delete stale
-       * items.
+       * Standard node-style callback interface to get list of directory entries.
        *
-       * Returns `undefined` if the item is stale, unless
-       * {@link LRUCache.OptionsBase.allowStale} is set.
+       * If the Path cannot or does not contain any children, then an empty array
+       * is returned.
+       *
+       * Results are cached, and thus may be out of date if the filesystem is
+       * mutated.
+       *
+       * @param cb The callback called with (er, entries).  Note that the `er`
+       * param is somewhat extraneous, as all readdir() errors are handled and
+       * simply result in an empty set of entries being returned.
+       * @param allowZalgo Boolean indicating that immediately known results should
+       * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
+       * zalgo at your peril, the dark pony lord is devious and unforgiving.
        */
-      peek(k, peekOptions = {}) {
-        const { allowStale = this.allowStale } = peekOptions;
-        const index = this.#keyMap.get(k);
-        if (index === void 0 || !allowStale && this.#isStale(index)) {
+      readdirCB(cb, allowZalgo = false) {
+        if (!this.canReaddir()) {
+          if (allowZalgo)
+            cb(null, []);
+          else
+            queueMicrotask(() => cb(null, []));
           return;
         }
-        const v = this.#valList[index];
-        return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
-      }
-      #backgroundFetch(k, index, options, context2) {
-        const v = index === void 0 ? void 0 : this.#valList[index];
-        if (this.#isBackgroundFetch(v)) {
-          return v;
+        const children = this.children();
+        if (this.calledReaddir()) {
+          const c = children.slice(0, children.provisional);
+          if (allowZalgo)
+            cb(null, c);
+          else
+            queueMicrotask(() => cb(null, c));
+          return;
         }
-        const ac = new AC();
-        const { signal } = options;
-        signal?.addEventListener("abort", () => ac.abort(signal.reason), {
-          signal: ac.signal
-        });
-        const fetchOpts = {
-          signal: ac.signal,
-          options,
-          context: context2
-        };
-        const cb = (v2, updateCache = false) => {
-          const { aborted } = ac.signal;
-          const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;
-          if (options.status) {
-            if (aborted && !updateCache) {
-              options.status.fetchAborted = true;
-              options.status.fetchError = ac.signal.reason;
-              if (ignoreAbort)
-                options.status.fetchAbortIgnored = true;
-            } else {
-              options.status.fetchResolved = true;
-            }
-          }
-          if (aborted && !ignoreAbort && !updateCache) {
-            return fetchFail(ac.signal.reason);
-          }
-          const bf2 = p;
-          if (this.#valList[index] === p) {
-            if (v2 === void 0) {
-              if (bf2.__staleWhileFetching) {
-                this.#valList[index] = bf2.__staleWhileFetching;
-              } else {
-                this.#delete(k, "fetch");
-              }
-            } else {
-              if (options.status)
-                options.status.fetchUpdated = true;
-              this.set(k, v2, fetchOpts.options);
-            }
-          }
-          return v2;
-        };
-        const eb = (er) => {
-          if (options.status) {
-            options.status.fetchRejected = true;
-            options.status.fetchError = er;
-          }
-          return fetchFail(er);
-        };
-        const fetchFail = (er) => {
-          const { aborted } = ac.signal;
-          const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
-          const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
-          const noDelete = allowStale || options.noDeleteOnFetchRejection;
-          const bf2 = p;
-          if (this.#valList[index] === p) {
-            const del = !noDelete || bf2.__staleWhileFetching === void 0;
-            if (del) {
-              this.#delete(k, "fetch");
-            } else if (!allowStaleAborted) {
-              this.#valList[index] = bf2.__staleWhileFetching;
-            }
-          }
-          if (allowStale) {
-            if (options.status && bf2.__staleWhileFetching !== void 0) {
-              options.status.returnedStale = true;
+        this.#onReaddirCB.push(cb);
+        if (this.#readdirCBInFlight) {
+          return;
+        }
+        this.#readdirCBInFlight = true;
+        const fullpath = this.fullpath();
+        this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {
+          if (er) {
+            this.#readdirFail(er.code);
+            children.provisional = 0;
+          } else {
+            for (const e of entries) {
+              this.#readdirAddChild(e, children);
             }
-            return bf2.__staleWhileFetching;
-          } else if (bf2.__returned === bf2) {
-            throw er;
-          }
-        };
-        const pcall = (res, rej) => {
-          const fmp = this.#fetchMethod?.(k, v, fetchOpts);
-          if (fmp && fmp instanceof Promise) {
-            fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
+            this.#readdirSuccess(children);
           }
-          ac.signal.addEventListener("abort", () => {
-            if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
-              res(void 0);
-              if (options.allowStaleOnFetchAbort) {
-                res = (v2) => cb(v2, true);
-              }
-            }
-          });
-        };
-        if (options.status)
-          options.status.fetchDispatched = true;
-        const p = new Promise(pcall).then(cb, eb);
-        const bf = Object.assign(p, {
-          __abortController: ac,
-          __staleWhileFetching: v,
-          __returned: void 0
+          this.#callOnReaddirCB(children.slice(0, children.provisional));
+          return;
         });
-        if (index === void 0) {
-          this.set(k, bf, { ...fetchOpts.options, status: void 0 });
-          index = this.#keyMap.get(k);
-        } else {
-          this.#valList[index] = bf;
-        }
-        return bf;
-      }
-      #isBackgroundFetch(p) {
-        if (!this.#hasFetchMethod)
-          return false;
-        const b = p;
-        return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
       }
-      async fetch(k, fetchOptions = {}) {
-        const {
-          // get options
-          allowStale = this.allowStale,
-          updateAgeOnGet = this.updateAgeOnGet,
-          noDeleteOnStaleGet = this.noDeleteOnStaleGet,
-          // set options
-          ttl = this.ttl,
-          noDisposeOnSet = this.noDisposeOnSet,
-          size = 0,
-          sizeCalculation = this.sizeCalculation,
-          noUpdateTTL = this.noUpdateTTL,
-          // fetch exclusive options
-          noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
-          allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
-          ignoreFetchAbort = this.ignoreFetchAbort,
-          allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
-          context: context2,
-          forceRefresh = false,
-          status,
-          signal
-        } = fetchOptions;
-        if (!this.#hasFetchMethod) {
-          if (status)
-            status.fetch = "get";
-          return this.get(k, {
-            allowStale,
-            updateAgeOnGet,
-            noDeleteOnStaleGet,
-            status
-          });
+      #asyncReaddirInFlight;
+      /**
+       * Return an array of known child entries.
+       *
+       * If the Path cannot or does not contain any children, then an empty array
+       * is returned.
+       *
+       * Results are cached, and thus may be out of date if the filesystem is
+       * mutated.
+       */
+      async readdir() {
+        if (!this.canReaddir()) {
+          return [];
         }
-        const options = {
-          allowStale,
-          updateAgeOnGet,
-          noDeleteOnStaleGet,
-          ttl,
-          noDisposeOnSet,
-          size,
-          sizeCalculation,
-          noUpdateTTL,
-          noDeleteOnFetchRejection,
-          allowStaleOnFetchRejection,
-          allowStaleOnFetchAbort,
-          ignoreFetchAbort,
-          status,
-          signal
-        };
-        let index = this.#keyMap.get(k);
-        if (index === void 0) {
-          if (status)
-            status.fetch = "miss";
-          const p = this.#backgroundFetch(k, index, options, context2);
-          return p.__returned = p;
+        const children = this.children();
+        if (this.calledReaddir()) {
+          return children.slice(0, children.provisional);
+        }
+        const fullpath = this.fullpath();
+        if (this.#asyncReaddirInFlight) {
+          await this.#asyncReaddirInFlight;
         } else {
-          const v = this.#valList[index];
-          if (this.#isBackgroundFetch(v)) {
-            const stale = allowStale && v.__staleWhileFetching !== void 0;
-            if (status) {
-              status.fetch = "inflight";
-              if (stale)
-                status.returnedStale = true;
-            }
-            return stale ? v.__staleWhileFetching : v.__returned = v;
-          }
-          const isStale = this.#isStale(index);
-          if (!forceRefresh && !isStale) {
-            if (status)
-              status.fetch = "hit";
-            this.#moveToTail(index);
-            if (updateAgeOnGet) {
-              this.#updateItemAge(index);
+          let resolve2 = () => {
+          };
+          this.#asyncReaddirInFlight = new Promise((res) => resolve2 = res);
+          try {
+            for (const e of await this.#fs.promises.readdir(fullpath, {
+              withFileTypes: true
+            })) {
+              this.#readdirAddChild(e, children);
             }
-            if (status)
-              this.#statusTTL(status, index);
-            return v;
-          }
-          const p = this.#backgroundFetch(k, index, options, context2);
-          const hasStale = p.__staleWhileFetching !== void 0;
-          const staleVal = hasStale && allowStale;
-          if (status) {
-            status.fetch = isStale ? "stale" : "refresh";
-            if (staleVal && isStale)
-              status.returnedStale = true;
+            this.#readdirSuccess(children);
+          } catch (er) {
+            this.#readdirFail(er.code);
+            children.provisional = 0;
           }
-          return staleVal ? p.__staleWhileFetching : p.__returned = p;
+          this.#asyncReaddirInFlight = void 0;
+          resolve2();
         }
+        return children.slice(0, children.provisional);
       }
-      async forceFetch(k, fetchOptions = {}) {
-        const v = await this.fetch(k, fetchOptions);
-        if (v === void 0)
-          throw new Error("fetch() returned undefined");
-        return v;
+      /**
+       * synchronous {@link PathBase.readdir}
+       */
+      readdirSync() {
+        if (!this.canReaddir()) {
+          return [];
+        }
+        const children = this.children();
+        if (this.calledReaddir()) {
+          return children.slice(0, children.provisional);
+        }
+        const fullpath = this.fullpath();
+        try {
+          for (const e of this.#fs.readdirSync(fullpath, {
+            withFileTypes: true
+          })) {
+            this.#readdirAddChild(e, children);
+          }
+          this.#readdirSuccess(children);
+        } catch (er) {
+          this.#readdirFail(er.code);
+          children.provisional = 0;
+        }
+        return children.slice(0, children.provisional);
       }
-      memo(k, memoOptions = {}) {
-        const memoMethod = this.#memoMethod;
-        if (!memoMethod) {
-          throw new Error("no memoMethod provided to constructor");
+      canReaddir() {
+        if (this.#type & ENOCHILD)
+          return false;
+        const ifmt = IFMT & this.#type;
+        if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
+          return false;
         }
-        const { context: context2, forceRefresh, ...options } = memoOptions;
-        const v = this.get(k, options);
-        if (!forceRefresh && v !== void 0)
-          return v;
-        const vv = memoMethod(k, v, {
-          options,
-          context: context2
-        });
-        this.set(k, vv, options);
-        return vv;
+        return true;
+      }
+      shouldWalk(dirs, walkFilter) {
+        return (this.#type & IFDIR) === IFDIR && !(this.#type & ENOCHILD) && !dirs.has(this) && (!walkFilter || walkFilter(this));
       }
       /**
-       * Return a value from the cache. Will update the recency of the cache
-       * entry found.
+       * Return the Path object corresponding to path as resolved
+       * by realpath(3).
        *
-       * If the key is not found, get() will return `undefined`.
+       * If the realpath call fails for any reason, `undefined` is returned.
+       *
+       * Result is cached, and thus may be outdated if the filesystem is mutated.
+       * On success, returns a Path object.
        */
-      get(k, getOptions = {}) {
-        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
-        const index = this.#keyMap.get(k);
-        if (index !== void 0) {
-          const value = this.#valList[index];
-          const fetching = this.#isBackgroundFetch(value);
-          if (status)
-            this.#statusTTL(status, index);
-          if (this.#isStale(index)) {
-            if (status)
-              status.get = "stale";
-            if (!fetching) {
-              if (!noDeleteOnStaleGet) {
-                this.#delete(k, "expire");
-              }
-              if (status && allowStale)
-                status.returnedStale = true;
-              return allowStale ? value : void 0;
-            } else {
-              if (status && allowStale && value.__staleWhileFetching !== void 0) {
-                status.returnedStale = true;
-              }
-              return allowStale ? value.__staleWhileFetching : void 0;
-            }
-          } else {
-            if (status)
-              status.get = "hit";
-            if (fetching) {
-              return value.__staleWhileFetching;
-            }
-            this.#moveToTail(index);
-            if (updateAgeOnGet) {
-              this.#updateItemAge(index);
-            }
-            return value;
-          }
-        } else if (status) {
-          status.get = "miss";
+      async realpath() {
+        if (this.#realpath)
+          return this.#realpath;
+        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
+          return void 0;
+        try {
+          const rp = await this.#fs.promises.realpath(this.fullpath());
+          return this.#realpath = this.resolve(rp);
+        } catch (_2) {
+          this.#markENOREALPATH();
         }
       }
-      #connect(p, n) {
-        this.#prev[n] = p;
-        this.#next[p] = n;
-      }
-      #moveToTail(index) {
-        if (index !== this.#tail) {
-          if (index === this.#head) {
-            this.#head = this.#next[index];
-          } else {
-            this.#connect(this.#prev[index], this.#next[index]);
-          }
-          this.#connect(this.#tail, index);
-          this.#tail = index;
+      /**
+       * Synchronous {@link realpath}
+       */
+      realpathSync() {
+        if (this.#realpath)
+          return this.#realpath;
+        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
+          return void 0;
+        try {
+          const rp = this.#fs.realpathSync(this.fullpath());
+          return this.#realpath = this.resolve(rp);
+        } catch (_2) {
+          this.#markENOREALPATH();
         }
       }
       /**
-       * Deletes a key out of the cache.
+       * Internal method to mark this Path object as the scurry cwd,
+       * called by {@link PathScurry#chdir}
        *
-       * Returns true if the key was deleted, false otherwise.
+       * @internal
        */
-      delete(k) {
-        return this.#delete(k, "delete");
-      }
-      #delete(k, reason) {
-        let deleted = false;
-        if (this.#size !== 0) {
-          const index = this.#keyMap.get(k);
-          if (index !== void 0) {
-            deleted = true;
-            if (this.#size === 1) {
-              this.#clear(reason);
-            } else {
-              this.#removeItemSize(index);
-              const v = this.#valList[index];
-              if (this.#isBackgroundFetch(v)) {
-                v.__abortController.abort(new Error("deleted"));
-              } else if (this.#hasDispose || this.#hasDisposeAfter) {
-                if (this.#hasDispose) {
-                  this.#dispose?.(v, k, reason);
-                }
-                if (this.#hasDisposeAfter) {
-                  this.#disposed?.push([v, k, reason]);
-                }
-              }
-              this.#keyMap.delete(k);
-              this.#keyList[index] = void 0;
-              this.#valList[index] = void 0;
-              if (index === this.#tail) {
-                this.#tail = this.#prev[index];
-              } else if (index === this.#head) {
-                this.#head = this.#next[index];
-              } else {
-                const pi = this.#prev[index];
-                this.#next[pi] = this.#next[index];
-                const ni = this.#next[index];
-                this.#prev[ni] = this.#prev[index];
-              }
-              this.#size--;
-              this.#free.push(index);
-            }
-          }
+      [setAsCwd](oldCwd) {
+        if (oldCwd === this)
+          return;
+        oldCwd.isCWD = false;
+        this.isCWD = true;
+        const changed = /* @__PURE__ */ new Set([]);
+        let rp = [];
+        let p = this;
+        while (p && p.parent) {
+          changed.add(p);
+          p.#relative = rp.join(this.sep);
+          p.#relativePosix = rp.join("/");
+          p = p.parent;
+          rp.push("..");
         }
-        if (this.#hasDisposeAfter && this.#disposed?.length) {
-          const dt = this.#disposed;
-          let task;
-          while (task = dt?.shift()) {
-            this.#disposeAfter?.(...task);
-          }
+        p = oldCwd;
+        while (p && p.parent && !changed.has(p)) {
+          p.#relative = void 0;
+          p.#relativePosix = void 0;
+          p = p.parent;
         }
-        return deleted;
       }
+    };
+    exports2.PathBase = PathBase;
+    var PathWin32 = class _PathWin32 extends PathBase {
       /**
-       * Clear the cache entirely, throwing away all values.
+       * Separator for generating path strings.
        */
-      clear() {
-        return this.#clear("delete");
+      sep = "\\";
+      /**
+       * Separator for parsing path strings.
+       */
+      splitSep = eitherSep;
+      /**
+       * Do not create new Path objects directly.  They should always be accessed
+       * via the PathScurry class or other methods on the Path class.
+       *
+       * @internal
+       */
+      constructor(name, type2 = UNKNOWN, root, roots, nocase, children, opts) {
+        super(name, type2, root, roots, nocase, children, opts);
       }
-      #clear(reason) {
-        for (const index of this.#rindexes({ allowStale: true })) {
-          const v = this.#valList[index];
-          if (this.#isBackgroundFetch(v)) {
-            v.__abortController.abort(new Error("deleted"));
-          } else {
-            const k = this.#keyList[index];
-            if (this.#hasDispose) {
-              this.#dispose?.(v, k, reason);
-            }
-            if (this.#hasDisposeAfter) {
-              this.#disposed?.push([v, k, reason]);
-            }
-          }
-        }
-        this.#keyMap.clear();
-        this.#valList.fill(void 0);
-        this.#keyList.fill(void 0);
-        if (this.#ttls && this.#starts) {
-          this.#ttls.fill(0);
-          this.#starts.fill(0);
-        }
-        if (this.#sizes) {
-          this.#sizes.fill(0);
+      /**
+       * @internal
+       */
+      newChild(name, type2 = UNKNOWN, opts = {}) {
+        return new _PathWin32(name, type2, this.root, this.roots, this.nocase, this.childrenCache(), opts);
+      }
+      /**
+       * @internal
+       */
+      getRootString(path2) {
+        return node_path_1.win32.parse(path2).root;
+      }
+      /**
+       * @internal
+       */
+      getRoot(rootPath) {
+        rootPath = uncToDrive(rootPath.toUpperCase());
+        if (rootPath === this.root.name) {
+          return this.root;
         }
-        this.#head = 0;
-        this.#tail = 0;
-        this.#free.length = 0;
-        this.#calculatedSize = 0;
-        this.#size = 0;
-        if (this.#hasDisposeAfter && this.#disposed) {
-          const dt = this.#disposed;
-          let task;
-          while (task = dt?.shift()) {
-            this.#disposeAfter?.(...task);
+        for (const [compare2, root] of Object.entries(this.roots)) {
+          if (this.sameRoot(rootPath, compare2)) {
+            return this.roots[rootPath] = root;
           }
         }
+        return this.roots[rootPath] = new PathScurryWin32(rootPath, this).root;
       }
-    };
-    exports2.LRUCache = LRUCache;
-  }
-});
-
-// node_modules/minipass/dist/commonjs/index.js
-var require_commonjs15 = __commonJS({
-  "node_modules/minipass/dist/commonjs/index.js"(exports2) {
-    "use strict";
-    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
-      return mod && mod.__esModule ? mod : { "default": mod };
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Minipass = exports2.isWritable = exports2.isReadable = exports2.isStream = void 0;
-    var proc = typeof process === "object" && process ? process : {
-      stdout: null,
-      stderr: null
-    };
-    var node_events_1 = require("node:events");
-    var node_stream_1 = __importDefault4(require("node:stream"));
-    var node_string_decoder_1 = require("node:string_decoder");
-    var isStream = (s) => !!s && typeof s === "object" && (s instanceof Minipass || s instanceof node_stream_1.default || (0, exports2.isReadable)(s) || (0, exports2.isWritable)(s));
-    exports2.isStream = isStream;
-    var isReadable = (s) => !!s && typeof s === "object" && s instanceof node_events_1.EventEmitter && typeof s.pipe === "function" && // node core Writable streams have a pipe() method, but it throws
-    s.pipe !== node_stream_1.default.Writable.prototype.pipe;
-    exports2.isReadable = isReadable;
-    var isWritable = (s) => !!s && typeof s === "object" && s instanceof node_events_1.EventEmitter && typeof s.write === "function" && typeof s.end === "function";
-    exports2.isWritable = isWritable;
-    var EOF = Symbol("EOF");
-    var MAYBE_EMIT_END = Symbol("maybeEmitEnd");
-    var EMITTED_END = Symbol("emittedEnd");
-    var EMITTING_END = Symbol("emittingEnd");
-    var EMITTED_ERROR = Symbol("emittedError");
-    var CLOSED = Symbol("closed");
-    var READ = Symbol("read");
-    var FLUSH = Symbol("flush");
-    var FLUSHCHUNK = Symbol("flushChunk");
-    var ENCODING = Symbol("encoding");
-    var DECODER = Symbol("decoder");
-    var FLOWING = Symbol("flowing");
-    var PAUSED = Symbol("paused");
-    var RESUME = Symbol("resume");
-    var BUFFER = Symbol("buffer");
-    var PIPES = Symbol("pipes");
-    var BUFFERLENGTH = Symbol("bufferLength");
-    var BUFFERPUSH = Symbol("bufferPush");
-    var BUFFERSHIFT = Symbol("bufferShift");
-    var OBJECTMODE = Symbol("objectMode");
-    var DESTROYED = Symbol("destroyed");
-    var ERROR = Symbol("error");
-    var EMITDATA = Symbol("emitData");
-    var EMITEND = Symbol("emitEnd");
-    var EMITEND2 = Symbol("emitEnd2");
-    var ASYNC = Symbol("async");
-    var ABORT = Symbol("abort");
-    var ABORTED = Symbol("aborted");
-    var SIGNAL = Symbol("signal");
-    var DATALISTENERS = Symbol("dataListeners");
-    var DISCARDED = Symbol("discarded");
-    var defer = (fn) => Promise.resolve().then(fn);
-    var nodefer = (fn) => fn();
-    var isEndish = (ev) => ev === "end" || ev === "finish" || ev === "prefinish";
-    var isArrayBufferLike = (b) => b instanceof ArrayBuffer || !!b && typeof b === "object" && b.constructor && b.constructor.name === "ArrayBuffer" && b.byteLength >= 0;
-    var isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
-    var Pipe = class {
-      src;
-      dest;
-      opts;
-      ondrain;
-      constructor(src, dest, opts) {
-        this.src = src;
-        this.dest = dest;
-        this.opts = opts;
-        this.ondrain = () => src[RESUME]();
-        this.dest.on("drain", this.ondrain);
-      }
-      unpipe() {
-        this.dest.removeListener("drain", this.ondrain);
+      /**
+       * @internal
+       */
+      sameRoot(rootPath, compare2 = this.root.name) {
+        rootPath = rootPath.toUpperCase().replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
+        return rootPath === compare2;
       }
-      // only here for the prototype
-      /* c8 ignore start */
-      proxyErrors(_er) {
+    };
+    exports2.PathWin32 = PathWin32;
+    var PathPosix = class _PathPosix extends PathBase {
+      /**
+       * separator for parsing path strings
+       */
+      splitSep = "/";
+      /**
+       * separator for generating path strings
+       */
+      sep = "/";
+      /**
+       * Do not create new Path objects directly.  They should always be accessed
+       * via the PathScurry class or other methods on the Path class.
+       *
+       * @internal
+       */
+      constructor(name, type2 = UNKNOWN, root, roots, nocase, children, opts) {
+        super(name, type2, root, roots, nocase, children, opts);
       }
-      /* c8 ignore stop */
-      end() {
-        this.unpipe();
-        if (this.opts.end)
-          this.dest.end();
+      /**
+       * @internal
+       */
+      getRootString(path2) {
+        return path2.startsWith("/") ? "/" : "";
       }
-    };
-    var PipeProxyErrors = class extends Pipe {
-      unpipe() {
-        this.src.removeListener("error", this.proxyErrors);
-        super.unpipe();
+      /**
+       * @internal
+       */
+      getRoot(_rootPath) {
+        return this.root;
       }
-      constructor(src, dest, opts) {
-        super(src, dest, opts);
-        this.proxyErrors = (er) => dest.emit("error", er);
-        src.on("error", this.proxyErrors);
+      /**
+       * @internal
+       */
+      newChild(name, type2 = UNKNOWN, opts = {}) {
+        return new _PathPosix(name, type2, this.root, this.roots, this.nocase, this.childrenCache(), opts);
       }
     };
-    var isObjectModeOptions = (o) => !!o.objectMode;
-    var isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== "buffer";
-    var Minipass = class extends node_events_1.EventEmitter {
-      [FLOWING] = false;
-      [PAUSED] = false;
-      [PIPES] = [];
-      [BUFFER] = [];
-      [OBJECTMODE];
-      [ENCODING];
-      [ASYNC];
-      [DECODER];
-      [EOF] = false;
-      [EMITTED_END] = false;
-      [EMITTING_END] = false;
-      [CLOSED] = false;
-      [EMITTED_ERROR] = null;
-      [BUFFERLENGTH] = 0;
-      [DESTROYED] = false;
-      [SIGNAL];
-      [ABORTED] = false;
-      [DATALISTENERS] = 0;
-      [DISCARDED] = false;
+    exports2.PathPosix = PathPosix;
+    var PathScurryBase = class {
       /**
-       * true if the stream can be written
+       * The root Path entry for the current working directory of this Scurry
        */
-      writable = true;
+      root;
       /**
-       * true if the stream can be read
+       * The string path for the root of this Scurry's current working directory
        */
-      readable = true;
+      rootPath;
       /**
-       * If `RType` is Buffer, then options do not need to be provided.
-       * Otherwise, an options object must be provided to specify either
-       * {@link Minipass.SharedOptions.objectMode} or
-       * {@link Minipass.SharedOptions.encoding}, as appropriate.
+       * A collection of all roots encountered, referenced by rootPath
        */
-      constructor(...args) {
-        const options = args[0] || {};
-        super();
-        if (options.objectMode && typeof options.encoding === "string") {
-          throw new TypeError("Encoding and objectMode may not be used together");
-        }
-        if (isObjectModeOptions(options)) {
-          this[OBJECTMODE] = true;
-          this[ENCODING] = null;
-        } else if (isEncodingOptions(options)) {
-          this[ENCODING] = options.encoding;
-          this[OBJECTMODE] = false;
-        } else {
-          this[OBJECTMODE] = false;
-          this[ENCODING] = null;
+      roots;
+      /**
+       * The Path entry corresponding to this PathScurry's current working directory.
+       */
+      cwd;
+      #resolveCache;
+      #resolvePosixCache;
+      #children;
+      /**
+       * Perform path comparisons case-insensitively.
+       *
+       * Defaults true on Darwin and Windows systems, false elsewhere.
+       */
+      nocase;
+      #fs;
+      /**
+       * This class should not be instantiated directly.
+       *
+       * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
+       *
+       * @internal
+       */
+      constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs: fs2 = defaultFS } = {}) {
+        this.#fs = fsFromOption(fs2);
+        if (cwd instanceof URL || cwd.startsWith("file://")) {
+          cwd = (0, node_url_1.fileURLToPath)(cwd);
         }
-        this[ASYNC] = !!options.async;
-        this[DECODER] = this[ENCODING] ? new node_string_decoder_1.StringDecoder(this[ENCODING]) : null;
-        if (options && options.debugExposeBuffer === true) {
-          Object.defineProperty(this, "buffer", { get: () => this[BUFFER] });
+        const cwdPath = pathImpl.resolve(cwd);
+        this.roots = /* @__PURE__ */ Object.create(null);
+        this.rootPath = this.parseRootPath(cwdPath);
+        this.#resolveCache = new ResolveCache();
+        this.#resolvePosixCache = new ResolveCache();
+        this.#children = new ChildrenCache(childrenCacheSize);
+        const split = cwdPath.substring(this.rootPath.length).split(sep);
+        if (split.length === 1 && !split[0]) {
+          split.pop();
         }
-        if (options && options.debugExposePipes === true) {
-          Object.defineProperty(this, "pipes", { get: () => this[PIPES] });
+        if (nocase === void 0) {
+          throw new TypeError("must provide nocase setting to PathScurryBase ctor");
         }
-        const { signal } = options;
-        if (signal) {
-          this[SIGNAL] = signal;
-          if (signal.aborted) {
-            this[ABORT]();
-          } else {
-            signal.addEventListener("abort", () => this[ABORT]());
-          }
+        this.nocase = nocase;
+        this.root = this.newRoot(this.#fs);
+        this.roots[this.rootPath] = this.root;
+        let prev = this.root;
+        let len = split.length - 1;
+        const joinSep = pathImpl.sep;
+        let abs = this.rootPath;
+        let sawFirst = false;
+        for (const part of split) {
+          const l = len--;
+          prev = prev.child(part, {
+            relative: new Array(l).fill("..").join(joinSep),
+            relativePosix: new Array(l).fill("..").join("/"),
+            fullpath: abs += (sawFirst ? "" : joinSep) + part
+          });
+          sawFirst = true;
         }
+        this.cwd = prev;
       }
       /**
-       * The amount of data stored in the buffer waiting to be read.
-       *
-       * For Buffer strings, this will be the total byte length.
-       * For string encoding streams, this will be the string character length,
-       * according to JavaScript's `string.length` logic.
-       * For objectMode streams, this is a count of the items waiting to be
-       * emitted.
+       * Get the depth of a provided path, string, or the cwd
        */
-      get bufferLength() {
-        return this[BUFFERLENGTH];
+      depth(path2 = this.cwd) {
+        if (typeof path2 === "string") {
+          path2 = this.cwd.resolve(path2);
+        }
+        return path2.depth();
       }
       /**
-       * The `BufferEncoding` currently in use, or `null`
+       * Return the cache of child entries.  Exposed so subclasses can create
+       * child Path objects in a platform-specific way.
+       *
+       * @internal
        */
-      get encoding() {
-        return this[ENCODING];
+      childrenCache() {
+        return this.#children;
       }
       /**
-       * @deprecated - This is a read only property
+       * Resolve one or more path strings to a resolved string
+       *
+       * Same interface as require('path').resolve.
+       *
+       * Much faster than path.resolve() when called multiple times for the same
+       * path, because the resolved Path objects are cached.  Much slower
+       * otherwise.
        */
-      set encoding(_enc) {
-        throw new Error("Encoding must be set at instantiation time");
+      resolve(...paths) {
+        let r = "";
+        for (let i = paths.length - 1; i >= 0; i--) {
+          const p = paths[i];
+          if (!p || p === ".")
+            continue;
+          r = r ? `${p}/${r}` : p;
+          if (this.isAbsolute(p)) {
+            break;
+          }
+        }
+        const cached = this.#resolveCache.get(r);
+        if (cached !== void 0) {
+          return cached;
+        }
+        const result = this.cwd.resolve(r).fullpath();
+        this.#resolveCache.set(r, result);
+        return result;
       }
       /**
-       * @deprecated - Encoding may only be set at instantiation time
+       * Resolve one or more path strings to a resolved string, returning
+       * the posix path.  Identical to .resolve() on posix systems, but on
+       * windows will return a forward-slash separated UNC path.
+       *
+       * Same interface as require('path').resolve.
+       *
+       * Much faster than path.resolve() when called multiple times for the same
+       * path, because the resolved Path objects are cached.  Much slower
+       * otherwise.
        */
-      setEncoding(_enc) {
-        throw new Error("Encoding must be set at instantiation time");
+      resolvePosix(...paths) {
+        let r = "";
+        for (let i = paths.length - 1; i >= 0; i--) {
+          const p = paths[i];
+          if (!p || p === ".")
+            continue;
+          r = r ? `${p}/${r}` : p;
+          if (this.isAbsolute(p)) {
+            break;
+          }
+        }
+        const cached = this.#resolvePosixCache.get(r);
+        if (cached !== void 0) {
+          return cached;
+        }
+        const result = this.cwd.resolve(r).fullpathPosix();
+        this.#resolvePosixCache.set(r, result);
+        return result;
       }
       /**
-       * True if this is an objectMode stream
+       * find the relative path from the cwd to the supplied path string or entry
        */
-      get objectMode() {
-        return this[OBJECTMODE];
+      relative(entry = this.cwd) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        }
+        return entry.relative();
       }
       /**
-       * @deprecated - This is a read-only property
+       * find the relative path from the cwd to the supplied path string or
+       * entry, using / as the path delimiter, even on Windows.
        */
-      set objectMode(_om) {
-        throw new Error("objectMode must be set at instantiation time");
+      relativePosix(entry = this.cwd) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        }
+        return entry.relativePosix();
       }
       /**
-       * true if this is an async stream
+       * Return the basename for the provided string or Path object
        */
-      get ["async"]() {
-        return this[ASYNC];
+      basename(entry = this.cwd) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        }
+        return entry.name;
       }
       /**
-       * Set to true to make this stream async.
-       *
-       * Once set, it cannot be unset, as this would potentially cause incorrect
-       * behavior.  Ie, a sync stream can be made async, but an async stream
-       * cannot be safely made sync.
+       * Return the dirname for the provided string or Path object
        */
-      set ["async"](a) {
-        this[ASYNC] = this[ASYNC] || !!a;
+      dirname(entry = this.cwd) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        }
+        return (entry.parent || entry).fullpath();
       }
-      // drop everything and get out of the flow completely
-      [ABORT]() {
-        this[ABORTED] = true;
-        this.emit("abort", this[SIGNAL]?.reason);
-        this.destroy(this[SIGNAL]?.reason);
+      async readdir(entry = this.cwd, opts = {
+        withFileTypes: true
+      }) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          opts = entry;
+          entry = this.cwd;
+        }
+        const { withFileTypes } = opts;
+        if (!entry.canReaddir()) {
+          return [];
+        } else {
+          const p = await entry.readdir();
+          return withFileTypes ? p : p.map((e) => e.name);
+        }
+      }
+      readdirSync(entry = this.cwd, opts = {
+        withFileTypes: true
+      }) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          opts = entry;
+          entry = this.cwd;
+        }
+        const { withFileTypes = true } = opts;
+        if (!entry.canReaddir()) {
+          return [];
+        } else if (withFileTypes) {
+          return entry.readdirSync();
+        } else {
+          return entry.readdirSync().map((e) => e.name);
+        }
       }
       /**
-       * True if the stream has been aborted.
+       * Call lstat() on the string or Path object, and update all known
+       * information that can be determined.
+       *
+       * Note that unlike `fs.lstat()`, the returned value does not contain some
+       * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
+       * information is required, you will need to call `fs.lstat` yourself.
+       *
+       * If the Path refers to a nonexistent file, or if the lstat call fails for
+       * any reason, `undefined` is returned.  Otherwise the updated Path object is
+       * returned.
+       *
+       * Results are cached, and thus may be out of date if the filesystem is
+       * mutated.
        */
-      get aborted() {
-        return this[ABORTED];
+      async lstat(entry = this.cwd) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        }
+        return entry.lstat();
       }
       /**
-       * No-op setter. Stream aborted status is set via the AbortSignal provided
-       * in the constructor options.
+       * synchronous {@link PathScurryBase.lstat}
        */
-      set aborted(_2) {
+      lstatSync(entry = this.cwd) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        }
+        return entry.lstatSync();
       }
-      write(chunk, encoding, cb) {
-        if (this[ABORTED])
-          return false;
-        if (this[EOF])
-          throw new Error("write after end");
-        if (this[DESTROYED]) {
-          this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" }));
-          return true;
+      async readlink(entry = this.cwd, { withFileTypes } = {
+        withFileTypes: false
+      }) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          withFileTypes = entry.withFileTypes;
+          entry = this.cwd;
         }
-        if (typeof encoding === "function") {
-          cb = encoding;
-          encoding = "utf8";
+        const e = await entry.readlink();
+        return withFileTypes ? e : e?.fullpath();
+      }
+      readlinkSync(entry = this.cwd, { withFileTypes } = {
+        withFileTypes: false
+      }) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          withFileTypes = entry.withFileTypes;
+          entry = this.cwd;
         }
-        if (!encoding)
-          encoding = "utf8";
-        const fn = this[ASYNC] ? defer : nodefer;
-        if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
-          if (isArrayBufferView(chunk)) {
-            chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
-          } else if (isArrayBufferLike(chunk)) {
-            chunk = Buffer.from(chunk);
-          } else if (typeof chunk !== "string") {
-            throw new Error("Non-contiguous data written to non-objectMode stream");
-          }
+        const e = entry.readlinkSync();
+        return withFileTypes ? e : e?.fullpath();
+      }
+      async realpath(entry = this.cwd, { withFileTypes } = {
+        withFileTypes: false
+      }) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          withFileTypes = entry.withFileTypes;
+          entry = this.cwd;
         }
-        if (this[OBJECTMODE]) {
-          if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
-            this[FLUSH](true);
-          if (this[FLOWING])
-            this.emit("data", chunk);
-          else
-            this[BUFFERPUSH](chunk);
-          if (this[BUFFERLENGTH] !== 0)
-            this.emit("readable");
-          if (cb)
-            fn(cb);
-          return this[FLOWING];
+        const e = await entry.realpath();
+        return withFileTypes ? e : e?.fullpath();
+      }
+      realpathSync(entry = this.cwd, { withFileTypes } = {
+        withFileTypes: false
+      }) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          withFileTypes = entry.withFileTypes;
+          entry = this.cwd;
         }
-        if (!chunk.length) {
-          if (this[BUFFERLENGTH] !== 0)
-            this.emit("readable");
-          if (cb)
-            fn(cb);
-          return this[FLOWING];
+        const e = entry.realpathSync();
+        return withFileTypes ? e : e?.fullpath();
+      }
+      async walk(entry = this.cwd, opts = {}) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          opts = entry;
+          entry = this.cwd;
         }
-        if (typeof chunk === "string" && // unless it is a string already ready for us to use
-        !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
-          chunk = Buffer.from(chunk, encoding);
+        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
+        const results = [];
+        if (!filter || filter(entry)) {
+          results.push(withFileTypes ? entry : entry.fullpath());
         }
-        if (Buffer.isBuffer(chunk) && this[ENCODING]) {
-          chunk = this[DECODER].write(chunk);
+        const dirs = /* @__PURE__ */ new Set();
+        const walk = (dir, cb) => {
+          dirs.add(dir);
+          dir.readdirCB((er, entries) => {
+            if (er) {
+              return cb(er);
+            }
+            let len = entries.length;
+            if (!len)
+              return cb();
+            const next = () => {
+              if (--len === 0) {
+                cb();
+              }
+            };
+            for (const e of entries) {
+              if (!filter || filter(e)) {
+                results.push(withFileTypes ? e : e.fullpath());
+              }
+              if (follow && e.isSymbolicLink()) {
+                e.realpath().then((r) => r?.isUnknown() ? r.lstat() : r).then((r) => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next());
+              } else {
+                if (e.shouldWalk(dirs, walkFilter)) {
+                  walk(e, next);
+                } else {
+                  next();
+                }
+              }
+            }
+          }, true);
+        };
+        const start = entry;
+        return new Promise((res, rej) => {
+          walk(start, (er) => {
+            if (er)
+              return rej(er);
+            res(results);
+          });
+        });
+      }
+      walkSync(entry = this.cwd, opts = {}) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          opts = entry;
+          entry = this.cwd;
         }
-        if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
-          this[FLUSH](true);
-        if (this[FLOWING])
-          this.emit("data", chunk);
-        else
-          this[BUFFERPUSH](chunk);
-        if (this[BUFFERLENGTH] !== 0)
-          this.emit("readable");
-        if (cb)
-          fn(cb);
-        return this[FLOWING];
+        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
+        const results = [];
+        if (!filter || filter(entry)) {
+          results.push(withFileTypes ? entry : entry.fullpath());
+        }
+        const dirs = /* @__PURE__ */ new Set([entry]);
+        for (const dir of dirs) {
+          const entries = dir.readdirSync();
+          for (const e of entries) {
+            if (!filter || filter(e)) {
+              results.push(withFileTypes ? e : e.fullpath());
+            }
+            let r = e;
+            if (e.isSymbolicLink()) {
+              if (!(follow && (r = e.realpathSync())))
+                continue;
+              if (r.isUnknown())
+                r.lstatSync();
+            }
+            if (r.shouldWalk(dirs, walkFilter)) {
+              dirs.add(r);
+            }
+          }
+        }
+        return results;
       }
       /**
-       * Low-level explicit read method.
+       * Support for `for await`
        *
-       * In objectMode, the argument is ignored, and one item is returned if
-       * available.
+       * Alias for {@link PathScurryBase.iterate}
        *
-       * `n` is the number of bytes (or in the case of encoding streams,
-       * characters) to consume. If `n` is not provided, then the entire buffer
-       * is returned, or `null` is returned if no data is available.
+       * Note: As of Node 19, this is very slow, compared to other methods of
+       * walking.  Consider using {@link PathScurryBase.stream} if memory overhead
+       * and backpressure are concerns, or {@link PathScurryBase.walk} if not.
+       */
+      [Symbol.asyncIterator]() {
+        return this.iterate();
+      }
+      iterate(entry = this.cwd, options = {}) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          options = entry;
+          entry = this.cwd;
+        }
+        return this.stream(entry, options)[Symbol.asyncIterator]();
+      }
+      /**
+       * Iterating over a PathScurry performs a synchronous walk.
        *
-       * If `n` is greater that the amount of data in the internal buffer,
-       * then `null` is returned.
+       * Alias for {@link PathScurryBase.iterateSync}
        */
-      read(n) {
-        if (this[DESTROYED])
-          return null;
-        this[DISCARDED] = false;
-        if (this[BUFFERLENGTH] === 0 || n === 0 || n && n > this[BUFFERLENGTH]) {
-          this[MAYBE_EMIT_END]();
-          return null;
+      [Symbol.iterator]() {
+        return this.iterateSync();
+      }
+      *iterateSync(entry = this.cwd, opts = {}) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          opts = entry;
+          entry = this.cwd;
         }
-        if (this[OBJECTMODE])
-          n = null;
-        if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
-          this[BUFFER] = [
-            this[ENCODING] ? this[BUFFER].join("") : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])
-          ];
+        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
+        if (!filter || filter(entry)) {
+          yield withFileTypes ? entry : entry.fullpath();
+        }
+        const dirs = /* @__PURE__ */ new Set([entry]);
+        for (const dir of dirs) {
+          const entries = dir.readdirSync();
+          for (const e of entries) {
+            if (!filter || filter(e)) {
+              yield withFileTypes ? e : e.fullpath();
+            }
+            let r = e;
+            if (e.isSymbolicLink()) {
+              if (!(follow && (r = e.realpathSync())))
+                continue;
+              if (r.isUnknown())
+                r.lstatSync();
+            }
+            if (r.shouldWalk(dirs, walkFilter)) {
+              dirs.add(r);
+            }
+          }
         }
-        const ret = this[READ](n || null, this[BUFFER][0]);
-        this[MAYBE_EMIT_END]();
-        return ret;
       }
-      [READ](n, chunk) {
-        if (this[OBJECTMODE])
-          this[BUFFERSHIFT]();
-        else {
-          const c = chunk;
-          if (n === c.length || n === null)
-            this[BUFFERSHIFT]();
-          else if (typeof c === "string") {
-            this[BUFFER][0] = c.slice(n);
-            chunk = c.slice(0, n);
-            this[BUFFERLENGTH] -= n;
-          } else {
-            this[BUFFER][0] = c.subarray(n);
-            chunk = c.subarray(0, n);
-            this[BUFFERLENGTH] -= n;
+      stream(entry = this.cwd, opts = {}) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          opts = entry;
+          entry = this.cwd;
+        }
+        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
+        const results = new minipass_1.Minipass({ objectMode: true });
+        if (!filter || filter(entry)) {
+          results.write(withFileTypes ? entry : entry.fullpath());
+        }
+        const dirs = /* @__PURE__ */ new Set();
+        const queue = [entry];
+        let processing = 0;
+        const process2 = () => {
+          let paused = false;
+          while (!paused) {
+            const dir = queue.shift();
+            if (!dir) {
+              if (processing === 0)
+                results.end();
+              return;
+            }
+            processing++;
+            dirs.add(dir);
+            const onReaddir = (er, entries, didRealpaths = false) => {
+              if (er)
+                return results.emit("error", er);
+              if (follow && !didRealpaths) {
+                const promises2 = [];
+                for (const e of entries) {
+                  if (e.isSymbolicLink()) {
+                    promises2.push(e.realpath().then((r) => r?.isUnknown() ? r.lstat() : r));
+                  }
+                }
+                if (promises2.length) {
+                  Promise.all(promises2).then(() => onReaddir(null, entries, true));
+                  return;
+                }
+              }
+              for (const e of entries) {
+                if (e && (!filter || filter(e))) {
+                  if (!results.write(withFileTypes ? e : e.fullpath())) {
+                    paused = true;
+                  }
+                }
+              }
+              processing--;
+              for (const e of entries) {
+                const r = e.realpathCached() || e;
+                if (r.shouldWalk(dirs, walkFilter)) {
+                  queue.push(r);
+                }
+              }
+              if (paused && !results.flowing) {
+                results.once("drain", process2);
+              } else if (!sync) {
+                process2();
+              }
+            };
+            let sync = true;
+            dir.readdirCB(onReaddir, true);
+            sync = false;
           }
-        }
-        this.emit("data", chunk);
-        if (!this[BUFFER].length && !this[EOF])
-          this.emit("drain");
-        return chunk;
+        };
+        process2();
+        return results;
       }
-      end(chunk, encoding, cb) {
-        if (typeof chunk === "function") {
-          cb = chunk;
-          chunk = void 0;
-        }
-        if (typeof encoding === "function") {
-          cb = encoding;
-          encoding = "utf8";
+      streamSync(entry = this.cwd, opts = {}) {
+        if (typeof entry === "string") {
+          entry = this.cwd.resolve(entry);
+        } else if (!(entry instanceof PathBase)) {
+          opts = entry;
+          entry = this.cwd;
         }
-        if (chunk !== void 0)
-          this.write(chunk, encoding);
-        if (cb)
-          this.once("end", cb);
-        this[EOF] = true;
-        this.writable = false;
-        if (this[FLOWING] || !this[PAUSED])
-          this[MAYBE_EMIT_END]();
-        return this;
-      }
-      // don't let the internal resume be overwritten
-      [RESUME]() {
-        if (this[DESTROYED])
-          return;
-        if (!this[DATALISTENERS] && !this[PIPES].length) {
-          this[DISCARDED] = true;
+        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
+        const results = new minipass_1.Minipass({ objectMode: true });
+        const dirs = /* @__PURE__ */ new Set();
+        if (!filter || filter(entry)) {
+          results.write(withFileTypes ? entry : entry.fullpath());
         }
-        this[PAUSED] = false;
-        this[FLOWING] = true;
-        this.emit("resume");
-        if (this[BUFFER].length)
-          this[FLUSH]();
-        else if (this[EOF])
-          this[MAYBE_EMIT_END]();
-        else
-          this.emit("drain");
+        const queue = [entry];
+        let processing = 0;
+        const process2 = () => {
+          let paused = false;
+          while (!paused) {
+            const dir = queue.shift();
+            if (!dir) {
+              if (processing === 0)
+                results.end();
+              return;
+            }
+            processing++;
+            dirs.add(dir);
+            const entries = dir.readdirSync();
+            for (const e of entries) {
+              if (!filter || filter(e)) {
+                if (!results.write(withFileTypes ? e : e.fullpath())) {
+                  paused = true;
+                }
+              }
+            }
+            processing--;
+            for (const e of entries) {
+              let r = e;
+              if (e.isSymbolicLink()) {
+                if (!(follow && (r = e.realpathSync())))
+                  continue;
+                if (r.isUnknown())
+                  r.lstatSync();
+              }
+              if (r.shouldWalk(dirs, walkFilter)) {
+                queue.push(r);
+              }
+            }
+          }
+          if (paused && !results.flowing)
+            results.once("drain", process2);
+        };
+        process2();
+        return results;
       }
-      /**
-       * Resume the stream if it is currently in a paused state
-       *
-       * If called when there are no pipe destinations or `data` event listeners,
-       * this will place the stream in a "discarded" state, where all data will
-       * be thrown away. The discarded state is removed if a pipe destination or
-       * data handler is added, if pause() is called, or if any synchronous or
-       * asynchronous iteration is started.
-       */
-      resume() {
-        return this[RESUME]();
+      chdir(path2 = this.cwd) {
+        const oldCwd = this.cwd;
+        this.cwd = typeof path2 === "string" ? this.cwd.resolve(path2) : path2;
+        this.cwd[setAsCwd](oldCwd);
       }
+    };
+    exports2.PathScurryBase = PathScurryBase;
+    var PathScurryWin32 = class extends PathScurryBase {
       /**
-       * Pause the stream
+       * separator for generating path strings
        */
-      pause() {
-        this[FLOWING] = false;
-        this[PAUSED] = true;
-        this[DISCARDED] = false;
+      sep = "\\";
+      constructor(cwd = process.cwd(), opts = {}) {
+        const { nocase = true } = opts;
+        super(cwd, node_path_1.win32, "\\", { ...opts, nocase });
+        this.nocase = nocase;
+        for (let p = this.cwd; p; p = p.parent) {
+          p.nocase = this.nocase;
+        }
       }
       /**
-       * true if the stream has been forcibly destroyed
+       * @internal
        */
-      get destroyed() {
-        return this[DESTROYED];
+      parseRootPath(dir) {
+        return node_path_1.win32.parse(dir).root.toUpperCase();
       }
       /**
-       * true if the stream is currently in a flowing state, meaning that
-       * any writes will be immediately emitted.
+       * @internal
        */
-      get flowing() {
-        return this[FLOWING];
+      newRoot(fs2) {
+        return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
       }
       /**
-       * true if the stream is currently in a paused state
+       * Return true if the provided path string is an absolute path
        */
-      get paused() {
-        return this[PAUSED];
-      }
-      [BUFFERPUSH](chunk) {
-        if (this[OBJECTMODE])
-          this[BUFFERLENGTH] += 1;
-        else
-          this[BUFFERLENGTH] += chunk.length;
-        this[BUFFER].push(chunk);
-      }
-      [BUFFERSHIFT]() {
-        if (this[OBJECTMODE])
-          this[BUFFERLENGTH] -= 1;
-        else
-          this[BUFFERLENGTH] -= this[BUFFER][0].length;
-        return this[BUFFER].shift();
-      }
-      [FLUSH](noDrain = false) {
-        do {
-        } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length);
-        if (!noDrain && !this[BUFFER].length && !this[EOF])
-          this.emit("drain");
-      }
-      [FLUSHCHUNK](chunk) {
-        this.emit("data", chunk);
-        return this[FLOWING];
+      isAbsolute(p) {
+        return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
       }
+    };
+    exports2.PathScurryWin32 = PathScurryWin32;
+    var PathScurryPosix = class extends PathScurryBase {
       /**
-       * Pipe all data emitted by this stream into the destination provided.
-       *
-       * Triggers the flow of data.
+       * separator for generating path strings
        */
-      pipe(dest, opts) {
-        if (this[DESTROYED])
-          return dest;
-        this[DISCARDED] = false;
-        const ended = this[EMITTED_END];
-        opts = opts || {};
-        if (dest === proc.stdout || dest === proc.stderr)
-          opts.end = false;
-        else
-          opts.end = opts.end !== false;
-        opts.proxyErrors = !!opts.proxyErrors;
-        if (ended) {
-          if (opts.end)
-            dest.end();
-        } else {
-          this[PIPES].push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts));
-          if (this[ASYNC])
-            defer(() => this[RESUME]());
-          else
-            this[RESUME]();
-        }
-        return dest;
+      sep = "/";
+      constructor(cwd = process.cwd(), opts = {}) {
+        const { nocase = false } = opts;
+        super(cwd, node_path_1.posix, "/", { ...opts, nocase });
+        this.nocase = nocase;
       }
       /**
-       * Fully unhook a piped destination stream.
-       *
-       * If the destination stream was the only consumer of this stream (ie,
-       * there are no other piped destinations or `'data'` event listeners)
-       * then the flow of data will stop until there is another consumer or
-       * {@link Minipass#resume} is explicitly called.
+       * @internal
        */
-      unpipe(dest) {
-        const p = this[PIPES].find((p2) => p2.dest === dest);
-        if (p) {
-          if (this[PIPES].length === 1) {
-            if (this[FLOWING] && this[DATALISTENERS] === 0) {
-              this[FLOWING] = false;
-            }
-            this[PIPES] = [];
-          } else
-            this[PIPES].splice(this[PIPES].indexOf(p), 1);
-          p.unpipe();
-        }
+      parseRootPath(_dir) {
+        return "/";
       }
       /**
-       * Alias for {@link Minipass#on}
+       * @internal
        */
-      addListener(ev, handler) {
-        return this.on(ev, handler);
+      newRoot(fs2) {
+        return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
       }
       /**
-       * Mostly identical to `EventEmitter.on`, with the following
-       * behavior differences to prevent data loss and unnecessary hangs:
-       *
-       * - Adding a 'data' event handler will trigger the flow of data
-       *
-       * - Adding a 'readable' event handler when there is data waiting to be read
-       *   will cause 'readable' to be emitted immediately.
-       *
-       * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
-       *   already passed will cause the event to be emitted immediately and all
-       *   handlers removed.
-       *
-       * - Adding an 'error' event handler after an error has been emitted will
-       *   cause the event to be re-emitted immediately with the error previously
-       *   raised.
+       * Return true if the provided path string is an absolute path
        */
-      on(ev, handler) {
-        const ret = super.on(ev, handler);
-        if (ev === "data") {
-          this[DISCARDED] = false;
-          this[DATALISTENERS]++;
-          if (!this[PIPES].length && !this[FLOWING]) {
-            this[RESUME]();
-          }
-        } else if (ev === "readable" && this[BUFFERLENGTH] !== 0) {
-          super.emit("readable");
-        } else if (isEndish(ev) && this[EMITTED_END]) {
-          super.emit(ev);
-          this.removeAllListeners(ev);
-        } else if (ev === "error" && this[EMITTED_ERROR]) {
-          const h = handler;
-          if (this[ASYNC])
-            defer(() => h.call(this, this[EMITTED_ERROR]));
-          else
-            h.call(this, this[EMITTED_ERROR]);
-        }
-        return ret;
+      isAbsolute(p) {
+        return p.startsWith("/");
       }
-      /**
-       * Alias for {@link Minipass#off}
-       */
-      removeListener(ev, handler) {
-        return this.off(ev, handler);
+    };
+    exports2.PathScurryPosix = PathScurryPosix;
+    var PathScurryDarwin = class extends PathScurryPosix {
+      constructor(cwd = process.cwd(), opts = {}) {
+        const { nocase = true } = opts;
+        super(cwd, { ...opts, nocase });
       }
-      /**
-       * Mostly identical to `EventEmitter.off`
-       *
-       * If a 'data' event handler is removed, and it was the last consumer
-       * (ie, there are no pipe destinations or other 'data' event listeners),
-       * then the flow of data will stop until there is another consumer or
-       * {@link Minipass#resume} is explicitly called.
-       */
-      off(ev, handler) {
-        const ret = super.off(ev, handler);
-        if (ev === "data") {
-          this[DATALISTENERS] = this.listeners("data").length;
-          if (this[DATALISTENERS] === 0 && !this[DISCARDED] && !this[PIPES].length) {
-            this[FLOWING] = false;
+    };
+    exports2.PathScurryDarwin = PathScurryDarwin;
+    exports2.Path = process.platform === "win32" ? PathWin32 : PathPosix;
+    exports2.PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
+  }
+});
+
+// node_modules/archiver-utils/node_modules/glob/dist/commonjs/pattern.js
+var require_pattern = __commonJS({
+  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/pattern.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.Pattern = void 0;
+    var minimatch_1 = require_commonjs13();
+    var isPatternList = (pl) => pl.length >= 1;
+    var isGlobList = (gl) => gl.length >= 1;
+    var Pattern = class _Pattern {
+      #patternList;
+      #globList;
+      #index;
+      length;
+      #platform;
+      #rest;
+      #globString;
+      #isDrive;
+      #isUNC;
+      #isAbsolute;
+      #followGlobstar = true;
+      constructor(patternList, globList, index, platform) {
+        if (!isPatternList(patternList)) {
+          throw new TypeError("empty pattern list");
+        }
+        if (!isGlobList(globList)) {
+          throw new TypeError("empty glob list");
+        }
+        if (globList.length !== patternList.length) {
+          throw new TypeError("mismatched pattern list and glob list lengths");
+        }
+        this.length = patternList.length;
+        if (index < 0 || index >= this.length) {
+          throw new TypeError("index out of range");
+        }
+        this.#patternList = patternList;
+        this.#globList = globList;
+        this.#index = index;
+        this.#platform = platform;
+        if (this.#index === 0) {
+          if (this.isUNC()) {
+            const [p0, p1, p2, p3, ...prest] = this.#patternList;
+            const [g0, g1, g2, g3, ...grest] = this.#globList;
+            if (prest[0] === "") {
+              prest.shift();
+              grest.shift();
+            }
+            const p = [p0, p1, p2, p3, ""].join("/");
+            const g = [g0, g1, g2, g3, ""].join("/");
+            this.#patternList = [p, ...prest];
+            this.#globList = [g, ...grest];
+            this.length = this.#patternList.length;
+          } else if (this.isDrive() || this.isAbsolute()) {
+            const [p1, ...prest] = this.#patternList;
+            const [g1, ...grest] = this.#globList;
+            if (prest[0] === "") {
+              prest.shift();
+              grest.shift();
+            }
+            const p = p1 + "/";
+            const g = g1 + "/";
+            this.#patternList = [p, ...prest];
+            this.#globList = [g, ...grest];
+            this.length = this.#patternList.length;
           }
         }
-        return ret;
       }
       /**
-       * Mostly identical to `EventEmitter.removeAllListeners`
-       *
-       * If all 'data' event handlers are removed, and they were the last consumer
-       * (ie, there are no pipe destinations), then the flow of data will stop
-       * until there is another consumer or {@link Minipass#resume} is explicitly
-       * called.
+       * The first entry in the parsed list of patterns
        */
-      removeAllListeners(ev) {
-        const ret = super.removeAllListeners(ev);
-        if (ev === "data" || ev === void 0) {
-          this[DATALISTENERS] = 0;
-          if (!this[DISCARDED] && !this[PIPES].length) {
-            this[FLOWING] = false;
-          }
-        }
-        return ret;
+      pattern() {
+        return this.#patternList[this.#index];
       }
       /**
-       * true if the 'end' event has been emitted
+       * true of if pattern() returns a string
        */
-      get emittedEnd() {
-        return this[EMITTED_END];
-      }
-      [MAYBE_EMIT_END]() {
-        if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF]) {
-          this[EMITTING_END] = true;
-          this.emit("end");
-          this.emit("prefinish");
-          this.emit("finish");
-          if (this[CLOSED])
-            this.emit("close");
-          this[EMITTING_END] = false;
-        }
+      isString() {
+        return typeof this.#patternList[this.#index] === "string";
       }
       /**
-       * Mostly identical to `EventEmitter.emit`, with the following
-       * behavior differences to prevent data loss and unnecessary hangs:
-       *
-       * If the stream has been destroyed, and the event is something other
-       * than 'close' or 'error', then `false` is returned and no handlers
-       * are called.
-       *
-       * If the event is 'end', and has already been emitted, then the event
-       * is ignored. If the stream is in a paused or non-flowing state, then
-       * the event will be deferred until data flow resumes. If the stream is
-       * async, then handlers will be called on the next tick rather than
-       * immediately.
-       *
-       * If the event is 'close', and 'end' has not yet been emitted, then
-       * the event will be deferred until after 'end' is emitted.
-       *
-       * If the event is 'error', and an AbortSignal was provided for the stream,
-       * and there are no listeners, then the event is ignored, matching the
-       * behavior of node core streams in the presense of an AbortSignal.
-       *
-       * If the event is 'finish' or 'prefinish', then all listeners will be
-       * removed after emitting the event, to prevent double-firing.
+       * true of if pattern() returns GLOBSTAR
        */
-      emit(ev, ...args) {
-        const data = args[0];
-        if (ev !== "error" && ev !== "close" && ev !== DESTROYED && this[DESTROYED]) {
-          return false;
-        } else if (ev === "data") {
-          return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? (defer(() => this[EMITDATA](data)), true) : this[EMITDATA](data);
-        } else if (ev === "end") {
-          return this[EMITEND]();
-        } else if (ev === "close") {
-          this[CLOSED] = true;
-          if (!this[EMITTED_END] && !this[DESTROYED])
-            return false;
-          const ret2 = super.emit("close");
-          this.removeAllListeners("close");
-          return ret2;
-        } else if (ev === "error") {
-          this[EMITTED_ERROR] = data;
-          super.emit(ERROR, data);
-          const ret2 = !this[SIGNAL] || this.listeners("error").length ? super.emit("error", data) : false;
-          this[MAYBE_EMIT_END]();
-          return ret2;
-        } else if (ev === "resume") {
-          const ret2 = super.emit("resume");
-          this[MAYBE_EMIT_END]();
-          return ret2;
-        } else if (ev === "finish" || ev === "prefinish") {
-          const ret2 = super.emit(ev);
-          this.removeAllListeners(ev);
-          return ret2;
-        }
-        const ret = super.emit(ev, ...args);
-        this[MAYBE_EMIT_END]();
-        return ret;
+      isGlobstar() {
+        return this.#patternList[this.#index] === minimatch_1.GLOBSTAR;
       }
-      [EMITDATA](data) {
-        for (const p of this[PIPES]) {
-          if (p.dest.write(data) === false)
-            this.pause();
-        }
-        const ret = this[DISCARDED] ? false : super.emit("data", data);
-        this[MAYBE_EMIT_END]();
-        return ret;
+      /**
+       * true if pattern() returns a regexp
+       */
+      isRegExp() {
+        return this.#patternList[this.#index] instanceof RegExp;
       }
-      [EMITEND]() {
-        if (this[EMITTED_END])
-          return false;
-        this[EMITTED_END] = true;
-        this.readable = false;
-        return this[ASYNC] ? (defer(() => this[EMITEND2]()), true) : this[EMITEND2]();
+      /**
+       * The /-joined set of glob parts that make up this pattern
+       */
+      globString() {
+        return this.#globString = this.#globString || (this.#index === 0 ? this.isAbsolute() ? this.#globList[0] + this.#globList.slice(1).join("/") : this.#globList.join("/") : this.#globList.slice(this.#index).join("/"));
       }
-      [EMITEND2]() {
-        if (this[DECODER]) {
-          const data = this[DECODER].end();
-          if (data) {
-            for (const p of this[PIPES]) {
-              p.dest.write(data);
-            }
-            if (!this[DISCARDED])
-              super.emit("data", data);
-          }
-        }
-        for (const p of this[PIPES]) {
-          p.end();
-        }
-        const ret = super.emit("end");
-        this.removeAllListeners("end");
-        return ret;
+      /**
+       * true if there are more pattern parts after this one
+       */
+      hasMore() {
+        return this.length > this.#index + 1;
       }
       /**
-       * Return a Promise that resolves to an array of all emitted data once
-       * the stream ends.
+       * The rest of the pattern after this part, or null if this is the end
        */
-      async collect() {
-        const buf = Object.assign([], {
-          dataLength: 0
-        });
-        if (!this[OBJECTMODE])
-          buf.dataLength = 0;
-        const p = this.promise();
-        this.on("data", (c) => {
-          buf.push(c);
-          if (!this[OBJECTMODE])
-            buf.dataLength += c.length;
-        });
-        await p;
-        return buf;
+      rest() {
+        if (this.#rest !== void 0)
+          return this.#rest;
+        if (!this.hasMore())
+          return this.#rest = null;
+        this.#rest = new _Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
+        this.#rest.#isAbsolute = this.#isAbsolute;
+        this.#rest.#isUNC = this.#isUNC;
+        this.#rest.#isDrive = this.#isDrive;
+        return this.#rest;
       }
       /**
-       * Return a Promise that resolves to the concatenation of all emitted data
-       * once the stream ends.
-       *
-       * Not allowed on objectMode streams.
+       * true if the pattern represents a //unc/path/ on windows
        */
-      async concat() {
-        if (this[OBJECTMODE]) {
-          throw new Error("cannot concat in objectMode");
-        }
-        const buf = await this.collect();
-        return this[ENCODING] ? buf.join("") : Buffer.concat(buf, buf.dataLength);
+      isUNC() {
+        const pl = this.#patternList;
+        return this.#isUNC !== void 0 ? this.#isUNC : this.#isUNC = this.#platform === "win32" && this.#index === 0 && pl[0] === "" && pl[1] === "" && typeof pl[2] === "string" && !!pl[2] && typeof pl[3] === "string" && !!pl[3];
       }
+      // pattern like C:/...
+      // split = ['C:', ...]
+      // XXX: would be nice to handle patterns like `c:*` to test the cwd
+      // in c: for *, but I don't know of a way to even figure out what that
+      // cwd is without actually chdir'ing into it?
       /**
-       * Return a void Promise that resolves once the stream ends.
+       * True if the pattern starts with a drive letter on Windows
        */
-      async promise() {
-        return new Promise((resolve2, reject) => {
-          this.on(DESTROYED, () => reject(new Error("stream destroyed")));
-          this.on("error", (er) => reject(er));
-          this.on("end", () => resolve2());
-        });
+      isDrive() {
+        const pl = this.#patternList;
+        return this.#isDrive !== void 0 ? this.#isDrive : this.#isDrive = this.#platform === "win32" && this.#index === 0 && this.length > 1 && typeof pl[0] === "string" && /^[a-z]:$/i.test(pl[0]);
       }
+      // pattern = '/' or '/...' or '/x/...'
+      // split = ['', ''] or ['', ...] or ['', 'x', ...]
+      // Drive and UNC both considered absolute on windows
       /**
-       * Asynchronous `for await of` iteration.
-       *
-       * This will continue emitting all chunks until the stream terminates.
+       * True if the pattern is rooted on an absolute path
        */
-      [Symbol.asyncIterator]() {
-        this[DISCARDED] = false;
-        let stopped = false;
-        const stop = async () => {
-          this.pause();
-          stopped = true;
-          return { value: void 0, done: true };
-        };
-        const next = () => {
-          if (stopped)
-            return stop();
-          const res = this.read();
-          if (res !== null)
-            return Promise.resolve({ done: false, value: res });
-          if (this[EOF])
-            return stop();
-          let resolve2;
-          let reject;
-          const onerr = (er) => {
-            this.off("data", ondata);
-            this.off("end", onend);
-            this.off(DESTROYED, ondestroy);
-            stop();
-            reject(er);
-          };
-          const ondata = (value) => {
-            this.off("error", onerr);
-            this.off("end", onend);
-            this.off(DESTROYED, ondestroy);
-            this.pause();
-            resolve2({ value, done: !!this[EOF] });
-          };
-          const onend = () => {
-            this.off("error", onerr);
-            this.off("data", ondata);
-            this.off(DESTROYED, ondestroy);
-            stop();
-            resolve2({ done: true, value: void 0 });
-          };
-          const ondestroy = () => onerr(new Error("stream destroyed"));
-          return new Promise((res2, rej) => {
-            reject = rej;
-            resolve2 = res2;
-            this.once(DESTROYED, ondestroy);
-            this.once("error", onerr);
-            this.once("end", onend);
-            this.once("data", ondata);
-          });
-        };
-        return {
-          next,
-          throw: stop,
-          return: stop,
-          [Symbol.asyncIterator]() {
-            return this;
-          }
-        };
+      isAbsolute() {
+        const pl = this.#patternList;
+        return this.#isAbsolute !== void 0 ? this.#isAbsolute : this.#isAbsolute = pl[0] === "" && pl.length > 1 || this.isDrive() || this.isUNC();
       }
       /**
-       * Synchronous `for of` iteration.
-       *
-       * The iteration will terminate when the internal buffer runs out, even
-       * if the stream has not yet terminated.
+       * consume the root of the pattern, and return it
        */
-      [Symbol.iterator]() {
-        this[DISCARDED] = false;
-        let stopped = false;
-        const stop = () => {
-          this.pause();
-          this.off(ERROR, stop);
-          this.off(DESTROYED, stop);
-          this.off("end", stop);
-          stopped = true;
-          return { done: true, value: void 0 };
-        };
-        const next = () => {
-          if (stopped)
-            return stop();
-          const value = this.read();
-          return value === null ? stop() : { done: false, value };
-        };
-        this.once("end", stop);
-        this.once(ERROR, stop);
-        this.once(DESTROYED, stop);
-        return {
-          next,
-          throw: stop,
-          return: stop,
-          [Symbol.iterator]() {
-            return this;
-          }
-        };
+      root() {
+        const p = this.#patternList[0];
+        return typeof p === "string" && this.isAbsolute() && this.#index === 0 ? p : "";
       }
       /**
-       * Destroy a stream, preventing it from being used for any further purpose.
-       *
-       * If the stream has a `close()` method, then it will be called on
-       * destruction.
-       *
-       * After destruction, any attempt to write data, read data, or emit most
-       * events will be ignored.
-       *
-       * If an error argument is provided, then it will be emitted in an
-       * 'error' event.
+       * Check to see if the current globstar pattern is allowed to follow
+       * a symbolic link.
        */
-      destroy(er) {
-        if (this[DESTROYED]) {
-          if (er)
-            this.emit("error", er);
-          else
-            this.emit(DESTROYED);
-          return this;
-        }
-        this[DESTROYED] = true;
-        this[DISCARDED] = true;
-        this[BUFFER].length = 0;
-        this[BUFFERLENGTH] = 0;
-        const wc = this;
-        if (typeof wc.close === "function" && !this[CLOSED])
-          wc.close();
-        if (er)
-          this.emit("error", er);
-        else
-          this.emit(DESTROYED);
-        return this;
+      checkFollowGlobstar() {
+        return !(this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar);
       }
       /**
-       * Alias for {@link isStream}
-       *
-       * Former export location, maintained for backwards compatibility.
-       *
-       * @deprecated
+       * Mark that the current globstar pattern is following a symbolic link
        */
-      static get isStream() {
-        return exports2.isStream;
+      markFollowGlobstar() {
+        if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
+          return false;
+        this.#followGlobstar = false;
+        return true;
       }
     };
-    exports2.Minipass = Minipass;
+    exports2.Pattern = Pattern;
   }
 });
 
-// node_modules/archiver-utils/node_modules/path-scurry/dist/commonjs/index.js
-var require_commonjs16 = __commonJS({
-  "node_modules/archiver-utils/node_modules/path-scurry/dist/commonjs/index.js"(exports2) {
+// node_modules/archiver-utils/node_modules/glob/dist/commonjs/ignore.js
+var require_ignore = __commonJS({
+  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/ignore.js"(exports2) {
     "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.Ignore = void 0;
+    var minimatch_1 = require_commonjs13();
+    var pattern_js_1 = require_pattern();
+    var defaultPlatform = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
+    var Ignore = class {
+      relative;
+      relativeChildren;
+      absolute;
+      absoluteChildren;
+      platform;
+      mmopts;
+      constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform }) {
+        this.relative = [];
+        this.absolute = [];
+        this.relativeChildren = [];
+        this.absoluteChildren = [];
+        this.platform = platform;
+        this.mmopts = {
+          dot: true,
+          nobrace,
+          nocase,
+          noext,
+          noglobstar,
+          optimizationLevel: 2,
+          platform,
+          nocomment: true,
+          nonegate: true
+        };
+        for (const ign of ignored)
+          this.add(ign);
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      add(ign) {
+        const mm = new minimatch_1.Minimatch(ign, this.mmopts);
+        for (let i = 0; i < mm.set.length; i++) {
+          const parsed = mm.set[i];
+          const globParts = mm.globParts[i];
+          if (!parsed || !globParts) {
+            throw new Error("invalid pattern object");
+          }
+          while (parsed[0] === "." && globParts[0] === ".") {
+            parsed.shift();
+            globParts.shift();
+          }
+          const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform);
+          const m = new minimatch_1.Minimatch(p.globString(), this.mmopts);
+          const children = globParts[globParts.length - 1] === "**";
+          const absolute = p.isAbsolute();
+          if (absolute)
+            this.absolute.push(m);
+          else
+            this.relative.push(m);
+          if (children) {
+            if (absolute)
+              this.absoluteChildren.push(m);
+            else
+              this.relativeChildren.push(m);
+          }
+        }
       }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.PathScurry = exports2.Path = exports2.PathScurryDarwin = exports2.PathScurryPosix = exports2.PathScurryWin32 = exports2.PathScurryBase = exports2.PathPosix = exports2.PathWin32 = exports2.PathBase = exports2.ChildrenCache = exports2.ResolveCache = void 0;
-    var lru_cache_1 = require_commonjs14();
-    var node_path_1 = require("node:path");
-    var node_url_1 = require("node:url");
-    var fs_1 = require("fs");
-    var actualFS = __importStar4(require("node:fs"));
-    var realpathSync = fs_1.realpathSync.native;
-    var promises_1 = require("node:fs/promises");
-    var minipass_1 = require_commonjs15();
-    var defaultFS = {
-      lstatSync: fs_1.lstatSync,
-      readdir: fs_1.readdir,
-      readdirSync: fs_1.readdirSync,
-      readlinkSync: fs_1.readlinkSync,
-      realpathSync,
-      promises: {
-        lstat: promises_1.lstat,
-        readdir: promises_1.readdir,
-        readlink: promises_1.readlink,
-        realpath: promises_1.realpath
+      ignored(p) {
+        const fullpath = p.fullpath();
+        const fullpaths = `${fullpath}/`;
+        const relative = p.relative() || ".";
+        const relatives = `${relative}/`;
+        for (const m of this.relative) {
+          if (m.match(relative) || m.match(relatives))
+            return true;
+        }
+        for (const m of this.absolute) {
+          if (m.match(fullpath) || m.match(fullpaths))
+            return true;
+        }
+        return false;
       }
-    };
-    var fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ? defaultFS : {
-      ...defaultFS,
-      ...fsOption,
-      promises: {
-        ...defaultFS.promises,
-        ...fsOption.promises || {}
+      childrenIgnored(p) {
+        const fullpath = p.fullpath() + "/";
+        const relative = (p.relative() || ".") + "/";
+        for (const m of this.relativeChildren) {
+          if (m.match(relative))
+            return true;
+        }
+        for (const m of this.absoluteChildren) {
+          if (m.match(fullpath))
+            return true;
+        }
+        return false;
       }
     };
-    var uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
-    var uncToDrive = (rootPath) => rootPath.replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
-    var eitherSep = /[\\\/]/;
-    var UNKNOWN = 0;
-    var IFIFO = 1;
-    var IFCHR = 2;
-    var IFDIR = 4;
-    var IFBLK = 6;
-    var IFREG = 8;
-    var IFLNK = 10;
-    var IFSOCK = 12;
-    var IFMT = 15;
-    var IFMT_UNKNOWN = ~IFMT;
-    var READDIR_CALLED = 16;
-    var LSTAT_CALLED = 32;
-    var ENOTDIR = 64;
-    var ENOENT = 128;
-    var ENOREADLINK = 256;
-    var ENOREALPATH = 512;
-    var ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
-    var TYPEMASK = 1023;
-    var entToType = (s) => s.isFile() ? IFREG : s.isDirectory() ? IFDIR : s.isSymbolicLink() ? IFLNK : s.isCharacterDevice() ? IFCHR : s.isBlockDevice() ? IFBLK : s.isSocket() ? IFSOCK : s.isFIFO() ? IFIFO : UNKNOWN;
-    var normalizeCache = /* @__PURE__ */ new Map();
-    var normalize2 = (s) => {
-      const c = normalizeCache.get(s);
-      if (c)
-        return c;
-      const n = s.normalize("NFKD");
-      normalizeCache.set(s, n);
-      return n;
-    };
-    var normalizeNocaseCache = /* @__PURE__ */ new Map();
-    var normalizeNocase = (s) => {
-      const c = normalizeNocaseCache.get(s);
-      if (c)
-        return c;
-      const n = normalize2(s.toLowerCase());
-      normalizeNocaseCache.set(s, n);
-      return n;
-    };
-    var ResolveCache = class extends lru_cache_1.LRUCache {
-      constructor() {
-        super({ max: 256 });
+    exports2.Ignore = Ignore;
+  }
+});
+
+// node_modules/archiver-utils/node_modules/glob/dist/commonjs/processor.js
+var require_processor = __commonJS({
+  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/processor.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.Processor = exports2.SubWalks = exports2.MatchRecord = exports2.HasWalkedCache = void 0;
+    var minimatch_1 = require_commonjs13();
+    var HasWalkedCache = class _HasWalkedCache {
+      store;
+      constructor(store = /* @__PURE__ */ new Map()) {
+        this.store = store;
       }
-    };
-    exports2.ResolveCache = ResolveCache;
-    var ChildrenCache = class extends lru_cache_1.LRUCache {
-      constructor(maxSize = 16 * 1024) {
-        super({
-          maxSize,
-          // parent + children
-          sizeCalculation: (a) => a.length + 1
-        });
+      copy() {
+        return new _HasWalkedCache(new Map(this.store));
       }
-    };
-    exports2.ChildrenCache = ChildrenCache;
-    var setAsCwd = Symbol("PathScurry setAsCwd");
-    var PathBase = class {
-      /**
-       * the basename of this path
-       *
-       * **Important**: *always* test the path name against any test string
-       * usingthe {@link isNamed} method, and not by directly comparing this
-       * string. Otherwise, unicode path strings that the system sees as identical
-       * will not be properly treated as the same path, leading to incorrect
-       * behavior and possible security issues.
-       */
-      name;
-      /**
-       * the Path entry corresponding to the path root.
-       *
-       * @internal
-       */
-      root;
-      /**
-       * All roots found within the current PathScurry family
-       *
-       * @internal
-       */
-      roots;
-      /**
-       * a reference to the parent path, or undefined in the case of root entries
-       *
-       * @internal
-       */
-      parent;
-      /**
-       * boolean indicating whether paths are compared case-insensitively
-       * @internal
-       */
-      nocase;
-      /**
-       * boolean indicating that this path is the current working directory
-       * of the PathScurry collection that contains it.
-       */
-      isCWD = false;
-      // potential default fs override
-      #fs;
-      // Stats fields
-      #dev;
-      get dev() {
-        return this.#dev;
+      hasWalked(target, pattern) {
+        return this.store.get(target.fullpath())?.has(pattern.globString());
+      }
+      storeWalked(target, pattern) {
+        const fullpath = target.fullpath();
+        const cached = this.store.get(fullpath);
+        if (cached)
+          cached.add(pattern.globString());
+        else
+          this.store.set(fullpath, /* @__PURE__ */ new Set([pattern.globString()]));
       }
-      #mode;
-      get mode() {
-        return this.#mode;
+    };
+    exports2.HasWalkedCache = HasWalkedCache;
+    var MatchRecord = class {
+      store = /* @__PURE__ */ new Map();
+      add(target, absolute, ifDir) {
+        const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
+        const current = this.store.get(target);
+        this.store.set(target, current === void 0 ? n : n & current);
       }
-      #nlink;
-      get nlink() {
-        return this.#nlink;
+      // match, absolute, ifdir
+      entries() {
+        return [...this.store.entries()].map(([path2, n]) => [
+          path2,
+          !!(n & 2),
+          !!(n & 1)
+        ]);
       }
-      #uid;
-      get uid() {
-        return this.#uid;
+    };
+    exports2.MatchRecord = MatchRecord;
+    var SubWalks = class {
+      store = /* @__PURE__ */ new Map();
+      add(target, pattern) {
+        if (!target.canReaddir()) {
+          return;
+        }
+        const subs = this.store.get(target);
+        if (subs) {
+          if (!subs.find((p) => p.globString() === pattern.globString())) {
+            subs.push(pattern);
+          }
+        } else
+          this.store.set(target, [pattern]);
       }
-      #gid;
-      get gid() {
-        return this.#gid;
+      get(target) {
+        const subs = this.store.get(target);
+        if (!subs) {
+          throw new Error("attempting to walk unknown path");
+        }
+        return subs;
       }
-      #rdev;
-      get rdev() {
-        return this.#rdev;
+      entries() {
+        return this.keys().map((k) => [k, this.store.get(k)]);
       }
-      #blksize;
-      get blksize() {
-        return this.#blksize;
+      keys() {
+        return [...this.store.keys()].filter((t) => t.canReaddir());
       }
-      #ino;
-      get ino() {
-        return this.#ino;
+    };
+    exports2.SubWalks = SubWalks;
+    var Processor = class _Processor {
+      hasWalkedCache;
+      matches = new MatchRecord();
+      subwalks = new SubWalks();
+      patterns;
+      follow;
+      dot;
+      opts;
+      constructor(opts, hasWalkedCache) {
+        this.opts = opts;
+        this.follow = !!opts.follow;
+        this.dot = !!opts.dot;
+        this.hasWalkedCache = hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
       }
-      #size;
-      get size() {
-        return this.#size;
+      processPatterns(target, patterns) {
+        this.patterns = patterns;
+        const processingSet = patterns.map((p) => [target, p]);
+        for (let [t, pattern] of processingSet) {
+          this.hasWalkedCache.storeWalked(t, pattern);
+          const root = pattern.root();
+          const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
+          if (root) {
+            t = t.resolve(root === "/" && this.opts.root !== void 0 ? this.opts.root : root);
+            const rest2 = pattern.rest();
+            if (!rest2) {
+              this.matches.add(t, true, false);
+              continue;
+            } else {
+              pattern = rest2;
+            }
+          }
+          if (t.isENOENT())
+            continue;
+          let p;
+          let rest;
+          let changed = false;
+          while (typeof (p = pattern.pattern()) === "string" && (rest = pattern.rest())) {
+            const c = t.resolve(p);
+            t = c;
+            pattern = rest;
+            changed = true;
+          }
+          p = pattern.pattern();
+          rest = pattern.rest();
+          if (changed) {
+            if (this.hasWalkedCache.hasWalked(t, pattern))
+              continue;
+            this.hasWalkedCache.storeWalked(t, pattern);
+          }
+          if (typeof p === "string") {
+            const ifDir = p === ".." || p === "" || p === ".";
+            this.matches.add(t.resolve(p), absolute, ifDir);
+            continue;
+          } else if (p === minimatch_1.GLOBSTAR) {
+            if (!t.isSymbolicLink() || this.follow || pattern.checkFollowGlobstar()) {
+              this.subwalks.add(t, pattern);
+            }
+            const rp = rest?.pattern();
+            const rrest = rest?.rest();
+            if (!rest || (rp === "" || rp === ".") && !rrest) {
+              this.matches.add(t, absolute, rp === "" || rp === ".");
+            } else {
+              if (rp === "..") {
+                const tp = t.parent || t;
+                if (!rrest)
+                  this.matches.add(tp, absolute, true);
+                else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
+                  this.subwalks.add(tp, rrest);
+                }
+              }
+            }
+          } else if (p instanceof RegExp) {
+            this.subwalks.add(t, pattern);
+          }
+        }
+        return this;
       }
-      #blocks;
-      get blocks() {
-        return this.#blocks;
+      subwalkTargets() {
+        return this.subwalks.keys();
       }
-      #atimeMs;
-      get atimeMs() {
-        return this.#atimeMs;
+      child() {
+        return new _Processor(this.opts, this.hasWalkedCache);
       }
-      #mtimeMs;
-      get mtimeMs() {
-        return this.#mtimeMs;
+      // return a new Processor containing the subwalks for each
+      // child entry, and a set of matches, and
+      // a hasWalkedCache that's a copy of this one
+      // then we're going to call
+      filterEntries(parent, entries) {
+        const patterns = this.subwalks.get(parent);
+        const results = this.child();
+        for (const e of entries) {
+          for (const pattern of patterns) {
+            const absolute = pattern.isAbsolute();
+            const p = pattern.pattern();
+            const rest = pattern.rest();
+            if (p === minimatch_1.GLOBSTAR) {
+              results.testGlobstar(e, pattern, rest, absolute);
+            } else if (p instanceof RegExp) {
+              results.testRegExp(e, p, rest, absolute);
+            } else {
+              results.testString(e, p, rest, absolute);
+            }
+          }
+        }
+        return results;
       }
-      #ctimeMs;
-      get ctimeMs() {
-        return this.#ctimeMs;
+      testGlobstar(e, pattern, rest, absolute) {
+        if (this.dot || !e.name.startsWith(".")) {
+          if (!pattern.hasMore()) {
+            this.matches.add(e, absolute, false);
+          }
+          if (e.canReaddir()) {
+            if (this.follow || !e.isSymbolicLink()) {
+              this.subwalks.add(e, pattern);
+            } else if (e.isSymbolicLink()) {
+              if (rest && pattern.checkFollowGlobstar()) {
+                this.subwalks.add(e, rest);
+              } else if (pattern.markFollowGlobstar()) {
+                this.subwalks.add(e, pattern);
+              }
+            }
+          }
+        }
+        if (rest) {
+          const rp = rest.pattern();
+          if (typeof rp === "string" && // dots and empty were handled already
+          rp !== ".." && rp !== "" && rp !== ".") {
+            this.testString(e, rp, rest.rest(), absolute);
+          } else if (rp === "..") {
+            const ep = e.parent || e;
+            this.subwalks.add(ep, rest);
+          } else if (rp instanceof RegExp) {
+            this.testRegExp(e, rp, rest.rest(), absolute);
+          }
+        }
       }
-      #birthtimeMs;
-      get birthtimeMs() {
-        return this.#birthtimeMs;
+      testRegExp(e, p, rest, absolute) {
+        if (!p.test(e.name))
+          return;
+        if (!rest) {
+          this.matches.add(e, absolute, false);
+        } else {
+          this.subwalks.add(e, rest);
+        }
       }
-      #atime;
-      get atime() {
-        return this.#atime;
+      testString(e, p, rest, absolute) {
+        if (!e.isNamed(p))
+          return;
+        if (!rest) {
+          this.matches.add(e, absolute, false);
+        } else {
+          this.subwalks.add(e, rest);
+        }
       }
-      #mtime;
-      get mtime() {
-        return this.#mtime;
+    };
+    exports2.Processor = Processor;
+  }
+});
+
+// node_modules/archiver-utils/node_modules/glob/dist/commonjs/walker.js
+var require_walker = __commonJS({
+  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/walker.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.GlobStream = exports2.GlobWalker = exports2.GlobUtil = void 0;
+    var minipass_1 = require_commonjs15();
+    var ignore_js_1 = require_ignore();
+    var processor_js_1 = require_processor();
+    var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new ignore_js_1.Ignore([ignore], opts) : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts) : ignore;
+    var GlobUtil = class {
+      path;
+      patterns;
+      opts;
+      seen = /* @__PURE__ */ new Set();
+      paused = false;
+      aborted = false;
+      #onResume = [];
+      #ignore;
+      #sep;
+      signal;
+      maxDepth;
+      includeChildMatches;
+      constructor(patterns, path2, opts) {
+        this.patterns = patterns;
+        this.path = path2;
+        this.opts = opts;
+        this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
+        this.includeChildMatches = opts.includeChildMatches !== false;
+        if (opts.ignore || !this.includeChildMatches) {
+          this.#ignore = makeIgnore(opts.ignore ?? [], opts);
+          if (!this.includeChildMatches && typeof this.#ignore.add !== "function") {
+            const m = "cannot ignore child matches, ignore lacks add() method.";
+            throw new Error(m);
+          }
+        }
+        this.maxDepth = opts.maxDepth || Infinity;
+        if (opts.signal) {
+          this.signal = opts.signal;
+          this.signal.addEventListener("abort", () => {
+            this.#onResume.length = 0;
+          });
+        }
       }
-      #ctime;
-      get ctime() {
-        return this.#ctime;
+      #ignored(path2) {
+        return this.seen.has(path2) || !!this.#ignore?.ignored?.(path2);
       }
-      #birthtime;
-      get birthtime() {
-        return this.#birthtime;
+      #childrenIgnored(path2) {
+        return !!this.#ignore?.childrenIgnored?.(path2);
       }
-      #matchName;
-      #depth;
-      #fullpath;
-      #fullpathPosix;
-      #relative;
-      #relativePosix;
-      #type;
-      #children;
-      #linkTarget;
-      #realpath;
-      /**
-       * This property is for compatibility with the Dirent class as of
-       * Node v20, where Dirent['parentPath'] refers to the path of the
-       * directory that was passed to readdir. For root entries, it's the path
-       * to the entry itself.
-       */
-      get parentPath() {
-        return (this.parent || this).fullpath();
+      // backpressure mechanism
+      pause() {
+        this.paused = true;
       }
-      /**
-       * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
-       * this property refers to the *parent* path, not the path object itself.
-       */
-      get path() {
-        return this.parentPath;
+      resume() {
+        if (this.signal?.aborted)
+          return;
+        this.paused = false;
+        let fn = void 0;
+        while (!this.paused && (fn = this.#onResume.shift())) {
+          fn();
+        }
       }
-      /**
-       * Do not create new Path objects directly.  They should always be accessed
-       * via the PathScurry class or other methods on the Path class.
-       *
-       * @internal
-       */
-      constructor(name, type2 = UNKNOWN, root, roots, nocase, children, opts) {
-        this.name = name;
-        this.#matchName = nocase ? normalizeNocase(name) : normalize2(name);
-        this.#type = type2 & TYPEMASK;
-        this.nocase = nocase;
-        this.roots = roots;
-        this.root = root || this;
-        this.#children = children;
-        this.#fullpath = opts.fullpath;
-        this.#relative = opts.relative;
-        this.#relativePosix = opts.relativePosix;
-        this.parent = opts.parent;
-        if (this.parent) {
-          this.#fs = this.parent.#fs;
+      onResume(fn) {
+        if (this.signal?.aborted)
+          return;
+        if (!this.paused) {
+          fn();
         } else {
-          this.#fs = fsFromOption(opts.fs);
+          this.#onResume.push(fn);
         }
       }
-      /**
-       * Returns the depth of the Path object from its root.
-       *
-       * For example, a path at `/foo/bar` would have a depth of 2.
-       */
-      depth() {
-        if (this.#depth !== void 0)
-          return this.#depth;
-        if (!this.parent)
-          return this.#depth = 0;
-        return this.#depth = this.parent.depth() + 1;
+      // do the requisite realpath/stat checking, and return the path
+      // to add or undefined to filter it out.
+      async matchCheck(e, ifDir) {
+        if (ifDir && this.opts.nodir)
+          return void 0;
+        let rpc;
+        if (this.opts.realpath) {
+          rpc = e.realpathCached() || await e.realpath();
+          if (!rpc)
+            return void 0;
+          e = rpc;
+        }
+        const needStat = e.isUnknown() || this.opts.stat;
+        const s = needStat ? await e.lstat() : e;
+        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
+          const target = await s.realpath();
+          if (target && (target.isUnknown() || this.opts.stat)) {
+            await target.lstat();
+          }
+        }
+        return this.matchCheckTest(s, ifDir);
       }
-      /**
-       * @internal
-       */
-      childrenCache() {
-        return this.#children;
+      matchCheckTest(e, ifDir) {
+        return e && (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && (!ifDir || e.canReaddir()) && (!this.opts.nodir || !e.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !e.isSymbolicLink() || !e.realpathCached()?.isDirectory()) && !this.#ignored(e) ? e : void 0;
       }
-      /**
-       * Get the Path object referenced by the string path, resolved from this Path
-       */
-      resolve(path2) {
-        if (!path2) {
-          return this;
+      matchCheckSync(e, ifDir) {
+        if (ifDir && this.opts.nodir)
+          return void 0;
+        let rpc;
+        if (this.opts.realpath) {
+          rpc = e.realpathCached() || e.realpathSync();
+          if (!rpc)
+            return void 0;
+          e = rpc;
         }
-        const rootPath = this.getRootString(path2);
-        const dir = path2.substring(rootPath.length);
-        const dirParts = dir.split(this.splitSep);
-        const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
-        return result;
-      }
-      #resolveParts(dirParts) {
-        let p = this;
-        for (const part of dirParts) {
-          p = p.child(part);
+        const needStat = e.isUnknown() || this.opts.stat;
+        const s = needStat ? e.lstatSync() : e;
+        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
+          const target = s.realpathSync();
+          if (target && (target?.isUnknown() || this.opts.stat)) {
+            target.lstatSync();
+          }
         }
-        return p;
+        return this.matchCheckTest(s, ifDir);
       }
-      /**
-       * Returns the cached children Path objects, if still available.  If they
-       * have fallen out of the cache, then returns an empty array, and resets the
-       * READDIR_CALLED bit, so that future calls to readdir() will require an fs
-       * lookup.
-       *
-       * @internal
-       */
-      children() {
-        const cached = this.#children.get(this);
-        if (cached) {
-          return cached;
+      matchFinish(e, absolute) {
+        if (this.#ignored(e))
+          return;
+        if (!this.includeChildMatches && this.#ignore?.add) {
+          const ign = `${e.relativePosix()}/**`;
+          this.#ignore.add(ign);
+        }
+        const abs = this.opts.absolute === void 0 ? absolute : this.opts.absolute;
+        this.seen.add(e);
+        const mark = this.opts.mark && e.isDirectory() ? this.#sep : "";
+        if (this.opts.withFileTypes) {
+          this.matchEmit(e);
+        } else if (abs) {
+          const abs2 = this.opts.posix ? e.fullpathPosix() : e.fullpath();
+          this.matchEmit(abs2 + mark);
+        } else {
+          const rel = this.opts.posix ? e.relativePosix() : e.relative();
+          const pre = this.opts.dotRelative && !rel.startsWith(".." + this.#sep) ? "." + this.#sep : "";
+          this.matchEmit(!rel ? "." + mark : pre + rel + mark);
         }
-        const children = Object.assign([], { provisional: 0 });
-        this.#children.set(this, children);
-        this.#type &= ~READDIR_CALLED;
-        return children;
       }
-      /**
-       * Resolves a path portion and returns or creates the child Path.
-       *
-       * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
-       * `'..'`.
-       *
-       * This should not be called directly.  If `pathPart` contains any path
-       * separators, it will lead to unsafe undefined behavior.
-       *
-       * Use `Path.resolve()` instead.
-       *
-       * @internal
-       */
-      child(pathPart, opts) {
-        if (pathPart === "" || pathPart === ".") {
-          return this;
+      async match(e, absolute, ifDir) {
+        const p = await this.matchCheck(e, ifDir);
+        if (p)
+          this.matchFinish(p, absolute);
+      }
+      matchSync(e, absolute, ifDir) {
+        const p = this.matchCheckSync(e, ifDir);
+        if (p)
+          this.matchFinish(p, absolute);
+      }
+      walkCB(target, patterns, cb) {
+        if (this.signal?.aborted)
+          cb();
+        this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb);
+      }
+      walkCB2(target, patterns, processor, cb) {
+        if (this.#childrenIgnored(target))
+          return cb();
+        if (this.signal?.aborted)
+          cb();
+        if (this.paused) {
+          this.onResume(() => this.walkCB2(target, patterns, processor, cb));
+          return;
         }
-        if (pathPart === "..") {
-          return this.parent || this;
+        processor.processPatterns(target, patterns);
+        let tasks = 1;
+        const next = () => {
+          if (--tasks === 0)
+            cb();
+        };
+        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+          if (this.#ignored(m))
+            continue;
+          tasks++;
+          this.match(m, absolute, ifDir).then(() => next());
         }
-        const children = this.children();
-        const name = this.nocase ? normalizeNocase(pathPart) : normalize2(pathPart);
-        for (const p of children) {
-          if (p.#matchName === name) {
-            return p;
+        for (const t of processor.subwalkTargets()) {
+          if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
+            continue;
+          }
+          tasks++;
+          const childrenCached = t.readdirCached();
+          if (t.calledReaddir())
+            this.walkCB3(t, childrenCached, processor, next);
+          else {
+            t.readdirCB((_2, entries) => this.walkCB3(t, entries, processor, next), true);
           }
         }
-        const s = this.parent ? this.sep : "";
-        const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : void 0;
-        const pchild = this.newChild(pathPart, UNKNOWN, {
-          ...opts,
-          parent: this,
-          fullpath
-        });
-        if (!this.canReaddir()) {
-          pchild.#type |= ENOENT;
-        }
-        children.push(pchild);
-        return pchild;
+        next();
       }
-      /**
-       * The relative path from the cwd. If it does not share an ancestor with
-       * the cwd, then this ends up being equivalent to the fullpath()
-       */
-      relative() {
-        if (this.isCWD)
-          return "";
-        if (this.#relative !== void 0) {
-          return this.#relative;
+      walkCB3(target, entries, processor, cb) {
+        processor = processor.filterEntries(target, entries);
+        let tasks = 1;
+        const next = () => {
+          if (--tasks === 0)
+            cb();
+        };
+        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+          if (this.#ignored(m))
+            continue;
+          tasks++;
+          this.match(m, absolute, ifDir).then(() => next());
         }
-        const name = this.name;
-        const p = this.parent;
-        if (!p) {
-          return this.#relative = this.name;
+        for (const [target2, patterns] of processor.subwalks.entries()) {
+          tasks++;
+          this.walkCB2(target2, patterns, processor.child(), next);
         }
-        const pv = p.relative();
-        return pv + (!pv || !p.parent ? "" : this.sep) + name;
+        next();
       }
-      /**
-       * The relative path from the cwd, using / as the path separator.
-       * If it does not share an ancestor with
-       * the cwd, then this ends up being equivalent to the fullpathPosix()
-       * On posix systems, this is identical to relative().
-       */
-      relativePosix() {
-        if (this.sep === "/")
-          return this.relative();
-        if (this.isCWD)
-          return "";
-        if (this.#relativePosix !== void 0)
-          return this.#relativePosix;
-        const name = this.name;
-        const p = this.parent;
-        if (!p) {
-          return this.#relativePosix = this.fullpathPosix();
-        }
-        const pv = p.relativePosix();
-        return pv + (!pv || !p.parent ? "" : "/") + name;
+      walkCBSync(target, patterns, cb) {
+        if (this.signal?.aborted)
+          cb();
+        this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb);
       }
-      /**
-       * The fully resolved path string for this Path entry
-       */
-      fullpath() {
-        if (this.#fullpath !== void 0) {
-          return this.#fullpath;
+      walkCB2Sync(target, patterns, processor, cb) {
+        if (this.#childrenIgnored(target))
+          return cb();
+        if (this.signal?.aborted)
+          cb();
+        if (this.paused) {
+          this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
+          return;
         }
-        const name = this.name;
-        const p = this.parent;
-        if (!p) {
-          return this.#fullpath = this.name;
+        processor.processPatterns(target, patterns);
+        let tasks = 1;
+        const next = () => {
+          if (--tasks === 0)
+            cb();
+        };
+        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+          if (this.#ignored(m))
+            continue;
+          this.matchSync(m, absolute, ifDir);
         }
-        const pv = p.fullpath();
-        const fp = pv + (!p.parent ? "" : this.sep) + name;
-        return this.#fullpath = fp;
-      }
-      /**
-       * On platforms other than windows, this is identical to fullpath.
-       *
-       * On windows, this is overridden to return the forward-slash form of the
-       * full UNC path.
-       */
-      fullpathPosix() {
-        if (this.#fullpathPosix !== void 0)
-          return this.#fullpathPosix;
-        if (this.sep === "/")
-          return this.#fullpathPosix = this.fullpath();
-        if (!this.parent) {
-          const p2 = this.fullpath().replace(/\\/g, "/");
-          if (/^[a-z]:\//i.test(p2)) {
-            return this.#fullpathPosix = `//?/${p2}`;
-          } else {
-            return this.#fullpathPosix = p2;
+        for (const t of processor.subwalkTargets()) {
+          if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
+            continue;
           }
+          tasks++;
+          const children = t.readdirSync();
+          this.walkCB3Sync(t, children, processor, next);
         }
-        const p = this.parent;
-        const pfpp = p.fullpathPosix();
-        const fpp = pfpp + (!pfpp || !p.parent ? "" : "/") + this.name;
-        return this.#fullpathPosix = fpp;
-      }
-      /**
-       * Is the Path of an unknown type?
-       *
-       * Note that we might know *something* about it if there has been a previous
-       * filesystem operation, for example that it does not exist, or is not a
-       * link, or whether it has child entries.
-       */
-      isUnknown() {
-        return (this.#type & IFMT) === UNKNOWN;
-      }
-      isType(type2) {
-        return this[`is${type2}`]();
-      }
-      getType() {
-        return this.isUnknown() ? "Unknown" : this.isDirectory() ? "Directory" : this.isFile() ? "File" : this.isSymbolicLink() ? "SymbolicLink" : this.isFIFO() ? "FIFO" : this.isCharacterDevice() ? "CharacterDevice" : this.isBlockDevice() ? "BlockDevice" : (
-          /* c8 ignore start */
-          this.isSocket() ? "Socket" : "Unknown"
-        );
-      }
-      /**
-       * Is the Path a regular file?
-       */
-      isFile() {
-        return (this.#type & IFMT) === IFREG;
-      }
-      /**
-       * Is the Path a directory?
-       */
-      isDirectory() {
-        return (this.#type & IFMT) === IFDIR;
-      }
-      /**
-       * Is the path a character device?
-       */
-      isCharacterDevice() {
-        return (this.#type & IFMT) === IFCHR;
+        next();
       }
-      /**
-       * Is the path a block device?
-       */
-      isBlockDevice() {
-        return (this.#type & IFMT) === IFBLK;
+      walkCB3Sync(target, entries, processor, cb) {
+        processor = processor.filterEntries(target, entries);
+        let tasks = 1;
+        const next = () => {
+          if (--tasks === 0)
+            cb();
+        };
+        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+          if (this.#ignored(m))
+            continue;
+          this.matchSync(m, absolute, ifDir);
+        }
+        for (const [target2, patterns] of processor.subwalks.entries()) {
+          tasks++;
+          this.walkCB2Sync(target2, patterns, processor.child(), next);
+        }
+        next();
       }
-      /**
-       * Is the path a FIFO pipe?
-       */
-      isFIFO() {
-        return (this.#type & IFMT) === IFIFO;
+    };
+    exports2.GlobUtil = GlobUtil;
+    var GlobWalker = class extends GlobUtil {
+      matches = /* @__PURE__ */ new Set();
+      constructor(patterns, path2, opts) {
+        super(patterns, path2, opts);
       }
-      /**
-       * Is the path a socket?
-       */
-      isSocket() {
-        return (this.#type & IFMT) === IFSOCK;
+      matchEmit(e) {
+        this.matches.add(e);
       }
-      /**
-       * Is the path a symbolic link?
-       */
-      isSymbolicLink() {
-        return (this.#type & IFLNK) === IFLNK;
+      async walk() {
+        if (this.signal?.aborted)
+          throw this.signal.reason;
+        if (this.path.isUnknown()) {
+          await this.path.lstat();
+        }
+        await new Promise((res, rej) => {
+          this.walkCB(this.path, this.patterns, () => {
+            if (this.signal?.aborted) {
+              rej(this.signal.reason);
+            } else {
+              res(this.matches);
+            }
+          });
+        });
+        return this.matches;
       }
-      /**
-       * Return the entry if it has been subject of a successful lstat, or
-       * undefined otherwise.
-       *
-       * Does not read the filesystem, so an undefined result *could* simply
-       * mean that we haven't called lstat on it.
-       */
-      lstatCached() {
-        return this.#type & LSTAT_CALLED ? this : void 0;
+      walkSync() {
+        if (this.signal?.aborted)
+          throw this.signal.reason;
+        if (this.path.isUnknown()) {
+          this.path.lstatSync();
+        }
+        this.walkCBSync(this.path, this.patterns, () => {
+          if (this.signal?.aborted)
+            throw this.signal.reason;
+        });
+        return this.matches;
       }
-      /**
-       * Return the cached link target if the entry has been the subject of a
-       * successful readlink, or undefined otherwise.
-       *
-       * Does not read the filesystem, so an undefined result *could* just mean we
-       * don't have any cached data. Only use it if you are very sure that a
-       * readlink() has been called at some point.
-       */
-      readlinkCached() {
-        return this.#linkTarget;
+    };
+    exports2.GlobWalker = GlobWalker;
+    var GlobStream = class extends GlobUtil {
+      results;
+      constructor(patterns, path2, opts) {
+        super(patterns, path2, opts);
+        this.results = new minipass_1.Minipass({
+          signal: this.signal,
+          objectMode: true
+        });
+        this.results.on("drain", () => this.resume());
+        this.results.on("resume", () => this.resume());
       }
-      /**
-       * Returns the cached realpath target if the entry has been the subject
-       * of a successful realpath, or undefined otherwise.
-       *
-       * Does not read the filesystem, so an undefined result *could* just mean we
-       * don't have any cached data. Only use it if you are very sure that a
-       * realpath() has been called at some point.
-       */
-      realpathCached() {
-        return this.#realpath;
+      matchEmit(e) {
+        this.results.write(e);
+        if (!this.results.flowing)
+          this.pause();
       }
-      /**
-       * Returns the cached child Path entries array if the entry has been the
-       * subject of a successful readdir(), or [] otherwise.
-       *
-       * Does not read the filesystem, so an empty array *could* just mean we
-       * don't have any cached data. Only use it if you are very sure that a
-       * readdir() has been called recently enough to still be valid.
-       */
-      readdirCached() {
-        const children = this.children();
-        return children.slice(0, children.provisional);
+      stream() {
+        const target = this.path;
+        if (target.isUnknown()) {
+          target.lstat().then(() => {
+            this.walkCB(target, this.patterns, () => this.results.end());
+          });
+        } else {
+          this.walkCB(target, this.patterns, () => this.results.end());
+        }
+        return this.results;
       }
-      /**
-       * Return true if it's worth trying to readlink.  Ie, we don't (yet) have
-       * any indication that readlink will definitely fail.
-       *
-       * Returns false if the path is known to not be a symlink, if a previous
-       * readlink failed, or if the entry does not exist.
-       */
-      canReadlink() {
-        if (this.#linkTarget)
-          return true;
-        if (!this.parent)
-          return false;
-        const ifmt = this.#type & IFMT;
-        return !(ifmt !== UNKNOWN && ifmt !== IFLNK || this.#type & ENOREADLINK || this.#type & ENOENT);
+      streamSync() {
+        if (this.path.isUnknown()) {
+          this.path.lstatSync();
+        }
+        this.walkCBSync(this.path, this.patterns, () => this.results.end());
+        return this.results;
       }
+    };
+    exports2.GlobStream = GlobStream;
+  }
+});
+
+// node_modules/archiver-utils/node_modules/glob/dist/commonjs/glob.js
+var require_glob = __commonJS({
+  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/glob.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.Glob = void 0;
+    var minimatch_1 = require_commonjs13();
+    var node_url_1 = require("node:url");
+    var path_scurry_1 = require_commonjs16();
+    var pattern_js_1 = require_pattern();
+    var walker_js_1 = require_walker();
+    var defaultPlatform = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
+    var Glob = class {
+      absolute;
+      cwd;
+      root;
+      dot;
+      dotRelative;
+      follow;
+      ignore;
+      magicalBraces;
+      mark;
+      matchBase;
+      maxDepth;
+      nobrace;
+      nocase;
+      nodir;
+      noext;
+      noglobstar;
+      pattern;
+      platform;
+      realpath;
+      scurry;
+      stat;
+      signal;
+      windowsPathsNoEscape;
+      withFileTypes;
+      includeChildMatches;
       /**
-       * Return true if readdir has previously been successfully called on this
-       * path, indicating that cachedReaddir() is likely valid.
+       * The options provided to the constructor.
        */
-      calledReaddir() {
-        return !!(this.#type & READDIR_CALLED);
-      }
+      opts;
       /**
-       * Returns true if the path is known to not exist. That is, a previous lstat
-       * or readdir failed to verify its existence when that would have been
-       * expected, or a parent entry was marked either enoent or enotdir.
+       * An array of parsed immutable {@link Pattern} objects.
        */
-      isENOENT() {
-        return !!(this.#type & ENOENT);
-      }
+      patterns;
       /**
-       * Return true if the path is a match for the given path name.  This handles
-       * case sensitivity and unicode normalization.
-       *
-       * Note: even on case-sensitive systems, it is **not** safe to test the
-       * equality of the `.name` property to determine whether a given pathname
-       * matches, due to unicode normalization mismatches.
+       * All options are stored as properties on the `Glob` object.
        *
-       * Always use this method instead of testing the `path.name` property
-       * directly.
-       */
-      isNamed(n) {
-        return !this.nocase ? this.#matchName === normalize2(n) : this.#matchName === normalizeNocase(n);
-      }
-      /**
-       * Return the Path object corresponding to the target of a symbolic link.
+       * See {@link GlobOptions} for full options descriptions.
        *
-       * If the Path is not a symbolic link, or if the readlink call fails for any
-       * reason, `undefined` is returned.
+       * Note that a previous `Glob` object can be passed as the
+       * `GlobOptions` to another `Glob` instantiation to re-use settings
+       * and caches with a new pattern.
        *
-       * Result is cached, and thus may be outdated if the filesystem is mutated.
-       */
-      async readlink() {
-        const target = this.#linkTarget;
-        if (target) {
-          return target;
-        }
-        if (!this.canReadlink()) {
-          return void 0;
-        }
-        if (!this.parent) {
-          return void 0;
-        }
-        try {
-          const read = await this.#fs.promises.readlink(this.fullpath());
-          const linkTarget = (await this.parent.realpath())?.resolve(read);
-          if (linkTarget) {
-            return this.#linkTarget = linkTarget;
-          }
-        } catch (er) {
-          this.#readlinkFail(er.code);
-          return void 0;
-        }
-      }
-      /**
-       * Synchronous {@link PathBase.readlink}
+       * Traversal functions can be called multiple times to run the walk
+       * again.
        */
-      readlinkSync() {
-        const target = this.#linkTarget;
-        if (target) {
-          return target;
-        }
-        if (!this.canReadlink()) {
-          return void 0;
-        }
-        if (!this.parent) {
-          return void 0;
-        }
-        try {
-          const read = this.#fs.readlinkSync(this.fullpath());
-          const linkTarget = this.parent.realpathSync()?.resolve(read);
-          if (linkTarget) {
-            return this.#linkTarget = linkTarget;
-          }
-        } catch (er) {
-          this.#readlinkFail(er.code);
-          return void 0;
-        }
-      }
-      #readdirSuccess(children) {
-        this.#type |= READDIR_CALLED;
-        for (let p = children.provisional; p < children.length; p++) {
-          const c = children[p];
-          if (c)
-            c.#markENOENT();
+      constructor(pattern, opts) {
+        if (!opts)
+          throw new TypeError("glob options required");
+        this.withFileTypes = !!opts.withFileTypes;
+        this.signal = opts.signal;
+        this.follow = !!opts.follow;
+        this.dot = !!opts.dot;
+        this.dotRelative = !!opts.dotRelative;
+        this.nodir = !!opts.nodir;
+        this.mark = !!opts.mark;
+        if (!opts.cwd) {
+          this.cwd = "";
+        } else if (opts.cwd instanceof URL || opts.cwd.startsWith("file://")) {
+          opts.cwd = (0, node_url_1.fileURLToPath)(opts.cwd);
         }
-      }
-      #markENOENT() {
-        if (this.#type & ENOENT)
-          return;
-        this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN;
-        this.#markChildrenENOENT();
-      }
-      #markChildrenENOENT() {
-        const children = this.children();
-        children.provisional = 0;
-        for (const p of children) {
-          p.#markENOENT();
+        this.cwd = opts.cwd || "";
+        this.root = opts.root;
+        this.magicalBraces = !!opts.magicalBraces;
+        this.nobrace = !!opts.nobrace;
+        this.noext = !!opts.noext;
+        this.realpath = !!opts.realpath;
+        this.absolute = opts.absolute;
+        this.includeChildMatches = opts.includeChildMatches !== false;
+        this.noglobstar = !!opts.noglobstar;
+        this.matchBase = !!opts.matchBase;
+        this.maxDepth = typeof opts.maxDepth === "number" ? opts.maxDepth : Infinity;
+        this.stat = !!opts.stat;
+        this.ignore = opts.ignore;
+        if (this.withFileTypes && this.absolute !== void 0) {
+          throw new Error("cannot set absolute and withFileTypes:true");
         }
-      }
-      #markENOREALPATH() {
-        this.#type |= ENOREALPATH;
-        this.#markENOTDIR();
-      }
-      // save the information when we know the entry is not a dir
-      #markENOTDIR() {
-        if (this.#type & ENOTDIR)
-          return;
-        let t = this.#type;
-        if ((t & IFMT) === IFDIR)
-          t &= IFMT_UNKNOWN;
-        this.#type = t | ENOTDIR;
-        this.#markChildrenENOENT();
-      }
-      #readdirFail(code = "") {
-        if (code === "ENOTDIR" || code === "EPERM") {
-          this.#markENOTDIR();
-        } else if (code === "ENOENT") {
-          this.#markENOENT();
-        } else {
-          this.children().provisional = 0;
+        if (typeof pattern === "string") {
+          pattern = [pattern];
         }
-      }
-      #lstatFail(code = "") {
-        if (code === "ENOTDIR") {
-          const p = this.parent;
-          p.#markENOTDIR();
-        } else if (code === "ENOENT") {
-          this.#markENOENT();
+        this.windowsPathsNoEscape = !!opts.windowsPathsNoEscape || opts.allowWindowsEscape === false;
+        if (this.windowsPathsNoEscape) {
+          pattern = pattern.map((p) => p.replace(/\\/g, "/"));
         }
-      }
-      #readlinkFail(code = "") {
-        let ter = this.#type;
-        ter |= ENOREADLINK;
-        if (code === "ENOENT")
-          ter |= ENOENT;
-        if (code === "EINVAL" || code === "UNKNOWN") {
-          ter &= IFMT_UNKNOWN;
+        if (this.matchBase) {
+          if (opts.noglobstar) {
+            throw new TypeError("base matching requires globstar");
+          }
+          pattern = pattern.map((p) => p.includes("/") ? p : `./**/${p}`);
         }
-        this.#type = ter;
-        if (code === "ENOTDIR" && this.parent) {
-          this.parent.#markENOTDIR();
+        this.pattern = pattern;
+        this.platform = opts.platform || defaultPlatform;
+        this.opts = { ...opts, platform: this.platform };
+        if (opts.scurry) {
+          this.scurry = opts.scurry;
+          if (opts.nocase !== void 0 && opts.nocase !== opts.scurry.nocase) {
+            throw new Error("nocase option contradicts provided scurry option");
+          }
+        } else {
+          const Scurry = opts.platform === "win32" ? path_scurry_1.PathScurryWin32 : opts.platform === "darwin" ? path_scurry_1.PathScurryDarwin : opts.platform ? path_scurry_1.PathScurryPosix : path_scurry_1.PathScurry;
+          this.scurry = new Scurry(this.cwd, {
+            nocase: opts.nocase,
+            fs: opts.fs
+          });
         }
+        this.nocase = this.scurry.nocase;
+        const nocaseMagicOnly = this.platform === "darwin" || this.platform === "win32";
+        const mmo = {
+          // default nocase based on platform
+          ...opts,
+          dot: this.dot,
+          matchBase: this.matchBase,
+          nobrace: this.nobrace,
+          nocase: this.nocase,
+          nocaseMagicOnly,
+          nocomment: true,
+          noext: this.noext,
+          nonegate: true,
+          optimizationLevel: 2,
+          platform: this.platform,
+          windowsPathsNoEscape: this.windowsPathsNoEscape,
+          debug: !!this.opts.debug
+        };
+        const mms = this.pattern.map((p) => new minimatch_1.Minimatch(p, mmo));
+        const [matchSet, globParts] = mms.reduce((set2, m) => {
+          set2[0].push(...m.set);
+          set2[1].push(...m.globParts);
+          return set2;
+        }, [[], []]);
+        this.patterns = matchSet.map((set2, i) => {
+          const g = globParts[i];
+          if (!g)
+            throw new Error("invalid pattern object");
+          return new pattern_js_1.Pattern(set2, g, 0, this.platform);
+        });
       }
-      #readdirAddChild(e, c) {
-        return this.#readdirMaybePromoteChild(e, c) || this.#readdirAddNewChild(e, c);
+      async walk() {
+        return [
+          ...await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
+            ...this.opts,
+            maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
+            platform: this.platform,
+            nocase: this.nocase,
+            includeChildMatches: this.includeChildMatches
+          }).walk()
+        ];
       }
-      #readdirAddNewChild(e, c) {
-        const type2 = entToType(e);
-        const child = this.newChild(e.name, type2, { parent: this });
-        const ifmt = child.#type & IFMT;
-        if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
-          child.#type |= ENOTDIR;
-        }
-        c.unshift(child);
-        c.provisional++;
-        return child;
+      walkSync() {
+        return [
+          ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
+            ...this.opts,
+            maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
+            platform: this.platform,
+            nocase: this.nocase,
+            includeChildMatches: this.includeChildMatches
+          }).walkSync()
+        ];
       }
-      #readdirMaybePromoteChild(e, c) {
-        for (let p = c.provisional; p < c.length; p++) {
-          const pchild = c[p];
-          const name = this.nocase ? normalizeNocase(e.name) : normalize2(e.name);
-          if (name !== pchild.#matchName) {
-            continue;
-          }
-          return this.#readdirPromoteChild(e, pchild, p, c);
-        }
+      stream() {
+        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
+          ...this.opts,
+          maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
+          platform: this.platform,
+          nocase: this.nocase,
+          includeChildMatches: this.includeChildMatches
+        }).stream();
       }
-      #readdirPromoteChild(e, p, index, c) {
-        const v = p.name;
-        p.#type = p.#type & IFMT_UNKNOWN | entToType(e);
-        if (v !== e.name)
-          p.name = e.name;
-        if (index !== c.provisional) {
-          if (index === c.length - 1)
-            c.pop();
-          else
-            c.splice(index, 1);
-          c.unshift(p);
-        }
-        c.provisional++;
-        return p;
+      streamSync() {
+        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
+          ...this.opts,
+          maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
+          platform: this.platform,
+          nocase: this.nocase,
+          includeChildMatches: this.includeChildMatches
+        }).streamSync();
       }
       /**
-       * Call lstat() on this Path, and update all known information that can be
-       * determined.
-       *
-       * Note that unlike `fs.lstat()`, the returned value does not contain some
-       * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
-       * information is required, you will need to call `fs.lstat` yourself.
-       *
-       * If the Path refers to a nonexistent file, or if the lstat call fails for
-       * any reason, `undefined` is returned.  Otherwise the updated Path object is
-       * returned.
-       *
-       * Results are cached, and thus may be out of date if the filesystem is
-       * mutated.
+       * Default sync iteration function. Returns a Generator that
+       * iterates over the results.
        */
-      async lstat() {
-        if ((this.#type & ENOENT) === 0) {
-          try {
-            this.#applyStat(await this.#fs.promises.lstat(this.fullpath()));
-            return this;
-          } catch (er) {
-            this.#lstatFail(er.code);
-          }
-        }
+      iterateSync() {
+        return this.streamSync()[Symbol.iterator]();
+      }
+      [Symbol.iterator]() {
+        return this.iterateSync();
       }
       /**
-       * synchronous {@link PathBase.lstat}
+       * Default async iteration function. Returns an AsyncGenerator that
+       * iterates over the results.
        */
-      lstatSync() {
-        if ((this.#type & ENOENT) === 0) {
-          try {
-            this.#applyStat(this.#fs.lstatSync(this.fullpath()));
-            return this;
-          } catch (er) {
-            this.#lstatFail(er.code);
-          }
-        }
+      iterate() {
+        return this.stream()[Symbol.asyncIterator]();
       }
-      #applyStat(st) {
-        const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid } = st;
-        this.#atime = atime;
-        this.#atimeMs = atimeMs;
-        this.#birthtime = birthtime;
-        this.#birthtimeMs = birthtimeMs;
-        this.#blksize = blksize;
-        this.#blocks = blocks;
-        this.#ctime = ctime;
-        this.#ctimeMs = ctimeMs;
-        this.#dev = dev;
-        this.#gid = gid;
-        this.#ino = ino;
-        this.#mode = mode;
-        this.#mtime = mtime;
-        this.#mtimeMs = mtimeMs;
-        this.#nlink = nlink;
-        this.#rdev = rdev;
-        this.#size = size;
-        this.#uid = uid;
-        const ifmt = entToType(st);
-        this.#type = this.#type & IFMT_UNKNOWN | ifmt | LSTAT_CALLED;
-        if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
-          this.#type |= ENOTDIR;
-        }
+      [Symbol.asyncIterator]() {
+        return this.iterate();
       }
-      #onReaddirCB = [];
-      #readdirCBInFlight = false;
-      #callOnReaddirCB(children) {
-        this.#readdirCBInFlight = false;
-        const cbs = this.#onReaddirCB.slice();
-        this.#onReaddirCB.length = 0;
-        cbs.forEach((cb) => cb(null, children));
+    };
+    exports2.Glob = Glob;
+  }
+});
+
+// node_modules/archiver-utils/node_modules/glob/dist/commonjs/has-magic.js
+var require_has_magic = __commonJS({
+  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/has-magic.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.hasMagic = void 0;
+    var minimatch_1 = require_commonjs13();
+    var hasMagic = (pattern, options = {}) => {
+      if (!Array.isArray(pattern)) {
+        pattern = [pattern];
       }
-      /**
-       * Standard node-style callback interface to get list of directory entries.
-       *
-       * If the Path cannot or does not contain any children, then an empty array
-       * is returned.
-       *
-       * Results are cached, and thus may be out of date if the filesystem is
-       * mutated.
-       *
-       * @param cb The callback called with (er, entries).  Note that the `er`
-       * param is somewhat extraneous, as all readdir() errors are handled and
-       * simply result in an empty set of entries being returned.
-       * @param allowZalgo Boolean indicating that immediately known results should
-       * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
-       * zalgo at your peril, the dark pony lord is devious and unforgiving.
-       */
-      readdirCB(cb, allowZalgo = false) {
-        if (!this.canReaddir()) {
-          if (allowZalgo)
-            cb(null, []);
-          else
-            queueMicrotask(() => cb(null, []));
-          return;
-        }
-        const children = this.children();
-        if (this.calledReaddir()) {
-          const c = children.slice(0, children.provisional);
-          if (allowZalgo)
-            cb(null, c);
-          else
-            queueMicrotask(() => cb(null, c));
-          return;
+      for (const p of pattern) {
+        if (new minimatch_1.Minimatch(p, options).hasMagic())
+          return true;
+      }
+      return false;
+    };
+    exports2.hasMagic = hasMagic;
+  }
+});
+
+// node_modules/archiver-utils/node_modules/glob/dist/commonjs/index.js
+var require_commonjs17 = __commonJS({
+  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/index.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.glob = exports2.sync = exports2.iterate = exports2.iterateSync = exports2.stream = exports2.streamSync = exports2.Ignore = exports2.hasMagic = exports2.Glob = exports2.unescape = exports2.escape = void 0;
+    exports2.globStreamSync = globStreamSync;
+    exports2.globStream = globStream;
+    exports2.globSync = globSync;
+    exports2.globIterateSync = globIterateSync;
+    exports2.globIterate = globIterate;
+    var minimatch_1 = require_commonjs13();
+    var glob_js_1 = require_glob();
+    var has_magic_js_1 = require_has_magic();
+    var minimatch_2 = require_commonjs13();
+    Object.defineProperty(exports2, "escape", { enumerable: true, get: function() {
+      return minimatch_2.escape;
+    } });
+    Object.defineProperty(exports2, "unescape", { enumerable: true, get: function() {
+      return minimatch_2.unescape;
+    } });
+    var glob_js_2 = require_glob();
+    Object.defineProperty(exports2, "Glob", { enumerable: true, get: function() {
+      return glob_js_2.Glob;
+    } });
+    var has_magic_js_2 = require_has_magic();
+    Object.defineProperty(exports2, "hasMagic", { enumerable: true, get: function() {
+      return has_magic_js_2.hasMagic;
+    } });
+    var ignore_js_1 = require_ignore();
+    Object.defineProperty(exports2, "Ignore", { enumerable: true, get: function() {
+      return ignore_js_1.Ignore;
+    } });
+    function globStreamSync(pattern, options = {}) {
+      return new glob_js_1.Glob(pattern, options).streamSync();
+    }
+    function globStream(pattern, options = {}) {
+      return new glob_js_1.Glob(pattern, options).stream();
+    }
+    function globSync(pattern, options = {}) {
+      return new glob_js_1.Glob(pattern, options).walkSync();
+    }
+    async function glob_(pattern, options = {}) {
+      return new glob_js_1.Glob(pattern, options).walk();
+    }
+    function globIterateSync(pattern, options = {}) {
+      return new glob_js_1.Glob(pattern, options).iterateSync();
+    }
+    function globIterate(pattern, options = {}) {
+      return new glob_js_1.Glob(pattern, options).iterate();
+    }
+    exports2.streamSync = globStreamSync;
+    exports2.stream = Object.assign(globStream, { sync: globStreamSync });
+    exports2.iterateSync = globIterateSync;
+    exports2.iterate = Object.assign(globIterate, {
+      sync: globIterateSync
+    });
+    exports2.sync = Object.assign(globSync, {
+      stream: globStreamSync,
+      iterate: globIterateSync
+    });
+    exports2.glob = Object.assign(glob_, {
+      glob: glob_,
+      globSync,
+      sync: exports2.sync,
+      globStream,
+      stream: exports2.stream,
+      globStreamSync,
+      streamSync: exports2.streamSync,
+      globIterate,
+      iterate: exports2.iterate,
+      globIterateSync,
+      iterateSync: exports2.iterateSync,
+      Glob: glob_js_1.Glob,
+      hasMagic: has_magic_js_1.hasMagic,
+      escape: minimatch_1.escape,
+      unescape: minimatch_1.unescape
+    });
+    exports2.glob.glob = exports2.glob;
+  }
+});
+
+// node_modules/archiver-utils/file.js
+var require_file3 = __commonJS({
+  "node_modules/archiver-utils/file.js"(exports2, module2) {
+    var fs2 = require_graceful_fs();
+    var path2 = require("path");
+    var flatten = require_flatten();
+    var difference = require_difference();
+    var union = require_union();
+    var isPlainObject = require_isPlainObject();
+    var glob2 = require_commonjs17();
+    var file = module2.exports = {};
+    var pathSeparatorRe = /[\/\\]/g;
+    var processPatterns = function(patterns, fn) {
+      var result = [];
+      flatten(patterns).forEach(function(pattern) {
+        var exclusion = pattern.indexOf("!") === 0;
+        if (exclusion) {
+          pattern = pattern.slice(1);
         }
-        this.#onReaddirCB.push(cb);
-        if (this.#readdirCBInFlight) {
-          return;
+        var matches = fn(pattern);
+        if (exclusion) {
+          result = difference(result, matches);
+        } else {
+          result = union(result, matches);
         }
-        this.#readdirCBInFlight = true;
-        const fullpath = this.fullpath();
-        this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {
-          if (er) {
-            this.#readdirFail(er.code);
-            children.provisional = 0;
-          } else {
-            for (const e of entries) {
-              this.#readdirAddChild(e, children);
+      });
+      return result;
+    };
+    file.exists = function() {
+      var filepath = path2.join.apply(path2, arguments);
+      return fs2.existsSync(filepath);
+    };
+    file.expand = function(...args) {
+      var options = isPlainObject(args[0]) ? args.shift() : {};
+      var patterns = Array.isArray(args[0]) ? args[0] : args;
+      if (patterns.length === 0) {
+        return [];
+      }
+      var matches = processPatterns(patterns, function(pattern) {
+        return glob2.sync(pattern, options);
+      });
+      if (options.filter) {
+        matches = matches.filter(function(filepath) {
+          filepath = path2.join(options.cwd || "", filepath);
+          try {
+            if (typeof options.filter === "function") {
+              return options.filter(filepath);
+            } else {
+              return fs2.statSync(filepath)[options.filter]();
             }
-            this.#readdirSuccess(children);
+          } catch (e) {
+            return false;
           }
-          this.#callOnReaddirCB(children.slice(0, children.provisional));
-          return;
         });
       }
-      #asyncReaddirInFlight;
-      /**
-       * Return an array of known child entries.
-       *
-       * If the Path cannot or does not contain any children, then an empty array
-       * is returned.
-       *
-       * Results are cached, and thus may be out of date if the filesystem is
-       * mutated.
-       */
-      async readdir() {
-        if (!this.canReaddir()) {
-          return [];
+      return matches;
+    };
+    file.expandMapping = function(patterns, destBase, options) {
+      options = Object.assign({
+        rename: function(destBase2, destPath) {
+          return path2.join(destBase2 || "", destPath);
         }
-        const children = this.children();
-        if (this.calledReaddir()) {
-          return children.slice(0, children.provisional);
+      }, options);
+      var files = [];
+      var fileByDest = {};
+      file.expand(options, patterns).forEach(function(src) {
+        var destPath = src;
+        if (options.flatten) {
+          destPath = path2.basename(destPath);
         }
-        const fullpath = this.fullpath();
-        if (this.#asyncReaddirInFlight) {
-          await this.#asyncReaddirInFlight;
-        } else {
-          let resolve2 = () => {
-          };
-          this.#asyncReaddirInFlight = new Promise((res) => resolve2 = res);
-          try {
-            for (const e of await this.#fs.promises.readdir(fullpath, {
-              withFileTypes: true
-            })) {
-              this.#readdirAddChild(e, children);
-            }
-            this.#readdirSuccess(children);
-          } catch (er) {
-            this.#readdirFail(er.code);
-            children.provisional = 0;
-          }
-          this.#asyncReaddirInFlight = void 0;
-          resolve2();
+        if (options.ext) {
+          destPath = destPath.replace(/(\.[^\/]*)?$/, options.ext);
         }
-        return children.slice(0, children.provisional);
-      }
-      /**
-       * synchronous {@link PathBase.readdir}
-       */
-      readdirSync() {
-        if (!this.canReaddir()) {
-          return [];
+        var dest = options.rename(destBase, destPath, options);
+        if (options.cwd) {
+          src = path2.join(options.cwd, src);
         }
-        const children = this.children();
-        if (this.calledReaddir()) {
-          return children.slice(0, children.provisional);
+        dest = dest.replace(pathSeparatorRe, "/");
+        src = src.replace(pathSeparatorRe, "/");
+        if (fileByDest[dest]) {
+          fileByDest[dest].src.push(src);
+        } else {
+          files.push({
+            src: [src],
+            dest
+          });
+          fileByDest[dest] = files[files.length - 1];
         }
-        const fullpath = this.fullpath();
-        try {
-          for (const e of this.#fs.readdirSync(fullpath, {
-            withFileTypes: true
-          })) {
-            this.#readdirAddChild(e, children);
-          }
-          this.#readdirSuccess(children);
-        } catch (er) {
-          this.#readdirFail(er.code);
-          children.provisional = 0;
+      });
+      return files;
+    };
+    file.normalizeFilesArray = function(data) {
+      var files = [];
+      data.forEach(function(obj) {
+        var prop;
+        if ("src" in obj || "dest" in obj) {
+          files.push(obj);
         }
-        return children.slice(0, children.provisional);
+      });
+      if (files.length === 0) {
+        return [];
       }
-      canReaddir() {
-        if (this.#type & ENOCHILD)
-          return false;
-        const ifmt = IFMT & this.#type;
-        if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
-          return false;
+      files = _(files).chain().forEach(function(obj) {
+        if (!("src" in obj) || !obj.src) {
+          return;
         }
-        return true;
-      }
-      shouldWalk(dirs, walkFilter) {
-        return (this.#type & IFDIR) === IFDIR && !(this.#type & ENOCHILD) && !dirs.has(this) && (!walkFilter || walkFilter(this));
-      }
-      /**
-       * Return the Path object corresponding to path as resolved
-       * by realpath(3).
-       *
-       * If the realpath call fails for any reason, `undefined` is returned.
-       *
-       * Result is cached, and thus may be outdated if the filesystem is mutated.
-       * On success, returns a Path object.
-       */
-      async realpath() {
-        if (this.#realpath)
-          return this.#realpath;
-        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
-          return void 0;
-        try {
-          const rp = await this.#fs.promises.realpath(this.fullpath());
-          return this.#realpath = this.resolve(rp);
-        } catch (_2) {
-          this.#markENOREALPATH();
+        if (Array.isArray(obj.src)) {
+          obj.src = flatten(obj.src);
+        } else {
+          obj.src = [obj.src];
         }
-      }
-      /**
-       * Synchronous {@link realpath}
-       */
-      realpathSync() {
-        if (this.#realpath)
-          return this.#realpath;
-        if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
-          return void 0;
-        try {
-          const rp = this.#fs.realpathSync(this.fullpath());
-          return this.#realpath = this.resolve(rp);
-        } catch (_2) {
-          this.#markENOREALPATH();
+      }).map(function(obj) {
+        var expandOptions = Object.assign({}, obj);
+        delete expandOptions.src;
+        delete expandOptions.dest;
+        if (obj.expand) {
+          return file.expandMapping(obj.src, obj.dest, expandOptions).map(function(mapObj) {
+            var result2 = Object.assign({}, obj);
+            result2.orig = Object.assign({}, obj);
+            result2.src = mapObj.src;
+            result2.dest = mapObj.dest;
+            ["expand", "cwd", "flatten", "rename", "ext"].forEach(function(prop) {
+              delete result2[prop];
+            });
+            return result2;
+          });
         }
-      }
-      /**
-       * Internal method to mark this Path object as the scurry cwd,
-       * called by {@link PathScurry#chdir}
-       *
-       * @internal
-       */
-      [setAsCwd](oldCwd) {
-        if (oldCwd === this)
-          return;
-        oldCwd.isCWD = false;
-        this.isCWD = true;
-        const changed = /* @__PURE__ */ new Set([]);
-        let rp = [];
-        let p = this;
-        while (p && p.parent) {
-          changed.add(p);
-          p.#relative = rp.join(this.sep);
-          p.#relativePosix = rp.join("/");
-          p = p.parent;
-          rp.push("..");
+        var result = Object.assign({}, obj);
+        result.orig = Object.assign({}, obj);
+        if ("src" in result) {
+          Object.defineProperty(result, "src", {
+            enumerable: true,
+            get: function fn() {
+              var src;
+              if (!("result" in fn)) {
+                src = obj.src;
+                src = Array.isArray(src) ? flatten(src) : [src];
+                fn.result = file.expand(expandOptions, src);
+              }
+              return fn.result;
+            }
+          });
         }
-        p = oldCwd;
-        while (p && p.parent && !changed.has(p)) {
-          p.#relative = void 0;
-          p.#relativePosix = void 0;
-          p = p.parent;
+        if ("dest" in result) {
+          result.dest = obj.dest;
         }
-      }
+        return result;
+      }).flatten().value();
+      return files;
     };
-    exports2.PathBase = PathBase;
-    var PathWin32 = class _PathWin32 extends PathBase {
-      /**
-       * Separator for generating path strings.
-       */
-      sep = "\\";
-      /**
-       * Separator for parsing path strings.
-       */
-      splitSep = eitherSep;
-      /**
-       * Do not create new Path objects directly.  They should always be accessed
-       * via the PathScurry class or other methods on the Path class.
-       *
-       * @internal
-       */
-      constructor(name, type2 = UNKNOWN, root, roots, nocase, children, opts) {
-        super(name, type2, root, roots, nocase, children, opts);
+  }
+});
+
+// node_modules/archiver-utils/index.js
+var require_archiver_utils = __commonJS({
+  "node_modules/archiver-utils/index.js"(exports2, module2) {
+    var fs2 = require_graceful_fs();
+    var path2 = require("path");
+    var isStream = require_is_stream();
+    var lazystream = require_lazystream();
+    var normalizePath = require_normalize_path();
+    var defaults = require_defaults();
+    var Stream = require("stream").Stream;
+    var PassThrough = require_ours().PassThrough;
+    var utils = module2.exports = {};
+    utils.file = require_file3();
+    utils.collectStream = function(source, callback) {
+      var collection = [];
+      var size = 0;
+      source.on("error", callback);
+      source.on("data", function(chunk) {
+        collection.push(chunk);
+        size += chunk.length;
+      });
+      source.on("end", function() {
+        var buf = Buffer.alloc(size);
+        var offset = 0;
+        collection.forEach(function(data) {
+          data.copy(buf, offset);
+          offset += data.length;
+        });
+        callback(null, buf);
+      });
+    };
+    utils.dateify = function(dateish) {
+      dateish = dateish || /* @__PURE__ */ new Date();
+      if (dateish instanceof Date) {
+        dateish = dateish;
+      } else if (typeof dateish === "string") {
+        dateish = new Date(dateish);
+      } else {
+        dateish = /* @__PURE__ */ new Date();
       }
-      /**
-       * @internal
-       */
-      newChild(name, type2 = UNKNOWN, opts = {}) {
-        return new _PathWin32(name, type2, this.root, this.roots, this.nocase, this.childrenCache(), opts);
+      return dateish;
+    };
+    utils.defaults = function(object, source, guard) {
+      var args = arguments;
+      args[0] = args[0] || {};
+      return defaults(...args);
+    };
+    utils.isStream = function(source) {
+      return isStream(source);
+    };
+    utils.lazyReadStream = function(filepath) {
+      return new lazystream.Readable(function() {
+        return fs2.createReadStream(filepath);
+      });
+    };
+    utils.normalizeInputSource = function(source) {
+      if (source === null) {
+        return Buffer.alloc(0);
+      } else if (typeof source === "string") {
+        return Buffer.from(source);
+      } else if (utils.isStream(source)) {
+        return source.pipe(new PassThrough());
       }
-      /**
-       * @internal
-       */
-      getRootString(path2) {
-        return node_path_1.win32.parse(path2).root;
+      return source;
+    };
+    utils.sanitizePath = function(filepath) {
+      return normalizePath(filepath, false).replace(/^\w+:/, "").replace(/^(\.\.\/|\/)+/, "");
+    };
+    utils.trailingSlashIt = function(str2) {
+      return str2.slice(-1) !== "/" ? str2 + "/" : str2;
+    };
+    utils.unixifyPath = function(filepath) {
+      return normalizePath(filepath, false).replace(/^\w+:/, "");
+    };
+    utils.walkdir = function(dirpath, base, callback) {
+      var results = [];
+      if (typeof base === "function") {
+        callback = base;
+        base = dirpath;
       }
-      /**
-       * @internal
-       */
-      getRoot(rootPath) {
-        rootPath = uncToDrive(rootPath.toUpperCase());
-        if (rootPath === this.root.name) {
-          return this.root;
+      fs2.readdir(dirpath, function(err, list) {
+        var i = 0;
+        var file;
+        var filepath;
+        if (err) {
+          return callback(err);
         }
-        for (const [compare2, root] of Object.entries(this.roots)) {
-          if (this.sameRoot(rootPath, compare2)) {
-            return this.roots[rootPath] = root;
+        (function next() {
+          file = list[i++];
+          if (!file) {
+            return callback(null, results);
           }
-        }
-        return this.roots[rootPath] = new PathScurryWin32(rootPath, this).root;
+          filepath = path2.join(dirpath, file);
+          fs2.stat(filepath, function(err2, stats) {
+            results.push({
+              path: filepath,
+              relative: path2.relative(base, filepath).replace(/\\/g, "/"),
+              stats
+            });
+            if (stats && stats.isDirectory()) {
+              utils.walkdir(filepath, base, function(err3, res) {
+                if (err3) {
+                  return callback(err3);
+                }
+                res.forEach(function(dirEntry) {
+                  results.push(dirEntry);
+                });
+                next();
+              });
+            } else {
+              next();
+            }
+          });
+        })();
+      });
+    };
+  }
+});
+
+// node_modules/archiver/lib/error.js
+var require_error2 = __commonJS({
+  "node_modules/archiver/lib/error.js"(exports2, module2) {
+    var util = require("util");
+    var ERROR_CODES = {
+      "ABORTED": "archive was aborted",
+      "DIRECTORYDIRPATHREQUIRED": "diretory dirpath argument must be a non-empty string value",
+      "DIRECTORYFUNCTIONINVALIDDATA": "invalid data returned by directory custom data function",
+      "ENTRYNAMEREQUIRED": "entry name must be a non-empty string value",
+      "FILEFILEPATHREQUIRED": "file filepath argument must be a non-empty string value",
+      "FINALIZING": "archive already finalizing",
+      "QUEUECLOSED": "queue closed",
+      "NOENDMETHOD": "no suitable finalize/end method defined by module",
+      "DIRECTORYNOTSUPPORTED": "support for directory entries not defined by module",
+      "FORMATSET": "archive format already set",
+      "INPUTSTEAMBUFFERREQUIRED": "input source must be valid Stream or Buffer instance",
+      "MODULESET": "module already set",
+      "SYMLINKNOTSUPPORTED": "support for symlink entries not defined by module",
+      "SYMLINKFILEPATHREQUIRED": "symlink filepath argument must be a non-empty string value",
+      "SYMLINKTARGETREQUIRED": "symlink target argument must be a non-empty string value",
+      "ENTRYNOTSUPPORTED": "entry not supported"
+    };
+    function ArchiverError(code, data) {
+      Error.captureStackTrace(this, this.constructor);
+      this.message = ERROR_CODES[code] || code;
+      this.code = code;
+      this.data = data;
+    }
+    util.inherits(ArchiverError, Error);
+    exports2 = module2.exports = ArchiverError;
+  }
+});
+
+// node_modules/archiver/lib/core.js
+var require_core2 = __commonJS({
+  "node_modules/archiver/lib/core.js"(exports2, module2) {
+    var fs2 = require("fs");
+    var glob2 = require_readdir_glob();
+    var async = require_async();
+    var path2 = require("path");
+    var util = require_archiver_utils();
+    var inherits = require("util").inherits;
+    var ArchiverError = require_error2();
+    var Transform = require_ours().Transform;
+    var win32 = process.platform === "win32";
+    var Archiver = function(format, options) {
+      if (!(this instanceof Archiver)) {
+        return new Archiver(format, options);
       }
-      /**
-       * @internal
-       */
-      sameRoot(rootPath, compare2 = this.root.name) {
-        rootPath = rootPath.toUpperCase().replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
-        return rootPath === compare2;
+      if (typeof format !== "string") {
+        options = format;
+        format = "zip";
       }
+      options = this.options = util.defaults(options, {
+        highWaterMark: 1024 * 1024,
+        statConcurrency: 4
+      });
+      Transform.call(this, options);
+      this._format = false;
+      this._module = false;
+      this._pending = 0;
+      this._pointer = 0;
+      this._entriesCount = 0;
+      this._entriesProcessedCount = 0;
+      this._fsEntriesTotalBytes = 0;
+      this._fsEntriesProcessedBytes = 0;
+      this._queue = async.queue(this._onQueueTask.bind(this), 1);
+      this._queue.drain(this._onQueueDrain.bind(this));
+      this._statQueue = async.queue(this._onStatQueueTask.bind(this), options.statConcurrency);
+      this._statQueue.drain(this._onQueueDrain.bind(this));
+      this._state = {
+        aborted: false,
+        finalize: false,
+        finalizing: false,
+        finalized: false,
+        modulePiped: false
+      };
+      this._streams = [];
     };
-    exports2.PathWin32 = PathWin32;
-    var PathPosix = class _PathPosix extends PathBase {
-      /**
-       * separator for parsing path strings
-       */
-      splitSep = "/";
-      /**
-       * separator for generating path strings
-       */
-      sep = "/";
-      /**
-       * Do not create new Path objects directly.  They should always be accessed
-       * via the PathScurry class or other methods on the Path class.
-       *
-       * @internal
-       */
-      constructor(name, type2 = UNKNOWN, root, roots, nocase, children, opts) {
-        super(name, type2, root, roots, nocase, children, opts);
+    inherits(Archiver, Transform);
+    Archiver.prototype._abort = function() {
+      this._state.aborted = true;
+      this._queue.kill();
+      this._statQueue.kill();
+      if (this._queue.idle()) {
+        this._shutdown();
       }
-      /**
-       * @internal
-       */
-      getRootString(path2) {
-        return path2.startsWith("/") ? "/" : "";
+    };
+    Archiver.prototype._append = function(filepath, data) {
+      data = data || {};
+      var task = {
+        source: null,
+        filepath
+      };
+      if (!data.name) {
+        data.name = filepath;
       }
-      /**
-       * @internal
-       */
-      getRoot(_rootPath) {
-        return this.root;
+      data.sourcePath = filepath;
+      task.data = data;
+      this._entriesCount++;
+      if (data.stats && data.stats instanceof fs2.Stats) {
+        task = this._updateQueueTaskWithStats(task, data.stats);
+        if (task) {
+          if (data.stats.size) {
+            this._fsEntriesTotalBytes += data.stats.size;
+          }
+          this._queue.push(task);
+        }
+      } else {
+        this._statQueue.push(task);
       }
-      /**
-       * @internal
-       */
-      newChild(name, type2 = UNKNOWN, opts = {}) {
-        return new _PathPosix(name, type2, this.root, this.roots, this.nocase, this.childrenCache(), opts);
+    };
+    Archiver.prototype._finalize = function() {
+      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
+        return;
       }
+      this._state.finalizing = true;
+      this._moduleFinalize();
+      this._state.finalizing = false;
+      this._state.finalized = true;
     };
-    exports2.PathPosix = PathPosix;
-    var PathScurryBase = class {
-      /**
-       * The root Path entry for the current working directory of this Scurry
-       */
-      root;
-      /**
-       * The string path for the root of this Scurry's current working directory
-       */
-      rootPath;
-      /**
-       * A collection of all roots encountered, referenced by rootPath
-       */
-      roots;
-      /**
-       * The Path entry corresponding to this PathScurry's current working directory.
-       */
-      cwd;
-      #resolveCache;
-      #resolvePosixCache;
-      #children;
-      /**
-       * Perform path comparisons case-insensitively.
-       *
-       * Defaults true on Darwin and Windows systems, false elsewhere.
-       */
-      nocase;
-      #fs;
-      /**
-       * This class should not be instantiated directly.
-       *
-       * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
-       *
-       * @internal
-       */
-      constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs: fs2 = defaultFS } = {}) {
-        this.#fs = fsFromOption(fs2);
-        if (cwd instanceof URL || cwd.startsWith("file://")) {
-          cwd = (0, node_url_1.fileURLToPath)(cwd);
-        }
-        const cwdPath = pathImpl.resolve(cwd);
-        this.roots = /* @__PURE__ */ Object.create(null);
-        this.rootPath = this.parseRootPath(cwdPath);
-        this.#resolveCache = new ResolveCache();
-        this.#resolvePosixCache = new ResolveCache();
-        this.#children = new ChildrenCache(childrenCacheSize);
-        const split = cwdPath.substring(this.rootPath.length).split(sep);
-        if (split.length === 1 && !split[0]) {
-          split.pop();
+    Archiver.prototype._maybeFinalize = function() {
+      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
+        return false;
+      }
+      if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) {
+        this._finalize();
+        return true;
+      }
+      return false;
+    };
+    Archiver.prototype._moduleAppend = function(source, data, callback) {
+      if (this._state.aborted) {
+        callback();
+        return;
+      }
+      this._module.append(source, data, function(err) {
+        this._task = null;
+        if (this._state.aborted) {
+          this._shutdown();
+          return;
         }
-        if (nocase === void 0) {
-          throw new TypeError("must provide nocase setting to PathScurryBase ctor");
+        if (err) {
+          this.emit("error", err);
+          setImmediate(callback);
+          return;
         }
-        this.nocase = nocase;
-        this.root = this.newRoot(this.#fs);
-        this.roots[this.rootPath] = this.root;
-        let prev = this.root;
-        let len = split.length - 1;
-        const joinSep = pathImpl.sep;
-        let abs = this.rootPath;
-        let sawFirst = false;
-        for (const part of split) {
-          const l = len--;
-          prev = prev.child(part, {
-            relative: new Array(l).fill("..").join(joinSep),
-            relativePosix: new Array(l).fill("..").join("/"),
-            fullpath: abs += (sawFirst ? "" : joinSep) + part
-          });
-          sawFirst = true;
+        this.emit("entry", data);
+        this._entriesProcessedCount++;
+        if (data.stats && data.stats.size) {
+          this._fsEntriesProcessedBytes += data.stats.size;
         }
-        this.cwd = prev;
+        this.emit("progress", {
+          entries: {
+            total: this._entriesCount,
+            processed: this._entriesProcessedCount
+          },
+          fs: {
+            totalBytes: this._fsEntriesTotalBytes,
+            processedBytes: this._fsEntriesProcessedBytes
+          }
+        });
+        setImmediate(callback);
+      }.bind(this));
+    };
+    Archiver.prototype._moduleFinalize = function() {
+      if (typeof this._module.finalize === "function") {
+        this._module.finalize();
+      } else if (typeof this._module.end === "function") {
+        this._module.end();
+      } else {
+        this.emit("error", new ArchiverError("NOENDMETHOD"));
       }
-      /**
-       * Get the depth of a provided path, string, or the cwd
-       */
-      depth(path2 = this.cwd) {
-        if (typeof path2 === "string") {
-          path2 = this.cwd.resolve(path2);
-        }
-        return path2.depth();
+    };
+    Archiver.prototype._modulePipe = function() {
+      this._module.on("error", this._onModuleError.bind(this));
+      this._module.pipe(this);
+      this._state.modulePiped = true;
+    };
+    Archiver.prototype._moduleSupports = function(key) {
+      if (!this._module.supports || !this._module.supports[key]) {
+        return false;
       }
-      /**
-       * Return the cache of child entries.  Exposed so subclasses can create
-       * child Path objects in a platform-specific way.
-       *
-       * @internal
-       */
-      childrenCache() {
-        return this.#children;
+      return this._module.supports[key];
+    };
+    Archiver.prototype._moduleUnpipe = function() {
+      this._module.unpipe(this);
+      this._state.modulePiped = false;
+    };
+    Archiver.prototype._normalizeEntryData = function(data, stats) {
+      data = util.defaults(data, {
+        type: "file",
+        name: null,
+        date: null,
+        mode: null,
+        prefix: null,
+        sourcePath: null,
+        stats: false
+      });
+      if (stats && data.stats === false) {
+        data.stats = stats;
       }
-      /**
-       * Resolve one or more path strings to a resolved string
-       *
-       * Same interface as require('path').resolve.
-       *
-       * Much faster than path.resolve() when called multiple times for the same
-       * path, because the resolved Path objects are cached.  Much slower
-       * otherwise.
-       */
-      resolve(...paths) {
-        let r = "";
-        for (let i = paths.length - 1; i >= 0; i--) {
-          const p = paths[i];
-          if (!p || p === ".")
-            continue;
-          r = r ? `${p}/${r}` : p;
-          if (this.isAbsolute(p)) {
-            break;
-          }
+      var isDir = data.type === "directory";
+      if (data.name) {
+        if (typeof data.prefix === "string" && "" !== data.prefix) {
+          data.name = data.prefix + "/" + data.name;
+          data.prefix = null;
         }
-        const cached = this.#resolveCache.get(r);
-        if (cached !== void 0) {
-          return cached;
+        data.name = util.sanitizePath(data.name);
+        if (data.type !== "symlink" && data.name.slice(-1) === "/") {
+          isDir = true;
+          data.type = "directory";
+        } else if (isDir) {
+          data.name += "/";
         }
-        const result = this.cwd.resolve(r).fullpath();
-        this.#resolveCache.set(r, result);
-        return result;
       }
-      /**
-       * Resolve one or more path strings to a resolved string, returning
-       * the posix path.  Identical to .resolve() on posix systems, but on
-       * windows will return a forward-slash separated UNC path.
-       *
-       * Same interface as require('path').resolve.
-       *
-       * Much faster than path.resolve() when called multiple times for the same
-       * path, because the resolved Path objects are cached.  Much slower
-       * otherwise.
-       */
-      resolvePosix(...paths) {
-        let r = "";
-        for (let i = paths.length - 1; i >= 0; i--) {
-          const p = paths[i];
-          if (!p || p === ".")
-            continue;
-          r = r ? `${p}/${r}` : p;
-          if (this.isAbsolute(p)) {
-            break;
-          }
+      if (typeof data.mode === "number") {
+        if (win32) {
+          data.mode &= 511;
+        } else {
+          data.mode &= 4095;
         }
-        const cached = this.#resolvePosixCache.get(r);
-        if (cached !== void 0) {
-          return cached;
+      } else if (data.stats && data.mode === null) {
+        if (win32) {
+          data.mode = data.stats.mode & 511;
+        } else {
+          data.mode = data.stats.mode & 4095;
         }
-        const result = this.cwd.resolve(r).fullpathPosix();
-        this.#resolvePosixCache.set(r, result);
-        return result;
-      }
-      /**
-       * find the relative path from the cwd to the supplied path string or entry
-       */
-      relative(entry = this.cwd) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
+        if (win32 && isDir) {
+          data.mode = 493;
         }
-        return entry.relative();
+      } else if (data.mode === null) {
+        data.mode = isDir ? 493 : 420;
       }
-      /**
-       * find the relative path from the cwd to the supplied path string or
-       * entry, using / as the path delimiter, even on Windows.
-       */
-      relativePosix(entry = this.cwd) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        }
-        return entry.relativePosix();
+      if (data.stats && data.date === null) {
+        data.date = data.stats.mtime;
+      } else {
+        data.date = util.dateify(data.date);
       }
-      /**
-       * Return the basename for the provided string or Path object
-       */
-      basename(entry = this.cwd) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        }
-        return entry.name;
+      return data;
+    };
+    Archiver.prototype._onModuleError = function(err) {
+      this.emit("error", err);
+    };
+    Archiver.prototype._onQueueDrain = function() {
+      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
+        return;
       }
-      /**
-       * Return the dirname for the provided string or Path object
-       */
-      dirname(entry = this.cwd) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
+      if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) {
+        this._finalize();
+      }
+    };
+    Archiver.prototype._onQueueTask = function(task, callback) {
+      var fullCallback = () => {
+        if (task.data.callback) {
+          task.data.callback();
         }
-        return (entry.parent || entry).fullpath();
+        callback();
+      };
+      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
+        fullCallback();
+        return;
       }
-      async readdir(entry = this.cwd, opts = {
-        withFileTypes: true
-      }) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          opts = entry;
-          entry = this.cwd;
+      this._task = task;
+      this._moduleAppend(task.source, task.data, fullCallback);
+    };
+    Archiver.prototype._onStatQueueTask = function(task, callback) {
+      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
+        callback();
+        return;
+      }
+      fs2.lstat(task.filepath, function(err, stats) {
+        if (this._state.aborted) {
+          setImmediate(callback);
+          return;
         }
-        const { withFileTypes } = opts;
-        if (!entry.canReaddir()) {
-          return [];
-        } else {
-          const p = await entry.readdir();
-          return withFileTypes ? p : p.map((e) => e.name);
+        if (err) {
+          this._entriesCount--;
+          this.emit("warning", err);
+          setImmediate(callback);
+          return;
         }
-      }
-      readdirSync(entry = this.cwd, opts = {
-        withFileTypes: true
-      }) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          opts = entry;
-          entry = this.cwd;
+        task = this._updateQueueTaskWithStats(task, stats);
+        if (task) {
+          if (stats.size) {
+            this._fsEntriesTotalBytes += stats.size;
+          }
+          this._queue.push(task);
         }
-        const { withFileTypes = true } = opts;
-        if (!entry.canReaddir()) {
-          return [];
-        } else if (withFileTypes) {
-          return entry.readdirSync();
+        setImmediate(callback);
+      }.bind(this));
+    };
+    Archiver.prototype._shutdown = function() {
+      this._moduleUnpipe();
+      this.end();
+    };
+    Archiver.prototype._transform = function(chunk, encoding, callback) {
+      if (chunk) {
+        this._pointer += chunk.length;
+      }
+      callback(null, chunk);
+    };
+    Archiver.prototype._updateQueueTaskWithStats = function(task, stats) {
+      if (stats.isFile()) {
+        task.data.type = "file";
+        task.data.sourceType = "stream";
+        task.source = util.lazyReadStream(task.filepath);
+      } else if (stats.isDirectory() && this._moduleSupports("directory")) {
+        task.data.name = util.trailingSlashIt(task.data.name);
+        task.data.type = "directory";
+        task.data.sourcePath = util.trailingSlashIt(task.filepath);
+        task.data.sourceType = "buffer";
+        task.source = Buffer.concat([]);
+      } else if (stats.isSymbolicLink() && this._moduleSupports("symlink")) {
+        var linkPath = fs2.readlinkSync(task.filepath);
+        var dirName = path2.dirname(task.filepath);
+        task.data.type = "symlink";
+        task.data.linkname = path2.relative(dirName, path2.resolve(dirName, linkPath));
+        task.data.sourceType = "buffer";
+        task.source = Buffer.concat([]);
+      } else {
+        if (stats.isDirectory()) {
+          this.emit("warning", new ArchiverError("DIRECTORYNOTSUPPORTED", task.data));
+        } else if (stats.isSymbolicLink()) {
+          this.emit("warning", new ArchiverError("SYMLINKNOTSUPPORTED", task.data));
         } else {
-          return entry.readdirSync().map((e) => e.name);
+          this.emit("warning", new ArchiverError("ENTRYNOTSUPPORTED", task.data));
         }
+        return null;
       }
-      /**
-       * Call lstat() on the string or Path object, and update all known
-       * information that can be determined.
-       *
-       * Note that unlike `fs.lstat()`, the returned value does not contain some
-       * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
-       * information is required, you will need to call `fs.lstat` yourself.
-       *
-       * If the Path refers to a nonexistent file, or if the lstat call fails for
-       * any reason, `undefined` is returned.  Otherwise the updated Path object is
-       * returned.
-       *
-       * Results are cached, and thus may be out of date if the filesystem is
-       * mutated.
-       */
-      async lstat(entry = this.cwd) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        }
-        return entry.lstat();
+      task.data = this._normalizeEntryData(task.data, stats);
+      return task;
+    };
+    Archiver.prototype.abort = function() {
+      if (this._state.aborted || this._state.finalized) {
+        return this;
       }
-      /**
-       * synchronous {@link PathScurryBase.lstat}
-       */
-      lstatSync(entry = this.cwd) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        }
-        return entry.lstatSync();
+      this._abort();
+      return this;
+    };
+    Archiver.prototype.append = function(source, data) {
+      if (this._state.finalize || this._state.aborted) {
+        this.emit("error", new ArchiverError("QUEUECLOSED"));
+        return this;
       }
-      async readlink(entry = this.cwd, { withFileTypes } = {
-        withFileTypes: false
-      }) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          withFileTypes = entry.withFileTypes;
-          entry = this.cwd;
-        }
-        const e = await entry.readlink();
-        return withFileTypes ? e : e?.fullpath();
+      data = this._normalizeEntryData(data);
+      if (typeof data.name !== "string" || data.name.length === 0) {
+        this.emit("error", new ArchiverError("ENTRYNAMEREQUIRED"));
+        return this;
       }
-      readlinkSync(entry = this.cwd, { withFileTypes } = {
-        withFileTypes: false
-      }) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          withFileTypes = entry.withFileTypes;
-          entry = this.cwd;
-        }
-        const e = entry.readlinkSync();
-        return withFileTypes ? e : e?.fullpath();
+      if (data.type === "directory" && !this._moduleSupports("directory")) {
+        this.emit("error", new ArchiverError("DIRECTORYNOTSUPPORTED", { name: data.name }));
+        return this;
       }
-      async realpath(entry = this.cwd, { withFileTypes } = {
-        withFileTypes: false
-      }) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          withFileTypes = entry.withFileTypes;
-          entry = this.cwd;
-        }
-        const e = await entry.realpath();
-        return withFileTypes ? e : e?.fullpath();
+      source = util.normalizeInputSource(source);
+      if (Buffer.isBuffer(source)) {
+        data.sourceType = "buffer";
+      } else if (util.isStream(source)) {
+        data.sourceType = "stream";
+      } else {
+        this.emit("error", new ArchiverError("INPUTSTEAMBUFFERREQUIRED", { name: data.name }));
+        return this;
       }
-      realpathSync(entry = this.cwd, { withFileTypes } = {
-        withFileTypes: false
-      }) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          withFileTypes = entry.withFileTypes;
-          entry = this.cwd;
-        }
-        const e = entry.realpathSync();
-        return withFileTypes ? e : e?.fullpath();
+      this._entriesCount++;
+      this._queue.push({
+        data,
+        source
+      });
+      return this;
+    };
+    Archiver.prototype.directory = function(dirpath, destpath, data) {
+      if (this._state.finalize || this._state.aborted) {
+        this.emit("error", new ArchiverError("QUEUECLOSED"));
+        return this;
       }
-      async walk(entry = this.cwd, opts = {}) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          opts = entry;
-          entry = this.cwd;
-        }
-        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
-        const results = [];
-        if (!filter || filter(entry)) {
-          results.push(withFileTypes ? entry : entry.fullpath());
-        }
-        const dirs = /* @__PURE__ */ new Set();
-        const walk = (dir, cb) => {
-          dirs.add(dir);
-          dir.readdirCB((er, entries) => {
-            if (er) {
-              return cb(er);
-            }
-            let len = entries.length;
-            if (!len)
-              return cb();
-            const next = () => {
-              if (--len === 0) {
-                cb();
-              }
-            };
-            for (const e of entries) {
-              if (!filter || filter(e)) {
-                results.push(withFileTypes ? e : e.fullpath());
-              }
-              if (follow && e.isSymbolicLink()) {
-                e.realpath().then((r) => r?.isUnknown() ? r.lstat() : r).then((r) => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next());
-              } else {
-                if (e.shouldWalk(dirs, walkFilter)) {
-                  walk(e, next);
-                } else {
-                  next();
-                }
-              }
-            }
-          }, true);
-        };
-        const start = entry;
-        return new Promise((res, rej) => {
-          walk(start, (er) => {
-            if (er)
-              return rej(er);
-            res(results);
-          });
-        });
+      if (typeof dirpath !== "string" || dirpath.length === 0) {
+        this.emit("error", new ArchiverError("DIRECTORYDIRPATHREQUIRED"));
+        return this;
+      }
+      this._pending++;
+      if (destpath === false) {
+        destpath = "";
+      } else if (typeof destpath !== "string") {
+        destpath = dirpath;
+      }
+      var dataFunction = false;
+      if (typeof data === "function") {
+        dataFunction = data;
+        data = {};
+      } else if (typeof data !== "object") {
+        data = {};
+      }
+      var globOptions = {
+        stat: true,
+        dot: true
+      };
+      function onGlobEnd() {
+        this._pending--;
+        this._maybeFinalize();
       }
-      walkSync(entry = this.cwd, opts = {}) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          opts = entry;
-          entry = this.cwd;
-        }
-        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
-        const results = [];
-        if (!filter || filter(entry)) {
-          results.push(withFileTypes ? entry : entry.fullpath());
-        }
-        const dirs = /* @__PURE__ */ new Set([entry]);
-        for (const dir of dirs) {
-          const entries = dir.readdirSync();
-          for (const e of entries) {
-            if (!filter || filter(e)) {
-              results.push(withFileTypes ? e : e.fullpath());
-            }
-            let r = e;
-            if (e.isSymbolicLink()) {
-              if (!(follow && (r = e.realpathSync())))
-                continue;
-              if (r.isUnknown())
-                r.lstatSync();
-            }
-            if (r.shouldWalk(dirs, walkFilter)) {
-              dirs.add(r);
+      function onGlobError(err) {
+        this.emit("error", err);
+      }
+      function onGlobMatch(match) {
+        globber.pause();
+        var ignoreMatch = false;
+        var entryData = Object.assign({}, data);
+        entryData.name = match.relative;
+        entryData.prefix = destpath;
+        entryData.stats = match.stat;
+        entryData.callback = globber.resume.bind(globber);
+        try {
+          if (dataFunction) {
+            entryData = dataFunction(entryData);
+            if (entryData === false) {
+              ignoreMatch = true;
+            } else if (typeof entryData !== "object") {
+              throw new ArchiverError("DIRECTORYFUNCTIONINVALIDDATA", { dirpath });
             }
           }
+        } catch (e) {
+          this.emit("error", e);
+          return;
         }
-        return results;
+        if (ignoreMatch) {
+          globber.resume();
+          return;
+        }
+        this._append(match.absolute, entryData);
       }
-      /**
-       * Support for `for await`
-       *
-       * Alias for {@link PathScurryBase.iterate}
-       *
-       * Note: As of Node 19, this is very slow, compared to other methods of
-       * walking.  Consider using {@link PathScurryBase.stream} if memory overhead
-       * and backpressure are concerns, or {@link PathScurryBase.walk} if not.
-       */
-      [Symbol.asyncIterator]() {
-        return this.iterate();
+      var globber = glob2(dirpath, globOptions);
+      globber.on("error", onGlobError.bind(this));
+      globber.on("match", onGlobMatch.bind(this));
+      globber.on("end", onGlobEnd.bind(this));
+      return this;
+    };
+    Archiver.prototype.file = function(filepath, data) {
+      if (this._state.finalize || this._state.aborted) {
+        this.emit("error", new ArchiverError("QUEUECLOSED"));
+        return this;
       }
-      iterate(entry = this.cwd, options = {}) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          options = entry;
-          entry = this.cwd;
-        }
-        return this.stream(entry, options)[Symbol.asyncIterator]();
+      if (typeof filepath !== "string" || filepath.length === 0) {
+        this.emit("error", new ArchiverError("FILEFILEPATHREQUIRED"));
+        return this;
       }
-      /**
-       * Iterating over a PathScurry performs a synchronous walk.
-       *
-       * Alias for {@link PathScurryBase.iterateSync}
-       */
-      [Symbol.iterator]() {
-        return this.iterateSync();
+      this._append(filepath, data);
+      return this;
+    };
+    Archiver.prototype.glob = function(pattern, options, data) {
+      this._pending++;
+      options = util.defaults(options, {
+        stat: true,
+        pattern
+      });
+      function onGlobEnd() {
+        this._pending--;
+        this._maybeFinalize();
       }
-      *iterateSync(entry = this.cwd, opts = {}) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          opts = entry;
-          entry = this.cwd;
-        }
-        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
-        if (!filter || filter(entry)) {
-          yield withFileTypes ? entry : entry.fullpath();
-        }
-        const dirs = /* @__PURE__ */ new Set([entry]);
-        for (const dir of dirs) {
-          const entries = dir.readdirSync();
-          for (const e of entries) {
-            if (!filter || filter(e)) {
-              yield withFileTypes ? e : e.fullpath();
-            }
-            let r = e;
-            if (e.isSymbolicLink()) {
-              if (!(follow && (r = e.realpathSync())))
-                continue;
-              if (r.isUnknown())
-                r.lstatSync();
-            }
-            if (r.shouldWalk(dirs, walkFilter)) {
-              dirs.add(r);
-            }
-          }
-        }
+      function onGlobError(err) {
+        this.emit("error", err);
       }
-      stream(entry = this.cwd, opts = {}) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          opts = entry;
-          entry = this.cwd;
-        }
-        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
-        const results = new minipass_1.Minipass({ objectMode: true });
-        if (!filter || filter(entry)) {
-          results.write(withFileTypes ? entry : entry.fullpath());
-        }
-        const dirs = /* @__PURE__ */ new Set();
-        const queue = [entry];
-        let processing = 0;
-        const process2 = () => {
-          let paused = false;
-          while (!paused) {
-            const dir = queue.shift();
-            if (!dir) {
-              if (processing === 0)
-                results.end();
-              return;
-            }
-            processing++;
-            dirs.add(dir);
-            const onReaddir = (er, entries, didRealpaths = false) => {
-              if (er)
-                return results.emit("error", er);
-              if (follow && !didRealpaths) {
-                const promises2 = [];
-                for (const e of entries) {
-                  if (e.isSymbolicLink()) {
-                    promises2.push(e.realpath().then((r) => r?.isUnknown() ? r.lstat() : r));
-                  }
-                }
-                if (promises2.length) {
-                  Promise.all(promises2).then(() => onReaddir(null, entries, true));
-                  return;
-                }
-              }
-              for (const e of entries) {
-                if (e && (!filter || filter(e))) {
-                  if (!results.write(withFileTypes ? e : e.fullpath())) {
-                    paused = true;
-                  }
-                }
-              }
-              processing--;
-              for (const e of entries) {
-                const r = e.realpathCached() || e;
-                if (r.shouldWalk(dirs, walkFilter)) {
-                  queue.push(r);
-                }
-              }
-              if (paused && !results.flowing) {
-                results.once("drain", process2);
-              } else if (!sync) {
-                process2();
-              }
-            };
-            let sync = true;
-            dir.readdirCB(onReaddir, true);
-            sync = false;
-          }
-        };
-        process2();
-        return results;
+      function onGlobMatch(match) {
+        globber.pause();
+        var entryData = Object.assign({}, data);
+        entryData.callback = globber.resume.bind(globber);
+        entryData.stats = match.stat;
+        entryData.name = match.relative;
+        this._append(match.absolute, entryData);
       }
-      streamSync(entry = this.cwd, opts = {}) {
-        if (typeof entry === "string") {
-          entry = this.cwd.resolve(entry);
-        } else if (!(entry instanceof PathBase)) {
-          opts = entry;
-          entry = this.cwd;
-        }
-        const { withFileTypes = true, follow = false, filter, walkFilter } = opts;
-        const results = new minipass_1.Minipass({ objectMode: true });
-        const dirs = /* @__PURE__ */ new Set();
-        if (!filter || filter(entry)) {
-          results.write(withFileTypes ? entry : entry.fullpath());
-        }
-        const queue = [entry];
-        let processing = 0;
-        const process2 = () => {
-          let paused = false;
-          while (!paused) {
-            const dir = queue.shift();
-            if (!dir) {
-              if (processing === 0)
-                results.end();
-              return;
-            }
-            processing++;
-            dirs.add(dir);
-            const entries = dir.readdirSync();
-            for (const e of entries) {
-              if (!filter || filter(e)) {
-                if (!results.write(withFileTypes ? e : e.fullpath())) {
-                  paused = true;
-                }
-              }
-            }
-            processing--;
-            for (const e of entries) {
-              let r = e;
-              if (e.isSymbolicLink()) {
-                if (!(follow && (r = e.realpathSync())))
-                  continue;
-                if (r.isUnknown())
-                  r.lstatSync();
-              }
-              if (r.shouldWalk(dirs, walkFilter)) {
-                queue.push(r);
-              }
-            }
+      var globber = glob2(options.cwd || ".", options);
+      globber.on("error", onGlobError.bind(this));
+      globber.on("match", onGlobMatch.bind(this));
+      globber.on("end", onGlobEnd.bind(this));
+      return this;
+    };
+    Archiver.prototype.finalize = function() {
+      if (this._state.aborted) {
+        var abortedError = new ArchiverError("ABORTED");
+        this.emit("error", abortedError);
+        return Promise.reject(abortedError);
+      }
+      if (this._state.finalize) {
+        var finalizingError = new ArchiverError("FINALIZING");
+        this.emit("error", finalizingError);
+        return Promise.reject(finalizingError);
+      }
+      this._state.finalize = true;
+      if (this._pending === 0 && this._queue.idle() && this._statQueue.idle()) {
+        this._finalize();
+      }
+      var self2 = this;
+      return new Promise(function(resolve2, reject) {
+        var errored;
+        self2._module.on("end", function() {
+          if (!errored) {
+            resolve2();
           }
-          if (paused && !results.flowing)
-            results.once("drain", process2);
-        };
-        process2();
-        return results;
+        });
+        self2._module.on("error", function(err) {
+          errored = true;
+          reject(err);
+        });
+      });
+    };
+    Archiver.prototype.setFormat = function(format) {
+      if (this._format) {
+        this.emit("error", new ArchiverError("FORMATSET"));
+        return this;
       }
-      chdir(path2 = this.cwd) {
-        const oldCwd = this.cwd;
-        this.cwd = typeof path2 === "string" ? this.cwd.resolve(path2) : path2;
-        this.cwd[setAsCwd](oldCwd);
+      this._format = format;
+      return this;
+    };
+    Archiver.prototype.setModule = function(module3) {
+      if (this._state.aborted) {
+        this.emit("error", new ArchiverError("ABORTED"));
+        return this;
+      }
+      if (this._state.module) {
+        this.emit("error", new ArchiverError("MODULESET"));
+        return this;
+      }
+      this._module = module3;
+      this._modulePipe();
+      return this;
+    };
+    Archiver.prototype.symlink = function(filepath, target, mode) {
+      if (this._state.finalize || this._state.aborted) {
+        this.emit("error", new ArchiverError("QUEUECLOSED"));
+        return this;
+      }
+      if (typeof filepath !== "string" || filepath.length === 0) {
+        this.emit("error", new ArchiverError("SYMLINKFILEPATHREQUIRED"));
+        return this;
+      }
+      if (typeof target !== "string" || target.length === 0) {
+        this.emit("error", new ArchiverError("SYMLINKTARGETREQUIRED", { filepath }));
+        return this;
+      }
+      if (!this._moduleSupports("symlink")) {
+        this.emit("error", new ArchiverError("SYMLINKNOTSUPPORTED", { filepath }));
+        return this;
+      }
+      var data = {};
+      data.type = "symlink";
+      data.name = filepath.replace(/\\/g, "/");
+      data.linkname = target.replace(/\\/g, "/");
+      data.sourceType = "buffer";
+      if (typeof mode === "number") {
+        data.mode = mode;
+      }
+      this._entriesCount++;
+      this._queue.push({
+        data,
+        source: Buffer.concat([])
+      });
+      return this;
+    };
+    Archiver.prototype.pointer = function() {
+      return this._pointer;
+    };
+    Archiver.prototype.use = function(plugin) {
+      this._streams.push(plugin);
+      return this;
+    };
+    module2.exports = Archiver;
+  }
+});
+
+// node_modules/compress-commons/lib/archivers/archive-entry.js
+var require_archive_entry = __commonJS({
+  "node_modules/compress-commons/lib/archivers/archive-entry.js"(exports2, module2) {
+    var ArchiveEntry = module2.exports = function() {
+    };
+    ArchiveEntry.prototype.getName = function() {
+    };
+    ArchiveEntry.prototype.getSize = function() {
+    };
+    ArchiveEntry.prototype.getLastModifiedDate = function() {
+    };
+    ArchiveEntry.prototype.isDirectory = function() {
+    };
+  }
+});
+
+// node_modules/compress-commons/lib/archivers/zip/util.js
+var require_util13 = __commonJS({
+  "node_modules/compress-commons/lib/archivers/zip/util.js"(exports2, module2) {
+    var util = module2.exports = {};
+    util.dateToDos = function(d, forceLocalTime) {
+      forceLocalTime = forceLocalTime || false;
+      var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear();
+      if (year < 1980) {
+        return 2162688;
+      } else if (year >= 2044) {
+        return 2141175677;
+      }
+      var val2 = {
+        year,
+        month: forceLocalTime ? d.getMonth() : d.getUTCMonth(),
+        date: forceLocalTime ? d.getDate() : d.getUTCDate(),
+        hours: forceLocalTime ? d.getHours() : d.getUTCHours(),
+        minutes: forceLocalTime ? d.getMinutes() : d.getUTCMinutes(),
+        seconds: forceLocalTime ? d.getSeconds() : d.getUTCSeconds()
+      };
+      return val2.year - 1980 << 25 | val2.month + 1 << 21 | val2.date << 16 | val2.hours << 11 | val2.minutes << 5 | val2.seconds / 2;
+    };
+    util.dosToDate = function(dos) {
+      return new Date((dos >> 25 & 127) + 1980, (dos >> 21 & 15) - 1, dos >> 16 & 31, dos >> 11 & 31, dos >> 5 & 63, (dos & 31) << 1);
+    };
+    util.fromDosTime = function(buf) {
+      return util.dosToDate(buf.readUInt32LE(0));
+    };
+    util.getEightBytes = function(v) {
+      var buf = Buffer.alloc(8);
+      buf.writeUInt32LE(v % 4294967296, 0);
+      buf.writeUInt32LE(v / 4294967296 | 0, 4);
+      return buf;
+    };
+    util.getShortBytes = function(v) {
+      var buf = Buffer.alloc(2);
+      buf.writeUInt16LE((v & 65535) >>> 0, 0);
+      return buf;
+    };
+    util.getShortBytesValue = function(buf, offset) {
+      return buf.readUInt16LE(offset);
+    };
+    util.getLongBytes = function(v) {
+      var buf = Buffer.alloc(4);
+      buf.writeUInt32LE((v & 4294967295) >>> 0, 0);
+      return buf;
+    };
+    util.getLongBytesValue = function(buf, offset) {
+      return buf.readUInt32LE(offset);
+    };
+    util.toDosTime = function(d) {
+      return util.getLongBytes(util.dateToDos(d));
+    };
+  }
+});
+
+// node_modules/compress-commons/lib/archivers/zip/general-purpose-bit.js
+var require_general_purpose_bit = __commonJS({
+  "node_modules/compress-commons/lib/archivers/zip/general-purpose-bit.js"(exports2, module2) {
+    var zipUtil = require_util13();
+    var DATA_DESCRIPTOR_FLAG = 1 << 3;
+    var ENCRYPTION_FLAG = 1 << 0;
+    var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2;
+    var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1;
+    var STRONG_ENCRYPTION_FLAG = 1 << 6;
+    var UFT8_NAMES_FLAG = 1 << 11;
+    var GeneralPurposeBit = module2.exports = function() {
+      if (!(this instanceof GeneralPurposeBit)) {
+        return new GeneralPurposeBit();
       }
+      this.descriptor = false;
+      this.encryption = false;
+      this.utf8 = false;
+      this.numberOfShannonFanoTrees = 0;
+      this.strongEncryption = false;
+      this.slidingDictionarySize = 0;
+      return this;
+    };
+    GeneralPurposeBit.prototype.encode = function() {
+      return zipUtil.getShortBytes(
+        (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) | (this.utf8 ? UFT8_NAMES_FLAG : 0) | (this.encryption ? ENCRYPTION_FLAG : 0) | (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0)
+      );
+    };
+    GeneralPurposeBit.prototype.parse = function(buf, offset) {
+      var flag = zipUtil.getShortBytesValue(buf, offset);
+      var gbp = new GeneralPurposeBit();
+      gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0);
+      gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0);
+      gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0);
+      gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0);
+      gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096);
+      gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2);
+      return gbp;
+    };
+    GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) {
+      this.numberOfShannonFanoTrees = n;
+    };
+    GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() {
+      return this.numberOfShannonFanoTrees;
+    };
+    GeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) {
+      this.slidingDictionarySize = n;
+    };
+    GeneralPurposeBit.prototype.getSlidingDictionarySize = function() {
+      return this.slidingDictionarySize;
+    };
+    GeneralPurposeBit.prototype.useDataDescriptor = function(b) {
+      this.descriptor = b;
+    };
+    GeneralPurposeBit.prototype.usesDataDescriptor = function() {
+      return this.descriptor;
+    };
+    GeneralPurposeBit.prototype.useEncryption = function(b) {
+      this.encryption = b;
+    };
+    GeneralPurposeBit.prototype.usesEncryption = function() {
+      return this.encryption;
+    };
+    GeneralPurposeBit.prototype.useStrongEncryption = function(b) {
+      this.strongEncryption = b;
+    };
+    GeneralPurposeBit.prototype.usesStrongEncryption = function() {
+      return this.strongEncryption;
+    };
+    GeneralPurposeBit.prototype.useUTF8ForNames = function(b) {
+      this.utf8 = b;
     };
-    exports2.PathScurryBase = PathScurryBase;
-    var PathScurryWin32 = class extends PathScurryBase {
+    GeneralPurposeBit.prototype.usesUTF8ForNames = function() {
+      return this.utf8;
+    };
+  }
+});
+
+// node_modules/compress-commons/lib/archivers/zip/unix-stat.js
+var require_unix_stat = __commonJS({
+  "node_modules/compress-commons/lib/archivers/zip/unix-stat.js"(exports2, module2) {
+    module2.exports = {
       /**
-       * separator for generating path strings
+       * Bits used for permissions (and sticky bit)
        */
-      sep = "\\";
-      constructor(cwd = process.cwd(), opts = {}) {
-        const { nocase = true } = opts;
-        super(cwd, node_path_1.win32, "\\", { ...opts, nocase });
-        this.nocase = nocase;
-        for (let p = this.cwd; p; p = p.parent) {
-          p.nocase = this.nocase;
-        }
-      }
+      PERM_MASK: 4095,
+      // 07777
       /**
-       * @internal
+       * Bits used to indicate the filesystem object type.
        */
-      parseRootPath(dir) {
-        return node_path_1.win32.parse(dir).root.toUpperCase();
-      }
+      FILE_TYPE_FLAG: 61440,
+      // 0170000
       /**
-       * @internal
+       * Indicates symbolic links.
        */
-      newRoot(fs2) {
-        return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
-      }
+      LINK_FLAG: 40960,
+      // 0120000
       /**
-       * Return true if the provided path string is an absolute path
+       * Indicates plain files.
        */
-      isAbsolute(p) {
-        return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
-      }
-    };
-    exports2.PathScurryWin32 = PathScurryWin32;
-    var PathScurryPosix = class extends PathScurryBase {
+      FILE_FLAG: 32768,
+      // 0100000
       /**
-       * separator for generating path strings
+       * Indicates directories.
        */
-      sep = "/";
-      constructor(cwd = process.cwd(), opts = {}) {
-        const { nocase = false } = opts;
-        super(cwd, node_path_1.posix, "/", { ...opts, nocase });
-        this.nocase = nocase;
-      }
+      DIR_FLAG: 16384,
+      // 040000
+      // ----------------------------------------------------------
+      // somewhat arbitrary choices that are quite common for shared
+      // installations
+      // -----------------------------------------------------------
       /**
-       * @internal
+       * Default permissions for symbolic links.
        */
-      parseRootPath(_dir) {
-        return "/";
-      }
+      DEFAULT_LINK_PERM: 511,
+      // 0777
       /**
-       * @internal
+       * Default permissions for directories.
        */
-      newRoot(fs2) {
-        return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
-      }
+      DEFAULT_DIR_PERM: 493,
+      // 0755
       /**
-       * Return true if the provided path string is an absolute path
+       * Default permissions for plain files.
        */
-      isAbsolute(p) {
-        return p.startsWith("/");
-      }
+      DEFAULT_FILE_PERM: 420
+      // 0644
     };
-    exports2.PathScurryPosix = PathScurryPosix;
-    var PathScurryDarwin = class extends PathScurryPosix {
-      constructor(cwd = process.cwd(), opts = {}) {
-        const { nocase = true } = opts;
-        super(cwd, { ...opts, nocase });
-      }
+  }
+});
+
+// node_modules/compress-commons/lib/archivers/zip/constants.js
+var require_constants8 = __commonJS({
+  "node_modules/compress-commons/lib/archivers/zip/constants.js"(exports2, module2) {
+    module2.exports = {
+      WORD: 4,
+      DWORD: 8,
+      EMPTY: Buffer.alloc(0),
+      SHORT: 2,
+      SHORT_MASK: 65535,
+      SHORT_SHIFT: 16,
+      SHORT_ZERO: Buffer.from(Array(2)),
+      LONG: 4,
+      LONG_ZERO: Buffer.from(Array(4)),
+      MIN_VERSION_INITIAL: 10,
+      MIN_VERSION_DATA_DESCRIPTOR: 20,
+      MIN_VERSION_ZIP64: 45,
+      VERSION_MADEBY: 45,
+      METHOD_STORED: 0,
+      METHOD_DEFLATED: 8,
+      PLATFORM_UNIX: 3,
+      PLATFORM_FAT: 0,
+      SIG_LFH: 67324752,
+      SIG_DD: 134695760,
+      SIG_CFH: 33639248,
+      SIG_EOCD: 101010256,
+      SIG_ZIP64_EOCD: 101075792,
+      SIG_ZIP64_EOCD_LOC: 117853008,
+      ZIP64_MAGIC_SHORT: 65535,
+      ZIP64_MAGIC: 4294967295,
+      ZIP64_EXTRA_ID: 1,
+      ZLIB_NO_COMPRESSION: 0,
+      ZLIB_BEST_SPEED: 1,
+      ZLIB_BEST_COMPRESSION: 9,
+      ZLIB_DEFAULT_COMPRESSION: -1,
+      MODE_MASK: 4095,
+      DEFAULT_FILE_MODE: 33188,
+      // 010644 = -rw-r--r-- = S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
+      DEFAULT_DIR_MODE: 16877,
+      // 040755 = drwxr-xr-x = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
+      EXT_FILE_ATTR_DIR: 1106051088,
+      // 010173200020 = drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D)
+      EXT_FILE_ATTR_FILE: 2175008800,
+      // 020151000040 = -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A) >>> 0
+      // Unix file types
+      S_IFMT: 61440,
+      // 0170000 type of file mask
+      S_IFIFO: 4096,
+      // 010000 named pipe (fifo)
+      S_IFCHR: 8192,
+      // 020000 character special
+      S_IFDIR: 16384,
+      // 040000 directory
+      S_IFBLK: 24576,
+      // 060000 block special
+      S_IFREG: 32768,
+      // 0100000 regular
+      S_IFLNK: 40960,
+      // 0120000 symbolic link
+      S_IFSOCK: 49152,
+      // 0140000 socket
+      // DOS file type flags
+      S_DOS_A: 32,
+      // 040 Archive
+      S_DOS_D: 16,
+      // 020 Directory
+      S_DOS_V: 8,
+      // 010 Volume
+      S_DOS_S: 4,
+      // 04 System
+      S_DOS_H: 2,
+      // 02 Hidden
+      S_DOS_R: 1
+      // 01 Read Only
     };
-    exports2.PathScurryDarwin = PathScurryDarwin;
-    exports2.Path = process.platform === "win32" ? PathWin32 : PathPosix;
-    exports2.PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
   }
 });
 
-// node_modules/archiver-utils/node_modules/glob/dist/commonjs/pattern.js
-var require_pattern = __commonJS({
-  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/pattern.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Pattern = void 0;
-    var minimatch_1 = require_commonjs13();
-    var isPatternList = (pl) => pl.length >= 1;
-    var isGlobList = (gl) => gl.length >= 1;
-    var Pattern = class _Pattern {
-      #patternList;
-      #globList;
-      #index;
-      length;
-      #platform;
-      #rest;
-      #globString;
-      #isDrive;
-      #isUNC;
-      #isAbsolute;
-      #followGlobstar = true;
-      constructor(patternList, globList, index, platform) {
-        if (!isPatternList(patternList)) {
-          throw new TypeError("empty pattern list");
-        }
-        if (!isGlobList(globList)) {
-          throw new TypeError("empty glob list");
-        }
-        if (globList.length !== patternList.length) {
-          throw new TypeError("mismatched pattern list and glob list lengths");
-        }
-        this.length = patternList.length;
-        if (index < 0 || index >= this.length) {
-          throw new TypeError("index out of range");
-        }
-        this.#patternList = patternList;
-        this.#globList = globList;
-        this.#index = index;
-        this.#platform = platform;
-        if (this.#index === 0) {
-          if (this.isUNC()) {
-            const [p0, p1, p2, p3, ...prest] = this.#patternList;
-            const [g0, g1, g2, g3, ...grest] = this.#globList;
-            if (prest[0] === "") {
-              prest.shift();
-              grest.shift();
-            }
-            const p = [p0, p1, p2, p3, ""].join("/");
-            const g = [g0, g1, g2, g3, ""].join("/");
-            this.#patternList = [p, ...prest];
-            this.#globList = [g, ...grest];
-            this.length = this.#patternList.length;
-          } else if (this.isDrive() || this.isAbsolute()) {
-            const [p1, ...prest] = this.#patternList;
-            const [g1, ...grest] = this.#globList;
-            if (prest[0] === "") {
-              prest.shift();
-              grest.shift();
-            }
-            const p = p1 + "/";
-            const g = g1 + "/";
-            this.#patternList = [p, ...prest];
-            this.#globList = [g, ...grest];
-            this.length = this.#patternList.length;
-          }
-        }
+// node_modules/compress-commons/lib/archivers/zip/zip-archive-entry.js
+var require_zip_archive_entry = __commonJS({
+  "node_modules/compress-commons/lib/archivers/zip/zip-archive-entry.js"(exports2, module2) {
+    var inherits = require("util").inherits;
+    var normalizePath = require_normalize_path();
+    var ArchiveEntry = require_archive_entry();
+    var GeneralPurposeBit = require_general_purpose_bit();
+    var UnixStat = require_unix_stat();
+    var constants = require_constants8();
+    var zipUtil = require_util13();
+    var ZipArchiveEntry = module2.exports = function(name) {
+      if (!(this instanceof ZipArchiveEntry)) {
+        return new ZipArchiveEntry(name);
       }
-      /**
-       * The first entry in the parsed list of patterns
-       */
-      pattern() {
-        return this.#patternList[this.#index];
+      ArchiveEntry.call(this);
+      this.platform = constants.PLATFORM_FAT;
+      this.method = -1;
+      this.name = null;
+      this.size = 0;
+      this.csize = 0;
+      this.gpb = new GeneralPurposeBit();
+      this.crc = 0;
+      this.time = -1;
+      this.minver = constants.MIN_VERSION_INITIAL;
+      this.mode = -1;
+      this.extra = null;
+      this.exattr = 0;
+      this.inattr = 0;
+      this.comment = null;
+      if (name) {
+        this.setName(name);
       }
-      /**
-       * true of if pattern() returns a string
-       */
-      isString() {
-        return typeof this.#patternList[this.#index] === "string";
+    };
+    inherits(ZipArchiveEntry, ArchiveEntry);
+    ZipArchiveEntry.prototype.getCentralDirectoryExtra = function() {
+      return this.getExtra();
+    };
+    ZipArchiveEntry.prototype.getComment = function() {
+      return this.comment !== null ? this.comment : "";
+    };
+    ZipArchiveEntry.prototype.getCompressedSize = function() {
+      return this.csize;
+    };
+    ZipArchiveEntry.prototype.getCrc = function() {
+      return this.crc;
+    };
+    ZipArchiveEntry.prototype.getExternalAttributes = function() {
+      return this.exattr;
+    };
+    ZipArchiveEntry.prototype.getExtra = function() {
+      return this.extra !== null ? this.extra : constants.EMPTY;
+    };
+    ZipArchiveEntry.prototype.getGeneralPurposeBit = function() {
+      return this.gpb;
+    };
+    ZipArchiveEntry.prototype.getInternalAttributes = function() {
+      return this.inattr;
+    };
+    ZipArchiveEntry.prototype.getLastModifiedDate = function() {
+      return this.getTime();
+    };
+    ZipArchiveEntry.prototype.getLocalFileDataExtra = function() {
+      return this.getExtra();
+    };
+    ZipArchiveEntry.prototype.getMethod = function() {
+      return this.method;
+    };
+    ZipArchiveEntry.prototype.getName = function() {
+      return this.name;
+    };
+    ZipArchiveEntry.prototype.getPlatform = function() {
+      return this.platform;
+    };
+    ZipArchiveEntry.prototype.getSize = function() {
+      return this.size;
+    };
+    ZipArchiveEntry.prototype.getTime = function() {
+      return this.time !== -1 ? zipUtil.dosToDate(this.time) : -1;
+    };
+    ZipArchiveEntry.prototype.getTimeDos = function() {
+      return this.time !== -1 ? this.time : 0;
+    };
+    ZipArchiveEntry.prototype.getUnixMode = function() {
+      return this.platform !== constants.PLATFORM_UNIX ? 0 : this.getExternalAttributes() >> constants.SHORT_SHIFT & constants.SHORT_MASK;
+    };
+    ZipArchiveEntry.prototype.getVersionNeededToExtract = function() {
+      return this.minver;
+    };
+    ZipArchiveEntry.prototype.setComment = function(comment) {
+      if (Buffer.byteLength(comment) !== comment.length) {
+        this.getGeneralPurposeBit().useUTF8ForNames(true);
       }
-      /**
-       * true of if pattern() returns GLOBSTAR
-       */
-      isGlobstar() {
-        return this.#patternList[this.#index] === minimatch_1.GLOBSTAR;
+      this.comment = comment;
+    };
+    ZipArchiveEntry.prototype.setCompressedSize = function(size) {
+      if (size < 0) {
+        throw new Error("invalid entry compressed size");
       }
-      /**
-       * true if pattern() returns a regexp
-       */
-      isRegExp() {
-        return this.#patternList[this.#index] instanceof RegExp;
+      this.csize = size;
+    };
+    ZipArchiveEntry.prototype.setCrc = function(crc) {
+      if (crc < 0) {
+        throw new Error("invalid entry crc32");
       }
-      /**
-       * The /-joined set of glob parts that make up this pattern
-       */
-      globString() {
-        return this.#globString = this.#globString || (this.#index === 0 ? this.isAbsolute() ? this.#globList[0] + this.#globList.slice(1).join("/") : this.#globList.join("/") : this.#globList.slice(this.#index).join("/"));
+      this.crc = crc;
+    };
+    ZipArchiveEntry.prototype.setExternalAttributes = function(attr) {
+      this.exattr = attr >>> 0;
+    };
+    ZipArchiveEntry.prototype.setExtra = function(extra) {
+      this.extra = extra;
+    };
+    ZipArchiveEntry.prototype.setGeneralPurposeBit = function(gpb) {
+      if (!(gpb instanceof GeneralPurposeBit)) {
+        throw new Error("invalid entry GeneralPurposeBit");
       }
-      /**
-       * true if there are more pattern parts after this one
-       */
-      hasMore() {
-        return this.length > this.#index + 1;
+      this.gpb = gpb;
+    };
+    ZipArchiveEntry.prototype.setInternalAttributes = function(attr) {
+      this.inattr = attr;
+    };
+    ZipArchiveEntry.prototype.setMethod = function(method) {
+      if (method < 0) {
+        throw new Error("invalid entry compression method");
       }
-      /**
-       * The rest of the pattern after this part, or null if this is the end
-       */
-      rest() {
-        if (this.#rest !== void 0)
-          return this.#rest;
-        if (!this.hasMore())
-          return this.#rest = null;
-        this.#rest = new _Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
-        this.#rest.#isAbsolute = this.#isAbsolute;
-        this.#rest.#isUNC = this.#isUNC;
-        this.#rest.#isDrive = this.#isDrive;
-        return this.#rest;
+      this.method = method;
+    };
+    ZipArchiveEntry.prototype.setName = function(name, prependSlash = false) {
+      name = normalizePath(name, false).replace(/^\w+:/, "").replace(/^(\.\.\/|\/)+/, "");
+      if (prependSlash) {
+        name = `/${name}`;
+      }
+      if (Buffer.byteLength(name) !== name.length) {
+        this.getGeneralPurposeBit().useUTF8ForNames(true);
+      }
+      this.name = name;
+    };
+    ZipArchiveEntry.prototype.setPlatform = function(platform) {
+      this.platform = platform;
+    };
+    ZipArchiveEntry.prototype.setSize = function(size) {
+      if (size < 0) {
+        throw new Error("invalid entry size");
+      }
+      this.size = size;
+    };
+    ZipArchiveEntry.prototype.setTime = function(time, forceLocalTime) {
+      if (!(time instanceof Date)) {
+        throw new Error("invalid entry time");
+      }
+      this.time = zipUtil.dateToDos(time, forceLocalTime);
+    };
+    ZipArchiveEntry.prototype.setUnixMode = function(mode) {
+      mode |= this.isDirectory() ? constants.S_IFDIR : constants.S_IFREG;
+      var extattr = 0;
+      extattr |= mode << constants.SHORT_SHIFT | (this.isDirectory() ? constants.S_DOS_D : constants.S_DOS_A);
+      this.setExternalAttributes(extattr);
+      this.mode = mode & constants.MODE_MASK;
+      this.platform = constants.PLATFORM_UNIX;
+    };
+    ZipArchiveEntry.prototype.setVersionNeededToExtract = function(minver) {
+      this.minver = minver;
+    };
+    ZipArchiveEntry.prototype.isDirectory = function() {
+      return this.getName().slice(-1) === "/";
+    };
+    ZipArchiveEntry.prototype.isUnixSymlink = function() {
+      return (this.getUnixMode() & UnixStat.FILE_TYPE_FLAG) === UnixStat.LINK_FLAG;
+    };
+    ZipArchiveEntry.prototype.isZip64 = function() {
+      return this.csize > constants.ZIP64_MAGIC || this.size > constants.ZIP64_MAGIC;
+    };
+  }
+});
+
+// node_modules/compress-commons/node_modules/is-stream/index.js
+var require_is_stream2 = __commonJS({
+  "node_modules/compress-commons/node_modules/is-stream/index.js"(exports2, module2) {
+    "use strict";
+    var isStream = (stream) => stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
+    isStream.writable = (stream) => isStream(stream) && stream.writable !== false && typeof stream._write === "function" && typeof stream._writableState === "object";
+    isStream.readable = (stream) => isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
+    isStream.duplex = (stream) => isStream.writable(stream) && isStream.readable(stream);
+    isStream.transform = (stream) => isStream.duplex(stream) && typeof stream._transform === "function";
+    module2.exports = isStream;
+  }
+});
+
+// node_modules/compress-commons/lib/util/index.js
+var require_util14 = __commonJS({
+  "node_modules/compress-commons/lib/util/index.js"(exports2, module2) {
+    var Stream = require("stream").Stream;
+    var PassThrough = require_ours().PassThrough;
+    var isStream = require_is_stream2();
+    var util = module2.exports = {};
+    util.normalizeInputSource = function(source) {
+      if (source === null) {
+        return Buffer.alloc(0);
+      } else if (typeof source === "string") {
+        return Buffer.from(source);
+      } else if (isStream(source) && !source._readableState) {
+        var normalized = new PassThrough();
+        source.pipe(normalized);
+        return normalized;
+      }
+      return source;
+    };
+  }
+});
+
+// node_modules/compress-commons/lib/archivers/archive-output-stream.js
+var require_archive_output_stream = __commonJS({
+  "node_modules/compress-commons/lib/archivers/archive-output-stream.js"(exports2, module2) {
+    var inherits = require("util").inherits;
+    var isStream = require_is_stream2();
+    var Transform = require_ours().Transform;
+    var ArchiveEntry = require_archive_entry();
+    var util = require_util14();
+    var ArchiveOutputStream = module2.exports = function(options) {
+      if (!(this instanceof ArchiveOutputStream)) {
+        return new ArchiveOutputStream(options);
+      }
+      Transform.call(this, options);
+      this.offset = 0;
+      this._archive = {
+        finish: false,
+        finished: false,
+        processing: false
+      };
+    };
+    inherits(ArchiveOutputStream, Transform);
+    ArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) {
+    };
+    ArchiveOutputStream.prototype._appendStream = function(zae, source, callback) {
+    };
+    ArchiveOutputStream.prototype._emitErrorCallback = function(err) {
+      if (err) {
+        this.emit("error", err);
+      }
+    };
+    ArchiveOutputStream.prototype._finish = function(ae) {
+    };
+    ArchiveOutputStream.prototype._normalizeEntry = function(ae) {
+    };
+    ArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) {
+      callback(null, chunk);
+    };
+    ArchiveOutputStream.prototype.entry = function(ae, source, callback) {
+      source = source || null;
+      if (typeof callback !== "function") {
+        callback = this._emitErrorCallback.bind(this);
       }
-      /**
-       * true if the pattern represents a //unc/path/ on windows
-       */
-      isUNC() {
-        const pl = this.#patternList;
-        return this.#isUNC !== void 0 ? this.#isUNC : this.#isUNC = this.#platform === "win32" && this.#index === 0 && pl[0] === "" && pl[1] === "" && typeof pl[2] === "string" && !!pl[2] && typeof pl[3] === "string" && !!pl[3];
+      if (!(ae instanceof ArchiveEntry)) {
+        callback(new Error("not a valid instance of ArchiveEntry"));
+        return;
       }
-      // pattern like C:/...
-      // split = ['C:', ...]
-      // XXX: would be nice to handle patterns like `c:*` to test the cwd
-      // in c: for *, but I don't know of a way to even figure out what that
-      // cwd is without actually chdir'ing into it?
-      /**
-       * True if the pattern starts with a drive letter on Windows
-       */
-      isDrive() {
-        const pl = this.#patternList;
-        return this.#isDrive !== void 0 ? this.#isDrive : this.#isDrive = this.#platform === "win32" && this.#index === 0 && this.length > 1 && typeof pl[0] === "string" && /^[a-z]:$/i.test(pl[0]);
+      if (this._archive.finish || this._archive.finished) {
+        callback(new Error("unacceptable entry after finish"));
+        return;
       }
-      // pattern = '/' or '/...' or '/x/...'
-      // split = ['', ''] or ['', ...] or ['', 'x', ...]
-      // Drive and UNC both considered absolute on windows
-      /**
-       * True if the pattern is rooted on an absolute path
-       */
-      isAbsolute() {
-        const pl = this.#patternList;
-        return this.#isAbsolute !== void 0 ? this.#isAbsolute : this.#isAbsolute = pl[0] === "" && pl.length > 1 || this.isDrive() || this.isUNC();
+      if (this._archive.processing) {
+        callback(new Error("already processing an entry"));
+        return;
       }
-      /**
-       * consume the root of the pattern, and return it
-       */
-      root() {
-        const p = this.#patternList[0];
-        return typeof p === "string" && this.isAbsolute() && this.#index === 0 ? p : "";
+      this._archive.processing = true;
+      this._normalizeEntry(ae);
+      this._entry = ae;
+      source = util.normalizeInputSource(source);
+      if (Buffer.isBuffer(source)) {
+        this._appendBuffer(ae, source, callback);
+      } else if (isStream(source)) {
+        this._appendStream(ae, source, callback);
+      } else {
+        this._archive.processing = false;
+        callback(new Error("input source must be valid Stream or Buffer instance"));
+        return;
       }
-      /**
-       * Check to see if the current globstar pattern is allowed to follow
-       * a symbolic link.
-       */
-      checkFollowGlobstar() {
-        return !(this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar);
+      return this;
+    };
+    ArchiveOutputStream.prototype.finish = function() {
+      if (this._archive.processing) {
+        this._archive.finish = true;
+        return;
       }
-      /**
-       * Mark that the current globstar pattern is following a symbolic link
-       */
-      markFollowGlobstar() {
-        if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
-          return false;
-        this.#followGlobstar = false;
-        return true;
+      this._finish();
+    };
+    ArchiveOutputStream.prototype.getBytesWritten = function() {
+      return this.offset;
+    };
+    ArchiveOutputStream.prototype.write = function(chunk, cb) {
+      if (chunk) {
+        this.offset += chunk.length;
       }
+      return Transform.prototype.write.call(this, chunk, cb);
     };
-    exports2.Pattern = Pattern;
   }
 });
 
-// node_modules/archiver-utils/node_modules/glob/dist/commonjs/ignore.js
-var require_ignore = __commonJS({
-  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/ignore.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Ignore = void 0;
-    var minimatch_1 = require_commonjs13();
-    var pattern_js_1 = require_pattern();
-    var defaultPlatform = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
-    var Ignore = class {
-      relative;
-      relativeChildren;
-      absolute;
-      absoluteChildren;
-      platform;
-      mmopts;
-      constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform }) {
-        this.relative = [];
-        this.absolute = [];
-        this.relativeChildren = [];
-        this.absoluteChildren = [];
-        this.platform = platform;
-        this.mmopts = {
-          dot: true,
-          nobrace,
-          nocase,
-          noext,
-          noglobstar,
-          optimizationLevel: 2,
-          platform,
-          nocomment: true,
-          nonegate: true
-        };
-        for (const ign of ignored)
-          this.add(ign);
-      }
-      add(ign) {
-        const mm = new minimatch_1.Minimatch(ign, this.mmopts);
-        for (let i = 0; i < mm.set.length; i++) {
-          const parsed = mm.set[i];
-          const globParts = mm.globParts[i];
-          if (!parsed || !globParts) {
-            throw new Error("invalid pattern object");
-          }
-          while (parsed[0] === "." && globParts[0] === ".") {
-            parsed.shift();
-            globParts.shift();
-          }
-          const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform);
-          const m = new minimatch_1.Minimatch(p.globString(), this.mmopts);
-          const children = globParts[globParts.length - 1] === "**";
-          const absolute = p.isAbsolute();
-          if (absolute)
-            this.absolute.push(m);
-          else
-            this.relative.push(m);
-          if (children) {
-            if (absolute)
-              this.absoluteChildren.push(m);
-            else
-              this.relativeChildren.push(m);
-          }
+// node_modules/crc-32/crc32.js
+var require_crc32 = __commonJS({
+  "node_modules/crc-32/crc32.js"(exports2) {
+    var CRC32;
+    (function(factory) {
+      if (typeof DO_NOT_EXPORT_CRC === "undefined") {
+        if ("object" === typeof exports2) {
+          factory(exports2);
+        } else if ("function" === typeof define && define.amd) {
+          define(function() {
+            var module3 = {};
+            factory(module3);
+            return module3;
+          });
+        } else {
+          factory(CRC32 = {});
         }
+      } else {
+        factory(CRC32 = {});
       }
-      ignored(p) {
-        const fullpath = p.fullpath();
-        const fullpaths = `${fullpath}/`;
-        const relative = p.relative() || ".";
-        const relatives = `${relative}/`;
-        for (const m of this.relative) {
-          if (m.match(relative) || m.match(relatives))
-            return true;
-        }
-        for (const m of this.absolute) {
-          if (m.match(fullpath) || m.match(fullpaths))
-            return true;
+    })(function(CRC322) {
+      CRC322.version = "1.2.2";
+      function signed_crc_table() {
+        var c = 0, table = new Array(256);
+        for (var n = 0; n != 256; ++n) {
+          c = n;
+          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
+          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
+          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
+          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
+          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
+          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
+          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
+          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
+          table[n] = c;
         }
-        return false;
+        return typeof Int32Array !== "undefined" ? new Int32Array(table) : table;
       }
-      childrenIgnored(p) {
-        const fullpath = p.fullpath() + "/";
-        const relative = (p.relative() || ".") + "/";
-        for (const m of this.relativeChildren) {
-          if (m.match(relative))
-            return true;
+      var T0 = signed_crc_table();
+      function slice_by_16_tables(T) {
+        var c = 0, v = 0, n = 0, table = typeof Int32Array !== "undefined" ? new Int32Array(4096) : new Array(4096);
+        for (n = 0; n != 256; ++n) table[n] = T[n];
+        for (n = 0; n != 256; ++n) {
+          v = T[n];
+          for (c = 256 + n; c < 4096; c += 256) v = table[c] = v >>> 8 ^ T[v & 255];
         }
-        for (const m of this.absoluteChildren) {
-          if (m.match(fullpath))
-            return true;
+        var out = [];
+        for (n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== "undefined" ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256);
+        return out;
+      }
+      var TT = slice_by_16_tables(T0);
+      var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];
+      var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];
+      var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];
+      function crc32_bstr(bstr, seed) {
+        var C = seed ^ -1;
+        for (var i = 0, L = bstr.length; i < L; ) C = C >>> 8 ^ T0[(C ^ bstr.charCodeAt(i++)) & 255];
+        return ~C;
+      }
+      function crc32_buf(B, seed) {
+        var C = seed ^ -1, L = B.length - 15, i = 0;
+        for (; i < L; ) C = Tf[B[i++] ^ C & 255] ^ Te[B[i++] ^ C >> 8 & 255] ^ Td[B[i++] ^ C >> 16 & 255] ^ Tc[B[i++] ^ C >>> 24] ^ Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];
+        L += 15;
+        while (i < L) C = C >>> 8 ^ T0[(C ^ B[i++]) & 255];
+        return ~C;
+      }
+      function crc32_str(str2, seed) {
+        var C = seed ^ -1;
+        for (var i = 0, L = str2.length, c = 0, d = 0; i < L; ) {
+          c = str2.charCodeAt(i++);
+          if (c < 128) {
+            C = C >>> 8 ^ T0[(C ^ c) & 255];
+          } else if (c < 2048) {
+            C = C >>> 8 ^ T0[(C ^ (192 | c >> 6 & 31)) & 255];
+            C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
+          } else if (c >= 55296 && c < 57344) {
+            c = (c & 1023) + 64;
+            d = str2.charCodeAt(i++) & 1023;
+            C = C >>> 8 ^ T0[(C ^ (240 | c >> 8 & 7)) & 255];
+            C = C >>> 8 ^ T0[(C ^ (128 | c >> 2 & 63)) & 255];
+            C = C >>> 8 ^ T0[(C ^ (128 | d >> 6 & 15 | (c & 3) << 4)) & 255];
+            C = C >>> 8 ^ T0[(C ^ (128 | d & 63)) & 255];
+          } else {
+            C = C >>> 8 ^ T0[(C ^ (224 | c >> 12 & 15)) & 255];
+            C = C >>> 8 ^ T0[(C ^ (128 | c >> 6 & 63)) & 255];
+            C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
+          }
         }
-        return false;
+        return ~C;
       }
-    };
-    exports2.Ignore = Ignore;
+      CRC322.table = T0;
+      CRC322.bstr = crc32_bstr;
+      CRC322.buf = crc32_buf;
+      CRC322.str = crc32_str;
+    });
   }
 });
 
-// node_modules/archiver-utils/node_modules/glob/dist/commonjs/processor.js
-var require_processor = __commonJS({
-  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/processor.js"(exports2) {
+// node_modules/crc32-stream/lib/crc32-stream.js
+var require_crc32_stream = __commonJS({
+  "node_modules/crc32-stream/lib/crc32-stream.js"(exports2, module2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Processor = exports2.SubWalks = exports2.MatchRecord = exports2.HasWalkedCache = void 0;
-    var minimatch_1 = require_commonjs13();
-    var HasWalkedCache = class _HasWalkedCache {
-      store;
-      constructor(store = /* @__PURE__ */ new Map()) {
-        this.store = store;
-      }
-      copy() {
-        return new _HasWalkedCache(new Map(this.store));
-      }
-      hasWalked(target, pattern) {
-        return this.store.get(target.fullpath())?.has(pattern.globString());
-      }
-      storeWalked(target, pattern) {
-        const fullpath = target.fullpath();
-        const cached = this.store.get(fullpath);
-        if (cached)
-          cached.add(pattern.globString());
-        else
-          this.store.set(fullpath, /* @__PURE__ */ new Set([pattern.globString()]));
-      }
-    };
-    exports2.HasWalkedCache = HasWalkedCache;
-    var MatchRecord = class {
-      store = /* @__PURE__ */ new Map();
-      add(target, absolute, ifDir) {
-        const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
-        const current = this.store.get(target);
-        this.store.set(target, current === void 0 ? n : n & current);
-      }
-      // match, absolute, ifdir
-      entries() {
-        return [...this.store.entries()].map(([path2, n]) => [
-          path2,
-          !!(n & 2),
-          !!(n & 1)
-        ]);
+    var { Transform } = require_ours();
+    var crc32 = require_crc32();
+    var CRC32Stream = class extends Transform {
+      constructor(options) {
+        super(options);
+        this.checksum = Buffer.allocUnsafe(4);
+        this.checksum.writeInt32BE(0, 0);
+        this.rawSize = 0;
       }
-    };
-    exports2.MatchRecord = MatchRecord;
-    var SubWalks = class {
-      store = /* @__PURE__ */ new Map();
-      add(target, pattern) {
-        if (!target.canReaddir()) {
-          return;
+      _transform(chunk, encoding, callback) {
+        if (chunk) {
+          this.checksum = crc32.buf(chunk, this.checksum) >>> 0;
+          this.rawSize += chunk.length;
         }
-        const subs = this.store.get(target);
-        if (subs) {
-          if (!subs.find((p) => p.globString() === pattern.globString())) {
-            subs.push(pattern);
-          }
-        } else
-          this.store.set(target, [pattern]);
+        callback(null, chunk);
       }
-      get(target) {
-        const subs = this.store.get(target);
-        if (!subs) {
-          throw new Error("attempting to walk unknown path");
-        }
-        return subs;
+      digest(encoding) {
+        const checksum = Buffer.allocUnsafe(4);
+        checksum.writeUInt32BE(this.checksum >>> 0, 0);
+        return encoding ? checksum.toString(encoding) : checksum;
       }
-      entries() {
-        return this.keys().map((k) => [k, this.store.get(k)]);
+      hex() {
+        return this.digest("hex").toUpperCase();
       }
-      keys() {
-        return [...this.store.keys()].filter((t) => t.canReaddir());
+      size() {
+        return this.rawSize;
       }
     };
-    exports2.SubWalks = SubWalks;
-    var Processor = class _Processor {
-      hasWalkedCache;
-      matches = new MatchRecord();
-      subwalks = new SubWalks();
-      patterns;
-      follow;
-      dot;
-      opts;
-      constructor(opts, hasWalkedCache) {
-        this.opts = opts;
-        this.follow = !!opts.follow;
-        this.dot = !!opts.dot;
-        this.hasWalkedCache = hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
-      }
-      processPatterns(target, patterns) {
-        this.patterns = patterns;
-        const processingSet = patterns.map((p) => [target, p]);
-        for (let [t, pattern] of processingSet) {
-          this.hasWalkedCache.storeWalked(t, pattern);
-          const root = pattern.root();
-          const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
-          if (root) {
-            t = t.resolve(root === "/" && this.opts.root !== void 0 ? this.opts.root : root);
-            const rest2 = pattern.rest();
-            if (!rest2) {
-              this.matches.add(t, true, false);
-              continue;
-            } else {
-              pattern = rest2;
-            }
-          }
-          if (t.isENOENT())
-            continue;
-          let p;
-          let rest;
-          let changed = false;
-          while (typeof (p = pattern.pattern()) === "string" && (rest = pattern.rest())) {
-            const c = t.resolve(p);
-            t = c;
-            pattern = rest;
-            changed = true;
-          }
-          p = pattern.pattern();
-          rest = pattern.rest();
-          if (changed) {
-            if (this.hasWalkedCache.hasWalked(t, pattern))
-              continue;
-            this.hasWalkedCache.storeWalked(t, pattern);
-          }
-          if (typeof p === "string") {
-            const ifDir = p === ".." || p === "" || p === ".";
-            this.matches.add(t.resolve(p), absolute, ifDir);
-            continue;
-          } else if (p === minimatch_1.GLOBSTAR) {
-            if (!t.isSymbolicLink() || this.follow || pattern.checkFollowGlobstar()) {
-              this.subwalks.add(t, pattern);
-            }
-            const rp = rest?.pattern();
-            const rrest = rest?.rest();
-            if (!rest || (rp === "" || rp === ".") && !rrest) {
-              this.matches.add(t, absolute, rp === "" || rp === ".");
-            } else {
-              if (rp === "..") {
-                const tp = t.parent || t;
-                if (!rrest)
-                  this.matches.add(tp, absolute, true);
-                else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
-                  this.subwalks.add(tp, rrest);
-                }
-              }
-            }
-          } else if (p instanceof RegExp) {
-            this.subwalks.add(t, pattern);
-          }
-        }
-        return this;
-      }
-      subwalkTargets() {
-        return this.subwalks.keys();
-      }
-      child() {
-        return new _Processor(this.opts, this.hasWalkedCache);
-      }
-      // return a new Processor containing the subwalks for each
-      // child entry, and a set of matches, and
-      // a hasWalkedCache that's a copy of this one
-      // then we're going to call
-      filterEntries(parent, entries) {
-        const patterns = this.subwalks.get(parent);
-        const results = this.child();
-        for (const e of entries) {
-          for (const pattern of patterns) {
-            const absolute = pattern.isAbsolute();
-            const p = pattern.pattern();
-            const rest = pattern.rest();
-            if (p === minimatch_1.GLOBSTAR) {
-              results.testGlobstar(e, pattern, rest, absolute);
-            } else if (p instanceof RegExp) {
-              results.testRegExp(e, p, rest, absolute);
-            } else {
-              results.testString(e, p, rest, absolute);
-            }
-          }
-        }
-        return results;
+    module2.exports = CRC32Stream;
+  }
+});
+
+// node_modules/crc32-stream/lib/deflate-crc32-stream.js
+var require_deflate_crc32_stream = __commonJS({
+  "node_modules/crc32-stream/lib/deflate-crc32-stream.js"(exports2, module2) {
+    "use strict";
+    var { DeflateRaw } = require("zlib");
+    var crc32 = require_crc32();
+    var DeflateCRC32Stream = class extends DeflateRaw {
+      constructor(options) {
+        super(options);
+        this.checksum = Buffer.allocUnsafe(4);
+        this.checksum.writeInt32BE(0, 0);
+        this.rawSize = 0;
+        this.compressedSize = 0;
       }
-      testGlobstar(e, pattern, rest, absolute) {
-        if (this.dot || !e.name.startsWith(".")) {
-          if (!pattern.hasMore()) {
-            this.matches.add(e, absolute, false);
-          }
-          if (e.canReaddir()) {
-            if (this.follow || !e.isSymbolicLink()) {
-              this.subwalks.add(e, pattern);
-            } else if (e.isSymbolicLink()) {
-              if (rest && pattern.checkFollowGlobstar()) {
-                this.subwalks.add(e, rest);
-              } else if (pattern.markFollowGlobstar()) {
-                this.subwalks.add(e, pattern);
-              }
-            }
-          }
-        }
-        if (rest) {
-          const rp = rest.pattern();
-          if (typeof rp === "string" && // dots and empty were handled already
-          rp !== ".." && rp !== "" && rp !== ".") {
-            this.testString(e, rp, rest.rest(), absolute);
-          } else if (rp === "..") {
-            const ep = e.parent || e;
-            this.subwalks.add(ep, rest);
-          } else if (rp instanceof RegExp) {
-            this.testRegExp(e, rp, rest.rest(), absolute);
-          }
+      push(chunk, encoding) {
+        if (chunk) {
+          this.compressedSize += chunk.length;
         }
+        return super.push(chunk, encoding);
       }
-      testRegExp(e, p, rest, absolute) {
-        if (!p.test(e.name))
-          return;
-        if (!rest) {
-          this.matches.add(e, absolute, false);
-        } else {
-          this.subwalks.add(e, rest);
+      _transform(chunk, encoding, callback) {
+        if (chunk) {
+          this.checksum = crc32.buf(chunk, this.checksum) >>> 0;
+          this.rawSize += chunk.length;
         }
+        super._transform(chunk, encoding, callback);
       }
-      testString(e, p, rest, absolute) {
-        if (!e.isNamed(p))
-          return;
-        if (!rest) {
-          this.matches.add(e, absolute, false);
+      digest(encoding) {
+        const checksum = Buffer.allocUnsafe(4);
+        checksum.writeUInt32BE(this.checksum >>> 0, 0);
+        return encoding ? checksum.toString(encoding) : checksum;
+      }
+      hex() {
+        return this.digest("hex").toUpperCase();
+      }
+      size(compressed = false) {
+        if (compressed) {
+          return this.compressedSize;
         } else {
-          this.subwalks.add(e, rest);
+          return this.rawSize;
         }
       }
     };
-    exports2.Processor = Processor;
+    module2.exports = DeflateCRC32Stream;
   }
 });
 
-// node_modules/archiver-utils/node_modules/glob/dist/commonjs/walker.js
-var require_walker = __commonJS({
-  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/walker.js"(exports2) {
+// node_modules/crc32-stream/lib/index.js
+var require_lib4 = __commonJS({
+  "node_modules/crc32-stream/lib/index.js"(exports2, module2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.GlobStream = exports2.GlobWalker = exports2.GlobUtil = void 0;
-    var minipass_1 = require_commonjs15();
-    var ignore_js_1 = require_ignore();
-    var processor_js_1 = require_processor();
-    var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new ignore_js_1.Ignore([ignore], opts) : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts) : ignore;
-    var GlobUtil = class {
-      path;
-      patterns;
-      opts;
-      seen = /* @__PURE__ */ new Set();
-      paused = false;
-      aborted = false;
-      #onResume = [];
-      #ignore;
-      #sep;
-      signal;
-      maxDepth;
-      includeChildMatches;
-      constructor(patterns, path2, opts) {
-        this.patterns = patterns;
-        this.path = path2;
-        this.opts = opts;
-        this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
-        this.includeChildMatches = opts.includeChildMatches !== false;
-        if (opts.ignore || !this.includeChildMatches) {
-          this.#ignore = makeIgnore(opts.ignore ?? [], opts);
-          if (!this.includeChildMatches && typeof this.#ignore.add !== "function") {
-            const m = "cannot ignore child matches, ignore lacks add() method.";
-            throw new Error(m);
-          }
-        }
-        this.maxDepth = opts.maxDepth || Infinity;
-        if (opts.signal) {
-          this.signal = opts.signal;
-          this.signal.addEventListener("abort", () => {
-            this.#onResume.length = 0;
-          });
-        }
+    module2.exports = {
+      CRC32Stream: require_crc32_stream(),
+      DeflateCRC32Stream: require_deflate_crc32_stream()
+    };
+  }
+});
+
+// node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js
+var require_zip_archive_output_stream = __commonJS({
+  "node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js"(exports2, module2) {
+    var inherits = require("util").inherits;
+    var crc32 = require_crc32();
+    var { CRC32Stream } = require_lib4();
+    var { DeflateCRC32Stream } = require_lib4();
+    var ArchiveOutputStream = require_archive_output_stream();
+    var ZipArchiveEntry = require_zip_archive_entry();
+    var GeneralPurposeBit = require_general_purpose_bit();
+    var constants = require_constants8();
+    var util = require_util14();
+    var zipUtil = require_util13();
+    var ZipArchiveOutputStream = module2.exports = function(options) {
+      if (!(this instanceof ZipArchiveOutputStream)) {
+        return new ZipArchiveOutputStream(options);
       }
-      #ignored(path2) {
-        return this.seen.has(path2) || !!this.#ignore?.ignored?.(path2);
+      options = this.options = this._defaults(options);
+      ArchiveOutputStream.call(this, options);
+      this._entry = null;
+      this._entries = [];
+      this._archive = {
+        centralLength: 0,
+        centralOffset: 0,
+        comment: "",
+        finish: false,
+        finished: false,
+        processing: false,
+        forceZip64: options.forceZip64,
+        forceLocalTime: options.forceLocalTime
+      };
+    };
+    inherits(ZipArchiveOutputStream, ArchiveOutputStream);
+    ZipArchiveOutputStream.prototype._afterAppend = function(ae) {
+      this._entries.push(ae);
+      if (ae.getGeneralPurposeBit().usesDataDescriptor()) {
+        this._writeDataDescriptor(ae);
       }
-      #childrenIgnored(path2) {
-        return !!this.#ignore?.childrenIgnored?.(path2);
+      this._archive.processing = false;
+      this._entry = null;
+      if (this._archive.finish && !this._archive.finished) {
+        this._finish();
       }
-      // backpressure mechanism
-      pause() {
-        this.paused = true;
+    };
+    ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) {
+      if (source.length === 0) {
+        ae.setMethod(constants.METHOD_STORED);
       }
-      resume() {
-        if (this.signal?.aborted)
-          return;
-        this.paused = false;
-        let fn = void 0;
-        while (!this.paused && (fn = this.#onResume.shift())) {
-          fn();
-        }
+      var method = ae.getMethod();
+      if (method === constants.METHOD_STORED) {
+        ae.setSize(source.length);
+        ae.setCompressedSize(source.length);
+        ae.setCrc(crc32.buf(source) >>> 0);
       }
-      onResume(fn) {
-        if (this.signal?.aborted)
-          return;
-        if (!this.paused) {
-          fn();
-        } else {
-          this.#onResume.push(fn);
-        }
+      this._writeLocalFileHeader(ae);
+      if (method === constants.METHOD_STORED) {
+        this.write(source);
+        this._afterAppend(ae);
+        callback(null, ae);
+        return;
+      } else if (method === constants.METHOD_DEFLATED) {
+        this._smartStream(ae, callback).end(source);
+        return;
+      } else {
+        callback(new Error("compression method " + method + " not implemented"));
+        return;
       }
-      // do the requisite realpath/stat checking, and return the path
-      // to add or undefined to filter it out.
-      async matchCheck(e, ifDir) {
-        if (ifDir && this.opts.nodir)
-          return void 0;
-        let rpc;
-        if (this.opts.realpath) {
-          rpc = e.realpathCached() || await e.realpath();
-          if (!rpc)
-            return void 0;
-          e = rpc;
-        }
-        const needStat = e.isUnknown() || this.opts.stat;
-        const s = needStat ? await e.lstat() : e;
-        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
-          const target = await s.realpath();
-          if (target && (target.isUnknown() || this.opts.stat)) {
-            await target.lstat();
-          }
-        }
-        return this.matchCheckTest(s, ifDir);
+    };
+    ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) {
+      ae.getGeneralPurposeBit().useDataDescriptor(true);
+      ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR);
+      this._writeLocalFileHeader(ae);
+      var smart = this._smartStream(ae, callback);
+      source.once("error", function(err) {
+        smart.emit("error", err);
+        smart.end();
+      });
+      source.pipe(smart);
+    };
+    ZipArchiveOutputStream.prototype._defaults = function(o) {
+      if (typeof o !== "object") {
+        o = {};
       }
-      matchCheckTest(e, ifDir) {
-        return e && (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && (!ifDir || e.canReaddir()) && (!this.opts.nodir || !e.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !e.isSymbolicLink() || !e.realpathCached()?.isDirectory()) && !this.#ignored(e) ? e : void 0;
+      if (typeof o.zlib !== "object") {
+        o.zlib = {};
       }
-      matchCheckSync(e, ifDir) {
-        if (ifDir && this.opts.nodir)
-          return void 0;
-        let rpc;
-        if (this.opts.realpath) {
-          rpc = e.realpathCached() || e.realpathSync();
-          if (!rpc)
-            return void 0;
-          e = rpc;
-        }
-        const needStat = e.isUnknown() || this.opts.stat;
-        const s = needStat ? e.lstatSync() : e;
-        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
-          const target = s.realpathSync();
-          if (target && (target?.isUnknown() || this.opts.stat)) {
-            target.lstatSync();
-          }
-        }
-        return this.matchCheckTest(s, ifDir);
+      if (typeof o.zlib.level !== "number") {
+        o.zlib.level = constants.ZLIB_BEST_SPEED;
       }
-      matchFinish(e, absolute) {
-        if (this.#ignored(e))
-          return;
-        if (!this.includeChildMatches && this.#ignore?.add) {
-          const ign = `${e.relativePosix()}/**`;
-          this.#ignore.add(ign);
-        }
-        const abs = this.opts.absolute === void 0 ? absolute : this.opts.absolute;
-        this.seen.add(e);
-        const mark = this.opts.mark && e.isDirectory() ? this.#sep : "";
-        if (this.opts.withFileTypes) {
-          this.matchEmit(e);
-        } else if (abs) {
-          const abs2 = this.opts.posix ? e.fullpathPosix() : e.fullpath();
-          this.matchEmit(abs2 + mark);
-        } else {
-          const rel = this.opts.posix ? e.relativePosix() : e.relative();
-          const pre = this.opts.dotRelative && !rel.startsWith(".." + this.#sep) ? "." + this.#sep : "";
-          this.matchEmit(!rel ? "." + mark : pre + rel + mark);
-        }
+      o.forceZip64 = !!o.forceZip64;
+      o.forceLocalTime = !!o.forceLocalTime;
+      return o;
+    };
+    ZipArchiveOutputStream.prototype._finish = function() {
+      this._archive.centralOffset = this.offset;
+      this._entries.forEach(function(ae) {
+        this._writeCentralFileHeader(ae);
+      }.bind(this));
+      this._archive.centralLength = this.offset - this._archive.centralOffset;
+      if (this.isZip64()) {
+        this._writeCentralDirectoryZip64();
       }
-      async match(e, absolute, ifDir) {
-        const p = await this.matchCheck(e, ifDir);
-        if (p)
-          this.matchFinish(p, absolute);
+      this._writeCentralDirectoryEnd();
+      this._archive.processing = false;
+      this._archive.finish = true;
+      this._archive.finished = true;
+      this.end();
+    };
+    ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) {
+      if (ae.getMethod() === -1) {
+        ae.setMethod(constants.METHOD_DEFLATED);
       }
-      matchSync(e, absolute, ifDir) {
-        const p = this.matchCheckSync(e, ifDir);
-        if (p)
-          this.matchFinish(p, absolute);
+      if (ae.getMethod() === constants.METHOD_DEFLATED) {
+        ae.getGeneralPurposeBit().useDataDescriptor(true);
+        ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR);
       }
-      walkCB(target, patterns, cb) {
-        if (this.signal?.aborted)
-          cb();
-        this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb);
+      if (ae.getTime() === -1) {
+        ae.setTime(/* @__PURE__ */ new Date(), this._archive.forceLocalTime);
       }
-      walkCB2(target, patterns, processor, cb) {
-        if (this.#childrenIgnored(target))
-          return cb();
-        if (this.signal?.aborted)
-          cb();
-        if (this.paused) {
-          this.onResume(() => this.walkCB2(target, patterns, processor, cb));
-          return;
-        }
-        processor.processPatterns(target, patterns);
-        let tasks = 1;
-        const next = () => {
-          if (--tasks === 0)
-            cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-          if (this.#ignored(m))
-            continue;
-          tasks++;
-          this.match(m, absolute, ifDir).then(() => next());
-        }
-        for (const t of processor.subwalkTargets()) {
-          if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
-            continue;
-          }
-          tasks++;
-          const childrenCached = t.readdirCached();
-          if (t.calledReaddir())
-            this.walkCB3(t, childrenCached, processor, next);
-          else {
-            t.readdirCB((_2, entries) => this.walkCB3(t, entries, processor, next), true);
-          }
-        }
-        next();
+      ae._offsets = {
+        file: 0,
+        data: 0,
+        contents: 0
+      };
+    };
+    ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) {
+      var deflate = ae.getMethod() === constants.METHOD_DEFLATED;
+      var process2 = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream();
+      var error4 = null;
+      function handleStuff() {
+        var digest = process2.digest().readUInt32BE(0);
+        ae.setCrc(digest);
+        ae.setSize(process2.size());
+        ae.setCompressedSize(process2.size(true));
+        this._afterAppend(ae);
+        callback(error4, ae);
+      }
+      process2.once("end", handleStuff.bind(this));
+      process2.once("error", function(err) {
+        error4 = err;
+      });
+      process2.pipe(this, { end: false });
+      return process2;
+    };
+    ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() {
+      var records = this._entries.length;
+      var size = this._archive.centralLength;
+      var offset = this._archive.centralOffset;
+      if (this.isZip64()) {
+        records = constants.ZIP64_MAGIC_SHORT;
+        size = constants.ZIP64_MAGIC;
+        offset = constants.ZIP64_MAGIC;
+      }
+      this.write(zipUtil.getLongBytes(constants.SIG_EOCD));
+      this.write(constants.SHORT_ZERO);
+      this.write(constants.SHORT_ZERO);
+      this.write(zipUtil.getShortBytes(records));
+      this.write(zipUtil.getShortBytes(records));
+      this.write(zipUtil.getLongBytes(size));
+      this.write(zipUtil.getLongBytes(offset));
+      var comment = this.getComment();
+      var commentLength = Buffer.byteLength(comment);
+      this.write(zipUtil.getShortBytes(commentLength));
+      this.write(comment);
+    };
+    ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() {
+      this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD));
+      this.write(zipUtil.getEightBytes(44));
+      this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64));
+      this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64));
+      this.write(constants.LONG_ZERO);
+      this.write(constants.LONG_ZERO);
+      this.write(zipUtil.getEightBytes(this._entries.length));
+      this.write(zipUtil.getEightBytes(this._entries.length));
+      this.write(zipUtil.getEightBytes(this._archive.centralLength));
+      this.write(zipUtil.getEightBytes(this._archive.centralOffset));
+      this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD_LOC));
+      this.write(constants.LONG_ZERO);
+      this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength));
+      this.write(zipUtil.getLongBytes(1));
+    };
+    ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) {
+      var gpb = ae.getGeneralPurposeBit();
+      var method = ae.getMethod();
+      var fileOffset = ae._offsets.file;
+      var size = ae.getSize();
+      var compressedSize = ae.getCompressedSize();
+      if (ae.isZip64() || fileOffset > constants.ZIP64_MAGIC) {
+        size = constants.ZIP64_MAGIC;
+        compressedSize = constants.ZIP64_MAGIC;
+        fileOffset = constants.ZIP64_MAGIC;
+        ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64);
+        var extraBuf = Buffer.concat([
+          zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID),
+          zipUtil.getShortBytes(24),
+          zipUtil.getEightBytes(ae.getSize()),
+          zipUtil.getEightBytes(ae.getCompressedSize()),
+          zipUtil.getEightBytes(ae._offsets.file)
+        ], 28);
+        ae.setExtra(extraBuf);
+      }
+      this.write(zipUtil.getLongBytes(constants.SIG_CFH));
+      this.write(zipUtil.getShortBytes(ae.getPlatform() << 8 | constants.VERSION_MADEBY));
+      this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));
+      this.write(gpb.encode());
+      this.write(zipUtil.getShortBytes(method));
+      this.write(zipUtil.getLongBytes(ae.getTimeDos()));
+      this.write(zipUtil.getLongBytes(ae.getCrc()));
+      this.write(zipUtil.getLongBytes(compressedSize));
+      this.write(zipUtil.getLongBytes(size));
+      var name = ae.getName();
+      var comment = ae.getComment();
+      var extra = ae.getCentralDirectoryExtra();
+      if (gpb.usesUTF8ForNames()) {
+        name = Buffer.from(name);
+        comment = Buffer.from(comment);
+      }
+      this.write(zipUtil.getShortBytes(name.length));
+      this.write(zipUtil.getShortBytes(extra.length));
+      this.write(zipUtil.getShortBytes(comment.length));
+      this.write(constants.SHORT_ZERO);
+      this.write(zipUtil.getShortBytes(ae.getInternalAttributes()));
+      this.write(zipUtil.getLongBytes(ae.getExternalAttributes()));
+      this.write(zipUtil.getLongBytes(fileOffset));
+      this.write(name);
+      this.write(extra);
+      this.write(comment);
+    };
+    ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) {
+      this.write(zipUtil.getLongBytes(constants.SIG_DD));
+      this.write(zipUtil.getLongBytes(ae.getCrc()));
+      if (ae.isZip64()) {
+        this.write(zipUtil.getEightBytes(ae.getCompressedSize()));
+        this.write(zipUtil.getEightBytes(ae.getSize()));
+      } else {
+        this.write(zipUtil.getLongBytes(ae.getCompressedSize()));
+        this.write(zipUtil.getLongBytes(ae.getSize()));
+      }
+    };
+    ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) {
+      var gpb = ae.getGeneralPurposeBit();
+      var method = ae.getMethod();
+      var name = ae.getName();
+      var extra = ae.getLocalFileDataExtra();
+      if (ae.isZip64()) {
+        gpb.useDataDescriptor(true);
+        ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64);
+      }
+      if (gpb.usesUTF8ForNames()) {
+        name = Buffer.from(name);
+      }
+      ae._offsets.file = this.offset;
+      this.write(zipUtil.getLongBytes(constants.SIG_LFH));
+      this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));
+      this.write(gpb.encode());
+      this.write(zipUtil.getShortBytes(method));
+      this.write(zipUtil.getLongBytes(ae.getTimeDos()));
+      ae._offsets.data = this.offset;
+      if (gpb.usesDataDescriptor()) {
+        this.write(constants.LONG_ZERO);
+        this.write(constants.LONG_ZERO);
+        this.write(constants.LONG_ZERO);
+      } else {
+        this.write(zipUtil.getLongBytes(ae.getCrc()));
+        this.write(zipUtil.getLongBytes(ae.getCompressedSize()));
+        this.write(zipUtil.getLongBytes(ae.getSize()));
+      }
+      this.write(zipUtil.getShortBytes(name.length));
+      this.write(zipUtil.getShortBytes(extra.length));
+      this.write(name);
+      this.write(extra);
+      ae._offsets.contents = this.offset;
+    };
+    ZipArchiveOutputStream.prototype.getComment = function(comment) {
+      return this._archive.comment !== null ? this._archive.comment : "";
+    };
+    ZipArchiveOutputStream.prototype.isZip64 = function() {
+      return this._archive.forceZip64 || this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC;
+    };
+    ZipArchiveOutputStream.prototype.setComment = function(comment) {
+      this._archive.comment = comment;
+    };
+  }
+});
+
+// node_modules/compress-commons/lib/compress-commons.js
+var require_compress_commons = __commonJS({
+  "node_modules/compress-commons/lib/compress-commons.js"(exports2, module2) {
+    module2.exports = {
+      ArchiveEntry: require_archive_entry(),
+      ZipArchiveEntry: require_zip_archive_entry(),
+      ArchiveOutputStream: require_archive_output_stream(),
+      ZipArchiveOutputStream: require_zip_archive_output_stream()
+    };
+  }
+});
+
+// node_modules/zip-stream/index.js
+var require_zip_stream = __commonJS({
+  "node_modules/zip-stream/index.js"(exports2, module2) {
+    var inherits = require("util").inherits;
+    var ZipArchiveOutputStream = require_compress_commons().ZipArchiveOutputStream;
+    var ZipArchiveEntry = require_compress_commons().ZipArchiveEntry;
+    var util = require_archiver_utils();
+    var ZipStream = module2.exports = function(options) {
+      if (!(this instanceof ZipStream)) {
+        return new ZipStream(options);
+      }
+      options = this.options = options || {};
+      options.zlib = options.zlib || {};
+      ZipArchiveOutputStream.call(this, options);
+      if (typeof options.level === "number" && options.level >= 0) {
+        options.zlib.level = options.level;
+        delete options.level;
       }
-      walkCB3(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
-        let tasks = 1;
-        const next = () => {
-          if (--tasks === 0)
-            cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-          if (this.#ignored(m))
-            continue;
-          tasks++;
-          this.match(m, absolute, ifDir).then(() => next());
-        }
-        for (const [target2, patterns] of processor.subwalks.entries()) {
-          tasks++;
-          this.walkCB2(target2, patterns, processor.child(), next);
-        }
-        next();
+      if (!options.forceZip64 && typeof options.zlib.level === "number" && options.zlib.level === 0) {
+        options.store = true;
       }
-      walkCBSync(target, patterns, cb) {
-        if (this.signal?.aborted)
-          cb();
-        this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb);
+      options.namePrependSlash = options.namePrependSlash || false;
+      if (options.comment && options.comment.length > 0) {
+        this.setComment(options.comment);
       }
-      walkCB2Sync(target, patterns, processor, cb) {
-        if (this.#childrenIgnored(target))
-          return cb();
-        if (this.signal?.aborted)
-          cb();
-        if (this.paused) {
-          this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
-          return;
-        }
-        processor.processPatterns(target, patterns);
-        let tasks = 1;
-        const next = () => {
-          if (--tasks === 0)
-            cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-          if (this.#ignored(m))
-            continue;
-          this.matchSync(m, absolute, ifDir);
-        }
-        for (const t of processor.subwalkTargets()) {
-          if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
-            continue;
-          }
-          tasks++;
-          const children = t.readdirSync();
-          this.walkCB3Sync(t, children, processor, next);
+    };
+    inherits(ZipStream, ZipArchiveOutputStream);
+    ZipStream.prototype._normalizeFileData = function(data) {
+      data = util.defaults(data, {
+        type: "file",
+        name: null,
+        namePrependSlash: this.options.namePrependSlash,
+        linkname: null,
+        date: null,
+        mode: null,
+        store: this.options.store,
+        comment: ""
+      });
+      var isDir = data.type === "directory";
+      var isSymlink = data.type === "symlink";
+      if (data.name) {
+        data.name = util.sanitizePath(data.name);
+        if (!isSymlink && data.name.slice(-1) === "/") {
+          isDir = true;
+          data.type = "directory";
+        } else if (isDir) {
+          data.name += "/";
         }
-        next();
       }
-      walkCB3Sync(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
-        let tasks = 1;
-        const next = () => {
-          if (--tasks === 0)
-            cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-          if (this.#ignored(m))
-            continue;
-          this.matchSync(m, absolute, ifDir);
-        }
-        for (const [target2, patterns] of processor.subwalks.entries()) {
-          tasks++;
-          this.walkCB2Sync(target2, patterns, processor.child(), next);
-        }
-        next();
+      if (isDir || isSymlink) {
+        data.store = true;
       }
+      data.date = util.dateify(data.date);
+      return data;
     };
-    exports2.GlobUtil = GlobUtil;
-    var GlobWalker = class extends GlobUtil {
-      matches = /* @__PURE__ */ new Set();
-      constructor(patterns, path2, opts) {
-        super(patterns, path2, opts);
+    ZipStream.prototype.entry = function(source, data, callback) {
+      if (typeof callback !== "function") {
+        callback = this._emitErrorCallback.bind(this);
       }
-      matchEmit(e) {
-        this.matches.add(e);
+      data = this._normalizeFileData(data);
+      if (data.type !== "file" && data.type !== "directory" && data.type !== "symlink") {
+        callback(new Error(data.type + " entries not currently supported"));
+        return;
       }
-      async walk() {
-        if (this.signal?.aborted)
-          throw this.signal.reason;
-        if (this.path.isUnknown()) {
-          await this.path.lstat();
-        }
-        await new Promise((res, rej) => {
-          this.walkCB(this.path, this.patterns, () => {
-            if (this.signal?.aborted) {
-              rej(this.signal.reason);
-            } else {
-              res(this.matches);
-            }
-          });
-        });
-        return this.matches;
+      if (typeof data.name !== "string" || data.name.length === 0) {
+        callback(new Error("entry name must be a non-empty string value"));
+        return;
       }
-      walkSync() {
-        if (this.signal?.aborted)
-          throw this.signal.reason;
-        if (this.path.isUnknown()) {
-          this.path.lstatSync();
-        }
-        this.walkCBSync(this.path, this.patterns, () => {
-          if (this.signal?.aborted)
-            throw this.signal.reason;
-        });
-        return this.matches;
+      if (data.type === "symlink" && typeof data.linkname !== "string") {
+        callback(new Error("entry linkname must be a non-empty string value when type equals symlink"));
+        return;
       }
-    };
-    exports2.GlobWalker = GlobWalker;
-    var GlobStream = class extends GlobUtil {
-      results;
-      constructor(patterns, path2, opts) {
-        super(patterns, path2, opts);
-        this.results = new minipass_1.Minipass({
-          signal: this.signal,
-          objectMode: true
-        });
-        this.results.on("drain", () => this.resume());
-        this.results.on("resume", () => this.resume());
+      var entry = new ZipArchiveEntry(data.name);
+      entry.setTime(data.date, this.options.forceLocalTime);
+      if (data.namePrependSlash) {
+        entry.setName(data.name, true);
       }
-      matchEmit(e) {
-        this.results.write(e);
-        if (!this.results.flowing)
-          this.pause();
+      if (data.store) {
+        entry.setMethod(0);
       }
-      stream() {
-        const target = this.path;
-        if (target.isUnknown()) {
-          target.lstat().then(() => {
-            this.walkCB(target, this.patterns, () => this.results.end());
-          });
-        } else {
-          this.walkCB(target, this.patterns, () => this.results.end());
-        }
-        return this.results;
+      if (data.comment.length > 0) {
+        entry.setComment(data.comment);
       }
-      streamSync() {
-        if (this.path.isUnknown()) {
-          this.path.lstatSync();
+      if (data.type === "symlink" && typeof data.mode !== "number") {
+        data.mode = 40960;
+      }
+      if (typeof data.mode === "number") {
+        if (data.type === "symlink") {
+          data.mode |= 40960;
         }
-        this.walkCBSync(this.path, this.patterns, () => this.results.end());
-        return this.results;
+        entry.setUnixMode(data.mode);
       }
+      if (data.type === "symlink" && typeof data.linkname === "string") {
+        source = Buffer.from(data.linkname);
+      }
+      return ZipArchiveOutputStream.prototype.entry.call(this, entry, source, callback);
+    };
+    ZipStream.prototype.finalize = function() {
+      this.finish();
     };
-    exports2.GlobStream = GlobStream;
   }
 });
 
-// node_modules/archiver-utils/node_modules/glob/dist/commonjs/glob.js
-var require_glob = __commonJS({
-  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/glob.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Glob = void 0;
-    var minimatch_1 = require_commonjs13();
-    var node_url_1 = require("node:url");
-    var path_scurry_1 = require_commonjs16();
-    var pattern_js_1 = require_pattern();
-    var walker_js_1 = require_walker();
-    var defaultPlatform = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
-    var Glob = class {
-      absolute;
-      cwd;
-      root;
-      dot;
-      dotRelative;
-      follow;
-      ignore;
-      magicalBraces;
-      mark;
-      matchBase;
-      maxDepth;
-      nobrace;
-      nocase;
-      nodir;
-      noext;
-      noglobstar;
-      pattern;
-      platform;
-      realpath;
-      scurry;
-      stat;
-      signal;
-      windowsPathsNoEscape;
-      withFileTypes;
-      includeChildMatches;
-      /**
-       * The options provided to the constructor.
-       */
-      opts;
-      /**
-       * An array of parsed immutable {@link Pattern} objects.
-       */
-      patterns;
-      /**
-       * All options are stored as properties on the `Glob` object.
-       *
-       * See {@link GlobOptions} for full options descriptions.
-       *
-       * Note that a previous `Glob` object can be passed as the
-       * `GlobOptions` to another `Glob` instantiation to re-use settings
-       * and caches with a new pattern.
-       *
-       * Traversal functions can be called multiple times to run the walk
-       * again.
-       */
-      constructor(pattern, opts) {
-        if (!opts)
-          throw new TypeError("glob options required");
-        this.withFileTypes = !!opts.withFileTypes;
-        this.signal = opts.signal;
-        this.follow = !!opts.follow;
-        this.dot = !!opts.dot;
-        this.dotRelative = !!opts.dotRelative;
-        this.nodir = !!opts.nodir;
-        this.mark = !!opts.mark;
-        if (!opts.cwd) {
-          this.cwd = "";
-        } else if (opts.cwd instanceof URL || opts.cwd.startsWith("file://")) {
-          opts.cwd = (0, node_url_1.fileURLToPath)(opts.cwd);
-        }
-        this.cwd = opts.cwd || "";
-        this.root = opts.root;
-        this.magicalBraces = !!opts.magicalBraces;
-        this.nobrace = !!opts.nobrace;
-        this.noext = !!opts.noext;
-        this.realpath = !!opts.realpath;
-        this.absolute = opts.absolute;
-        this.includeChildMatches = opts.includeChildMatches !== false;
-        this.noglobstar = !!opts.noglobstar;
-        this.matchBase = !!opts.matchBase;
-        this.maxDepth = typeof opts.maxDepth === "number" ? opts.maxDepth : Infinity;
-        this.stat = !!opts.stat;
-        this.ignore = opts.ignore;
-        if (this.withFileTypes && this.absolute !== void 0) {
-          throw new Error("cannot set absolute and withFileTypes:true");
-        }
-        if (typeof pattern === "string") {
-          pattern = [pattern];
-        }
-        this.windowsPathsNoEscape = !!opts.windowsPathsNoEscape || opts.allowWindowsEscape === false;
-        if (this.windowsPathsNoEscape) {
-          pattern = pattern.map((p) => p.replace(/\\/g, "/"));
-        }
-        if (this.matchBase) {
-          if (opts.noglobstar) {
-            throw new TypeError("base matching requires globstar");
-          }
-          pattern = pattern.map((p) => p.includes("/") ? p : `./**/${p}`);
-        }
-        this.pattern = pattern;
-        this.platform = opts.platform || defaultPlatform;
-        this.opts = { ...opts, platform: this.platform };
-        if (opts.scurry) {
-          this.scurry = opts.scurry;
-          if (opts.nocase !== void 0 && opts.nocase !== opts.scurry.nocase) {
-            throw new Error("nocase option contradicts provided scurry option");
-          }
-        } else {
-          const Scurry = opts.platform === "win32" ? path_scurry_1.PathScurryWin32 : opts.platform === "darwin" ? path_scurry_1.PathScurryDarwin : opts.platform ? path_scurry_1.PathScurryPosix : path_scurry_1.PathScurry;
-          this.scurry = new Scurry(this.cwd, {
-            nocase: opts.nocase,
-            fs: opts.fs
-          });
-        }
-        this.nocase = this.scurry.nocase;
-        const nocaseMagicOnly = this.platform === "darwin" || this.platform === "win32";
-        const mmo = {
-          // default nocase based on platform
-          ...opts,
-          dot: this.dot,
-          matchBase: this.matchBase,
-          nobrace: this.nobrace,
-          nocase: this.nocase,
-          nocaseMagicOnly,
-          nocomment: true,
-          noext: this.noext,
-          nonegate: true,
-          optimizationLevel: 2,
-          platform: this.platform,
-          windowsPathsNoEscape: this.windowsPathsNoEscape,
-          debug: !!this.opts.debug
-        };
-        const mms = this.pattern.map((p) => new minimatch_1.Minimatch(p, mmo));
-        const [matchSet, globParts] = mms.reduce((set2, m) => {
-          set2[0].push(...m.set);
-          set2[1].push(...m.globParts);
-          return set2;
-        }, [[], []]);
-        this.patterns = matchSet.map((set2, i) => {
-          const g = globParts[i];
-          if (!g)
-            throw new Error("invalid pattern object");
-          return new pattern_js_1.Pattern(set2, g, 0, this.platform);
-        });
+// node_modules/archiver/lib/plugins/zip.js
+var require_zip = __commonJS({
+  "node_modules/archiver/lib/plugins/zip.js"(exports2, module2) {
+    var engine = require_zip_stream();
+    var util = require_archiver_utils();
+    var Zip = function(options) {
+      if (!(this instanceof Zip)) {
+        return new Zip(options);
       }
-      async walk() {
-        return [
-          ...await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
-            ...this.opts,
-            maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
-            platform: this.platform,
-            nocase: this.nocase,
-            includeChildMatches: this.includeChildMatches
-          }).walk()
-        ];
+      options = this.options = util.defaults(options, {
+        comment: "",
+        forceUTC: false,
+        namePrependSlash: false,
+        store: false
+      });
+      this.supports = {
+        directory: true,
+        symlink: true
+      };
+      this.engine = new engine(options);
+    };
+    Zip.prototype.append = function(source, data, callback) {
+      this.engine.entry(source, data, callback);
+    };
+    Zip.prototype.finalize = function() {
+      this.engine.finalize();
+    };
+    Zip.prototype.on = function() {
+      return this.engine.on.apply(this.engine, arguments);
+    };
+    Zip.prototype.pipe = function() {
+      return this.engine.pipe.apply(this.engine, arguments);
+    };
+    Zip.prototype.unpipe = function() {
+      return this.engine.unpipe.apply(this.engine, arguments);
+    };
+    module2.exports = Zip;
+  }
+});
+
+// node_modules/queue-tick/queue-microtask.js
+var require_queue_microtask = __commonJS({
+  "node_modules/queue-tick/queue-microtask.js"(exports2, module2) {
+    module2.exports = typeof queueMicrotask === "function" ? queueMicrotask : (fn) => Promise.resolve().then(fn);
+  }
+});
+
+// node_modules/queue-tick/process-next-tick.js
+var require_process_next_tick = __commonJS({
+  "node_modules/queue-tick/process-next-tick.js"(exports2, module2) {
+    module2.exports = typeof process !== "undefined" && typeof process.nextTick === "function" ? process.nextTick.bind(process) : require_queue_microtask();
+  }
+});
+
+// node_modules/fast-fifo/fixed-size.js
+var require_fixed_size = __commonJS({
+  "node_modules/fast-fifo/fixed-size.js"(exports2, module2) {
+    module2.exports = class FixedFIFO {
+      constructor(hwm) {
+        if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two");
+        this.buffer = new Array(hwm);
+        this.mask = hwm - 1;
+        this.top = 0;
+        this.btm = 0;
+        this.next = null;
       }
-      walkSync() {
-        return [
-          ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
-            ...this.opts,
-            maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
-            platform: this.platform,
-            nocase: this.nocase,
-            includeChildMatches: this.includeChildMatches
-          }).walkSync()
-        ];
+      clear() {
+        this.top = this.btm = 0;
+        this.next = null;
+        this.buffer.fill(void 0);
       }
-      stream() {
-        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
-          ...this.opts,
-          maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
-          platform: this.platform,
-          nocase: this.nocase,
-          includeChildMatches: this.includeChildMatches
-        }).stream();
+      push(data) {
+        if (this.buffer[this.top] !== void 0) return false;
+        this.buffer[this.top] = data;
+        this.top = this.top + 1 & this.mask;
+        return true;
       }
-      streamSync() {
-        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
-          ...this.opts,
-          maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
-          platform: this.platform,
-          nocase: this.nocase,
-          includeChildMatches: this.includeChildMatches
-        }).streamSync();
+      shift() {
+        const last = this.buffer[this.btm];
+        if (last === void 0) return void 0;
+        this.buffer[this.btm] = void 0;
+        this.btm = this.btm + 1 & this.mask;
+        return last;
       }
-      /**
-       * Default sync iteration function. Returns a Generator that
-       * iterates over the results.
-       */
-      iterateSync() {
-        return this.streamSync()[Symbol.iterator]();
+      peek() {
+        return this.buffer[this.btm];
       }
-      [Symbol.iterator]() {
-        return this.iterateSync();
+      isEmpty() {
+        return this.buffer[this.btm] === void 0;
       }
-      /**
-       * Default async iteration function. Returns an AsyncGenerator that
-       * iterates over the results.
-       */
-      iterate() {
-        return this.stream()[Symbol.asyncIterator]();
+    };
+  }
+});
+
+// node_modules/fast-fifo/index.js
+var require_fast_fifo = __commonJS({
+  "node_modules/fast-fifo/index.js"(exports2, module2) {
+    var FixedFIFO = require_fixed_size();
+    module2.exports = class FastFIFO {
+      constructor(hwm) {
+        this.hwm = hwm || 16;
+        this.head = new FixedFIFO(this.hwm);
+        this.tail = this.head;
+        this.length = 0;
       }
-      [Symbol.asyncIterator]() {
-        return this.iterate();
+      clear() {
+        this.head = this.tail;
+        this.head.clear();
+        this.length = 0;
+      }
+      push(val2) {
+        this.length++;
+        if (!this.head.push(val2)) {
+          const prev = this.head;
+          this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
+          this.head.push(val2);
+        }
+      }
+      shift() {
+        if (this.length !== 0) this.length--;
+        const val2 = this.tail.shift();
+        if (val2 === void 0 && this.tail.next) {
+          const next = this.tail.next;
+          this.tail.next = null;
+          this.tail = next;
+          return this.tail.shift();
+        }
+        return val2;
       }
-    };
-    exports2.Glob = Glob;
-  }
-});
-
-// node_modules/archiver-utils/node_modules/glob/dist/commonjs/has-magic.js
-var require_has_magic = __commonJS({
-  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/has-magic.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.hasMagic = void 0;
-    var minimatch_1 = require_commonjs13();
-    var hasMagic = (pattern, options = {}) => {
-      if (!Array.isArray(pattern)) {
-        pattern = [pattern];
+      peek() {
+        const val2 = this.tail.peek();
+        if (val2 === void 0 && this.tail.next) return this.tail.next.peek();
+        return val2;
       }
-      for (const p of pattern) {
-        if (new minimatch_1.Minimatch(p, options).hasMagic())
-          return true;
+      isEmpty() {
+        return this.length === 0;
       }
-      return false;
     };
-    exports2.hasMagic = hasMagic;
   }
 });
 
-// node_modules/archiver-utils/node_modules/glob/dist/commonjs/index.js
-var require_commonjs17 = __commonJS({
-  "node_modules/archiver-utils/node_modules/glob/dist/commonjs/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.glob = exports2.sync = exports2.iterate = exports2.iterateSync = exports2.stream = exports2.streamSync = exports2.Ignore = exports2.hasMagic = exports2.Glob = exports2.unescape = exports2.escape = void 0;
-    exports2.globStreamSync = globStreamSync;
-    exports2.globStream = globStream;
-    exports2.globSync = globSync;
-    exports2.globIterateSync = globIterateSync;
-    exports2.globIterate = globIterate;
-    var minimatch_1 = require_commonjs13();
-    var glob_js_1 = require_glob();
-    var has_magic_js_1 = require_has_magic();
-    var minimatch_2 = require_commonjs13();
-    Object.defineProperty(exports2, "escape", { enumerable: true, get: function() {
-      return minimatch_2.escape;
-    } });
-    Object.defineProperty(exports2, "unescape", { enumerable: true, get: function() {
-      return minimatch_2.unescape;
-    } });
-    var glob_js_2 = require_glob();
-    Object.defineProperty(exports2, "Glob", { enumerable: true, get: function() {
-      return glob_js_2.Glob;
-    } });
-    var has_magic_js_2 = require_has_magic();
-    Object.defineProperty(exports2, "hasMagic", { enumerable: true, get: function() {
-      return has_magic_js_2.hasMagic;
-    } });
-    var ignore_js_1 = require_ignore();
-    Object.defineProperty(exports2, "Ignore", { enumerable: true, get: function() {
-      return ignore_js_1.Ignore;
-    } });
-    function globStreamSync(pattern, options = {}) {
-      return new glob_js_1.Glob(pattern, options).streamSync();
+// node_modules/b4a/index.js
+var require_b4a = __commonJS({
+  "node_modules/b4a/index.js"(exports2, module2) {
+    function isBuffer(value) {
+      return Buffer.isBuffer(value) || value instanceof Uint8Array;
     }
-    function globStream(pattern, options = {}) {
-      return new glob_js_1.Glob(pattern, options).stream();
+    function isEncoding(encoding) {
+      return Buffer.isEncoding(encoding);
     }
-    function globSync(pattern, options = {}) {
-      return new glob_js_1.Glob(pattern, options).walkSync();
+    function alloc(size, fill2, encoding) {
+      return Buffer.alloc(size, fill2, encoding);
     }
-    async function glob_(pattern, options = {}) {
-      return new glob_js_1.Glob(pattern, options).walk();
+    function allocUnsafe(size) {
+      return Buffer.allocUnsafe(size);
     }
-    function globIterateSync(pattern, options = {}) {
-      return new glob_js_1.Glob(pattern, options).iterateSync();
+    function allocUnsafeSlow(size) {
+      return Buffer.allocUnsafeSlow(size);
     }
-    function globIterate(pattern, options = {}) {
-      return new glob_js_1.Glob(pattern, options).iterate();
+    function byteLength(string, encoding) {
+      return Buffer.byteLength(string, encoding);
     }
-    exports2.streamSync = globStreamSync;
-    exports2.stream = Object.assign(globStream, { sync: globStreamSync });
-    exports2.iterateSync = globIterateSync;
-    exports2.iterate = Object.assign(globIterate, {
-      sync: globIterateSync
-    });
-    exports2.sync = Object.assign(globSync, {
-      stream: globStreamSync,
-      iterate: globIterateSync
-    });
-    exports2.glob = Object.assign(glob_, {
-      glob: glob_,
-      globSync,
-      sync: exports2.sync,
-      globStream,
-      stream: exports2.stream,
-      globStreamSync,
-      streamSync: exports2.streamSync,
-      globIterate,
-      iterate: exports2.iterate,
-      globIterateSync,
-      iterateSync: exports2.iterateSync,
-      Glob: glob_js_1.Glob,
-      hasMagic: has_magic_js_1.hasMagic,
-      escape: minimatch_1.escape,
-      unescape: minimatch_1.unescape
-    });
-    exports2.glob.glob = exports2.glob;
+    function compare2(a, b) {
+      return Buffer.compare(a, b);
+    }
+    function concat(buffers, totalLength) {
+      return Buffer.concat(buffers, totalLength);
+    }
+    function copy(source, target, targetStart, start, end) {
+      return toBuffer(source).copy(target, targetStart, start, end);
+    }
+    function equals(a, b) {
+      return toBuffer(a).equals(b);
+    }
+    function fill(buffer, value, offset, end, encoding) {
+      return toBuffer(buffer).fill(value, offset, end, encoding);
+    }
+    function from(value, encodingOrOffset, length) {
+      return Buffer.from(value, encodingOrOffset, length);
+    }
+    function includes(buffer, value, byteOffset, encoding) {
+      return toBuffer(buffer).includes(value, byteOffset, encoding);
+    }
+    function indexOf(buffer, value, byfeOffset, encoding) {
+      return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
+    }
+    function lastIndexOf(buffer, value, byteOffset, encoding) {
+      return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
+    }
+    function swap16(buffer) {
+      return toBuffer(buffer).swap16();
+    }
+    function swap32(buffer) {
+      return toBuffer(buffer).swap32();
+    }
+    function swap64(buffer) {
+      return toBuffer(buffer).swap64();
+    }
+    function toBuffer(buffer) {
+      if (Buffer.isBuffer(buffer)) return buffer;
+      return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
+    }
+    function toString2(buffer, encoding, start, end) {
+      return toBuffer(buffer).toString(encoding, start, end);
+    }
+    function write(buffer, string, offset, length, encoding) {
+      return toBuffer(buffer).write(string, offset, length, encoding);
+    }
+    function writeDoubleLE(buffer, value, offset) {
+      return toBuffer(buffer).writeDoubleLE(value, offset);
+    }
+    function writeFloatLE(buffer, value, offset) {
+      return toBuffer(buffer).writeFloatLE(value, offset);
+    }
+    function writeUInt32LE(buffer, value, offset) {
+      return toBuffer(buffer).writeUInt32LE(value, offset);
+    }
+    function writeInt32LE(buffer, value, offset) {
+      return toBuffer(buffer).writeInt32LE(value, offset);
+    }
+    function readDoubleLE(buffer, offset) {
+      return toBuffer(buffer).readDoubleLE(offset);
+    }
+    function readFloatLE(buffer, offset) {
+      return toBuffer(buffer).readFloatLE(offset);
+    }
+    function readUInt32LE(buffer, offset) {
+      return toBuffer(buffer).readUInt32LE(offset);
+    }
+    function readInt32LE(buffer, offset) {
+      return toBuffer(buffer).readInt32LE(offset);
+    }
+    function writeDoubleBE(buffer, value, offset) {
+      return toBuffer(buffer).writeDoubleBE(value, offset);
+    }
+    function writeFloatBE(buffer, value, offset) {
+      return toBuffer(buffer).writeFloatBE(value, offset);
+    }
+    function writeUInt32BE(buffer, value, offset) {
+      return toBuffer(buffer).writeUInt32BE(value, offset);
+    }
+    function writeInt32BE(buffer, value, offset) {
+      return toBuffer(buffer).writeInt32BE(value, offset);
+    }
+    function readDoubleBE(buffer, offset) {
+      return toBuffer(buffer).readDoubleBE(offset);
+    }
+    function readFloatBE(buffer, offset) {
+      return toBuffer(buffer).readFloatBE(offset);
+    }
+    function readUInt32BE(buffer, offset) {
+      return toBuffer(buffer).readUInt32BE(offset);
+    }
+    function readInt32BE(buffer, offset) {
+      return toBuffer(buffer).readInt32BE(offset);
+    }
+    module2.exports = {
+      isBuffer,
+      isEncoding,
+      alloc,
+      allocUnsafe,
+      allocUnsafeSlow,
+      byteLength,
+      compare: compare2,
+      concat,
+      copy,
+      equals,
+      fill,
+      from,
+      includes,
+      indexOf,
+      lastIndexOf,
+      swap16,
+      swap32,
+      swap64,
+      toBuffer,
+      toString: toString2,
+      write,
+      writeDoubleLE,
+      writeFloatLE,
+      writeUInt32LE,
+      writeInt32LE,
+      readDoubleLE,
+      readFloatLE,
+      readUInt32LE,
+      readInt32LE,
+      writeDoubleBE,
+      writeFloatBE,
+      writeUInt32BE,
+      writeInt32BE,
+      readDoubleBE,
+      readFloatBE,
+      readUInt32BE,
+      readInt32BE
+    };
   }
 });
 
-// node_modules/archiver-utils/file.js
-var require_file3 = __commonJS({
-  "node_modules/archiver-utils/file.js"(exports2, module2) {
-    var fs2 = require_graceful_fs();
-    var path2 = require("path");
-    var flatten = require_flatten();
-    var difference = require_difference();
-    var union = require_union();
-    var isPlainObject = require_isPlainObject();
-    var glob2 = require_commonjs17();
-    var file = module2.exports = {};
-    var pathSeparatorRe = /[\/\\]/g;
-    var processPatterns = function(patterns, fn) {
-      var result = [];
-      flatten(patterns).forEach(function(pattern) {
-        var exclusion = pattern.indexOf("!") === 0;
-        if (exclusion) {
-          pattern = pattern.slice(1);
-        }
-        var matches = fn(pattern);
-        if (exclusion) {
-          result = difference(result, matches);
-        } else {
-          result = union(result, matches);
-        }
-      });
-      return result;
-    };
-    file.exists = function() {
-      var filepath = path2.join.apply(path2, arguments);
-      return fs2.existsSync(filepath);
-    };
-    file.expand = function(...args) {
-      var options = isPlainObject(args[0]) ? args.shift() : {};
-      var patterns = Array.isArray(args[0]) ? args[0] : args;
-      if (patterns.length === 0) {
-        return [];
+// node_modules/text-decoder/lib/pass-through-decoder.js
+var require_pass_through_decoder = __commonJS({
+  "node_modules/text-decoder/lib/pass-through-decoder.js"(exports2, module2) {
+    var b4a = require_b4a();
+    module2.exports = class PassThroughDecoder {
+      constructor(encoding) {
+        this.encoding = encoding;
       }
-      var matches = processPatterns(patterns, function(pattern) {
-        return glob2.sync(pattern, options);
-      });
-      if (options.filter) {
-        matches = matches.filter(function(filepath) {
-          filepath = path2.join(options.cwd || "", filepath);
-          try {
-            if (typeof options.filter === "function") {
-              return options.filter(filepath);
-            } else {
-              return fs2.statSync(filepath)[options.filter]();
-            }
-          } catch (e) {
-            return false;
-          }
-        });
+      get remaining() {
+        return 0;
       }
-      return matches;
-    };
-    file.expandMapping = function(patterns, destBase, options) {
-      options = Object.assign({
-        rename: function(destBase2, destPath) {
-          return path2.join(destBase2 || "", destPath);
-        }
-      }, options);
-      var files = [];
-      var fileByDest = {};
-      file.expand(options, patterns).forEach(function(src) {
-        var destPath = src;
-        if (options.flatten) {
-          destPath = path2.basename(destPath);
-        }
-        if (options.ext) {
-          destPath = destPath.replace(/(\.[^\/]*)?$/, options.ext);
-        }
-        var dest = options.rename(destBase, destPath, options);
-        if (options.cwd) {
-          src = path2.join(options.cwd, src);
-        }
-        dest = dest.replace(pathSeparatorRe, "/");
-        src = src.replace(pathSeparatorRe, "/");
-        if (fileByDest[dest]) {
-          fileByDest[dest].src.push(src);
-        } else {
-          files.push({
-            src: [src],
-            dest
-          });
-          fileByDest[dest] = files[files.length - 1];
-        }
-      });
-      return files;
-    };
-    file.normalizeFilesArray = function(data) {
-      var files = [];
-      data.forEach(function(obj) {
-        var prop;
-        if ("src" in obj || "dest" in obj) {
-          files.push(obj);
-        }
-      });
-      if (files.length === 0) {
-        return [];
+      decode(tail) {
+        return b4a.toString(tail, this.encoding);
+      }
+      flush() {
+        return "";
       }
-      files = _(files).chain().forEach(function(obj) {
-        if (!("src" in obj) || !obj.src) {
-          return;
-        }
-        if (Array.isArray(obj.src)) {
-          obj.src = flatten(obj.src);
-        } else {
-          obj.src = [obj.src];
-        }
-      }).map(function(obj) {
-        var expandOptions = Object.assign({}, obj);
-        delete expandOptions.src;
-        delete expandOptions.dest;
-        if (obj.expand) {
-          return file.expandMapping(obj.src, obj.dest, expandOptions).map(function(mapObj) {
-            var result2 = Object.assign({}, obj);
-            result2.orig = Object.assign({}, obj);
-            result2.src = mapObj.src;
-            result2.dest = mapObj.dest;
-            ["expand", "cwd", "flatten", "rename", "ext"].forEach(function(prop) {
-              delete result2[prop];
-            });
-            return result2;
-          });
-        }
-        var result = Object.assign({}, obj);
-        result.orig = Object.assign({}, obj);
-        if ("src" in result) {
-          Object.defineProperty(result, "src", {
-            enumerable: true,
-            get: function fn() {
-              var src;
-              if (!("result" in fn)) {
-                src = obj.src;
-                src = Array.isArray(src) ? flatten(src) : [src];
-                fn.result = file.expand(expandOptions, src);
-              }
-              return fn.result;
-            }
-          });
-        }
-        if ("dest" in result) {
-          result.dest = obj.dest;
-        }
-        return result;
-      }).flatten().value();
-      return files;
     };
   }
 });
 
-// node_modules/archiver-utils/index.js
-var require_archiver_utils = __commonJS({
-  "node_modules/archiver-utils/index.js"(exports2, module2) {
-    var fs2 = require_graceful_fs();
-    var path2 = require("path");
-    var isStream = require_is_stream();
-    var lazystream = require_lazystream();
-    var normalizePath = require_normalize_path();
-    var defaults = require_defaults();
-    var Stream = require("stream").Stream;
-    var PassThrough = require_ours().PassThrough;
-    var utils = module2.exports = {};
-    utils.file = require_file3();
-    utils.collectStream = function(source, callback) {
-      var collection = [];
-      var size = 0;
-      source.on("error", callback);
-      source.on("data", function(chunk) {
-        collection.push(chunk);
-        size += chunk.length;
-      });
-      source.on("end", function() {
-        var buf = Buffer.alloc(size);
-        var offset = 0;
-        collection.forEach(function(data) {
-          data.copy(buf, offset);
-          offset += data.length;
-        });
-        callback(null, buf);
-      });
-    };
-    utils.dateify = function(dateish) {
-      dateish = dateish || /* @__PURE__ */ new Date();
-      if (dateish instanceof Date) {
-        dateish = dateish;
-      } else if (typeof dateish === "string") {
-        dateish = new Date(dateish);
-      } else {
-        dateish = /* @__PURE__ */ new Date();
-      }
-      return dateish;
-    };
-    utils.defaults = function(object, source, guard) {
-      var args = arguments;
-      args[0] = args[0] || {};
-      return defaults(...args);
-    };
-    utils.isStream = function(source) {
-      return isStream(source);
-    };
-    utils.lazyReadStream = function(filepath) {
-      return new lazystream.Readable(function() {
-        return fs2.createReadStream(filepath);
-      });
-    };
-    utils.normalizeInputSource = function(source) {
-      if (source === null) {
-        return Buffer.alloc(0);
-      } else if (typeof source === "string") {
-        return Buffer.from(source);
-      } else if (utils.isStream(source)) {
-        return source.pipe(new PassThrough());
-      }
-      return source;
-    };
-    utils.sanitizePath = function(filepath) {
-      return normalizePath(filepath, false).replace(/^\w+:/, "").replace(/^(\.\.\/|\/)+/, "");
-    };
-    utils.trailingSlashIt = function(str2) {
-      return str2.slice(-1) !== "/" ? str2 + "/" : str2;
-    };
-    utils.unixifyPath = function(filepath) {
-      return normalizePath(filepath, false).replace(/^\w+:/, "");
-    };
-    utils.walkdir = function(dirpath, base, callback) {
-      var results = [];
-      if (typeof base === "function") {
-        callback = base;
-        base = dirpath;
-      }
-      fs2.readdir(dirpath, function(err, list) {
-        var i = 0;
-        var file;
-        var filepath;
-        if (err) {
-          return callback(err);
-        }
-        (function next() {
-          file = list[i++];
-          if (!file) {
-            return callback(null, results);
+// node_modules/text-decoder/lib/utf8-decoder.js
+var require_utf8_decoder = __commonJS({
+  "node_modules/text-decoder/lib/utf8-decoder.js"(exports2, module2) {
+    var b4a = require_b4a();
+    module2.exports = class UTF8Decoder {
+      constructor() {
+        this.codePoint = 0;
+        this.bytesSeen = 0;
+        this.bytesNeeded = 0;
+        this.lowerBoundary = 128;
+        this.upperBoundary = 191;
+      }
+      get remaining() {
+        return this.bytesSeen;
+      }
+      decode(data) {
+        if (this.bytesNeeded === 0) {
+          let isBoundary = true;
+          for (let i = Math.max(0, data.byteLength - 4), n = data.byteLength; i < n && isBoundary; i++) {
+            isBoundary = data[i] <= 127;
           }
-          filepath = path2.join(dirpath, file);
-          fs2.stat(filepath, function(err2, stats) {
-            results.push({
-              path: filepath,
-              relative: path2.relative(base, filepath).replace(/\\/g, "/"),
-              stats
-            });
-            if (stats && stats.isDirectory()) {
-              utils.walkdir(filepath, base, function(err3, res) {
-                if (err3) {
-                  return callback(err3);
-                }
-                res.forEach(function(dirEntry) {
-                  results.push(dirEntry);
-                });
-                next();
-              });
+          if (isBoundary) return b4a.toString(data, "utf8");
+        }
+        let result = "";
+        for (let i = 0, n = data.byteLength; i < n; i++) {
+          const byte = data[i];
+          if (this.bytesNeeded === 0) {
+            if (byte <= 127) {
+              result += String.fromCharCode(byte);
             } else {
-              next();
+              this.bytesSeen = 1;
+              if (byte >= 194 && byte <= 223) {
+                this.bytesNeeded = 2;
+                this.codePoint = byte & 31;
+              } else if (byte >= 224 && byte <= 239) {
+                if (byte === 224) this.lowerBoundary = 160;
+                else if (byte === 237) this.upperBoundary = 159;
+                this.bytesNeeded = 3;
+                this.codePoint = byte & 15;
+              } else if (byte >= 240 && byte <= 244) {
+                if (byte === 240) this.lowerBoundary = 144;
+                if (byte === 244) this.upperBoundary = 143;
+                this.bytesNeeded = 4;
+                this.codePoint = byte & 7;
+              } else {
+                result += "\uFFFD";
+              }
             }
-          });
-        })();
-      });
+            continue;
+          }
+          if (byte < this.lowerBoundary || byte > this.upperBoundary) {
+            this.codePoint = 0;
+            this.bytesNeeded = 0;
+            this.bytesSeen = 0;
+            this.lowerBoundary = 128;
+            this.upperBoundary = 191;
+            result += "\uFFFD";
+            continue;
+          }
+          this.lowerBoundary = 128;
+          this.upperBoundary = 191;
+          this.codePoint = this.codePoint << 6 | byte & 63;
+          this.bytesSeen++;
+          if (this.bytesSeen !== this.bytesNeeded) continue;
+          result += String.fromCodePoint(this.codePoint);
+          this.codePoint = 0;
+          this.bytesNeeded = 0;
+          this.bytesSeen = 0;
+        }
+        return result;
+      }
+      flush() {
+        const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
+        this.codePoint = 0;
+        this.bytesNeeded = 0;
+        this.bytesSeen = 0;
+        this.lowerBoundary = 128;
+        this.upperBoundary = 191;
+        return result;
+      }
     };
   }
 });
 
-// node_modules/archiver/lib/error.js
-var require_error2 = __commonJS({
-  "node_modules/archiver/lib/error.js"(exports2, module2) {
-    var util = require("util");
-    var ERROR_CODES = {
-      "ABORTED": "archive was aborted",
-      "DIRECTORYDIRPATHREQUIRED": "diretory dirpath argument must be a non-empty string value",
-      "DIRECTORYFUNCTIONINVALIDDATA": "invalid data returned by directory custom data function",
-      "ENTRYNAMEREQUIRED": "entry name must be a non-empty string value",
-      "FILEFILEPATHREQUIRED": "file filepath argument must be a non-empty string value",
-      "FINALIZING": "archive already finalizing",
-      "QUEUECLOSED": "queue closed",
-      "NOENDMETHOD": "no suitable finalize/end method defined by module",
-      "DIRECTORYNOTSUPPORTED": "support for directory entries not defined by module",
-      "FORMATSET": "archive format already set",
-      "INPUTSTEAMBUFFERREQUIRED": "input source must be valid Stream or Buffer instance",
-      "MODULESET": "module already set",
-      "SYMLINKNOTSUPPORTED": "support for symlink entries not defined by module",
-      "SYMLINKFILEPATHREQUIRED": "symlink filepath argument must be a non-empty string value",
-      "SYMLINKTARGETREQUIRED": "symlink target argument must be a non-empty string value",
-      "ENTRYNOTSUPPORTED": "entry not supported"
+// node_modules/text-decoder/index.js
+var require_text_decoder = __commonJS({
+  "node_modules/text-decoder/index.js"(exports2, module2) {
+    var PassThroughDecoder = require_pass_through_decoder();
+    var UTF8Decoder = require_utf8_decoder();
+    module2.exports = class TextDecoder {
+      constructor(encoding = "utf8") {
+        this.encoding = normalizeEncoding(encoding);
+        switch (this.encoding) {
+          case "utf8":
+            this.decoder = new UTF8Decoder();
+            break;
+          case "utf16le":
+          case "base64":
+            throw new Error("Unsupported encoding: " + this.encoding);
+          default:
+            this.decoder = new PassThroughDecoder(this.encoding);
+        }
+      }
+      get remaining() {
+        return this.decoder.remaining;
+      }
+      push(data) {
+        if (typeof data === "string") return data;
+        return this.decoder.decode(data);
+      }
+      // For Node.js compatibility
+      write(data) {
+        return this.push(data);
+      }
+      end(data) {
+        let result = "";
+        if (data) result = this.push(data);
+        result += this.decoder.flush();
+        return result;
+      }
     };
-    function ArchiverError(code, data) {
-      Error.captureStackTrace(this, this.constructor);
-      this.message = ERROR_CODES[code] || code;
-      this.code = code;
-      this.data = data;
+    function normalizeEncoding(encoding) {
+      encoding = encoding.toLowerCase();
+      switch (encoding) {
+        case "utf8":
+        case "utf-8":
+          return "utf8";
+        case "ucs2":
+        case "ucs-2":
+        case "utf16le":
+        case "utf-16le":
+          return "utf16le";
+        case "latin1":
+        case "binary":
+          return "latin1";
+        case "base64":
+        case "ascii":
+        case "hex":
+          return encoding;
+        default:
+          throw new Error("Unknown encoding: " + encoding);
+      }
     }
-    util.inherits(ArchiverError, Error);
-    exports2 = module2.exports = ArchiverError;
   }
 });
 
-// node_modules/archiver/lib/core.js
-var require_core2 = __commonJS({
-  "node_modules/archiver/lib/core.js"(exports2, module2) {
-    var fs2 = require("fs");
-    var glob2 = require_readdir_glob();
-    var async = require_async();
-    var path2 = require("path");
-    var util = require_archiver_utils();
-    var inherits = require("util").inherits;
-    var ArchiverError = require_error2();
-    var Transform = require_ours().Transform;
-    var win32 = process.platform === "win32";
-    var Archiver = function(format, options) {
-      if (!(this instanceof Archiver)) {
-        return new Archiver(format, options);
-      }
-      if (typeof format !== "string") {
-        options = format;
-        format = "zip";
-      }
-      options = this.options = util.defaults(options, {
-        highWaterMark: 1024 * 1024,
-        statConcurrency: 4
-      });
-      Transform.call(this, options);
-      this._format = false;
-      this._module = false;
-      this._pending = 0;
-      this._pointer = 0;
-      this._entriesCount = 0;
-      this._entriesProcessedCount = 0;
-      this._fsEntriesTotalBytes = 0;
-      this._fsEntriesProcessedBytes = 0;
-      this._queue = async.queue(this._onQueueTask.bind(this), 1);
-      this._queue.drain(this._onQueueDrain.bind(this));
-      this._statQueue = async.queue(this._onStatQueueTask.bind(this), options.statConcurrency);
-      this._statQueue.drain(this._onQueueDrain.bind(this));
-      this._state = {
-        aborted: false,
-        finalize: false,
-        finalizing: false,
-        finalized: false,
-        modulePiped: false
-      };
-      this._streams = [];
-    };
-    inherits(Archiver, Transform);
-    Archiver.prototype._abort = function() {
-      this._state.aborted = true;
-      this._queue.kill();
-      this._statQueue.kill();
-      if (this._queue.idle()) {
-        this._shutdown();
+// node_modules/streamx/index.js
+var require_streamx = __commonJS({
+  "node_modules/streamx/index.js"(exports2, module2) {
+    var { EventEmitter } = require("events");
+    var STREAM_DESTROYED = new Error("Stream was destroyed");
+    var PREMATURE_CLOSE = new Error("Premature close");
+    var queueTick = require_process_next_tick();
+    var FIFO = require_fast_fifo();
+    var TextDecoder2 = require_text_decoder();
+    var MAX = (1 << 29) - 1;
+    var OPENING = 1;
+    var PREDESTROYING = 2;
+    var DESTROYING = 4;
+    var DESTROYED = 8;
+    var NOT_OPENING = MAX ^ OPENING;
+    var NOT_PREDESTROYING = MAX ^ PREDESTROYING;
+    var READ_ACTIVE = 1 << 4;
+    var READ_UPDATING = 2 << 4;
+    var READ_PRIMARY = 4 << 4;
+    var READ_QUEUED = 8 << 4;
+    var READ_RESUMED = 16 << 4;
+    var READ_PIPE_DRAINED = 32 << 4;
+    var READ_ENDING = 64 << 4;
+    var READ_EMIT_DATA = 128 << 4;
+    var READ_EMIT_READABLE = 256 << 4;
+    var READ_EMITTED_READABLE = 512 << 4;
+    var READ_DONE = 1024 << 4;
+    var READ_NEXT_TICK = 2048 << 4;
+    var READ_NEEDS_PUSH = 4096 << 4;
+    var READ_READ_AHEAD = 8192 << 4;
+    var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED;
+    var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH;
+    var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE;
+    var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED;
+    var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD;
+    var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE;
+    var READ_NON_PRIMARY = MAX ^ READ_PRIMARY;
+    var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH);
+    var READ_PUSHED = MAX ^ READ_NEEDS_PUSH;
+    var READ_PAUSED = MAX ^ READ_RESUMED;
+    var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE);
+    var READ_NOT_ENDING = MAX ^ READ_ENDING;
+    var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING;
+    var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK;
+    var READ_NOT_UPDATING = MAX ^ READ_UPDATING;
+    var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD;
+    var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD;
+    var WRITE_ACTIVE = 1 << 18;
+    var WRITE_UPDATING = 2 << 18;
+    var WRITE_PRIMARY = 4 << 18;
+    var WRITE_QUEUED = 8 << 18;
+    var WRITE_UNDRAINED = 16 << 18;
+    var WRITE_DONE = 32 << 18;
+    var WRITE_EMIT_DRAIN = 64 << 18;
+    var WRITE_NEXT_TICK = 128 << 18;
+    var WRITE_WRITING = 256 << 18;
+    var WRITE_FINISHING = 512 << 18;
+    var WRITE_CORKED = 1024 << 18;
+    var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING);
+    var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY;
+    var WRITE_NOT_FINISHING = MAX ^ WRITE_FINISHING;
+    var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED;
+    var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED;
+    var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK;
+    var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING;
+    var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED;
+    var ACTIVE = READ_ACTIVE | WRITE_ACTIVE;
+    var NOT_ACTIVE = MAX ^ ACTIVE;
+    var DONE = READ_DONE | WRITE_DONE;
+    var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING;
+    var OPEN_STATUS = DESTROY_STATUS | OPENING;
+    var AUTO_DESTROY = DESTROY_STATUS | DONE;
+    var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY;
+    var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK;
+    var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE;
+    var IS_OPENING = OPEN_STATUS | TICKING;
+    var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE;
+    var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED;
+    var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED;
+    var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE;
+    var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD;
+    var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE;
+    var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY;
+    var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE;
+    var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED;
+    var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE;
+    var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE;
+    var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED;
+    var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE;
+    var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING;
+    var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE;
+    var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE;
+    var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY;
+    var asyncIterator = Symbol.asyncIterator || Symbol("asyncIterator");
+    var WritableState = class {
+      constructor(stream, { highWaterMark = 16384, map: map2 = null, mapWritable, byteLength, byteLengthWritable } = {}) {
+        this.stream = stream;
+        this.queue = new FIFO();
+        this.highWaterMark = highWaterMark;
+        this.buffered = 0;
+        this.error = null;
+        this.pipeline = null;
+        this.drains = null;
+        this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
+        this.map = mapWritable || map2;
+        this.afterWrite = afterWrite.bind(this);
+        this.afterUpdateNextTick = updateWriteNT.bind(this);
       }
-    };
-    Archiver.prototype._append = function(filepath, data) {
-      data = data || {};
-      var task = {
-        source: null,
-        filepath
-      };
-      if (!data.name) {
-        data.name = filepath;
+      get ended() {
+        return (this.stream._duplexState & WRITE_DONE) !== 0;
       }
-      data.sourcePath = filepath;
-      task.data = data;
-      this._entriesCount++;
-      if (data.stats && data.stats instanceof fs2.Stats) {
-        task = this._updateQueueTaskWithStats(task, data.stats);
-        if (task) {
-          if (data.stats.size) {
-            this._fsEntriesTotalBytes += data.stats.size;
-          }
-          this._queue.push(task);
+      push(data) {
+        if (this.map !== null) data = this.map(data);
+        this.buffered += this.byteLength(data);
+        this.queue.push(data);
+        if (this.buffered < this.highWaterMark) {
+          this.stream._duplexState |= WRITE_QUEUED;
+          return true;
         }
-      } else {
-        this._statQueue.push(task);
+        this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
+        return false;
       }
-    };
-    Archiver.prototype._finalize = function() {
-      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
-        return;
+      shift() {
+        const data = this.queue.shift();
+        this.buffered -= this.byteLength(data);
+        if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
+        return data;
       }
-      this._state.finalizing = true;
-      this._moduleFinalize();
-      this._state.finalizing = false;
-      this._state.finalized = true;
-    };
-    Archiver.prototype._maybeFinalize = function() {
-      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
-        return false;
+      end(data) {
+        if (typeof data === "function") this.stream.once("finish", data);
+        else if (data !== void 0 && data !== null) this.push(data);
+        this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
       }
-      if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) {
-        this._finalize();
-        return true;
+      autoBatch(data, cb) {
+        const buffer = [];
+        const stream = this.stream;
+        buffer.push(data);
+        while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
+          buffer.push(stream._writableState.shift());
+        }
+        if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
+        stream._writev(buffer, cb);
       }
-      return false;
-    };
-    Archiver.prototype._moduleAppend = function(source, data, callback) {
-      if (this._state.aborted) {
-        callback();
-        return;
+      update() {
+        const stream = this.stream;
+        stream._duplexState |= WRITE_UPDATING;
+        do {
+          while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
+            const data = this.shift();
+            stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
+            stream._write(data, this.afterWrite);
+          }
+          if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
+        } while (this.continueUpdate() === true);
+        stream._duplexState &= WRITE_NOT_UPDATING;
       }
-      this._module.append(source, data, function(err) {
-        this._task = null;
-        if (this._state.aborted) {
-          this._shutdown();
+      updateNonPrimary() {
+        const stream = this.stream;
+        if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
+          stream._duplexState = (stream._duplexState | WRITE_ACTIVE) & WRITE_NOT_FINISHING;
+          stream._final(afterFinal.bind(this));
           return;
         }
-        if (err) {
-          this.emit("error", err);
-          setImmediate(callback);
+        if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
+          if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
+            stream._duplexState |= ACTIVE;
+            stream._destroy(afterDestroy.bind(this));
+          }
           return;
         }
-        this.emit("entry", data);
-        this._entriesProcessedCount++;
-        if (data.stats && data.stats.size) {
-          this._fsEntriesProcessedBytes += data.stats.size;
+        if ((stream._duplexState & IS_OPENING) === OPENING) {
+          stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
+          stream._open(afterOpen.bind(this));
         }
-        this.emit("progress", {
-          entries: {
-            total: this._entriesCount,
-            processed: this._entriesProcessedCount
-          },
-          fs: {
-            totalBytes: this._fsEntriesTotalBytes,
-            processedBytes: this._fsEntriesProcessedBytes
-          }
-        });
-        setImmediate(callback);
-      }.bind(this));
-    };
-    Archiver.prototype._moduleFinalize = function() {
-      if (typeof this._module.finalize === "function") {
-        this._module.finalize();
-      } else if (typeof this._module.end === "function") {
-        this._module.end();
-      } else {
-        this.emit("error", new ArchiverError("NOENDMETHOD"));
       }
-    };
-    Archiver.prototype._modulePipe = function() {
-      this._module.on("error", this._onModuleError.bind(this));
-      this._module.pipe(this);
-      this._state.modulePiped = true;
-    };
-    Archiver.prototype._moduleSupports = function(key) {
-      if (!this._module.supports || !this._module.supports[key]) {
-        return false;
+      continueUpdate() {
+        if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
+        this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
+        return true;
+      }
+      updateCallback() {
+        if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update();
+        else this.updateNextTick();
+      }
+      updateNextTick() {
+        if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
+        this.stream._duplexState |= WRITE_NEXT_TICK;
+        if ((this.stream._duplexState & WRITE_UPDATING) === 0) queueTick(this.afterUpdateNextTick);
       }
-      return this._module.supports[key];
-    };
-    Archiver.prototype._moduleUnpipe = function() {
-      this._module.unpipe(this);
-      this._state.modulePiped = false;
     };
-    Archiver.prototype._normalizeEntryData = function(data, stats) {
-      data = util.defaults(data, {
-        type: "file",
-        name: null,
-        date: null,
-        mode: null,
-        prefix: null,
-        sourcePath: null,
-        stats: false
-      });
-      if (stats && data.stats === false) {
-        data.stats = stats;
+    var ReadableState = class {
+      constructor(stream, { highWaterMark = 16384, map: map2 = null, mapReadable, byteLength, byteLengthReadable } = {}) {
+        this.stream = stream;
+        this.queue = new FIFO();
+        this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
+        this.buffered = 0;
+        this.readAhead = highWaterMark > 0;
+        this.error = null;
+        this.pipeline = null;
+        this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
+        this.map = mapReadable || map2;
+        this.pipeTo = null;
+        this.afterRead = afterRead.bind(this);
+        this.afterUpdateNextTick = updateReadNT.bind(this);
       }
-      var isDir = data.type === "directory";
-      if (data.name) {
-        if (typeof data.prefix === "string" && "" !== data.prefix) {
-          data.name = data.prefix + "/" + data.name;
-          data.prefix = null;
-        }
-        data.name = util.sanitizePath(data.name);
-        if (data.type !== "symlink" && data.name.slice(-1) === "/") {
-          isDir = true;
-          data.type = "directory";
-        } else if (isDir) {
-          data.name += "/";
-        }
+      get ended() {
+        return (this.stream._duplexState & READ_DONE) !== 0;
       }
-      if (typeof data.mode === "number") {
-        if (win32) {
-          data.mode &= 511;
+      pipe(pipeTo, cb) {
+        if (this.pipeTo !== null) throw new Error("Can only pipe to one destination");
+        if (typeof cb !== "function") cb = null;
+        this.stream._duplexState |= READ_PIPE_DRAINED;
+        this.pipeTo = pipeTo;
+        this.pipeline = new Pipeline(this.stream, pipeTo, cb);
+        if (cb) this.stream.on("error", noop);
+        if (isStreamx(pipeTo)) {
+          pipeTo._writableState.pipeline = this.pipeline;
+          if (cb) pipeTo.on("error", noop);
+          pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
         } else {
-          data.mode &= 4095;
+          const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
+          const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
+          pipeTo.on("error", onerror);
+          pipeTo.on("close", onclose);
+          pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
         }
-      } else if (data.stats && data.mode === null) {
-        if (win32) {
-          data.mode = data.stats.mode & 511;
-        } else {
-          data.mode = data.stats.mode & 4095;
+        pipeTo.on("drain", afterDrain.bind(this));
+        this.stream.emit("piping", pipeTo);
+        pipeTo.emit("pipe", this.stream);
+      }
+      push(data) {
+        const stream = this.stream;
+        if (data === null) {
+          this.highWaterMark = 0;
+          stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
+          return false;
         }
-        if (win32 && isDir) {
-          data.mode = 493;
+        if (this.map !== null) {
+          data = this.map(data);
+          if (data === null) {
+            stream._duplexState &= READ_PUSHED;
+            return this.buffered < this.highWaterMark;
+          }
         }
-      } else if (data.mode === null) {
-        data.mode = isDir ? 493 : 420;
+        this.buffered += this.byteLength(data);
+        this.queue.push(data);
+        stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
+        return this.buffered < this.highWaterMark;
       }
-      if (data.stats && data.date === null) {
-        data.date = data.stats.mtime;
-      } else {
-        data.date = util.dateify(data.date);
+      shift() {
+        const data = this.queue.shift();
+        this.buffered -= this.byteLength(data);
+        if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED;
+        return data;
       }
-      return data;
-    };
-    Archiver.prototype._onModuleError = function(err) {
-      this.emit("error", err);
-    };
-    Archiver.prototype._onQueueDrain = function() {
-      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
-        return;
+      unshift(data) {
+        const pending = [this.map !== null ? this.map(data) : data];
+        while (this.buffered > 0) pending.push(this.shift());
+        for (let i = 0; i < pending.length - 1; i++) {
+          const data2 = pending[i];
+          this.buffered += this.byteLength(data2);
+          this.queue.push(data2);
+        }
+        this.push(pending[pending.length - 1]);
       }
-      if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) {
-        this._finalize();
+      read() {
+        const stream = this.stream;
+        if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
+          const data = this.shift();
+          if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
+          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
+          return data;
+        }
+        if (this.readAhead === false) {
+          stream._duplexState |= READ_READ_AHEAD;
+          this.updateNextTick();
+        }
+        return null;
       }
-    };
-    Archiver.prototype._onQueueTask = function(task, callback) {
-      var fullCallback = () => {
-        if (task.data.callback) {
-          task.data.callback();
+      drain() {
+        const stream = this.stream;
+        while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
+          const data = this.shift();
+          if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
+          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
         }
-        callback();
-      };
-      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
-        fullCallback();
-        return;
       }
-      this._task = task;
-      this._moduleAppend(task.source, task.data, fullCallback);
-    };
-    Archiver.prototype._onStatQueueTask = function(task, callback) {
-      if (this._state.finalizing || this._state.finalized || this._state.aborted) {
-        callback();
-        return;
+      update() {
+        const stream = this.stream;
+        stream._duplexState |= READ_UPDATING;
+        do {
+          this.drain();
+          while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
+            stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
+            stream._read(this.afterRead);
+            this.drain();
+          }
+          if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
+            stream._duplexState |= READ_EMITTED_READABLE;
+            stream.emit("readable");
+          }
+          if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
+        } while (this.continueUpdate() === true);
+        stream._duplexState &= READ_NOT_UPDATING;
       }
-      fs2.lstat(task.filepath, function(err, stats) {
-        if (this._state.aborted) {
-          setImmediate(callback);
-          return;
+      updateNonPrimary() {
+        const stream = this.stream;
+        if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
+          stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
+          stream.emit("end");
+          if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING;
+          if (this.pipeTo !== null) this.pipeTo.end();
         }
-        if (err) {
-          this._entriesCount--;
-          this.emit("warning", err);
-          setImmediate(callback);
+        if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
+          if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
+            stream._duplexState |= ACTIVE;
+            stream._destroy(afterDestroy.bind(this));
+          }
           return;
         }
-        task = this._updateQueueTaskWithStats(task, stats);
-        if (task) {
-          if (stats.size) {
-            this._fsEntriesTotalBytes += stats.size;
-          }
-          this._queue.push(task);
+        if ((stream._duplexState & IS_OPENING) === OPENING) {
+          stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
+          stream._open(afterOpen.bind(this));
         }
-        setImmediate(callback);
-      }.bind(this));
-    };
-    Archiver.prototype._shutdown = function() {
-      this._moduleUnpipe();
-      this.end();
-    };
-    Archiver.prototype._transform = function(chunk, encoding, callback) {
-      if (chunk) {
-        this._pointer += chunk.length;
       }
-      callback(null, chunk);
-    };
-    Archiver.prototype._updateQueueTaskWithStats = function(task, stats) {
-      if (stats.isFile()) {
-        task.data.type = "file";
-        task.data.sourceType = "stream";
-        task.source = util.lazyReadStream(task.filepath);
-      } else if (stats.isDirectory() && this._moduleSupports("directory")) {
-        task.data.name = util.trailingSlashIt(task.data.name);
-        task.data.type = "directory";
-        task.data.sourcePath = util.trailingSlashIt(task.filepath);
-        task.data.sourceType = "buffer";
-        task.source = Buffer.concat([]);
-      } else if (stats.isSymbolicLink() && this._moduleSupports("symlink")) {
-        var linkPath = fs2.readlinkSync(task.filepath);
-        var dirName = path2.dirname(task.filepath);
-        task.data.type = "symlink";
-        task.data.linkname = path2.relative(dirName, path2.resolve(dirName, linkPath));
-        task.data.sourceType = "buffer";
-        task.source = Buffer.concat([]);
-      } else {
-        if (stats.isDirectory()) {
-          this.emit("warning", new ArchiverError("DIRECTORYNOTSUPPORTED", task.data));
-        } else if (stats.isSymbolicLink()) {
-          this.emit("warning", new ArchiverError("SYMLINKNOTSUPPORTED", task.data));
-        } else {
-          this.emit("warning", new ArchiverError("ENTRYNOTSUPPORTED", task.data));
-        }
-        return null;
+      continueUpdate() {
+        if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
+        this.stream._duplexState &= READ_NOT_NEXT_TICK;
+        return true;
       }
-      task.data = this._normalizeEntryData(task.data, stats);
-      return task;
-    };
-    Archiver.prototype.abort = function() {
-      if (this._state.aborted || this._state.finalized) {
-        return this;
+      updateCallback() {
+        if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update();
+        else this.updateNextTick();
+      }
+      updateNextTick() {
+        if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return;
+        this.stream._duplexState |= READ_NEXT_TICK;
+        if ((this.stream._duplexState & READ_UPDATING) === 0) queueTick(this.afterUpdateNextTick);
       }
-      this._abort();
-      return this;
     };
-    Archiver.prototype.append = function(source, data) {
-      if (this._state.finalize || this._state.aborted) {
-        this.emit("error", new ArchiverError("QUEUECLOSED"));
-        return this;
+    var TransformState = class {
+      constructor(stream) {
+        this.data = null;
+        this.afterTransform = afterTransform.bind(stream);
+        this.afterFinal = null;
       }
-      data = this._normalizeEntryData(data);
-      if (typeof data.name !== "string" || data.name.length === 0) {
-        this.emit("error", new ArchiverError("ENTRYNAMEREQUIRED"));
-        return this;
+    };
+    var Pipeline = class {
+      constructor(src, dst, cb) {
+        this.from = src;
+        this.to = dst;
+        this.afterPipe = cb;
+        this.error = null;
+        this.pipeToFinished = false;
       }
-      if (data.type === "directory" && !this._moduleSupports("directory")) {
-        this.emit("error", new ArchiverError("DIRECTORYNOTSUPPORTED", { name: data.name }));
-        return this;
+      finished() {
+        this.pipeToFinished = true;
       }
-      source = util.normalizeInputSource(source);
-      if (Buffer.isBuffer(source)) {
-        data.sourceType = "buffer";
-      } else if (util.isStream(source)) {
-        data.sourceType = "stream";
-      } else {
-        this.emit("error", new ArchiverError("INPUTSTEAMBUFFERREQUIRED", { name: data.name }));
-        return this;
+      done(stream, err) {
+        if (err) this.error = err;
+        if (stream === this.to) {
+          this.to = null;
+          if (this.from !== null) {
+            if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
+              this.from.destroy(this.error || new Error("Writable stream closed prematurely"));
+            }
+            return;
+          }
+        }
+        if (stream === this.from) {
+          this.from = null;
+          if (this.to !== null) {
+            if ((stream._duplexState & READ_DONE) === 0) {
+              this.to.destroy(this.error || new Error("Readable stream closed before ending"));
+            }
+            return;
+          }
+        }
+        if (this.afterPipe !== null) this.afterPipe(this.error);
+        this.to = this.from = this.afterPipe = null;
       }
-      this._entriesCount++;
-      this._queue.push({
-        data,
-        source
-      });
-      return this;
     };
-    Archiver.prototype.directory = function(dirpath, destpath, data) {
-      if (this._state.finalize || this._state.aborted) {
-        this.emit("error", new ArchiverError("QUEUECLOSED"));
-        return this;
+    function afterDrain() {
+      this.stream._duplexState |= READ_PIPE_DRAINED;
+      this.updateCallback();
+    }
+    function afterFinal(err) {
+      const stream = this.stream;
+      if (err) stream.destroy(err);
+      if ((stream._duplexState & DESTROY_STATUS) === 0) {
+        stream._duplexState |= WRITE_DONE;
+        stream.emit("finish");
       }
-      if (typeof dirpath !== "string" || dirpath.length === 0) {
-        this.emit("error", new ArchiverError("DIRECTORYDIRPATHREQUIRED"));
-        return this;
+      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
+        stream._duplexState |= DESTROYING;
       }
-      this._pending++;
-      if (destpath === false) {
-        destpath = "";
-      } else if (typeof destpath !== "string") {
-        destpath = dirpath;
+      stream._duplexState &= WRITE_NOT_ACTIVE;
+      if ((stream._duplexState & WRITE_UPDATING) === 0) this.update();
+      else this.updateNextTick();
+    }
+    function afterDestroy(err) {
+      const stream = this.stream;
+      if (!err && this.error !== STREAM_DESTROYED) err = this.error;
+      if (err) stream.emit("error", err);
+      stream._duplexState |= DESTROYED;
+      stream.emit("close");
+      const rs = stream._readableState;
+      const ws = stream._writableState;
+      if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err);
+      if (ws !== null) {
+        while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false);
+        if (ws.pipeline !== null) ws.pipeline.done(stream, err);
       }
-      var dataFunction = false;
-      if (typeof data === "function") {
-        dataFunction = data;
-        data = {};
-      } else if (typeof data !== "object") {
-        data = {};
+    }
+    function afterWrite(err) {
+      const stream = this.stream;
+      if (err) stream.destroy(err);
+      stream._duplexState &= WRITE_NOT_ACTIVE;
+      if (this.drains !== null) tickDrains(this.drains);
+      if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
+        stream._duplexState &= WRITE_DRAINED;
+        if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
+          stream.emit("drain");
+        }
       }
-      var globOptions = {
-        stat: true,
-        dot: true
-      };
-      function onGlobEnd() {
-        this._pending--;
-        this._maybeFinalize();
+      this.updateCallback();
+    }
+    function afterRead(err) {
+      if (err) this.stream.destroy(err);
+      this.stream._duplexState &= READ_NOT_ACTIVE;
+      if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) this.stream._duplexState &= READ_NO_READ_AHEAD;
+      this.updateCallback();
+    }
+    function updateReadNT() {
+      if ((this.stream._duplexState & READ_UPDATING) === 0) {
+        this.stream._duplexState &= READ_NOT_NEXT_TICK;
+        this.update();
       }
-      function onGlobError(err) {
-        this.emit("error", err);
+    }
+    function updateWriteNT() {
+      if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
+        this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
+        this.update();
       }
-      function onGlobMatch(match) {
-        globber.pause();
-        var ignoreMatch = false;
-        var entryData = Object.assign({}, data);
-        entryData.name = match.relative;
-        entryData.prefix = destpath;
-        entryData.stats = match.stat;
-        entryData.callback = globber.resume.bind(globber);
-        try {
-          if (dataFunction) {
-            entryData = dataFunction(entryData);
-            if (entryData === false) {
-              ignoreMatch = true;
-            } else if (typeof entryData !== "object") {
-              throw new ArchiverError("DIRECTORYFUNCTIONINVALIDDATA", { dirpath });
-            }
-          }
-        } catch (e) {
-          this.emit("error", e);
-          return;
-        }
-        if (ignoreMatch) {
-          globber.resume();
-          return;
+    }
+    function tickDrains(drains) {
+      for (let i = 0; i < drains.length; i++) {
+        if (--drains[i].writes === 0) {
+          drains.shift().resolve(true);
+          i--;
         }
-        this._append(match.absolute, entryData);
       }
-      var globber = glob2(dirpath, globOptions);
-      globber.on("error", onGlobError.bind(this));
-      globber.on("match", onGlobMatch.bind(this));
-      globber.on("end", onGlobEnd.bind(this));
-      return this;
-    };
-    Archiver.prototype.file = function(filepath, data) {
-      if (this._state.finalize || this._state.aborted) {
-        this.emit("error", new ArchiverError("QUEUECLOSED"));
-        return this;
+    }
+    function afterOpen(err) {
+      const stream = this.stream;
+      if (err) stream.destroy(err);
+      if ((stream._duplexState & DESTROYING) === 0) {
+        if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY;
+        if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY;
+        stream.emit("open");
       }
-      if (typeof filepath !== "string" || filepath.length === 0) {
-        this.emit("error", new ArchiverError("FILEFILEPATHREQUIRED"));
-        return this;
+      stream._duplexState &= NOT_ACTIVE;
+      if (stream._writableState !== null) {
+        stream._writableState.updateCallback();
       }
-      this._append(filepath, data);
-      return this;
-    };
-    Archiver.prototype.glob = function(pattern, options, data) {
-      this._pending++;
-      options = util.defaults(options, {
-        stat: true,
-        pattern
-      });
-      function onGlobEnd() {
-        this._pending--;
-        this._maybeFinalize();
+      if (stream._readableState !== null) {
+        stream._readableState.updateCallback();
       }
-      function onGlobError(err) {
-        this.emit("error", err);
+    }
+    function afterTransform(err, data) {
+      if (data !== void 0 && data !== null) this.push(data);
+      this._writableState.afterWrite(err);
+    }
+    function newListener(name) {
+      if (this._readableState !== null) {
+        if (name === "data") {
+          this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
+          this._readableState.updateNextTick();
+        }
+        if (name === "readable") {
+          this._duplexState |= READ_EMIT_READABLE;
+          this._readableState.updateNextTick();
+        }
       }
-      function onGlobMatch(match) {
-        globber.pause();
-        var entryData = Object.assign({}, data);
-        entryData.callback = globber.resume.bind(globber);
-        entryData.stats = match.stat;
-        entryData.name = match.relative;
-        this._append(match.absolute, entryData);
+      if (this._writableState !== null) {
+        if (name === "drain") {
+          this._duplexState |= WRITE_EMIT_DRAIN;
+          this._writableState.updateNextTick();
+        }
       }
-      var globber = glob2(options.cwd || ".", options);
-      globber.on("error", onGlobError.bind(this));
-      globber.on("match", onGlobMatch.bind(this));
-      globber.on("end", onGlobEnd.bind(this));
-      return this;
-    };
-    Archiver.prototype.finalize = function() {
-      if (this._state.aborted) {
-        var abortedError = new ArchiverError("ABORTED");
-        this.emit("error", abortedError);
-        return Promise.reject(abortedError);
+    }
+    var Stream = class extends EventEmitter {
+      constructor(opts) {
+        super();
+        this._duplexState = 0;
+        this._readableState = null;
+        this._writableState = null;
+        if (opts) {
+          if (opts.open) this._open = opts.open;
+          if (opts.destroy) this._destroy = opts.destroy;
+          if (opts.predestroy) this._predestroy = opts.predestroy;
+          if (opts.signal) {
+            opts.signal.addEventListener("abort", abort.bind(this));
+          }
+        }
+        this.on("newListener", newListener);
+      }
+      _open(cb) {
+        cb(null);
+      }
+      _destroy(cb) {
+        cb(null);
       }
-      if (this._state.finalize) {
-        var finalizingError = new ArchiverError("FINALIZING");
-        this.emit("error", finalizingError);
-        return Promise.reject(finalizingError);
+      _predestroy() {
       }
-      this._state.finalize = true;
-      if (this._pending === 0 && this._queue.idle() && this._statQueue.idle()) {
-        this._finalize();
+      get readable() {
+        return this._readableState !== null ? true : void 0;
       }
-      var self2 = this;
-      return new Promise(function(resolve2, reject) {
-        var errored;
-        self2._module.on("end", function() {
-          if (!errored) {
-            resolve2();
+      get writable() {
+        return this._writableState !== null ? true : void 0;
+      }
+      get destroyed() {
+        return (this._duplexState & DESTROYED) !== 0;
+      }
+      get destroying() {
+        return (this._duplexState & DESTROY_STATUS) !== 0;
+      }
+      destroy(err) {
+        if ((this._duplexState & DESTROY_STATUS) === 0) {
+          if (!err) err = STREAM_DESTROYED;
+          this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
+          if (this._readableState !== null) {
+            this._readableState.highWaterMark = 0;
+            this._readableState.error = err;
           }
-        });
-        self2._module.on("error", function(err) {
-          errored = true;
-          reject(err);
-        });
-      });
-    };
-    Archiver.prototype.setFormat = function(format) {
-      if (this._format) {
-        this.emit("error", new ArchiverError("FORMATSET"));
-        return this;
+          if (this._writableState !== null) {
+            this._writableState.highWaterMark = 0;
+            this._writableState.error = err;
+          }
+          this._duplexState |= PREDESTROYING;
+          this._predestroy();
+          this._duplexState &= NOT_PREDESTROYING;
+          if (this._readableState !== null) this._readableState.updateNextTick();
+          if (this._writableState !== null) this._writableState.updateNextTick();
+        }
       }
-      this._format = format;
-      return this;
     };
-    Archiver.prototype.setModule = function(module3) {
-      if (this._state.aborted) {
-        this.emit("error", new ArchiverError("ABORTED"));
-        return this;
+    var Readable = class _Readable extends Stream {
+      constructor(opts) {
+        super(opts);
+        this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD;
+        this._readableState = new ReadableState(this, opts);
+        if (opts) {
+          if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD;
+          if (opts.read) this._read = opts.read;
+          if (opts.eagerOpen) this._readableState.updateNextTick();
+          if (opts.encoding) this.setEncoding(opts.encoding);
+        }
       }
-      if (this._state.module) {
-        this.emit("error", new ArchiverError("MODULESET"));
+      setEncoding(encoding) {
+        const dec = new TextDecoder2(encoding);
+        const map2 = this._readableState.map || echo;
+        this._readableState.map = mapOrSkip;
         return this;
+        function mapOrSkip(data) {
+          const next = dec.push(data);
+          return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map2(next);
+        }
       }
-      this._module = module3;
-      this._modulePipe();
-      return this;
-    };
-    Archiver.prototype.symlink = function(filepath, target, mode) {
-      if (this._state.finalize || this._state.aborted) {
-        this.emit("error", new ArchiverError("QUEUECLOSED"));
-        return this;
+      _read(cb) {
+        cb(null);
       }
-      if (typeof filepath !== "string" || filepath.length === 0) {
-        this.emit("error", new ArchiverError("SYMLINKFILEPATHREQUIRED"));
-        return this;
+      pipe(dest, cb) {
+        this._readableState.updateNextTick();
+        this._readableState.pipe(dest, cb);
+        return dest;
       }
-      if (typeof target !== "string" || target.length === 0) {
-        this.emit("error", new ArchiverError("SYMLINKTARGETREQUIRED", { filepath }));
+      read() {
+        this._readableState.updateNextTick();
+        return this._readableState.read();
+      }
+      push(data) {
+        this._readableState.updateNextTick();
+        return this._readableState.push(data);
+      }
+      unshift(data) {
+        this._readableState.updateNextTick();
+        return this._readableState.unshift(data);
+      }
+      resume() {
+        this._duplexState |= READ_RESUMED_READ_AHEAD;
+        this._readableState.updateNextTick();
         return this;
       }
-      if (!this._moduleSupports("symlink")) {
-        this.emit("error", new ArchiverError("SYMLINKNOTSUPPORTED", { filepath }));
+      pause() {
+        this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
         return this;
       }
-      var data = {};
-      data.type = "symlink";
-      data.name = filepath.replace(/\\/g, "/");
-      data.linkname = target.replace(/\\/g, "/");
-      data.sourceType = "buffer";
-      if (typeof mode === "number") {
-        data.mode = mode;
+      static _fromAsyncIterator(ite, opts) {
+        let destroy;
+        const rs = new _Readable({
+          ...opts,
+          read(cb) {
+            ite.next().then(push).then(cb.bind(null, null)).catch(cb);
+          },
+          predestroy() {
+            destroy = ite.return();
+          },
+          destroy(cb) {
+            if (!destroy) return cb(null);
+            destroy.then(cb.bind(null, null)).catch(cb);
+          }
+        });
+        return rs;
+        function push(data) {
+          if (data.done) rs.push(null);
+          else rs.push(data.value);
+        }
       }
-      this._entriesCount++;
-      this._queue.push({
-        data,
-        source: Buffer.concat([])
-      });
-      return this;
-    };
-    Archiver.prototype.pointer = function() {
-      return this._pointer;
-    };
-    Archiver.prototype.use = function(plugin) {
-      this._streams.push(plugin);
-      return this;
-    };
-    module2.exports = Archiver;
-  }
-});
-
-// node_modules/compress-commons/lib/archivers/archive-entry.js
-var require_archive_entry = __commonJS({
-  "node_modules/compress-commons/lib/archivers/archive-entry.js"(exports2, module2) {
-    var ArchiveEntry = module2.exports = function() {
-    };
-    ArchiveEntry.prototype.getName = function() {
-    };
-    ArchiveEntry.prototype.getSize = function() {
-    };
-    ArchiveEntry.prototype.getLastModifiedDate = function() {
-    };
-    ArchiveEntry.prototype.isDirectory = function() {
-    };
-  }
-});
-
-// node_modules/compress-commons/lib/archivers/zip/util.js
-var require_util13 = __commonJS({
-  "node_modules/compress-commons/lib/archivers/zip/util.js"(exports2, module2) {
-    var util = module2.exports = {};
-    util.dateToDos = function(d, forceLocalTime) {
-      forceLocalTime = forceLocalTime || false;
-      var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear();
-      if (year < 1980) {
-        return 2162688;
-      } else if (year >= 2044) {
-        return 2141175677;
+      static from(data, opts) {
+        if (isReadStreamx(data)) return data;
+        if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
+        if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
+        let i = 0;
+        return new _Readable({
+          ...opts,
+          read(cb) {
+            this.push(i === data.length ? null : data[i++]);
+            cb(null);
+          }
+        });
       }
-      var val2 = {
-        year,
-        month: forceLocalTime ? d.getMonth() : d.getUTCMonth(),
-        date: forceLocalTime ? d.getDate() : d.getUTCDate(),
-        hours: forceLocalTime ? d.getHours() : d.getUTCHours(),
-        minutes: forceLocalTime ? d.getMinutes() : d.getUTCMinutes(),
-        seconds: forceLocalTime ? d.getSeconds() : d.getUTCSeconds()
-      };
-      return val2.year - 1980 << 25 | val2.month + 1 << 21 | val2.date << 16 | val2.hours << 11 | val2.minutes << 5 | val2.seconds / 2;
-    };
-    util.dosToDate = function(dos) {
-      return new Date((dos >> 25 & 127) + 1980, (dos >> 21 & 15) - 1, dos >> 16 & 31, dos >> 11 & 31, dos >> 5 & 63, (dos & 31) << 1);
-    };
-    util.fromDosTime = function(buf) {
-      return util.dosToDate(buf.readUInt32LE(0));
-    };
-    util.getEightBytes = function(v) {
-      var buf = Buffer.alloc(8);
-      buf.writeUInt32LE(v % 4294967296, 0);
-      buf.writeUInt32LE(v / 4294967296 | 0, 4);
-      return buf;
-    };
-    util.getShortBytes = function(v) {
-      var buf = Buffer.alloc(2);
-      buf.writeUInt16LE((v & 65535) >>> 0, 0);
-      return buf;
-    };
-    util.getShortBytesValue = function(buf, offset) {
-      return buf.readUInt16LE(offset);
-    };
-    util.getLongBytes = function(v) {
-      var buf = Buffer.alloc(4);
-      buf.writeUInt32LE((v & 4294967295) >>> 0, 0);
-      return buf;
-    };
-    util.getLongBytesValue = function(buf, offset) {
-      return buf.readUInt32LE(offset);
-    };
-    util.toDosTime = function(d) {
-      return util.getLongBytes(util.dateToDos(d));
-    };
-  }
-});
-
-// node_modules/compress-commons/lib/archivers/zip/general-purpose-bit.js
-var require_general_purpose_bit = __commonJS({
-  "node_modules/compress-commons/lib/archivers/zip/general-purpose-bit.js"(exports2, module2) {
-    var zipUtil = require_util13();
-    var DATA_DESCRIPTOR_FLAG = 1 << 3;
-    var ENCRYPTION_FLAG = 1 << 0;
-    var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2;
-    var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1;
-    var STRONG_ENCRYPTION_FLAG = 1 << 6;
-    var UFT8_NAMES_FLAG = 1 << 11;
-    var GeneralPurposeBit = module2.exports = function() {
-      if (!(this instanceof GeneralPurposeBit)) {
-        return new GeneralPurposeBit();
+      static isBackpressured(rs) {
+        return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
       }
-      this.descriptor = false;
-      this.encryption = false;
-      this.utf8 = false;
-      this.numberOfShannonFanoTrees = 0;
-      this.strongEncryption = false;
-      this.slidingDictionarySize = 0;
-      return this;
-    };
-    GeneralPurposeBit.prototype.encode = function() {
-      return zipUtil.getShortBytes(
-        (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) | (this.utf8 ? UFT8_NAMES_FLAG : 0) | (this.encryption ? ENCRYPTION_FLAG : 0) | (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0)
-      );
-    };
-    GeneralPurposeBit.prototype.parse = function(buf, offset) {
-      var flag = zipUtil.getShortBytesValue(buf, offset);
-      var gbp = new GeneralPurposeBit();
-      gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0);
-      gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0);
-      gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0);
-      gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0);
-      gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096);
-      gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2);
-      return gbp;
-    };
-    GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) {
-      this.numberOfShannonFanoTrees = n;
-    };
-    GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() {
-      return this.numberOfShannonFanoTrees;
-    };
-    GeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) {
-      this.slidingDictionarySize = n;
-    };
-    GeneralPurposeBit.prototype.getSlidingDictionarySize = function() {
-      return this.slidingDictionarySize;
-    };
-    GeneralPurposeBit.prototype.useDataDescriptor = function(b) {
-      this.descriptor = b;
-    };
-    GeneralPurposeBit.prototype.usesDataDescriptor = function() {
-      return this.descriptor;
-    };
-    GeneralPurposeBit.prototype.useEncryption = function(b) {
-      this.encryption = b;
-    };
-    GeneralPurposeBit.prototype.usesEncryption = function() {
-      return this.encryption;
-    };
-    GeneralPurposeBit.prototype.useStrongEncryption = function(b) {
-      this.strongEncryption = b;
-    };
-    GeneralPurposeBit.prototype.usesStrongEncryption = function() {
-      return this.strongEncryption;
-    };
-    GeneralPurposeBit.prototype.useUTF8ForNames = function(b) {
-      this.utf8 = b;
-    };
-    GeneralPurposeBit.prototype.usesUTF8ForNames = function() {
-      return this.utf8;
-    };
-  }
-});
-
-// node_modules/compress-commons/lib/archivers/zip/unix-stat.js
-var require_unix_stat = __commonJS({
-  "node_modules/compress-commons/lib/archivers/zip/unix-stat.js"(exports2, module2) {
-    module2.exports = {
-      /**
-       * Bits used for permissions (and sticky bit)
-       */
-      PERM_MASK: 4095,
-      // 07777
-      /**
-       * Bits used to indicate the filesystem object type.
-       */
-      FILE_TYPE_FLAG: 61440,
-      // 0170000
-      /**
-       * Indicates symbolic links.
-       */
-      LINK_FLAG: 40960,
-      // 0120000
-      /**
-       * Indicates plain files.
-       */
-      FILE_FLAG: 32768,
-      // 0100000
-      /**
-       * Indicates directories.
-       */
-      DIR_FLAG: 16384,
-      // 040000
-      // ----------------------------------------------------------
-      // somewhat arbitrary choices that are quite common for shared
-      // installations
-      // -----------------------------------------------------------
-      /**
-       * Default permissions for symbolic links.
-       */
-      DEFAULT_LINK_PERM: 511,
-      // 0777
-      /**
-       * Default permissions for directories.
-       */
-      DEFAULT_DIR_PERM: 493,
-      // 0755
-      /**
-       * Default permissions for plain files.
-       */
-      DEFAULT_FILE_PERM: 420
-      // 0644
-    };
-  }
-});
-
-// node_modules/compress-commons/lib/archivers/zip/constants.js
-var require_constants8 = __commonJS({
-  "node_modules/compress-commons/lib/archivers/zip/constants.js"(exports2, module2) {
-    module2.exports = {
-      WORD: 4,
-      DWORD: 8,
-      EMPTY: Buffer.alloc(0),
-      SHORT: 2,
-      SHORT_MASK: 65535,
-      SHORT_SHIFT: 16,
-      SHORT_ZERO: Buffer.from(Array(2)),
-      LONG: 4,
-      LONG_ZERO: Buffer.from(Array(4)),
-      MIN_VERSION_INITIAL: 10,
-      MIN_VERSION_DATA_DESCRIPTOR: 20,
-      MIN_VERSION_ZIP64: 45,
-      VERSION_MADEBY: 45,
-      METHOD_STORED: 0,
-      METHOD_DEFLATED: 8,
-      PLATFORM_UNIX: 3,
-      PLATFORM_FAT: 0,
-      SIG_LFH: 67324752,
-      SIG_DD: 134695760,
-      SIG_CFH: 33639248,
-      SIG_EOCD: 101010256,
-      SIG_ZIP64_EOCD: 101075792,
-      SIG_ZIP64_EOCD_LOC: 117853008,
-      ZIP64_MAGIC_SHORT: 65535,
-      ZIP64_MAGIC: 4294967295,
-      ZIP64_EXTRA_ID: 1,
-      ZLIB_NO_COMPRESSION: 0,
-      ZLIB_BEST_SPEED: 1,
-      ZLIB_BEST_COMPRESSION: 9,
-      ZLIB_DEFAULT_COMPRESSION: -1,
-      MODE_MASK: 4095,
-      DEFAULT_FILE_MODE: 33188,
-      // 010644 = -rw-r--r-- = S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
-      DEFAULT_DIR_MODE: 16877,
-      // 040755 = drwxr-xr-x = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
-      EXT_FILE_ATTR_DIR: 1106051088,
-      // 010173200020 = drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D)
-      EXT_FILE_ATTR_FILE: 2175008800,
-      // 020151000040 = -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A) >>> 0
-      // Unix file types
-      S_IFMT: 61440,
-      // 0170000 type of file mask
-      S_IFIFO: 4096,
-      // 010000 named pipe (fifo)
-      S_IFCHR: 8192,
-      // 020000 character special
-      S_IFDIR: 16384,
-      // 040000 directory
-      S_IFBLK: 24576,
-      // 060000 block special
-      S_IFREG: 32768,
-      // 0100000 regular
-      S_IFLNK: 40960,
-      // 0120000 symbolic link
-      S_IFSOCK: 49152,
-      // 0140000 socket
-      // DOS file type flags
-      S_DOS_A: 32,
-      // 040 Archive
-      S_DOS_D: 16,
-      // 020 Directory
-      S_DOS_V: 8,
-      // 010 Volume
-      S_DOS_S: 4,
-      // 04 System
-      S_DOS_H: 2,
-      // 02 Hidden
-      S_DOS_R: 1
-      // 01 Read Only
-    };
-  }
-});
-
-// node_modules/compress-commons/lib/archivers/zip/zip-archive-entry.js
-var require_zip_archive_entry = __commonJS({
-  "node_modules/compress-commons/lib/archivers/zip/zip-archive-entry.js"(exports2, module2) {
-    var inherits = require("util").inherits;
-    var normalizePath = require_normalize_path();
-    var ArchiveEntry = require_archive_entry();
-    var GeneralPurposeBit = require_general_purpose_bit();
-    var UnixStat = require_unix_stat();
-    var constants = require_constants8();
-    var zipUtil = require_util13();
-    var ZipArchiveEntry = module2.exports = function(name) {
-      if (!(this instanceof ZipArchiveEntry)) {
-        return new ZipArchiveEntry(name);
+      static isPaused(rs) {
+        return (rs._duplexState & READ_RESUMED) === 0;
       }
-      ArchiveEntry.call(this);
-      this.platform = constants.PLATFORM_FAT;
-      this.method = -1;
-      this.name = null;
-      this.size = 0;
-      this.csize = 0;
-      this.gpb = new GeneralPurposeBit();
-      this.crc = 0;
-      this.time = -1;
-      this.minver = constants.MIN_VERSION_INITIAL;
-      this.mode = -1;
-      this.extra = null;
-      this.exattr = 0;
-      this.inattr = 0;
-      this.comment = null;
-      if (name) {
-        this.setName(name);
+      [asyncIterator]() {
+        const stream = this;
+        let error4 = null;
+        let promiseResolve = null;
+        let promiseReject = null;
+        this.on("error", (err) => {
+          error4 = err;
+        });
+        this.on("readable", onreadable);
+        this.on("close", onclose);
+        return {
+          [asyncIterator]() {
+            return this;
+          },
+          next() {
+            return new Promise(function(resolve2, reject) {
+              promiseResolve = resolve2;
+              promiseReject = reject;
+              const data = stream.read();
+              if (data !== null) ondata(data);
+              else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
+            });
+          },
+          return() {
+            return destroy(null);
+          },
+          throw(err) {
+            return destroy(err);
+          }
+        };
+        function onreadable() {
+          if (promiseResolve !== null) ondata(stream.read());
+        }
+        function onclose() {
+          if (promiseResolve !== null) ondata(null);
+        }
+        function ondata(data) {
+          if (promiseReject === null) return;
+          if (error4) promiseReject(error4);
+          else if (data === null && (stream._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED);
+          else promiseResolve({ value: data, done: data === null });
+          promiseReject = promiseResolve = null;
+        }
+        function destroy(err) {
+          stream.destroy(err);
+          return new Promise((resolve2, reject) => {
+            if (stream._duplexState & DESTROYED) return resolve2({ value: void 0, done: true });
+            stream.once("close", function() {
+              if (err) reject(err);
+              else resolve2({ value: void 0, done: true });
+            });
+          });
+        }
       }
     };
-    inherits(ZipArchiveEntry, ArchiveEntry);
-    ZipArchiveEntry.prototype.getCentralDirectoryExtra = function() {
-      return this.getExtra();
-    };
-    ZipArchiveEntry.prototype.getComment = function() {
-      return this.comment !== null ? this.comment : "";
-    };
-    ZipArchiveEntry.prototype.getCompressedSize = function() {
-      return this.csize;
-    };
-    ZipArchiveEntry.prototype.getCrc = function() {
-      return this.crc;
-    };
-    ZipArchiveEntry.prototype.getExternalAttributes = function() {
-      return this.exattr;
-    };
-    ZipArchiveEntry.prototype.getExtra = function() {
-      return this.extra !== null ? this.extra : constants.EMPTY;
-    };
-    ZipArchiveEntry.prototype.getGeneralPurposeBit = function() {
-      return this.gpb;
-    };
-    ZipArchiveEntry.prototype.getInternalAttributes = function() {
-      return this.inattr;
-    };
-    ZipArchiveEntry.prototype.getLastModifiedDate = function() {
-      return this.getTime();
-    };
-    ZipArchiveEntry.prototype.getLocalFileDataExtra = function() {
-      return this.getExtra();
-    };
-    ZipArchiveEntry.prototype.getMethod = function() {
-      return this.method;
-    };
-    ZipArchiveEntry.prototype.getName = function() {
-      return this.name;
-    };
-    ZipArchiveEntry.prototype.getPlatform = function() {
-      return this.platform;
+    var Writable = class extends Stream {
+      constructor(opts) {
+        super(opts);
+        this._duplexState |= OPENING | READ_DONE;
+        this._writableState = new WritableState(this, opts);
+        if (opts) {
+          if (opts.writev) this._writev = opts.writev;
+          if (opts.write) this._write = opts.write;
+          if (opts.final) this._final = opts.final;
+          if (opts.eagerOpen) this._writableState.updateNextTick();
+        }
+      }
+      cork() {
+        this._duplexState |= WRITE_CORKED;
+      }
+      uncork() {
+        this._duplexState &= WRITE_NOT_CORKED;
+        this._writableState.updateNextTick();
+      }
+      _writev(batch, cb) {
+        cb(null);
+      }
+      _write(data, cb) {
+        this._writableState.autoBatch(data, cb);
+      }
+      _final(cb) {
+        cb(null);
+      }
+      static isBackpressured(ws) {
+        return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
+      }
+      static drained(ws) {
+        if (ws.destroyed) return Promise.resolve(false);
+        const state = ws._writableState;
+        const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
+        const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
+        if (writes === 0) return Promise.resolve(true);
+        if (state.drains === null) state.drains = [];
+        return new Promise((resolve2) => {
+          state.drains.push({ writes, resolve: resolve2 });
+        });
+      }
+      write(data) {
+        this._writableState.updateNextTick();
+        return this._writableState.push(data);
+      }
+      end(data) {
+        this._writableState.updateNextTick();
+        this._writableState.end(data);
+        return this;
+      }
     };
-    ZipArchiveEntry.prototype.getSize = function() {
-      return this.size;
+    var Duplex = class extends Readable {
+      // and Writable
+      constructor(opts) {
+        super(opts);
+        this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
+        this._writableState = new WritableState(this, opts);
+        if (opts) {
+          if (opts.writev) this._writev = opts.writev;
+          if (opts.write) this._write = opts.write;
+          if (opts.final) this._final = opts.final;
+        }
+      }
+      cork() {
+        this._duplexState |= WRITE_CORKED;
+      }
+      uncork() {
+        this._duplexState &= WRITE_NOT_CORKED;
+        this._writableState.updateNextTick();
+      }
+      _writev(batch, cb) {
+        cb(null);
+      }
+      _write(data, cb) {
+        this._writableState.autoBatch(data, cb);
+      }
+      _final(cb) {
+        cb(null);
+      }
+      write(data) {
+        this._writableState.updateNextTick();
+        return this._writableState.push(data);
+      }
+      end(data) {
+        this._writableState.updateNextTick();
+        this._writableState.end(data);
+        return this;
+      }
     };
-    ZipArchiveEntry.prototype.getTime = function() {
-      return this.time !== -1 ? zipUtil.dosToDate(this.time) : -1;
+    var Transform = class extends Duplex {
+      constructor(opts) {
+        super(opts);
+        this._transformState = new TransformState(this);
+        if (opts) {
+          if (opts.transform) this._transform = opts.transform;
+          if (opts.flush) this._flush = opts.flush;
+        }
+      }
+      _write(data, cb) {
+        if (this._readableState.buffered >= this._readableState.highWaterMark) {
+          this._transformState.data = data;
+        } else {
+          this._transform(data, this._transformState.afterTransform);
+        }
+      }
+      _read(cb) {
+        if (this._transformState.data !== null) {
+          const data = this._transformState.data;
+          this._transformState.data = null;
+          cb(null);
+          this._transform(data, this._transformState.afterTransform);
+        } else {
+          cb(null);
+        }
+      }
+      destroy(err) {
+        super.destroy(err);
+        if (this._transformState.data !== null) {
+          this._transformState.data = null;
+          this._transformState.afterTransform();
+        }
+      }
+      _transform(data, cb) {
+        cb(null, data);
+      }
+      _flush(cb) {
+        cb(null);
+      }
+      _final(cb) {
+        this._transformState.afterFinal = cb;
+        this._flush(transformAfterFlush.bind(this));
+      }
     };
-    ZipArchiveEntry.prototype.getTimeDos = function() {
-      return this.time !== -1 ? this.time : 0;
+    var PassThrough = class extends Transform {
     };
-    ZipArchiveEntry.prototype.getUnixMode = function() {
-      return this.platform !== constants.PLATFORM_UNIX ? 0 : this.getExternalAttributes() >> constants.SHORT_SHIFT & constants.SHORT_MASK;
+    function transformAfterFlush(err, data) {
+      const cb = this._transformState.afterFinal;
+      if (err) return cb(err);
+      if (data !== null && data !== void 0) this.push(data);
+      this.push(null);
+      cb(null);
+    }
+    function pipelinePromise(...streams) {
+      return new Promise((resolve2, reject) => {
+        return pipeline(...streams, (err) => {
+          if (err) return reject(err);
+          resolve2();
+        });
+      });
+    }
+    function pipeline(stream, ...streams) {
+      const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
+      const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
+      if (all.length < 2) throw new Error("Pipeline requires at least 2 streams");
+      let src = all[0];
+      let dest = null;
+      let error4 = null;
+      for (let i = 1; i < all.length; i++) {
+        dest = all[i];
+        if (isStreamx(src)) {
+          src.pipe(dest, onerror);
+        } else {
+          errorHandle(src, true, i > 1, onerror);
+          src.pipe(dest);
+        }
+        src = dest;
+      }
+      if (done) {
+        let fin = false;
+        const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
+        dest.on("error", (err) => {
+          if (error4 === null) error4 = err;
+        });
+        dest.on("finish", () => {
+          fin = true;
+          if (!autoDestroy) done(error4);
+        });
+        if (autoDestroy) {
+          dest.on("close", () => done(error4 || (fin ? null : PREMATURE_CLOSE)));
+        }
+      }
+      return dest;
+      function errorHandle(s, rd, wr, onerror2) {
+        s.on("error", onerror2);
+        s.on("close", onclose);
+        function onclose() {
+          if (rd && s._readableState && !s._readableState.ended) return onerror2(PREMATURE_CLOSE);
+          if (wr && s._writableState && !s._writableState.ended) return onerror2(PREMATURE_CLOSE);
+        }
+      }
+      function onerror(err) {
+        if (!err || error4) return;
+        error4 = err;
+        for (const s of all) {
+          s.destroy(err);
+        }
+      }
+    }
+    function echo(s) {
+      return s;
+    }
+    function isStream(stream) {
+      return !!stream._readableState || !!stream._writableState;
+    }
+    function isStreamx(stream) {
+      return typeof stream._duplexState === "number" && isStream(stream);
+    }
+    function isEnded(stream) {
+      return !!stream._readableState && stream._readableState.ended;
+    }
+    function isFinished(stream) {
+      return !!stream._writableState && stream._writableState.ended;
+    }
+    function getStreamError(stream, opts = {}) {
+      const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
+      return !opts.all && err === STREAM_DESTROYED ? null : err;
+    }
+    function isReadStreamx(stream) {
+      return isStreamx(stream) && stream.readable;
+    }
+    function isTypedArray(data) {
+      return typeof data === "object" && data !== null && typeof data.byteLength === "number";
+    }
+    function defaultByteLength(data) {
+      return isTypedArray(data) ? data.byteLength : 1024;
+    }
+    function noop() {
+    }
+    function abort() {
+      this.destroy(new Error("Stream aborted."));
+    }
+    function isWritev(s) {
+      return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
+    }
+    module2.exports = {
+      pipeline,
+      pipelinePromise,
+      isStream,
+      isStreamx,
+      isEnded,
+      isFinished,
+      getStreamError,
+      Stream,
+      Writable,
+      Readable,
+      Duplex,
+      Transform,
+      // Export PassThrough for compatibility with Node.js core's stream module
+      PassThrough
     };
-    ZipArchiveEntry.prototype.getVersionNeededToExtract = function() {
-      return this.minver;
+  }
+});
+
+// node_modules/tar-stream/headers.js
+var require_headers2 = __commonJS({
+  "node_modules/tar-stream/headers.js"(exports2) {
+    var b4a = require_b4a();
+    var ZEROS = "0000000000000000000";
+    var SEVENS = "7777777777777777777";
+    var ZERO_OFFSET = "0".charCodeAt(0);
+    var USTAR_MAGIC = b4a.from([117, 115, 116, 97, 114, 0]);
+    var USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]);
+    var GNU_MAGIC = b4a.from([117, 115, 116, 97, 114, 32]);
+    var GNU_VER = b4a.from([32, 0]);
+    var MASK = 4095;
+    var MAGIC_OFFSET = 257;
+    var VERSION_OFFSET = 263;
+    exports2.decodeLongPath = function decodeLongPath(buf, encoding) {
+      return decodeStr(buf, 0, buf.length, encoding);
     };
-    ZipArchiveEntry.prototype.setComment = function(comment) {
-      if (Buffer.byteLength(comment) !== comment.length) {
-        this.getGeneralPurposeBit().useUTF8ForNames(true);
+    exports2.encodePax = function encodePax(opts) {
+      let result = "";
+      if (opts.name) result += addLength(" path=" + opts.name + "\n");
+      if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n");
+      const pax = opts.pax;
+      if (pax) {
+        for (const key in pax) {
+          result += addLength(" " + key + "=" + pax[key] + "\n");
+        }
       }
-      this.comment = comment;
+      return b4a.from(result);
     };
-    ZipArchiveEntry.prototype.setCompressedSize = function(size) {
-      if (size < 0) {
-        throw new Error("invalid entry compressed size");
+    exports2.decodePax = function decodePax(buf) {
+      const result = {};
+      while (buf.length) {
+        let i = 0;
+        while (i < buf.length && buf[i] !== 32) i++;
+        const len = parseInt(b4a.toString(buf.subarray(0, i)), 10);
+        if (!len) return result;
+        const b = b4a.toString(buf.subarray(i + 1, len - 1));
+        const keyIndex = b.indexOf("=");
+        if (keyIndex === -1) return result;
+        result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1);
+        buf = buf.subarray(len);
       }
-      this.csize = size;
+      return result;
     };
-    ZipArchiveEntry.prototype.setCrc = function(crc) {
-      if (crc < 0) {
-        throw new Error("invalid entry crc32");
+    exports2.encode = function encode(opts) {
+      const buf = b4a.alloc(512);
+      let name = opts.name;
+      let prefix = "";
+      if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/";
+      if (b4a.byteLength(name) !== name.length) return null;
+      while (b4a.byteLength(name) > 100) {
+        const i = name.indexOf("/");
+        if (i === -1) return null;
+        prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i);
+        name = name.slice(i + 1);
       }
-      this.crc = crc;
-    };
-    ZipArchiveEntry.prototype.setExternalAttributes = function(attr) {
-      this.exattr = attr >>> 0;
+      if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null;
+      if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null;
+      b4a.write(buf, name);
+      b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100);
+      b4a.write(buf, encodeOct(opts.uid, 6), 108);
+      b4a.write(buf, encodeOct(opts.gid, 6), 116);
+      encodeSize(opts.size, buf, 124);
+      b4a.write(buf, encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136);
+      buf[156] = ZERO_OFFSET + toTypeflag(opts.type);
+      if (opts.linkname) b4a.write(buf, opts.linkname, 157);
+      b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET);
+      b4a.copy(USTAR_VER, buf, VERSION_OFFSET);
+      if (opts.uname) b4a.write(buf, opts.uname, 265);
+      if (opts.gname) b4a.write(buf, opts.gname, 297);
+      b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329);
+      b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337);
+      if (prefix) b4a.write(buf, prefix, 345);
+      b4a.write(buf, encodeOct(cksum(buf), 6), 148);
+      return buf;
     };
-    ZipArchiveEntry.prototype.setExtra = function(extra) {
-      this.extra = extra;
+    exports2.decode = function decode(buf, filenameEncoding, allowUnknownFormat) {
+      let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET;
+      let name = decodeStr(buf, 0, 100, filenameEncoding);
+      const mode = decodeOct(buf, 100, 8);
+      const uid = decodeOct(buf, 108, 8);
+      const gid = decodeOct(buf, 116, 8);
+      const size = decodeOct(buf, 124, 12);
+      const mtime = decodeOct(buf, 136, 12);
+      const type2 = toType(typeflag);
+      const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding);
+      const uname = decodeStr(buf, 265, 32);
+      const gname = decodeStr(buf, 297, 32);
+      const devmajor = decodeOct(buf, 329, 8);
+      const devminor = decodeOct(buf, 337, 8);
+      const c = cksum(buf);
+      if (c === 8 * 32) return null;
+      if (c !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");
+      if (isUSTAR(buf)) {
+        if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name;
+      } else if (isGNU(buf)) {
+      } else {
+        if (!allowUnknownFormat) {
+          throw new Error("Invalid tar header: unknown format.");
+        }
+      }
+      if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5;
+      return {
+        name,
+        mode,
+        uid,
+        gid,
+        size,
+        mtime: new Date(1e3 * mtime),
+        type: type2,
+        linkname,
+        uname,
+        gname,
+        devmajor,
+        devminor,
+        pax: null
+      };
     };
-    ZipArchiveEntry.prototype.setGeneralPurposeBit = function(gpb) {
-      if (!(gpb instanceof GeneralPurposeBit)) {
-        throw new Error("invalid entry GeneralPurposeBit");
+    function isUSTAR(buf) {
+      return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6));
+    }
+    function isGNU(buf) {
+      return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2));
+    }
+    function clamp(index, len, defaultValue) {
+      if (typeof index !== "number") return defaultValue;
+      index = ~~index;
+      if (index >= len) return len;
+      if (index >= 0) return index;
+      index += len;
+      if (index >= 0) return index;
+      return 0;
+    }
+    function toType(flag) {
+      switch (flag) {
+        case 0:
+          return "file";
+        case 1:
+          return "link";
+        case 2:
+          return "symlink";
+        case 3:
+          return "character-device";
+        case 4:
+          return "block-device";
+        case 5:
+          return "directory";
+        case 6:
+          return "fifo";
+        case 7:
+          return "contiguous-file";
+        case 72:
+          return "pax-header";
+        case 55:
+          return "pax-global-header";
+        case 27:
+          return "gnu-long-link-path";
+        case 28:
+        case 30:
+          return "gnu-long-path";
+      }
+      return null;
+    }
+    function toTypeflag(flag) {
+      switch (flag) {
+        case "file":
+          return 0;
+        case "link":
+          return 1;
+        case "symlink":
+          return 2;
+        case "character-device":
+          return 3;
+        case "block-device":
+          return 4;
+        case "directory":
+          return 5;
+        case "fifo":
+          return 6;
+        case "contiguous-file":
+          return 7;
+        case "pax-header":
+          return 72;
       }
-      this.gpb = gpb;
-    };
-    ZipArchiveEntry.prototype.setInternalAttributes = function(attr) {
-      this.inattr = attr;
-    };
-    ZipArchiveEntry.prototype.setMethod = function(method) {
-      if (method < 0) {
-        throw new Error("invalid entry compression method");
+      return 0;
+    }
+    function indexOf(block, num, offset, end) {
+      for (; offset < end; offset++) {
+        if (block[offset] === num) return offset;
       }
-      this.method = method;
-    };
-    ZipArchiveEntry.prototype.setName = function(name, prependSlash = false) {
-      name = normalizePath(name, false).replace(/^\w+:/, "").replace(/^(\.\.\/|\/)+/, "");
-      if (prependSlash) {
-        name = `/${name}`;
+      return end;
+    }
+    function cksum(block) {
+      let sum = 8 * 32;
+      for (let i = 0; i < 148; i++) sum += block[i];
+      for (let j = 156; j < 512; j++) sum += block[j];
+      return sum;
+    }
+    function encodeOct(val2, n) {
+      val2 = val2.toString(8);
+      if (val2.length > n) return SEVENS.slice(0, n) + " ";
+      return ZEROS.slice(0, n - val2.length) + val2 + " ";
+    }
+    function encodeSizeBin(num, buf, off) {
+      buf[off] = 128;
+      for (let i = 11; i > 0; i--) {
+        buf[off + i] = num & 255;
+        num = Math.floor(num / 256);
       }
-      if (Buffer.byteLength(name) !== name.length) {
-        this.getGeneralPurposeBit().useUTF8ForNames(true);
+    }
+    function encodeSize(num, buf, off) {
+      if (num.toString(8).length > 11) {
+        encodeSizeBin(num, buf, off);
+      } else {
+        b4a.write(buf, encodeOct(num, 11), off);
       }
-      this.name = name;
-    };
-    ZipArchiveEntry.prototype.setPlatform = function(platform) {
-      this.platform = platform;
-    };
-    ZipArchiveEntry.prototype.setSize = function(size) {
-      if (size < 0) {
-        throw new Error("invalid entry size");
+    }
+    function parse256(buf) {
+      let positive;
+      if (buf[0] === 128) positive = true;
+      else if (buf[0] === 255) positive = false;
+      else return null;
+      const tuple = [];
+      let i;
+      for (i = buf.length - 1; i > 0; i--) {
+        const byte = buf[i];
+        if (positive) tuple.push(byte);
+        else tuple.push(255 - byte);
       }
-      this.size = size;
-    };
-    ZipArchiveEntry.prototype.setTime = function(time, forceLocalTime) {
-      if (!(time instanceof Date)) {
-        throw new Error("invalid entry time");
+      let sum = 0;
+      const l = tuple.length;
+      for (i = 0; i < l; i++) {
+        sum += tuple[i] * Math.pow(256, i);
       }
-      this.time = zipUtil.dateToDos(time, forceLocalTime);
-    };
-    ZipArchiveEntry.prototype.setUnixMode = function(mode) {
-      mode |= this.isDirectory() ? constants.S_IFDIR : constants.S_IFREG;
-      var extattr = 0;
-      extattr |= mode << constants.SHORT_SHIFT | (this.isDirectory() ? constants.S_DOS_D : constants.S_DOS_A);
-      this.setExternalAttributes(extattr);
-      this.mode = mode & constants.MODE_MASK;
-      this.platform = constants.PLATFORM_UNIX;
-    };
-    ZipArchiveEntry.prototype.setVersionNeededToExtract = function(minver) {
-      this.minver = minver;
-    };
-    ZipArchiveEntry.prototype.isDirectory = function() {
-      return this.getName().slice(-1) === "/";
-    };
-    ZipArchiveEntry.prototype.isUnixSymlink = function() {
-      return (this.getUnixMode() & UnixStat.FILE_TYPE_FLAG) === UnixStat.LINK_FLAG;
-    };
-    ZipArchiveEntry.prototype.isZip64 = function() {
-      return this.csize > constants.ZIP64_MAGIC || this.size > constants.ZIP64_MAGIC;
-    };
-  }
-});
-
-// node_modules/compress-commons/node_modules/is-stream/index.js
-var require_is_stream2 = __commonJS({
-  "node_modules/compress-commons/node_modules/is-stream/index.js"(exports2, module2) {
-    "use strict";
-    var isStream = (stream) => stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
-    isStream.writable = (stream) => isStream(stream) && stream.writable !== false && typeof stream._write === "function" && typeof stream._writableState === "object";
-    isStream.readable = (stream) => isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
-    isStream.duplex = (stream) => isStream.writable(stream) && isStream.readable(stream);
-    isStream.transform = (stream) => isStream.duplex(stream) && typeof stream._transform === "function";
-    module2.exports = isStream;
-  }
-});
-
-// node_modules/compress-commons/lib/util/index.js
-var require_util14 = __commonJS({
-  "node_modules/compress-commons/lib/util/index.js"(exports2, module2) {
-    var Stream = require("stream").Stream;
-    var PassThrough = require_ours().PassThrough;
-    var isStream = require_is_stream2();
-    var util = module2.exports = {};
-    util.normalizeInputSource = function(source) {
-      if (source === null) {
-        return Buffer.alloc(0);
-      } else if (typeof source === "string") {
-        return Buffer.from(source);
-      } else if (isStream(source) && !source._readableState) {
-        var normalized = new PassThrough();
-        source.pipe(normalized);
-        return normalized;
+      return positive ? sum : -1 * sum;
+    }
+    function decodeOct(val2, offset, length) {
+      val2 = val2.subarray(offset, offset + length);
+      offset = 0;
+      if (val2[offset] & 128) {
+        return parse256(val2);
+      } else {
+        while (offset < val2.length && val2[offset] === 32) offset++;
+        const end = clamp(indexOf(val2, 32, offset, val2.length), val2.length, val2.length);
+        while (offset < end && val2[offset] === 0) offset++;
+        if (end === offset) return 0;
+        return parseInt(b4a.toString(val2.subarray(offset, end)), 8);
       }
-      return source;
-    };
+    }
+    function decodeStr(val2, offset, length, encoding) {
+      return b4a.toString(val2.subarray(offset, indexOf(val2, 0, offset, offset + length)), encoding);
+    }
+    function addLength(str2) {
+      const len = b4a.byteLength(str2);
+      let digits = Math.floor(Math.log(len) / Math.log(10)) + 1;
+      if (len + digits >= Math.pow(10, digits)) digits++;
+      return len + digits + str2;
+    }
   }
 });
 
-// node_modules/compress-commons/lib/archivers/archive-output-stream.js
-var require_archive_output_stream = __commonJS({
-  "node_modules/compress-commons/lib/archivers/archive-output-stream.js"(exports2, module2) {
-    var inherits = require("util").inherits;
-    var isStream = require_is_stream2();
-    var Transform = require_ours().Transform;
-    var ArchiveEntry = require_archive_entry();
-    var util = require_util14();
-    var ArchiveOutputStream = module2.exports = function(options) {
-      if (!(this instanceof ArchiveOutputStream)) {
-        return new ArchiveOutputStream(options);
+// node_modules/tar-stream/extract.js
+var require_extract = __commonJS({
+  "node_modules/tar-stream/extract.js"(exports2, module2) {
+    var { Writable, Readable, getStreamError } = require_streamx();
+    var FIFO = require_fast_fifo();
+    var b4a = require_b4a();
+    var headers = require_headers2();
+    var EMPTY = b4a.alloc(0);
+    var BufferList = class {
+      constructor() {
+        this.buffered = 0;
+        this.shifted = 0;
+        this.queue = new FIFO();
+        this._offset = 0;
       }
-      Transform.call(this, options);
-      this.offset = 0;
-      this._archive = {
-        finish: false,
-        finished: false,
-        processing: false
-      };
-    };
-    inherits(ArchiveOutputStream, Transform);
-    ArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) {
-    };
-    ArchiveOutputStream.prototype._appendStream = function(zae, source, callback) {
-    };
-    ArchiveOutputStream.prototype._emitErrorCallback = function(err) {
-      if (err) {
-        this.emit("error", err);
+      push(buffer) {
+        this.buffered += buffer.byteLength;
+        this.queue.push(buffer);
+      }
+      shiftFirst(size) {
+        return this._buffered === 0 ? null : this._next(size);
+      }
+      shift(size) {
+        if (size > this.buffered) return null;
+        if (size === 0) return EMPTY;
+        let chunk = this._next(size);
+        if (size === chunk.byteLength) return chunk;
+        const chunks = [chunk];
+        while ((size -= chunk.byteLength) > 0) {
+          chunk = this._next(size);
+          chunks.push(chunk);
+        }
+        return b4a.concat(chunks);
+      }
+      _next(size) {
+        const buf = this.queue.peek();
+        const rem = buf.byteLength - this._offset;
+        if (size >= rem) {
+          const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf;
+          this.queue.shift();
+          this._offset = 0;
+          this.buffered -= rem;
+          this.shifted += rem;
+          return sub;
+        }
+        this.buffered -= size;
+        this.shifted += size;
+        return buf.subarray(this._offset, this._offset += size);
       }
     };
-    ArchiveOutputStream.prototype._finish = function(ae) {
-    };
-    ArchiveOutputStream.prototype._normalizeEntry = function(ae) {
-    };
-    ArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) {
-      callback(null, chunk);
-    };
-    ArchiveOutputStream.prototype.entry = function(ae, source, callback) {
-      source = source || null;
-      if (typeof callback !== "function") {
-        callback = this._emitErrorCallback.bind(this);
+    var Source = class extends Readable {
+      constructor(self2, header, offset) {
+        super();
+        this.header = header;
+        this.offset = offset;
+        this._parent = self2;
       }
-      if (!(ae instanceof ArchiveEntry)) {
-        callback(new Error("not a valid instance of ArchiveEntry"));
-        return;
+      _read(cb) {
+        if (this.header.size === 0) {
+          this.push(null);
+        }
+        if (this._parent._stream === this) {
+          this._parent._update();
+        }
+        cb(null);
       }
-      if (this._archive.finish || this._archive.finished) {
-        callback(new Error("unacceptable entry after finish"));
-        return;
+      _predestroy() {
+        this._parent.destroy(getStreamError(this));
       }
-      if (this._archive.processing) {
-        callback(new Error("already processing an entry"));
-        return;
+      _detach() {
+        if (this._parent._stream === this) {
+          this._parent._stream = null;
+          this._parent._missing = overflow(this.header.size);
+          this._parent._update();
+        }
       }
-      this._archive.processing = true;
-      this._normalizeEntry(ae);
-      this._entry = ae;
-      source = util.normalizeInputSource(source);
-      if (Buffer.isBuffer(source)) {
-        this._appendBuffer(ae, source, callback);
-      } else if (isStream(source)) {
-        this._appendStream(ae, source, callback);
-      } else {
-        this._archive.processing = false;
-        callback(new Error("input source must be valid Stream or Buffer instance"));
-        return;
+      _destroy(cb) {
+        this._detach();
+        cb(null);
       }
-      return this;
     };
-    ArchiveOutputStream.prototype.finish = function() {
-      if (this._archive.processing) {
-        this._archive.finish = true;
-        return;
+    var Extract = class extends Writable {
+      constructor(opts) {
+        super(opts);
+        if (!opts) opts = {};
+        this._buffer = new BufferList();
+        this._offset = 0;
+        this._header = null;
+        this._stream = null;
+        this._missing = 0;
+        this._longHeader = false;
+        this._callback = noop;
+        this._locked = false;
+        this._finished = false;
+        this._pax = null;
+        this._paxGlobal = null;
+        this._gnuLongPath = null;
+        this._gnuLongLinkPath = null;
+        this._filenameEncoding = opts.filenameEncoding || "utf-8";
+        this._allowUnknownFormat = !!opts.allowUnknownFormat;
+        this._unlockBound = this._unlock.bind(this);
       }
-      this._finish();
-    };
-    ArchiveOutputStream.prototype.getBytesWritten = function() {
-      return this.offset;
-    };
-    ArchiveOutputStream.prototype.write = function(chunk, cb) {
-      if (chunk) {
-        this.offset += chunk.length;
+      _unlock(err) {
+        this._locked = false;
+        if (err) {
+          this.destroy(err);
+          this._continueWrite(err);
+          return;
+        }
+        this._update();
       }
-      return Transform.prototype.write.call(this, chunk, cb);
-    };
-  }
-});
-
-// node_modules/crc-32/crc32.js
-var require_crc32 = __commonJS({
-  "node_modules/crc-32/crc32.js"(exports2) {
-    var CRC32;
-    (function(factory) {
-      if (typeof DO_NOT_EXPORT_CRC === "undefined") {
-        if ("object" === typeof exports2) {
-          factory(exports2);
-        } else if ("function" === typeof define && define.amd) {
-          define(function() {
-            var module3 = {};
-            factory(module3);
-            return module3;
-          });
-        } else {
-          factory(CRC32 = {});
+      _consumeHeader() {
+        if (this._locked) return false;
+        this._offset = this._buffer.shifted;
+        try {
+          this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat);
+        } catch (err) {
+          this._continueWrite(err);
+          return false;
         }
-      } else {
-        factory(CRC32 = {});
+        if (!this._header) return true;
+        switch (this._header.type) {
+          case "gnu-long-path":
+          case "gnu-long-link-path":
+          case "pax-global-header":
+          case "pax-header":
+            this._longHeader = true;
+            this._missing = this._header.size;
+            return true;
+        }
+        this._locked = true;
+        this._applyLongHeaders();
+        if (this._header.size === 0 || this._header.type === "directory") {
+          this.emit("entry", this._header, this._createStream(), this._unlockBound);
+          return true;
+        }
+        this._stream = this._createStream();
+        this._missing = this._header.size;
+        this.emit("entry", this._header, this._stream, this._unlockBound);
+        return true;
       }
-    })(function(CRC322) {
-      CRC322.version = "1.2.2";
-      function signed_crc_table() {
-        var c = 0, table = new Array(256);
-        for (var n = 0; n != 256; ++n) {
-          c = n;
-          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
-          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
-          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
-          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
-          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
-          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
-          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
-          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
-          table[n] = c;
+      _applyLongHeaders() {
+        if (this._gnuLongPath) {
+          this._header.name = this._gnuLongPath;
+          this._gnuLongPath = null;
+        }
+        if (this._gnuLongLinkPath) {
+          this._header.linkname = this._gnuLongLinkPath;
+          this._gnuLongLinkPath = null;
+        }
+        if (this._pax) {
+          if (this._pax.path) this._header.name = this._pax.path;
+          if (this._pax.linkpath) this._header.linkname = this._pax.linkpath;
+          if (this._pax.size) this._header.size = parseInt(this._pax.size, 10);
+          this._header.pax = this._pax;
+          this._pax = null;
         }
-        return typeof Int32Array !== "undefined" ? new Int32Array(table) : table;
       }
-      var T0 = signed_crc_table();
-      function slice_by_16_tables(T) {
-        var c = 0, v = 0, n = 0, table = typeof Int32Array !== "undefined" ? new Int32Array(4096) : new Array(4096);
-        for (n = 0; n != 256; ++n) table[n] = T[n];
-        for (n = 0; n != 256; ++n) {
-          v = T[n];
-          for (c = 256 + n; c < 4096; c += 256) v = table[c] = v >>> 8 ^ T[v & 255];
+      _decodeLongHeader(buf) {
+        switch (this._header.type) {
+          case "gnu-long-path":
+            this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding);
+            break;
+          case "gnu-long-link-path":
+            this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding);
+            break;
+          case "pax-global-header":
+            this._paxGlobal = headers.decodePax(buf);
+            break;
+          case "pax-header":
+            this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf));
+            break;
         }
-        var out = [];
-        for (n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== "undefined" ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256);
-        return out;
       }
-      var TT = slice_by_16_tables(T0);
-      var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];
-      var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];
-      var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];
-      function crc32_bstr(bstr, seed) {
-        var C = seed ^ -1;
-        for (var i = 0, L = bstr.length; i < L; ) C = C >>> 8 ^ T0[(C ^ bstr.charCodeAt(i++)) & 255];
-        return ~C;
+      _consumeLongHeader() {
+        this._longHeader = false;
+        this._missing = overflow(this._header.size);
+        const buf = this._buffer.shift(this._header.size);
+        try {
+          this._decodeLongHeader(buf);
+        } catch (err) {
+          this._continueWrite(err);
+          return false;
+        }
+        return true;
       }
-      function crc32_buf(B, seed) {
-        var C = seed ^ -1, L = B.length - 15, i = 0;
-        for (; i < L; ) C = Tf[B[i++] ^ C & 255] ^ Te[B[i++] ^ C >> 8 & 255] ^ Td[B[i++] ^ C >> 16 & 255] ^ Tc[B[i++] ^ C >>> 24] ^ Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];
-        L += 15;
-        while (i < L) C = C >>> 8 ^ T0[(C ^ B[i++]) & 255];
-        return ~C;
+      _consumeStream() {
+        const buf = this._buffer.shiftFirst(this._missing);
+        if (buf === null) return false;
+        this._missing -= buf.byteLength;
+        const drained = this._stream.push(buf);
+        if (this._missing === 0) {
+          this._stream.push(null);
+          if (drained) this._stream._detach();
+          return drained && this._locked === false;
+        }
+        return drained;
       }
-      function crc32_str(str2, seed) {
-        var C = seed ^ -1;
-        for (var i = 0, L = str2.length, c = 0, d = 0; i < L; ) {
-          c = str2.charCodeAt(i++);
-          if (c < 128) {
-            C = C >>> 8 ^ T0[(C ^ c) & 255];
-          } else if (c < 2048) {
-            C = C >>> 8 ^ T0[(C ^ (192 | c >> 6 & 31)) & 255];
-            C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
-          } else if (c >= 55296 && c < 57344) {
-            c = (c & 1023) + 64;
-            d = str2.charCodeAt(i++) & 1023;
-            C = C >>> 8 ^ T0[(C ^ (240 | c >> 8 & 7)) & 255];
-            C = C >>> 8 ^ T0[(C ^ (128 | c >> 2 & 63)) & 255];
-            C = C >>> 8 ^ T0[(C ^ (128 | d >> 6 & 15 | (c & 3) << 4)) & 255];
-            C = C >>> 8 ^ T0[(C ^ (128 | d & 63)) & 255];
-          } else {
-            C = C >>> 8 ^ T0[(C ^ (224 | c >> 12 & 15)) & 255];
-            C = C >>> 8 ^ T0[(C ^ (128 | c >> 6 & 63)) & 255];
-            C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
+      _createStream() {
+        return new Source(this, this._header, this._offset);
+      }
+      _update() {
+        while (this._buffer.buffered > 0 && !this.destroying) {
+          if (this._missing > 0) {
+            if (this._stream !== null) {
+              if (this._consumeStream() === false) return;
+              continue;
+            }
+            if (this._longHeader === true) {
+              if (this._missing > this._buffer.buffered) break;
+              if (this._consumeLongHeader() === false) return false;
+              continue;
+            }
+            const ignore = this._buffer.shiftFirst(this._missing);
+            if (ignore !== null) this._missing -= ignore.byteLength;
+            continue;
           }
+          if (this._buffer.buffered < 512) break;
+          if (this._stream !== null || this._consumeHeader() === false) return;
         }
-        return ~C;
-      }
-      CRC322.table = T0;
-      CRC322.bstr = crc32_bstr;
-      CRC322.buf = crc32_buf;
-      CRC322.str = crc32_str;
-    });
-  }
-});
-
-// node_modules/crc32-stream/lib/crc32-stream.js
-var require_crc32_stream = __commonJS({
-  "node_modules/crc32-stream/lib/crc32-stream.js"(exports2, module2) {
-    "use strict";
-    var { Transform } = require_ours();
-    var crc32 = require_crc32();
-    var CRC32Stream = class extends Transform {
-      constructor(options) {
-        super(options);
-        this.checksum = Buffer.allocUnsafe(4);
-        this.checksum.writeInt32BE(0, 0);
-        this.rawSize = 0;
+        this._continueWrite(null);
       }
-      _transform(chunk, encoding, callback) {
-        if (chunk) {
-          this.checksum = crc32.buf(chunk, this.checksum) >>> 0;
-          this.rawSize += chunk.length;
-        }
-        callback(null, chunk);
+      _continueWrite(err) {
+        const cb = this._callback;
+        this._callback = noop;
+        cb(err);
       }
-      digest(encoding) {
-        const checksum = Buffer.allocUnsafe(4);
-        checksum.writeUInt32BE(this.checksum >>> 0, 0);
-        return encoding ? checksum.toString(encoding) : checksum;
+      _write(data, cb) {
+        this._callback = cb;
+        this._buffer.push(data);
+        this._update();
       }
-      hex() {
-        return this.digest("hex").toUpperCase();
+      _final(cb) {
+        this._finished = this._missing === 0 && this._buffer.buffered === 0;
+        cb(this._finished ? null : new Error("Unexpected end of data"));
       }
-      size() {
-        return this.rawSize;
+      _predestroy() {
+        this._continueWrite(null);
       }
-    };
-    module2.exports = CRC32Stream;
-  }
-});
-
-// node_modules/crc32-stream/lib/deflate-crc32-stream.js
-var require_deflate_crc32_stream = __commonJS({
-  "node_modules/crc32-stream/lib/deflate-crc32-stream.js"(exports2, module2) {
-    "use strict";
-    var { DeflateRaw } = require("zlib");
-    var crc32 = require_crc32();
-    var DeflateCRC32Stream = class extends DeflateRaw {
-      constructor(options) {
-        super(options);
-        this.checksum = Buffer.allocUnsafe(4);
-        this.checksum.writeInt32BE(0, 0);
-        this.rawSize = 0;
-        this.compressedSize = 0;
+      _destroy(cb) {
+        if (this._stream) this._stream.destroy(getStreamError(this));
+        cb(null);
       }
-      push(chunk, encoding) {
-        if (chunk) {
-          this.compressedSize += chunk.length;
+      [Symbol.asyncIterator]() {
+        let error4 = null;
+        let promiseResolve = null;
+        let promiseReject = null;
+        let entryStream = null;
+        let entryCallback = null;
+        const extract2 = this;
+        this.on("entry", onentry);
+        this.on("error", (err) => {
+          error4 = err;
+        });
+        this.on("close", onclose);
+        return {
+          [Symbol.asyncIterator]() {
+            return this;
+          },
+          next() {
+            return new Promise(onnext);
+          },
+          return() {
+            return destroy(null);
+          },
+          throw(err) {
+            return destroy(err);
+          }
+        };
+        function consumeCallback(err) {
+          if (!entryCallback) return;
+          const cb = entryCallback;
+          entryCallback = null;
+          cb(err);
         }
-        return super.push(chunk, encoding);
-      }
-      _transform(chunk, encoding, callback) {
-        if (chunk) {
-          this.checksum = crc32.buf(chunk, this.checksum) >>> 0;
-          this.rawSize += chunk.length;
+        function onnext(resolve2, reject) {
+          if (error4) {
+            return reject(error4);
+          }
+          if (entryStream) {
+            resolve2({ value: entryStream, done: false });
+            entryStream = null;
+            return;
+          }
+          promiseResolve = resolve2;
+          promiseReject = reject;
+          consumeCallback(null);
+          if (extract2._finished && promiseResolve) {
+            promiseResolve({ value: void 0, done: true });
+            promiseResolve = promiseReject = null;
+          }
         }
-        super._transform(chunk, encoding, callback);
-      }
-      digest(encoding) {
-        const checksum = Buffer.allocUnsafe(4);
-        checksum.writeUInt32BE(this.checksum >>> 0, 0);
-        return encoding ? checksum.toString(encoding) : checksum;
-      }
-      hex() {
-        return this.digest("hex").toUpperCase();
-      }
-      size(compressed = false) {
-        if (compressed) {
-          return this.compressedSize;
-        } else {
-          return this.rawSize;
+        function onentry(header, stream, callback) {
+          entryCallback = callback;
+          stream.on("error", noop);
+          if (promiseResolve) {
+            promiseResolve({ value: stream, done: false });
+            promiseResolve = promiseReject = null;
+          } else {
+            entryStream = stream;
+          }
+        }
+        function onclose() {
+          consumeCallback(error4);
+          if (!promiseResolve) return;
+          if (error4) promiseReject(error4);
+          else promiseResolve({ value: void 0, done: true });
+          promiseResolve = promiseReject = null;
+        }
+        function destroy(err) {
+          extract2.destroy(err);
+          consumeCallback(err);
+          return new Promise((resolve2, reject) => {
+            if (extract2.destroyed) return resolve2({ value: void 0, done: true });
+            extract2.once("close", function() {
+              if (err) reject(err);
+              else resolve2({ value: void 0, done: true });
+            });
+          });
         }
       }
     };
-    module2.exports = DeflateCRC32Stream;
+    module2.exports = function extract2(opts) {
+      return new Extract(opts);
+    };
+    function noop() {
+    }
+    function overflow(size) {
+      size &= 511;
+      return size && 512 - size;
+    }
   }
 });
 
-// node_modules/crc32-stream/lib/index.js
-var require_lib2 = __commonJS({
-  "node_modules/crc32-stream/lib/index.js"(exports2, module2) {
-    "use strict";
-    module2.exports = {
-      CRC32Stream: require_crc32_stream(),
-      DeflateCRC32Stream: require_deflate_crc32_stream()
+// node_modules/tar-stream/constants.js
+var require_constants9 = __commonJS({
+  "node_modules/tar-stream/constants.js"(exports2, module2) {
+    var constants = {
+      // just for envs without fs
+      S_IFMT: 61440,
+      S_IFDIR: 16384,
+      S_IFCHR: 8192,
+      S_IFBLK: 24576,
+      S_IFIFO: 4096,
+      S_IFLNK: 40960
     };
+    try {
+      module2.exports = require("fs").constants || constants;
+    } catch {
+      module2.exports = constants;
+    }
   }
 });
 
-// node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js
-var require_zip_archive_output_stream = __commonJS({
-  "node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js"(exports2, module2) {
-    var inherits = require("util").inherits;
-    var crc32 = require_crc32();
-    var { CRC32Stream } = require_lib2();
-    var { DeflateCRC32Stream } = require_lib2();
-    var ArchiveOutputStream = require_archive_output_stream();
-    var ZipArchiveEntry = require_zip_archive_entry();
-    var GeneralPurposeBit = require_general_purpose_bit();
-    var constants = require_constants8();
-    var util = require_util14();
-    var zipUtil = require_util13();
-    var ZipArchiveOutputStream = module2.exports = function(options) {
-      if (!(this instanceof ZipArchiveOutputStream)) {
-        return new ZipArchiveOutputStream(options);
-      }
-      options = this.options = this._defaults(options);
-      ArchiveOutputStream.call(this, options);
-      this._entry = null;
-      this._entries = [];
-      this._archive = {
-        centralLength: 0,
-        centralOffset: 0,
-        comment: "",
-        finish: false,
-        finished: false,
-        processing: false,
-        forceZip64: options.forceZip64,
-        forceLocalTime: options.forceLocalTime
-      };
-    };
-    inherits(ZipArchiveOutputStream, ArchiveOutputStream);
-    ZipArchiveOutputStream.prototype._afterAppend = function(ae) {
-      this._entries.push(ae);
-      if (ae.getGeneralPurposeBit().usesDataDescriptor()) {
-        this._writeDataDescriptor(ae);
-      }
-      this._archive.processing = false;
-      this._entry = null;
-      if (this._archive.finish && !this._archive.finished) {
-        this._finish();
-      }
-    };
-    ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) {
-      if (source.length === 0) {
-        ae.setMethod(constants.METHOD_STORED);
+// node_modules/tar-stream/pack.js
+var require_pack = __commonJS({
+  "node_modules/tar-stream/pack.js"(exports2, module2) {
+    var { Readable, Writable, getStreamError } = require_streamx();
+    var b4a = require_b4a();
+    var constants = require_constants9();
+    var headers = require_headers2();
+    var DMODE = 493;
+    var FMODE = 420;
+    var END_OF_TAR = b4a.alloc(1024);
+    var Sink = class extends Writable {
+      constructor(pack, header, callback) {
+        super({ mapWritable, eagerOpen: true });
+        this.written = 0;
+        this.header = header;
+        this._callback = callback;
+        this._linkname = null;
+        this._isLinkname = header.type === "symlink" && !header.linkname;
+        this._isVoid = header.type !== "file" && header.type !== "contiguous-file";
+        this._finished = false;
+        this._pack = pack;
+        this._openCallback = null;
+        if (this._pack._stream === null) this._pack._stream = this;
+        else this._pack._pending.push(this);
       }
-      var method = ae.getMethod();
-      if (method === constants.METHOD_STORED) {
-        ae.setSize(source.length);
-        ae.setCompressedSize(source.length);
-        ae.setCrc(crc32.buf(source) >>> 0);
+      _open(cb) {
+        this._openCallback = cb;
+        if (this._pack._stream === this) this._continueOpen();
       }
-      this._writeLocalFileHeader(ae);
-      if (method === constants.METHOD_STORED) {
-        this.write(source);
-        this._afterAppend(ae);
-        callback(null, ae);
-        return;
-      } else if (method === constants.METHOD_DEFLATED) {
-        this._smartStream(ae, callback).end(source);
-        return;
-      } else {
-        callback(new Error("compression method " + method + " not implemented"));
-        return;
+      _continuePack(err) {
+        if (this._callback === null) return;
+        const callback = this._callback;
+        this._callback = null;
+        callback(err);
       }
-    };
-    ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) {
-      ae.getGeneralPurposeBit().useDataDescriptor(true);
-      ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR);
-      this._writeLocalFileHeader(ae);
-      var smart = this._smartStream(ae, callback);
-      source.once("error", function(err) {
-        smart.emit("error", err);
-        smart.end();
-      });
-      source.pipe(smart);
-    };
-    ZipArchiveOutputStream.prototype._defaults = function(o) {
-      if (typeof o !== "object") {
-        o = {};
+      _continueOpen() {
+        if (this._pack._stream === null) this._pack._stream = this;
+        const cb = this._openCallback;
+        this._openCallback = null;
+        if (cb === null) return;
+        if (this._pack.destroying) return cb(new Error("pack stream destroyed"));
+        if (this._pack._finalized) return cb(new Error("pack stream is already finalized"));
+        this._pack._stream = this;
+        if (!this._isLinkname) {
+          this._pack._encode(this.header);
+        }
+        if (this._isVoid) {
+          this._finish();
+          this._continuePack(null);
+        }
+        cb(null);
       }
-      if (typeof o.zlib !== "object") {
-        o.zlib = {};
+      _write(data, cb) {
+        if (this._isLinkname) {
+          this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data;
+          return cb(null);
+        }
+        if (this._isVoid) {
+          if (data.byteLength > 0) {
+            return cb(new Error("No body allowed for this entry"));
+          }
+          return cb();
+        }
+        this.written += data.byteLength;
+        if (this._pack.push(data)) return cb();
+        this._pack._drain = cb;
       }
-      if (typeof o.zlib.level !== "number") {
-        o.zlib.level = constants.ZLIB_BEST_SPEED;
+      _finish() {
+        if (this._finished) return;
+        this._finished = true;
+        if (this._isLinkname) {
+          this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : "";
+          this._pack._encode(this.header);
+        }
+        overflow(this._pack, this.header.size);
+        this._pack._done(this);
       }
-      o.forceZip64 = !!o.forceZip64;
-      o.forceLocalTime = !!o.forceLocalTime;
-      return o;
-    };
-    ZipArchiveOutputStream.prototype._finish = function() {
-      this._archive.centralOffset = this.offset;
-      this._entries.forEach(function(ae) {
-        this._writeCentralFileHeader(ae);
-      }.bind(this));
-      this._archive.centralLength = this.offset - this._archive.centralOffset;
-      if (this.isZip64()) {
-        this._writeCentralDirectoryZip64();
+      _final(cb) {
+        if (this.written !== this.header.size) {
+          return cb(new Error("Size mismatch"));
+        }
+        this._finish();
+        cb(null);
       }
-      this._writeCentralDirectoryEnd();
-      this._archive.processing = false;
-      this._archive.finish = true;
-      this._archive.finished = true;
-      this.end();
-    };
-    ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) {
-      if (ae.getMethod() === -1) {
-        ae.setMethod(constants.METHOD_DEFLATED);
+      _getError() {
+        return getStreamError(this) || new Error("tar entry destroyed");
       }
-      if (ae.getMethod() === constants.METHOD_DEFLATED) {
-        ae.getGeneralPurposeBit().useDataDescriptor(true);
-        ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR);
+      _predestroy() {
+        this._pack.destroy(this._getError());
       }
-      if (ae.getTime() === -1) {
-        ae.setTime(/* @__PURE__ */ new Date(), this._archive.forceLocalTime);
+      _destroy(cb) {
+        this._pack._done(this);
+        this._continuePack(this._finished ? null : this._getError());
+        cb();
       }
-      ae._offsets = {
-        file: 0,
-        data: 0,
-        contents: 0
-      };
     };
-    ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) {
-      var deflate = ae.getMethod() === constants.METHOD_DEFLATED;
-      var process2 = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream();
-      var error4 = null;
-      function handleStuff() {
-        var digest = process2.digest().readUInt32BE(0);
-        ae.setCrc(digest);
-        ae.setSize(process2.size());
-        ae.setCompressedSize(process2.size(true));
-        this._afterAppend(ae);
-        callback(error4, ae);
+    var Pack = class extends Readable {
+      constructor(opts) {
+        super(opts);
+        this._drain = noop;
+        this._finalized = false;
+        this._finalizing = false;
+        this._pending = [];
+        this._stream = null;
       }
-      process2.once("end", handleStuff.bind(this));
-      process2.once("error", function(err) {
-        error4 = err;
-      });
-      process2.pipe(this, { end: false });
-      return process2;
-    };
-    ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() {
-      var records = this._entries.length;
-      var size = this._archive.centralLength;
-      var offset = this._archive.centralOffset;
-      if (this.isZip64()) {
-        records = constants.ZIP64_MAGIC_SHORT;
-        size = constants.ZIP64_MAGIC;
-        offset = constants.ZIP64_MAGIC;
+      entry(header, buffer, callback) {
+        if (this._finalized || this.destroying) throw new Error("already finalized or destroyed");
+        if (typeof buffer === "function") {
+          callback = buffer;
+          buffer = null;
+        }
+        if (!callback) callback = noop;
+        if (!header.size || header.type === "symlink") header.size = 0;
+        if (!header.type) header.type = modeToType(header.mode);
+        if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE;
+        if (!header.uid) header.uid = 0;
+        if (!header.gid) header.gid = 0;
+        if (!header.mtime) header.mtime = /* @__PURE__ */ new Date();
+        if (typeof buffer === "string") buffer = b4a.from(buffer);
+        const sink = new Sink(this, header, callback);
+        if (b4a.isBuffer(buffer)) {
+          header.size = buffer.byteLength;
+          sink.write(buffer);
+          sink.end();
+          return sink;
+        }
+        if (sink._isVoid) {
+          return sink;
+        }
+        return sink;
       }
-      this.write(zipUtil.getLongBytes(constants.SIG_EOCD));
-      this.write(constants.SHORT_ZERO);
-      this.write(constants.SHORT_ZERO);
-      this.write(zipUtil.getShortBytes(records));
-      this.write(zipUtil.getShortBytes(records));
-      this.write(zipUtil.getLongBytes(size));
-      this.write(zipUtil.getLongBytes(offset));
-      var comment = this.getComment();
-      var commentLength = Buffer.byteLength(comment);
-      this.write(zipUtil.getShortBytes(commentLength));
-      this.write(comment);
-    };
-    ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() {
-      this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD));
-      this.write(zipUtil.getEightBytes(44));
-      this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64));
-      this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64));
-      this.write(constants.LONG_ZERO);
-      this.write(constants.LONG_ZERO);
-      this.write(zipUtil.getEightBytes(this._entries.length));
-      this.write(zipUtil.getEightBytes(this._entries.length));
-      this.write(zipUtil.getEightBytes(this._archive.centralLength));
-      this.write(zipUtil.getEightBytes(this._archive.centralOffset));
-      this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD_LOC));
-      this.write(constants.LONG_ZERO);
-      this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength));
-      this.write(zipUtil.getLongBytes(1));
-    };
-    ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) {
-      var gpb = ae.getGeneralPurposeBit();
-      var method = ae.getMethod();
-      var fileOffset = ae._offsets.file;
-      var size = ae.getSize();
-      var compressedSize = ae.getCompressedSize();
-      if (ae.isZip64() || fileOffset > constants.ZIP64_MAGIC) {
-        size = constants.ZIP64_MAGIC;
-        compressedSize = constants.ZIP64_MAGIC;
-        fileOffset = constants.ZIP64_MAGIC;
-        ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64);
-        var extraBuf = Buffer.concat([
-          zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID),
-          zipUtil.getShortBytes(24),
-          zipUtil.getEightBytes(ae.getSize()),
-          zipUtil.getEightBytes(ae.getCompressedSize()),
-          zipUtil.getEightBytes(ae._offsets.file)
-        ], 28);
-        ae.setExtra(extraBuf);
+      finalize() {
+        if (this._stream || this._pending.length > 0) {
+          this._finalizing = true;
+          return;
+        }
+        if (this._finalized) return;
+        this._finalized = true;
+        this.push(END_OF_TAR);
+        this.push(null);
       }
-      this.write(zipUtil.getLongBytes(constants.SIG_CFH));
-      this.write(zipUtil.getShortBytes(ae.getPlatform() << 8 | constants.VERSION_MADEBY));
-      this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));
-      this.write(gpb.encode());
-      this.write(zipUtil.getShortBytes(method));
-      this.write(zipUtil.getLongBytes(ae.getTimeDos()));
-      this.write(zipUtil.getLongBytes(ae.getCrc()));
-      this.write(zipUtil.getLongBytes(compressedSize));
-      this.write(zipUtil.getLongBytes(size));
-      var name = ae.getName();
-      var comment = ae.getComment();
-      var extra = ae.getCentralDirectoryExtra();
-      if (gpb.usesUTF8ForNames()) {
-        name = Buffer.from(name);
-        comment = Buffer.from(comment);
+      _done(stream) {
+        if (stream !== this._stream) return;
+        this._stream = null;
+        if (this._finalizing) this.finalize();
+        if (this._pending.length) this._pending.shift()._continueOpen();
       }
-      this.write(zipUtil.getShortBytes(name.length));
-      this.write(zipUtil.getShortBytes(extra.length));
-      this.write(zipUtil.getShortBytes(comment.length));
-      this.write(constants.SHORT_ZERO);
-      this.write(zipUtil.getShortBytes(ae.getInternalAttributes()));
-      this.write(zipUtil.getLongBytes(ae.getExternalAttributes()));
-      this.write(zipUtil.getLongBytes(fileOffset));
-      this.write(name);
-      this.write(extra);
-      this.write(comment);
-    };
-    ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) {
-      this.write(zipUtil.getLongBytes(constants.SIG_DD));
-      this.write(zipUtil.getLongBytes(ae.getCrc()));
-      if (ae.isZip64()) {
-        this.write(zipUtil.getEightBytes(ae.getCompressedSize()));
-        this.write(zipUtil.getEightBytes(ae.getSize()));
-      } else {
-        this.write(zipUtil.getLongBytes(ae.getCompressedSize()));
-        this.write(zipUtil.getLongBytes(ae.getSize()));
+      _encode(header) {
+        if (!header.pax) {
+          const buf = headers.encode(header);
+          if (buf) {
+            this.push(buf);
+            return;
+          }
+        }
+        this._encodePax(header);
       }
-    };
-    ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) {
-      var gpb = ae.getGeneralPurposeBit();
-      var method = ae.getMethod();
-      var name = ae.getName();
-      var extra = ae.getLocalFileDataExtra();
-      if (ae.isZip64()) {
-        gpb.useDataDescriptor(true);
-        ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64);
+      _encodePax(header) {
+        const paxHeader = headers.encodePax({
+          name: header.name,
+          linkname: header.linkname,
+          pax: header.pax
+        });
+        const newHeader = {
+          name: "PaxHeader",
+          mode: header.mode,
+          uid: header.uid,
+          gid: header.gid,
+          size: paxHeader.byteLength,
+          mtime: header.mtime,
+          type: "pax-header",
+          linkname: header.linkname && "PaxHeader",
+          uname: header.uname,
+          gname: header.gname,
+          devmajor: header.devmajor,
+          devminor: header.devminor
+        };
+        this.push(headers.encode(newHeader));
+        this.push(paxHeader);
+        overflow(this, paxHeader.byteLength);
+        newHeader.size = header.size;
+        newHeader.type = header.type;
+        this.push(headers.encode(newHeader));
       }
-      if (gpb.usesUTF8ForNames()) {
-        name = Buffer.from(name);
+      _doDrain() {
+        const drain = this._drain;
+        this._drain = noop;
+        drain();
       }
-      ae._offsets.file = this.offset;
-      this.write(zipUtil.getLongBytes(constants.SIG_LFH));
-      this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));
-      this.write(gpb.encode());
-      this.write(zipUtil.getShortBytes(method));
-      this.write(zipUtil.getLongBytes(ae.getTimeDos()));
-      ae._offsets.data = this.offset;
-      if (gpb.usesDataDescriptor()) {
-        this.write(constants.LONG_ZERO);
-        this.write(constants.LONG_ZERO);
-        this.write(constants.LONG_ZERO);
-      } else {
-        this.write(zipUtil.getLongBytes(ae.getCrc()));
-        this.write(zipUtil.getLongBytes(ae.getCompressedSize()));
-        this.write(zipUtil.getLongBytes(ae.getSize()));
+      _predestroy() {
+        const err = getStreamError(this);
+        if (this._stream) this._stream.destroy(err);
+        while (this._pending.length) {
+          const stream = this._pending.shift();
+          stream.destroy(err);
+          stream._continueOpen();
+        }
+        this._doDrain();
+      }
+      _read(cb) {
+        this._doDrain();
+        cb();
       }
-      this.write(zipUtil.getShortBytes(name.length));
-      this.write(zipUtil.getShortBytes(extra.length));
-      this.write(name);
-      this.write(extra);
-      ae._offsets.contents = this.offset;
-    };
-    ZipArchiveOutputStream.prototype.getComment = function(comment) {
-      return this._archive.comment !== null ? this._archive.comment : "";
-    };
-    ZipArchiveOutputStream.prototype.isZip64 = function() {
-      return this._archive.forceZip64 || this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC;
     };
-    ZipArchiveOutputStream.prototype.setComment = function(comment) {
-      this._archive.comment = comment;
+    module2.exports = function pack(opts) {
+      return new Pack(opts);
     };
+    function modeToType(mode) {
+      switch (mode & constants.S_IFMT) {
+        case constants.S_IFBLK:
+          return "block-device";
+        case constants.S_IFCHR:
+          return "character-device";
+        case constants.S_IFDIR:
+          return "directory";
+        case constants.S_IFIFO:
+          return "fifo";
+        case constants.S_IFLNK:
+          return "symlink";
+      }
+      return "file";
+    }
+    function noop() {
+    }
+    function overflow(self2, size) {
+      size &= 511;
+      if (size) self2.push(END_OF_TAR.subarray(0, 512 - size));
+    }
+    function mapWritable(buf) {
+      return b4a.isBuffer(buf) ? buf : b4a.from(buf);
+    }
   }
 });
 
-// node_modules/compress-commons/lib/compress-commons.js
-var require_compress_commons = __commonJS({
-  "node_modules/compress-commons/lib/compress-commons.js"(exports2, module2) {
-    module2.exports = {
-      ArchiveEntry: require_archive_entry(),
-      ZipArchiveEntry: require_zip_archive_entry(),
-      ArchiveOutputStream: require_archive_output_stream(),
-      ZipArchiveOutputStream: require_zip_archive_output_stream()
-    };
+// node_modules/tar-stream/index.js
+var require_tar_stream = __commonJS({
+  "node_modules/tar-stream/index.js"(exports2) {
+    exports2.extract = require_extract();
+    exports2.pack = require_pack();
   }
 });
 
-// node_modules/zip-stream/index.js
-var require_zip_stream = __commonJS({
-  "node_modules/zip-stream/index.js"(exports2, module2) {
-    var inherits = require("util").inherits;
-    var ZipArchiveOutputStream = require_compress_commons().ZipArchiveOutputStream;
-    var ZipArchiveEntry = require_compress_commons().ZipArchiveEntry;
+// node_modules/archiver/lib/plugins/tar.js
+var require_tar = __commonJS({
+  "node_modules/archiver/lib/plugins/tar.js"(exports2, module2) {
+    var zlib = require("zlib");
+    var engine = require_tar_stream();
     var util = require_archiver_utils();
-    var ZipStream = module2.exports = function(options) {
-      if (!(this instanceof ZipStream)) {
-        return new ZipStream(options);
-      }
-      options = this.options = options || {};
-      options.zlib = options.zlib || {};
-      ZipArchiveOutputStream.call(this, options);
-      if (typeof options.level === "number" && options.level >= 0) {
-        options.zlib.level = options.level;
-        delete options.level;
+    var Tar = function(options) {
+      if (!(this instanceof Tar)) {
+        return new Tar(options);
       }
-      if (!options.forceZip64 && typeof options.zlib.level === "number" && options.zlib.level === 0) {
-        options.store = true;
+      options = this.options = util.defaults(options, {
+        gzip: false
+      });
+      if (typeof options.gzipOptions !== "object") {
+        options.gzipOptions = {};
       }
-      options.namePrependSlash = options.namePrependSlash || false;
-      if (options.comment && options.comment.length > 0) {
-        this.setComment(options.comment);
+      this.supports = {
+        directory: true,
+        symlink: true
+      };
+      this.engine = engine.pack(options);
+      this.compressor = false;
+      if (options.gzip) {
+        this.compressor = zlib.createGzip(options.gzipOptions);
+        this.compressor.on("error", this._onCompressorError.bind(this));
       }
     };
-    inherits(ZipStream, ZipArchiveOutputStream);
-    ZipStream.prototype._normalizeFileData = function(data) {
-      data = util.defaults(data, {
-        type: "file",
-        name: null,
-        namePrependSlash: this.options.namePrependSlash,
-        linkname: null,
-        date: null,
-        mode: null,
-        store: this.options.store,
-        comment: ""
-      });
-      var isDir = data.type === "directory";
-      var isSymlink = data.type === "symlink";
-      if (data.name) {
-        data.name = util.sanitizePath(data.name);
-        if (!isSymlink && data.name.slice(-1) === "/") {
-          isDir = true;
-          data.type = "directory";
-        } else if (isDir) {
-          data.name += "/";
+    Tar.prototype._onCompressorError = function(err) {
+      this.engine.emit("error", err);
+    };
+    Tar.prototype.append = function(source, data, callback) {
+      var self2 = this;
+      data.mtime = data.date;
+      function append(err, sourceBuffer) {
+        if (err) {
+          callback(err);
+          return;
         }
+        self2.engine.entry(data, sourceBuffer, function(err2) {
+          callback(err2, data);
+        });
       }
-      if (isDir || isSymlink) {
-        data.store = true;
+      if (data.sourceType === "buffer") {
+        append(null, source);
+      } else if (data.sourceType === "stream" && data.stats) {
+        data.size = data.stats.size;
+        var entry = self2.engine.entry(data, function(err) {
+          callback(err, data);
+        });
+        source.pipe(entry);
+      } else if (data.sourceType === "stream") {
+        util.collectStream(source, append);
       }
-      data.date = util.dateify(data.date);
-      return data;
     };
-    ZipStream.prototype.entry = function(source, data, callback) {
-      if (typeof callback !== "function") {
-        callback = this._emitErrorCallback.bind(this);
-      }
-      data = this._normalizeFileData(data);
-      if (data.type !== "file" && data.type !== "directory" && data.type !== "symlink") {
-        callback(new Error(data.type + " entries not currently supported"));
-        return;
-      }
-      if (typeof data.name !== "string" || data.name.length === 0) {
-        callback(new Error("entry name must be a non-empty string value"));
-        return;
-      }
-      if (data.type === "symlink" && typeof data.linkname !== "string") {
-        callback(new Error("entry linkname must be a non-empty string value when type equals symlink"));
-        return;
-      }
-      var entry = new ZipArchiveEntry(data.name);
-      entry.setTime(data.date, this.options.forceLocalTime);
-      if (data.namePrependSlash) {
-        entry.setName(data.name, true);
+    Tar.prototype.finalize = function() {
+      this.engine.finalize();
+    };
+    Tar.prototype.on = function() {
+      return this.engine.on.apply(this.engine, arguments);
+    };
+    Tar.prototype.pipe = function(destination, options) {
+      if (this.compressor) {
+        return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options);
+      } else {
+        return this.engine.pipe.apply(this.engine, arguments);
       }
-      if (data.store) {
-        entry.setMethod(0);
+    };
+    Tar.prototype.unpipe = function() {
+      if (this.compressor) {
+        return this.compressor.unpipe.apply(this.compressor, arguments);
+      } else {
+        return this.engine.unpipe.apply(this.engine, arguments);
       }
-      if (data.comment.length > 0) {
-        entry.setComment(data.comment);
+    };
+    module2.exports = Tar;
+  }
+});
+
+// node_modules/buffer-crc32/dist/index.cjs
+var require_dist8 = __commonJS({
+  "node_modules/buffer-crc32/dist/index.cjs"(exports2, module2) {
+    "use strict";
+    function getDefaultExportFromCjs(x) {
+      return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
+    }
+    var CRC_TABLE = new Int32Array([
+      0,
+      1996959894,
+      3993919788,
+      2567524794,
+      124634137,
+      1886057615,
+      3915621685,
+      2657392035,
+      249268274,
+      2044508324,
+      3772115230,
+      2547177864,
+      162941995,
+      2125561021,
+      3887607047,
+      2428444049,
+      498536548,
+      1789927666,
+      4089016648,
+      2227061214,
+      450548861,
+      1843258603,
+      4107580753,
+      2211677639,
+      325883990,
+      1684777152,
+      4251122042,
+      2321926636,
+      335633487,
+      1661365465,
+      4195302755,
+      2366115317,
+      997073096,
+      1281953886,
+      3579855332,
+      2724688242,
+      1006888145,
+      1258607687,
+      3524101629,
+      2768942443,
+      901097722,
+      1119000684,
+      3686517206,
+      2898065728,
+      853044451,
+      1172266101,
+      3705015759,
+      2882616665,
+      651767980,
+      1373503546,
+      3369554304,
+      3218104598,
+      565507253,
+      1454621731,
+      3485111705,
+      3099436303,
+      671266974,
+      1594198024,
+      3322730930,
+      2970347812,
+      795835527,
+      1483230225,
+      3244367275,
+      3060149565,
+      1994146192,
+      31158534,
+      2563907772,
+      4023717930,
+      1907459465,
+      112637215,
+      2680153253,
+      3904427059,
+      2013776290,
+      251722036,
+      2517215374,
+      3775830040,
+      2137656763,
+      141376813,
+      2439277719,
+      3865271297,
+      1802195444,
+      476864866,
+      2238001368,
+      4066508878,
+      1812370925,
+      453092731,
+      2181625025,
+      4111451223,
+      1706088902,
+      314042704,
+      2344532202,
+      4240017532,
+      1658658271,
+      366619977,
+      2362670323,
+      4224994405,
+      1303535960,
+      984961486,
+      2747007092,
+      3569037538,
+      1256170817,
+      1037604311,
+      2765210733,
+      3554079995,
+      1131014506,
+      879679996,
+      2909243462,
+      3663771856,
+      1141124467,
+      855842277,
+      2852801631,
+      3708648649,
+      1342533948,
+      654459306,
+      3188396048,
+      3373015174,
+      1466479909,
+      544179635,
+      3110523913,
+      3462522015,
+      1591671054,
+      702138776,
+      2966460450,
+      3352799412,
+      1504918807,
+      783551873,
+      3082640443,
+      3233442989,
+      3988292384,
+      2596254646,
+      62317068,
+      1957810842,
+      3939845945,
+      2647816111,
+      81470997,
+      1943803523,
+      3814918930,
+      2489596804,
+      225274430,
+      2053790376,
+      3826175755,
+      2466906013,
+      167816743,
+      2097651377,
+      4027552580,
+      2265490386,
+      503444072,
+      1762050814,
+      4150417245,
+      2154129355,
+      426522225,
+      1852507879,
+      4275313526,
+      2312317920,
+      282753626,
+      1742555852,
+      4189708143,
+      2394877945,
+      397917763,
+      1622183637,
+      3604390888,
+      2714866558,
+      953729732,
+      1340076626,
+      3518719985,
+      2797360999,
+      1068828381,
+      1219638859,
+      3624741850,
+      2936675148,
+      906185462,
+      1090812512,
+      3747672003,
+      2825379669,
+      829329135,
+      1181335161,
+      3412177804,
+      3160834842,
+      628085408,
+      1382605366,
+      3423369109,
+      3138078467,
+      570562233,
+      1426400815,
+      3317316542,
+      2998733608,
+      733239954,
+      1555261956,
+      3268935591,
+      3050360625,
+      752459403,
+      1541320221,
+      2607071920,
+      3965973030,
+      1969922972,
+      40735498,
+      2617837225,
+      3943577151,
+      1913087877,
+      83908371,
+      2512341634,
+      3803740692,
+      2075208622,
+      213261112,
+      2463272603,
+      3855990285,
+      2094854071,
+      198958881,
+      2262029012,
+      4057260610,
+      1759359992,
+      534414190,
+      2176718541,
+      4139329115,
+      1873836001,
+      414664567,
+      2282248934,
+      4279200368,
+      1711684554,
+      285281116,
+      2405801727,
+      4167216745,
+      1634467795,
+      376229701,
+      2685067896,
+      3608007406,
+      1308918612,
+      956543938,
+      2808555105,
+      3495958263,
+      1231636301,
+      1047427035,
+      2932959818,
+      3654703836,
+      1088359270,
+      936918e3,
+      2847714899,
+      3736837829,
+      1202900863,
+      817233897,
+      3183342108,
+      3401237130,
+      1404277552,
+      615818150,
+      3134207493,
+      3453421203,
+      1423857449,
+      601450431,
+      3009837614,
+      3294710456,
+      1567103746,
+      711928724,
+      3020668471,
+      3272380065,
+      1510334235,
+      755167117
+    ]);
+    function ensureBuffer(input) {
+      if (Buffer.isBuffer(input)) {
+        return input;
       }
-      if (data.type === "symlink" && typeof data.mode !== "number") {
-        data.mode = 40960;
+      if (typeof input === "number") {
+        return Buffer.alloc(input);
+      } else if (typeof input === "string") {
+        return Buffer.from(input);
+      } else {
+        throw new Error("input must be buffer, number, or string, received " + typeof input);
       }
-      if (typeof data.mode === "number") {
-        if (data.type === "symlink") {
-          data.mode |= 40960;
-        }
-        entry.setUnixMode(data.mode);
+    }
+    function bufferizeInt(num) {
+      const tmp = ensureBuffer(4);
+      tmp.writeInt32BE(num, 0);
+      return tmp;
+    }
+    function _crc32(buf, previous) {
+      buf = ensureBuffer(buf);
+      if (Buffer.isBuffer(previous)) {
+        previous = previous.readUInt32BE(0);
       }
-      if (data.type === "symlink" && typeof data.linkname === "string") {
-        source = Buffer.from(data.linkname);
+      let crc = ~~previous ^ -1;
+      for (var n = 0; n < buf.length; n++) {
+        crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8;
       }
-      return ZipArchiveOutputStream.prototype.entry.call(this, entry, source, callback);
+      return crc ^ -1;
+    }
+    function crc32() {
+      return bufferizeInt(_crc32.apply(null, arguments));
+    }
+    crc32.signed = function() {
+      return _crc32.apply(null, arguments);
     };
-    ZipStream.prototype.finalize = function() {
-      this.finish();
+    crc32.unsigned = function() {
+      return _crc32.apply(null, arguments) >>> 0;
     };
+    var bufferCrc32 = crc32;
+    var index = /* @__PURE__ */ getDefaultExportFromCjs(bufferCrc32);
+    module2.exports = index;
   }
 });
 
-// node_modules/archiver/lib/plugins/zip.js
-var require_zip = __commonJS({
-  "node_modules/archiver/lib/plugins/zip.js"(exports2, module2) {
-    var engine = require_zip_stream();
+// node_modules/archiver/lib/plugins/json.js
+var require_json = __commonJS({
+  "node_modules/archiver/lib/plugins/json.js"(exports2, module2) {
+    var inherits = require("util").inherits;
+    var Transform = require_ours().Transform;
+    var crc32 = require_dist8();
     var util = require_archiver_utils();
-    var Zip = function(options) {
-      if (!(this instanceof Zip)) {
-        return new Zip(options);
+    var Json = function(options) {
+      if (!(this instanceof Json)) {
+        return new Json(options);
       }
-      options = this.options = util.defaults(options, {
-        comment: "",
-        forceUTC: false,
-        namePrependSlash: false,
-        store: false
-      });
+      options = this.options = util.defaults(options, {});
+      Transform.call(this, options);
       this.supports = {
         directory: true,
         symlink: true
       };
-      this.engine = new engine(options);
-    };
-    Zip.prototype.append = function(source, data, callback) {
-      this.engine.entry(source, data, callback);
+      this.files = [];
     };
-    Zip.prototype.finalize = function() {
-      this.engine.finalize();
+    inherits(Json, Transform);
+    Json.prototype._transform = function(chunk, encoding, callback) {
+      callback(null, chunk);
     };
-    Zip.prototype.on = function() {
-      return this.engine.on.apply(this.engine, arguments);
+    Json.prototype._writeStringified = function() {
+      var fileString = JSON.stringify(this.files);
+      this.write(fileString);
     };
-    Zip.prototype.pipe = function() {
-      return this.engine.pipe.apply(this.engine, arguments);
+    Json.prototype.append = function(source, data, callback) {
+      var self2 = this;
+      data.crc32 = 0;
+      function onend(err, sourceBuffer) {
+        if (err) {
+          callback(err);
+          return;
+        }
+        data.size = sourceBuffer.length || 0;
+        data.crc32 = crc32.unsigned(sourceBuffer);
+        self2.files.push(data);
+        callback(null, data);
+      }
+      if (data.sourceType === "buffer") {
+        onend(null, source);
+      } else if (data.sourceType === "stream") {
+        util.collectStream(source, onend);
+      }
     };
-    Zip.prototype.unpipe = function() {
-      return this.engine.unpipe.apply(this.engine, arguments);
+    Json.prototype.finalize = function() {
+      this._writeStringified();
+      this.end();
     };
-    module2.exports = Zip;
-  }
-});
-
-// node_modules/queue-tick/queue-microtask.js
-var require_queue_microtask = __commonJS({
-  "node_modules/queue-tick/queue-microtask.js"(exports2, module2) {
-    module2.exports = typeof queueMicrotask === "function" ? queueMicrotask : (fn) => Promise.resolve().then(fn);
-  }
-});
-
-// node_modules/queue-tick/process-next-tick.js
-var require_process_next_tick = __commonJS({
-  "node_modules/queue-tick/process-next-tick.js"(exports2, module2) {
-    module2.exports = typeof process !== "undefined" && typeof process.nextTick === "function" ? process.nextTick.bind(process) : require_queue_microtask();
+    module2.exports = Json;
   }
 });
 
-// node_modules/fast-fifo/fixed-size.js
-var require_fixed_size = __commonJS({
-  "node_modules/fast-fifo/fixed-size.js"(exports2, module2) {
-    module2.exports = class FixedFIFO {
-      constructor(hwm) {
-        if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two");
-        this.buffer = new Array(hwm);
-        this.mask = hwm - 1;
-        this.top = 0;
-        this.btm = 0;
-        this.next = null;
-      }
-      clear() {
-        this.top = this.btm = 0;
-        this.next = null;
-        this.buffer.fill(void 0);
+// node_modules/archiver/index.js
+var require_archiver = __commonJS({
+  "node_modules/archiver/index.js"(exports2, module2) {
+    var Archiver = require_core2();
+    var formats = {};
+    var vending = function(format, options) {
+      return vending.create(format, options);
+    };
+    vending.create = function(format, options) {
+      if (formats[format]) {
+        var instance = new Archiver(format, options);
+        instance.setFormat(format);
+        instance.setModule(new formats[format](options));
+        return instance;
+      } else {
+        throw new Error("create(" + format + "): format not registered");
       }
-      push(data) {
-        if (this.buffer[this.top] !== void 0) return false;
-        this.buffer[this.top] = data;
-        this.top = this.top + 1 & this.mask;
-        return true;
+    };
+    vending.registerFormat = function(format, module3) {
+      if (formats[format]) {
+        throw new Error("register(" + format + "): format already registered");
       }
-      shift() {
-        const last = this.buffer[this.btm];
-        if (last === void 0) return void 0;
-        this.buffer[this.btm] = void 0;
-        this.btm = this.btm + 1 & this.mask;
-        return last;
+      if (typeof module3 !== "function") {
+        throw new Error("register(" + format + "): format module invalid");
       }
-      peek() {
-        return this.buffer[this.btm];
+      if (typeof module3.prototype.append !== "function" || typeof module3.prototype.finalize !== "function") {
+        throw new Error("register(" + format + "): format module missing methods");
       }
-      isEmpty() {
-        return this.buffer[this.btm] === void 0;
+      formats[format] = module3;
+    };
+    vending.isRegisteredFormat = function(format) {
+      if (formats[format]) {
+        return true;
       }
+      return false;
     };
+    vending.registerFormat("zip", require_zip());
+    vending.registerFormat("tar", require_tar());
+    vending.registerFormat("json", require_json());
+    module2.exports = vending;
   }
 });
 
-// node_modules/fast-fifo/index.js
-var require_fast_fifo = __commonJS({
-  "node_modules/fast-fifo/index.js"(exports2, module2) {
-    var FixedFIFO = require_fixed_size();
-    module2.exports = class FastFIFO {
-      constructor(hwm) {
-        this.hwm = hwm || 16;
-        this.head = new FixedFIFO(this.hwm);
-        this.tail = this.head;
-        this.length = 0;
-      }
-      clear() {
-        this.head = this.tail;
-        this.head.clear();
-        this.length = 0;
+// node_modules/@actions/artifact/lib/internal/upload/zip.js
+var require_zip2 = __commonJS({
+  "node_modules/@actions/artifact/lib/internal/upload/zip.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      push(val2) {
-        this.length++;
-        if (!this.head.push(val2)) {
-          const prev = this.head;
-          this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
-          this.head.push(val2);
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
+      var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function(o2) {
+          var ar = [];
+          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
+          return ar;
+        };
+        return ownKeys(o);
+      };
+      return function(mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) {
+          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
         }
+        __setModuleDefault4(result, mod);
+        return result;
+      };
+    })();
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      shift() {
-        if (this.length !== 0) this.length--;
-        const val2 = this.tail.shift();
-        if (val2 === void 0 && this.tail.next) {
-          const next = this.tail.next;
-          this.tail.next = null;
-          this.tail = next;
-          return this.tail.shift();
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        return val2;
-      }
-      peek() {
-        const val2 = this.tail.peek();
-        if (val2 === void 0 && this.tail.next) return this.tail.next.peek();
-        return val2;
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.ZipUploadStream = exports2.DEFAULT_COMPRESSION_LEVEL = void 0;
+    exports2.createZipUploadStream = createZipUploadStream;
+    var stream = __importStar4(require("stream"));
+    var promises_1 = require("fs/promises");
+    var archiver2 = __importStar4(require_archiver());
+    var core14 = __importStar4(require_core());
+    var config_1 = require_config();
+    exports2.DEFAULT_COMPRESSION_LEVEL = 6;
+    var ZipUploadStream = class extends stream.Transform {
+      constructor(bufferSize) {
+        super({
+          highWaterMark: bufferSize
+        });
       }
-      isEmpty() {
-        return this.length === 0;
+      // eslint-disable-next-line @typescript-eslint/no-explicit-any
+      _transform(chunk, enc, cb) {
+        cb(null, chunk);
       }
     };
-  }
-});
-
-// node_modules/b4a/index.js
-var require_b4a = __commonJS({
-  "node_modules/b4a/index.js"(exports2, module2) {
-    function isBuffer(value) {
-      return Buffer.isBuffer(value) || value instanceof Uint8Array;
-    }
-    function isEncoding(encoding) {
-      return Buffer.isEncoding(encoding);
-    }
-    function alloc(size, fill2, encoding) {
-      return Buffer.alloc(size, fill2, encoding);
-    }
-    function allocUnsafe(size) {
-      return Buffer.allocUnsafe(size);
-    }
-    function allocUnsafeSlow(size) {
-      return Buffer.allocUnsafeSlow(size);
-    }
-    function byteLength(string, encoding) {
-      return Buffer.byteLength(string, encoding);
-    }
-    function compare2(a, b) {
-      return Buffer.compare(a, b);
-    }
-    function concat(buffers, totalLength) {
-      return Buffer.concat(buffers, totalLength);
-    }
-    function copy(source, target, targetStart, start, end) {
-      return toBuffer(source).copy(target, targetStart, start, end);
-    }
-    function equals(a, b) {
-      return toBuffer(a).equals(b);
-    }
-    function fill(buffer, value, offset, end, encoding) {
-      return toBuffer(buffer).fill(value, offset, end, encoding);
-    }
-    function from(value, encodingOrOffset, length) {
-      return Buffer.from(value, encodingOrOffset, length);
-    }
-    function includes(buffer, value, byteOffset, encoding) {
-      return toBuffer(buffer).includes(value, byteOffset, encoding);
-    }
-    function indexOf(buffer, value, byfeOffset, encoding) {
-      return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
-    }
-    function lastIndexOf(buffer, value, byteOffset, encoding) {
-      return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
-    }
-    function swap16(buffer) {
-      return toBuffer(buffer).swap16();
-    }
-    function swap32(buffer) {
-      return toBuffer(buffer).swap32();
-    }
-    function swap64(buffer) {
-      return toBuffer(buffer).swap64();
-    }
-    function toBuffer(buffer) {
-      if (Buffer.isBuffer(buffer)) return buffer;
-      return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
-    }
-    function toString2(buffer, encoding, start, end) {
-      return toBuffer(buffer).toString(encoding, start, end);
-    }
-    function write(buffer, string, offset, length, encoding) {
-      return toBuffer(buffer).write(string, offset, length, encoding);
-    }
-    function writeDoubleLE(buffer, value, offset) {
-      return toBuffer(buffer).writeDoubleLE(value, offset);
-    }
-    function writeFloatLE(buffer, value, offset) {
-      return toBuffer(buffer).writeFloatLE(value, offset);
-    }
-    function writeUInt32LE(buffer, value, offset) {
-      return toBuffer(buffer).writeUInt32LE(value, offset);
-    }
-    function writeInt32LE(buffer, value, offset) {
-      return toBuffer(buffer).writeInt32LE(value, offset);
-    }
-    function readDoubleLE(buffer, offset) {
-      return toBuffer(buffer).readDoubleLE(offset);
-    }
-    function readFloatLE(buffer, offset) {
-      return toBuffer(buffer).readFloatLE(offset);
-    }
-    function readUInt32LE(buffer, offset) {
-      return toBuffer(buffer).readUInt32LE(offset);
-    }
-    function readInt32LE(buffer, offset) {
-      return toBuffer(buffer).readInt32LE(offset);
-    }
-    function writeDoubleBE(buffer, value, offset) {
-      return toBuffer(buffer).writeDoubleBE(value, offset);
-    }
-    function writeFloatBE(buffer, value, offset) {
-      return toBuffer(buffer).writeFloatBE(value, offset);
-    }
-    function writeUInt32BE(buffer, value, offset) {
-      return toBuffer(buffer).writeUInt32BE(value, offset);
-    }
-    function writeInt32BE(buffer, value, offset) {
-      return toBuffer(buffer).writeInt32BE(value, offset);
-    }
-    function readDoubleBE(buffer, offset) {
-      return toBuffer(buffer).readDoubleBE(offset);
-    }
-    function readFloatBE(buffer, offset) {
-      return toBuffer(buffer).readFloatBE(offset);
-    }
-    function readUInt32BE(buffer, offset) {
-      return toBuffer(buffer).readUInt32BE(offset);
-    }
-    function readInt32BE(buffer, offset) {
-      return toBuffer(buffer).readInt32BE(offset);
+    exports2.ZipUploadStream = ZipUploadStream;
+    function createZipUploadStream(uploadSpecification_1) {
+      return __awaiter4(this, arguments, void 0, function* (uploadSpecification, compressionLevel = exports2.DEFAULT_COMPRESSION_LEVEL) {
+        core14.debug(`Creating Artifact archive with compressionLevel: ${compressionLevel}`);
+        const zip = archiver2.create("zip", {
+          highWaterMark: (0, config_1.getUploadChunkSize)(),
+          zlib: { level: compressionLevel }
+        });
+        zip.on("error", zipErrorCallback);
+        zip.on("warning", zipWarningCallback);
+        zip.on("finish", zipFinishCallback);
+        zip.on("end", zipEndCallback);
+        for (const file of uploadSpecification) {
+          if (file.sourcePath !== null) {
+            let sourcePath = file.sourcePath;
+            if (file.stats.isSymbolicLink()) {
+              sourcePath = yield (0, promises_1.realpath)(file.sourcePath);
+            }
+            zip.file(sourcePath, {
+              name: file.destinationPath
+            });
+          } else {
+            zip.append("", { name: file.destinationPath });
+          }
+        }
+        const bufferSize = (0, config_1.getUploadChunkSize)();
+        const zipUploadStream = new ZipUploadStream(bufferSize);
+        core14.debug(`Zip write high watermark value ${zipUploadStream.writableHighWaterMark}`);
+        core14.debug(`Zip read high watermark value ${zipUploadStream.readableHighWaterMark}`);
+        zip.pipe(zipUploadStream);
+        zip.finalize();
+        return zipUploadStream;
+      });
     }
-    module2.exports = {
-      isBuffer,
-      isEncoding,
-      alloc,
-      allocUnsafe,
-      allocUnsafeSlow,
-      byteLength,
-      compare: compare2,
-      concat,
-      copy,
-      equals,
-      fill,
-      from,
-      includes,
-      indexOf,
-      lastIndexOf,
-      swap16,
-      swap32,
-      swap64,
-      toBuffer,
-      toString: toString2,
-      write,
-      writeDoubleLE,
-      writeFloatLE,
-      writeUInt32LE,
-      writeInt32LE,
-      readDoubleLE,
-      readFloatLE,
-      readUInt32LE,
-      readInt32LE,
-      writeDoubleBE,
-      writeFloatBE,
-      writeUInt32BE,
-      writeInt32BE,
-      readDoubleBE,
-      readFloatBE,
-      readUInt32BE,
-      readInt32BE
+    var zipErrorCallback = (error4) => {
+      core14.error("An error has occurred while creating the zip file for upload");
+      core14.info(error4);
+      throw new Error("An error has occurred during zip creation for the artifact");
+    };
+    var zipWarningCallback = (error4) => {
+      if (error4.code === "ENOENT") {
+        core14.warning("ENOENT warning during artifact zip creation. No such file or directory");
+        core14.info(error4);
+      } else {
+        core14.warning(`A non-blocking warning has occurred during artifact zip creation: ${error4.code}`);
+        core14.info(error4);
+      }
+    };
+    var zipFinishCallback = () => {
+      core14.debug("Zip stream for upload has finished.");
+    };
+    var zipEndCallback = () => {
+      core14.debug("Zip stream for upload has ended.");
     };
   }
 });
 
-// node_modules/text-decoder/lib/pass-through-decoder.js
-var require_pass_through_decoder = __commonJS({
-  "node_modules/text-decoder/lib/pass-through-decoder.js"(exports2, module2) {
-    var b4a = require_b4a();
-    module2.exports = class PassThroughDecoder {
-      constructor(encoding) {
-        this.encoding = encoding;
-      }
-      get remaining() {
-        return 0;
-      }
-      decode(tail) {
-        return b4a.toString(tail, this.encoding);
+// node_modules/@actions/artifact/lib/internal/upload/upload-artifact.js
+var require_upload_artifact = __commonJS({
+  "node_modules/@actions/artifact/lib/internal/upload/upload-artifact.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      flush() {
-        return "";
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
+      var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function(o2) {
+          var ar = [];
+          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
+          return ar;
+        };
+        return ownKeys(o);
+      };
+      return function(mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) {
+          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
+        }
+        __setModuleDefault4(result, mod);
+        return result;
+      };
+    })();
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.uploadArtifact = uploadArtifact;
+    var core14 = __importStar4(require_core());
+    var retention_1 = require_retention();
+    var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation();
+    var artifact_twirp_client_1 = require_artifact_twirp_client2();
+    var upload_zip_specification_1 = require_upload_zip_specification();
+    var util_1 = require_util8();
+    var blob_upload_1 = require_blob_upload();
+    var zip_1 = require_zip2();
+    var generated_1 = require_generated();
+    var errors_1 = require_errors2();
+    function uploadArtifact(name, files, rootDirectory, options) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        (0, path_and_artifact_name_validation_1.validateArtifactName)(name);
+        (0, upload_zip_specification_1.validateRootDirectory)(rootDirectory);
+        const zipSpecification = (0, upload_zip_specification_1.getUploadZipSpecification)(files, rootDirectory);
+        if (zipSpecification.length === 0) {
+          throw new errors_1.FilesNotFoundError(zipSpecification.flatMap((s) => s.sourcePath ? [s.sourcePath] : []));
+        }
+        const backendIds = (0, util_1.getBackendIdsFromToken)();
+        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
+        const createArtifactReq = {
+          workflowRunBackendId: backendIds.workflowRunBackendId,
+          workflowJobRunBackendId: backendIds.workflowJobRunBackendId,
+          name,
+          version: 4
+        };
+        const expiresAt = (0, retention_1.getExpiration)(options === null || options === void 0 ? void 0 : options.retentionDays);
+        if (expiresAt) {
+          createArtifactReq.expiresAt = expiresAt;
+        }
+        const createArtifactResp = yield artifactClient.CreateArtifact(createArtifactReq);
+        if (!createArtifactResp.ok) {
+          throw new errors_1.InvalidResponseError("CreateArtifact: response from backend was not ok");
+        }
+        const zipUploadStream = yield (0, zip_1.createZipUploadStream)(zipSpecification, options === null || options === void 0 ? void 0 : options.compressionLevel);
+        const uploadResult = yield (0, blob_upload_1.uploadZipToBlobStorage)(createArtifactResp.signedUploadUrl, zipUploadStream);
+        const finalizeArtifactReq = {
+          workflowRunBackendId: backendIds.workflowRunBackendId,
+          workflowJobRunBackendId: backendIds.workflowJobRunBackendId,
+          name,
+          size: uploadResult.uploadSize ? uploadResult.uploadSize.toString() : "0"
+        };
+        if (uploadResult.sha256Hash) {
+          finalizeArtifactReq.hash = generated_1.StringValue.create({
+            value: `sha256:${uploadResult.sha256Hash}`
+          });
+        }
+        core14.info(`Finalizing artifact upload`);
+        const finalizeArtifactResp = yield artifactClient.FinalizeArtifact(finalizeArtifactReq);
+        if (!finalizeArtifactResp.ok) {
+          throw new errors_1.InvalidResponseError("FinalizeArtifact: response from backend was not ok");
+        }
+        const artifactId = BigInt(finalizeArtifactResp.artifactId);
+        core14.info(`Artifact ${name}.zip successfully finalized. Artifact ID ${artifactId}`);
+        return {
+          size: uploadResult.uploadSize,
+          digest: uploadResult.sha256Hash,
+          id: Number(artifactId)
+        };
+      });
+    }
   }
 });
 
-// node_modules/text-decoder/lib/utf8-decoder.js
-var require_utf8_decoder = __commonJS({
-  "node_modules/text-decoder/lib/utf8-decoder.js"(exports2, module2) {
-    var b4a = require_b4a();
-    module2.exports = class UTF8Decoder {
-      constructor() {
-        this.codePoint = 0;
-        this.bytesSeen = 0;
-        this.bytesNeeded = 0;
-        this.lowerBoundary = 128;
-        this.upperBoundary = 191;
+// node_modules/traverse/index.js
+var require_traverse = __commonJS({
+  "node_modules/traverse/index.js"(exports2, module2) {
+    module2.exports = Traverse;
+    function Traverse(obj) {
+      if (!(this instanceof Traverse)) return new Traverse(obj);
+      this.value = obj;
+    }
+    Traverse.prototype.get = function(ps) {
+      var node = this.value;
+      for (var i = 0; i < ps.length; i++) {
+        var key = ps[i];
+        if (!Object.hasOwnProperty.call(node, key)) {
+          node = void 0;
+          break;
+        }
+        node = node[key];
       }
-      get remaining() {
-        return this.bytesSeen;
+      return node;
+    };
+    Traverse.prototype.set = function(ps, value) {
+      var node = this.value;
+      for (var i = 0; i < ps.length - 1; i++) {
+        var key = ps[i];
+        if (!Object.hasOwnProperty.call(node, key)) node[key] = {};
+        node = node[key];
       }
-      decode(data) {
-        if (this.bytesNeeded === 0) {
-          let isBoundary = true;
-          for (let i = Math.max(0, data.byteLength - 4), n = data.byteLength; i < n && isBoundary; i++) {
-            isBoundary = data[i] <= 127;
+      node[ps[i]] = value;
+      return value;
+    };
+    Traverse.prototype.map = function(cb) {
+      return walk(this.value, cb, true);
+    };
+    Traverse.prototype.forEach = function(cb) {
+      this.value = walk(this.value, cb, false);
+      return this.value;
+    };
+    Traverse.prototype.reduce = function(cb, init) {
+      var skip = arguments.length === 1;
+      var acc = skip ? this.value : init;
+      this.forEach(function(x) {
+        if (!this.isRoot || !skip) {
+          acc = cb.call(this, acc, x);
+        }
+      });
+      return acc;
+    };
+    Traverse.prototype.deepEqual = function(obj) {
+      if (arguments.length !== 1) {
+        throw new Error(
+          "deepEqual requires exactly one object to compare against"
+        );
+      }
+      var equal = true;
+      var node = obj;
+      this.forEach(function(y) {
+        var notEqual = (function() {
+          equal = false;
+          return void 0;
+        }).bind(this);
+        if (!this.isRoot) {
+          if (typeof node !== "object") return notEqual();
+          node = node[this.key];
+        }
+        var x = node;
+        this.post(function() {
+          node = x;
+        });
+        var toS = function(o) {
+          return Object.prototype.toString.call(o);
+        };
+        if (this.circular) {
+          if (Traverse(obj).get(this.circular.path) !== x) notEqual();
+        } else if (typeof x !== typeof y) {
+          notEqual();
+        } else if (x === null || y === null || x === void 0 || y === void 0) {
+          if (x !== y) notEqual();
+        } else if (x.__proto__ !== y.__proto__) {
+          notEqual();
+        } else if (x === y) {
+        } else if (typeof x === "function") {
+          if (x instanceof RegExp) {
+            if (x.toString() != y.toString()) notEqual();
+          } else if (x !== y) notEqual();
+        } else if (typeof x === "object") {
+          if (toS(y) === "[object Arguments]" || toS(x) === "[object Arguments]") {
+            if (toS(x) !== toS(y)) {
+              notEqual();
+            }
+          } else if (x instanceof Date || y instanceof Date) {
+            if (!(x instanceof Date) || !(y instanceof Date) || x.getTime() !== y.getTime()) {
+              notEqual();
+            }
+          } else {
+            var kx = Object.keys(x);
+            var ky = Object.keys(y);
+            if (kx.length !== ky.length) return notEqual();
+            for (var i = 0; i < kx.length; i++) {
+              var k = kx[i];
+              if (!Object.hasOwnProperty.call(y, k)) {
+                notEqual();
+              }
+            }
           }
-          if (isBoundary) return b4a.toString(data, "utf8");
         }
-        let result = "";
-        for (let i = 0, n = data.byteLength; i < n; i++) {
-          const byte = data[i];
-          if (this.bytesNeeded === 0) {
-            if (byte <= 127) {
-              result += String.fromCharCode(byte);
+      });
+      return equal;
+    };
+    Traverse.prototype.paths = function() {
+      var acc = [];
+      this.forEach(function(x) {
+        acc.push(this.path);
+      });
+      return acc;
+    };
+    Traverse.prototype.nodes = function() {
+      var acc = [];
+      this.forEach(function(x) {
+        acc.push(this.node);
+      });
+      return acc;
+    };
+    Traverse.prototype.clone = function() {
+      var parents = [], nodes = [];
+      return (function clone(src) {
+        for (var i = 0; i < parents.length; i++) {
+          if (parents[i] === src) {
+            return nodes[i];
+          }
+        }
+        if (typeof src === "object" && src !== null) {
+          var dst = copy(src);
+          parents.push(src);
+          nodes.push(dst);
+          Object.keys(src).forEach(function(key) {
+            dst[key] = clone(src[key]);
+          });
+          parents.pop();
+          nodes.pop();
+          return dst;
+        } else {
+          return src;
+        }
+      })(this.value);
+    };
+    function walk(root, cb, immutable) {
+      var path2 = [];
+      var parents = [];
+      var alive = true;
+      return (function walker(node_) {
+        var node = immutable ? copy(node_) : node_;
+        var modifiers = {};
+        var state = {
+          node,
+          node_,
+          path: [].concat(path2),
+          parent: parents.slice(-1)[0],
+          key: path2.slice(-1)[0],
+          isRoot: path2.length === 0,
+          level: path2.length,
+          circular: null,
+          update: function(x) {
+            if (!state.isRoot) {
+              state.parent.node[state.key] = x;
+            }
+            state.node = x;
+          },
+          "delete": function() {
+            delete state.parent.node[state.key];
+          },
+          remove: function() {
+            if (Array.isArray(state.parent.node)) {
+              state.parent.node.splice(state.key, 1);
             } else {
-              this.bytesSeen = 1;
-              if (byte >= 194 && byte <= 223) {
-                this.bytesNeeded = 2;
-                this.codePoint = byte & 31;
-              } else if (byte >= 224 && byte <= 239) {
-                if (byte === 224) this.lowerBoundary = 160;
-                else if (byte === 237) this.upperBoundary = 159;
-                this.bytesNeeded = 3;
-                this.codePoint = byte & 15;
-              } else if (byte >= 240 && byte <= 244) {
-                if (byte === 240) this.lowerBoundary = 144;
-                if (byte === 244) this.upperBoundary = 143;
-                this.bytesNeeded = 4;
-                this.codePoint = byte & 7;
-              } else {
-                result += "\uFFFD";
-              }
+              delete state.parent.node[state.key];
             }
-            continue;
+          },
+          before: function(f) {
+            modifiers.before = f;
+          },
+          after: function(f) {
+            modifiers.after = f;
+          },
+          pre: function(f) {
+            modifiers.pre = f;
+          },
+          post: function(f) {
+            modifiers.post = f;
+          },
+          stop: function() {
+            alive = false;
           }
-          if (byte < this.lowerBoundary || byte > this.upperBoundary) {
-            this.codePoint = 0;
-            this.bytesNeeded = 0;
-            this.bytesSeen = 0;
-            this.lowerBoundary = 128;
-            this.upperBoundary = 191;
-            result += "\uFFFD";
-            continue;
+        };
+        if (!alive) return state;
+        if (typeof node === "object" && node !== null) {
+          state.isLeaf = Object.keys(node).length == 0;
+          for (var i = 0; i < parents.length; i++) {
+            if (parents[i].node_ === node_) {
+              state.circular = parents[i];
+              break;
+            }
           }
-          this.lowerBoundary = 128;
-          this.upperBoundary = 191;
-          this.codePoint = this.codePoint << 6 | byte & 63;
-          this.bytesSeen++;
-          if (this.bytesSeen !== this.bytesNeeded) continue;
-          result += String.fromCodePoint(this.codePoint);
-          this.codePoint = 0;
-          this.bytesNeeded = 0;
-          this.bytesSeen = 0;
+        } else {
+          state.isLeaf = true;
+        }
+        state.notLeaf = !state.isLeaf;
+        state.notRoot = !state.isRoot;
+        var ret = cb.call(state, state.node);
+        if (ret !== void 0 && state.update) state.update(ret);
+        if (modifiers.before) modifiers.before.call(state, state.node);
+        if (typeof state.node == "object" && state.node !== null && !state.circular) {
+          parents.push(state);
+          var keys = Object.keys(state.node);
+          keys.forEach(function(key, i2) {
+            path2.push(key);
+            if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);
+            var child = walker(state.node[key]);
+            if (immutable && Object.hasOwnProperty.call(state.node, key)) {
+              state.node[key] = child.node;
+            }
+            child.isLast = i2 == keys.length - 1;
+            child.isFirst = i2 == 0;
+            if (modifiers.post) modifiers.post.call(state, child);
+            path2.pop();
+          });
+          parents.pop();
+        }
+        if (modifiers.after) modifiers.after.call(state, state.node);
+        return state;
+      })(root).node;
+    }
+    Object.keys(Traverse.prototype).forEach(function(key) {
+      Traverse[key] = function(obj) {
+        var args = [].slice.call(arguments, 1);
+        var t = Traverse(obj);
+        return t[key].apply(t, args);
+      };
+    });
+    function copy(src) {
+      if (typeof src === "object" && src !== null) {
+        var dst;
+        if (Array.isArray(src)) {
+          dst = [];
+        } else if (src instanceof Date) {
+          dst = new Date(src);
+        } else if (src instanceof Boolean) {
+          dst = new Boolean(src);
+        } else if (src instanceof Number) {
+          dst = new Number(src);
+        } else if (src instanceof String) {
+          dst = new String(src);
+        } else {
+          dst = Object.create(Object.getPrototypeOf(src));
         }
-        return result;
-      }
-      flush() {
-        const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
-        this.codePoint = 0;
-        this.bytesNeeded = 0;
-        this.bytesSeen = 0;
-        this.lowerBoundary = 128;
-        this.upperBoundary = 191;
-        return result;
-      }
-    };
+        Object.keys(src).forEach(function(key) {
+          dst[key] = src[key];
+        });
+        return dst;
+      } else return src;
+    }
   }
 });
 
-// node_modules/text-decoder/index.js
-var require_text_decoder = __commonJS({
-  "node_modules/text-decoder/index.js"(exports2, module2) {
-    var PassThroughDecoder = require_pass_through_decoder();
-    var UTF8Decoder = require_utf8_decoder();
-    module2.exports = class TextDecoder {
-      constructor(encoding = "utf8") {
-        this.encoding = normalizeEncoding(encoding);
-        switch (this.encoding) {
-          case "utf8":
-            this.decoder = new UTF8Decoder();
-            break;
-          case "utf16le":
-          case "base64":
-            throw new Error("Unsupported encoding: " + this.encoding);
-          default:
-            this.decoder = new PassThroughDecoder(this.encoding);
+// node_modules/chainsaw/index.js
+var require_chainsaw = __commonJS({
+  "node_modules/chainsaw/index.js"(exports2, module2) {
+    var Traverse = require_traverse();
+    var EventEmitter = require("events").EventEmitter;
+    module2.exports = Chainsaw;
+    function Chainsaw(builder) {
+      var saw = Chainsaw.saw(builder, {});
+      var r = builder.call(saw.handlers, saw);
+      if (r !== void 0) saw.handlers = r;
+      saw.record();
+      return saw.chain();
+    }
+    Chainsaw.light = function ChainsawLight(builder) {
+      var saw = Chainsaw.saw(builder, {});
+      var r = builder.call(saw.handlers, saw);
+      if (r !== void 0) saw.handlers = r;
+      return saw.chain();
+    };
+    Chainsaw.saw = function(builder, handlers) {
+      var saw = new EventEmitter();
+      saw.handlers = handlers;
+      saw.actions = [];
+      saw.chain = function() {
+        var ch = Traverse(saw.handlers).map(function(node) {
+          if (this.isRoot) return node;
+          var ps = this.path;
+          if (typeof node === "function") {
+            this.update(function() {
+              saw.actions.push({
+                path: ps,
+                args: [].slice.call(arguments)
+              });
+              return ch;
+            });
+          }
+        });
+        process.nextTick(function() {
+          saw.emit("begin");
+          saw.next();
+        });
+        return ch;
+      };
+      saw.pop = function() {
+        return saw.actions.shift();
+      };
+      saw.next = function() {
+        var action = saw.pop();
+        if (!action) {
+          saw.emit("end");
+        } else if (!action.trap) {
+          var node = saw.handlers;
+          action.path.forEach(function(key) {
+            node = node[key];
+          });
+          node.apply(saw.handlers, action.args);
         }
-      }
-      get remaining() {
-        return this.decoder.remaining;
-      }
-      push(data) {
-        if (typeof data === "string") return data;
-        return this.decoder.decode(data);
-      }
-      // For Node.js compatibility
-      write(data) {
-        return this.push(data);
-      }
-      end(data) {
-        let result = "";
-        if (data) result = this.push(data);
-        result += this.decoder.flush();
-        return result;
-      }
+      };
+      saw.nest = function(cb) {
+        var args = [].slice.call(arguments, 1);
+        var autonext = true;
+        if (typeof cb === "boolean") {
+          var autonext = cb;
+          cb = args.shift();
+        }
+        var s = Chainsaw.saw(builder, {});
+        var r = builder.call(s.handlers, s);
+        if (r !== void 0) s.handlers = r;
+        if ("undefined" !== typeof saw.step) {
+          s.record();
+        }
+        cb.apply(s.chain(), args);
+        if (autonext !== false) s.on("end", saw.next);
+      };
+      saw.record = function() {
+        upgradeChainsaw(saw);
+      };
+      ["trap", "down", "jump"].forEach(function(method) {
+        saw[method] = function() {
+          throw new Error("To use the trap, down and jump features, please call record() first to start recording actions.");
+        };
+      });
+      return saw;
     };
-    function normalizeEncoding(encoding) {
-      encoding = encoding.toLowerCase();
-      switch (encoding) {
-        case "utf8":
-        case "utf-8":
-          return "utf8";
-        case "ucs2":
-        case "ucs-2":
-        case "utf16le":
-        case "utf-16le":
-          return "utf16le";
-        case "latin1":
-        case "binary":
-          return "latin1";
-        case "base64":
-        case "ascii":
-        case "hex":
-          return encoding;
-        default:
-          throw new Error("Unknown encoding: " + encoding);
-      }
+    function upgradeChainsaw(saw) {
+      saw.step = 0;
+      saw.pop = function() {
+        return saw.actions[saw.step++];
+      };
+      saw.trap = function(name, cb) {
+        var ps = Array.isArray(name) ? name : [name];
+        saw.actions.push({
+          path: ps,
+          step: saw.step,
+          cb,
+          trap: true
+        });
+      };
+      saw.down = function(name) {
+        var ps = (Array.isArray(name) ? name : [name]).join("/");
+        var i = saw.actions.slice(saw.step).map(function(x) {
+          if (x.trap && x.step <= saw.step) return false;
+          return x.path.join("/") == ps;
+        }).indexOf(true);
+        if (i >= 0) saw.step += i;
+        else saw.step = saw.actions.length;
+        var act = saw.actions[saw.step - 1];
+        if (act && act.trap) {
+          saw.step = act.step;
+          act.cb();
+        } else saw.next();
+      };
+      saw.jump = function(step) {
+        saw.step = step;
+        saw.next();
+      };
     }
   }
 });
 
-// node_modules/streamx/index.js
-var require_streamx = __commonJS({
-  "node_modules/streamx/index.js"(exports2, module2) {
-    var { EventEmitter } = require("events");
-    var STREAM_DESTROYED = new Error("Stream was destroyed");
-    var PREMATURE_CLOSE = new Error("Premature close");
-    var queueTick = require_process_next_tick();
-    var FIFO = require_fast_fifo();
-    var TextDecoder2 = require_text_decoder();
-    var MAX = (1 << 29) - 1;
-    var OPENING = 1;
-    var PREDESTROYING = 2;
-    var DESTROYING = 4;
-    var DESTROYED = 8;
-    var NOT_OPENING = MAX ^ OPENING;
-    var NOT_PREDESTROYING = MAX ^ PREDESTROYING;
-    var READ_ACTIVE = 1 << 4;
-    var READ_UPDATING = 2 << 4;
-    var READ_PRIMARY = 4 << 4;
-    var READ_QUEUED = 8 << 4;
-    var READ_RESUMED = 16 << 4;
-    var READ_PIPE_DRAINED = 32 << 4;
-    var READ_ENDING = 64 << 4;
-    var READ_EMIT_DATA = 128 << 4;
-    var READ_EMIT_READABLE = 256 << 4;
-    var READ_EMITTED_READABLE = 512 << 4;
-    var READ_DONE = 1024 << 4;
-    var READ_NEXT_TICK = 2048 << 4;
-    var READ_NEEDS_PUSH = 4096 << 4;
-    var READ_READ_AHEAD = 8192 << 4;
-    var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED;
-    var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH;
-    var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE;
-    var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED;
-    var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD;
-    var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE;
-    var READ_NON_PRIMARY = MAX ^ READ_PRIMARY;
-    var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH);
-    var READ_PUSHED = MAX ^ READ_NEEDS_PUSH;
-    var READ_PAUSED = MAX ^ READ_RESUMED;
-    var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE);
-    var READ_NOT_ENDING = MAX ^ READ_ENDING;
-    var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING;
-    var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK;
-    var READ_NOT_UPDATING = MAX ^ READ_UPDATING;
-    var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD;
-    var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD;
-    var WRITE_ACTIVE = 1 << 18;
-    var WRITE_UPDATING = 2 << 18;
-    var WRITE_PRIMARY = 4 << 18;
-    var WRITE_QUEUED = 8 << 18;
-    var WRITE_UNDRAINED = 16 << 18;
-    var WRITE_DONE = 32 << 18;
-    var WRITE_EMIT_DRAIN = 64 << 18;
-    var WRITE_NEXT_TICK = 128 << 18;
-    var WRITE_WRITING = 256 << 18;
-    var WRITE_FINISHING = 512 << 18;
-    var WRITE_CORKED = 1024 << 18;
-    var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING);
-    var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY;
-    var WRITE_NOT_FINISHING = MAX ^ WRITE_FINISHING;
-    var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED;
-    var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED;
-    var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK;
-    var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING;
-    var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED;
-    var ACTIVE = READ_ACTIVE | WRITE_ACTIVE;
-    var NOT_ACTIVE = MAX ^ ACTIVE;
-    var DONE = READ_DONE | WRITE_DONE;
-    var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING;
-    var OPEN_STATUS = DESTROY_STATUS | OPENING;
-    var AUTO_DESTROY = DESTROY_STATUS | DONE;
-    var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY;
-    var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK;
-    var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE;
-    var IS_OPENING = OPEN_STATUS | TICKING;
-    var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE;
-    var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED;
-    var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED;
-    var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE;
-    var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD;
-    var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE;
-    var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY;
-    var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE;
-    var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED;
-    var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE;
-    var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE;
-    var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED;
-    var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE;
-    var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING;
-    var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE;
-    var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE;
-    var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY;
-    var asyncIterator = Symbol.asyncIterator || Symbol("asyncIterator");
-    var WritableState = class {
-      constructor(stream, { highWaterMark = 16384, map: map2 = null, mapWritable, byteLength, byteLengthWritable } = {}) {
-        this.stream = stream;
-        this.queue = new FIFO();
-        this.highWaterMark = highWaterMark;
-        this.buffered = 0;
-        this.error = null;
-        this.pipeline = null;
-        this.drains = null;
-        this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
-        this.map = mapWritable || map2;
-        this.afterWrite = afterWrite.bind(this);
-        this.afterUpdateNextTick = updateWriteNT.bind(this);
+// node_modules/buffers/index.js
+var require_buffers = __commonJS({
+  "node_modules/buffers/index.js"(exports2, module2) {
+    module2.exports = Buffers;
+    function Buffers(bufs) {
+      if (!(this instanceof Buffers)) return new Buffers(bufs);
+      this.buffers = bufs || [];
+      this.length = this.buffers.reduce(function(size, buf) {
+        return size + buf.length;
+      }, 0);
+    }
+    Buffers.prototype.push = function() {
+      for (var i = 0; i < arguments.length; i++) {
+        if (!Buffer.isBuffer(arguments[i])) {
+          throw new TypeError("Tried to push a non-buffer");
+        }
       }
-      get ended() {
-        return (this.stream._duplexState & WRITE_DONE) !== 0;
+      for (var i = 0; i < arguments.length; i++) {
+        var buf = arguments[i];
+        this.buffers.push(buf);
+        this.length += buf.length;
       }
-      push(data) {
-        if (this.map !== null) data = this.map(data);
-        this.buffered += this.byteLength(data);
-        this.queue.push(data);
-        if (this.buffered < this.highWaterMark) {
-          this.stream._duplexState |= WRITE_QUEUED;
-          return true;
+      return this.length;
+    };
+    Buffers.prototype.unshift = function() {
+      for (var i = 0; i < arguments.length; i++) {
+        if (!Buffer.isBuffer(arguments[i])) {
+          throw new TypeError("Tried to unshift a non-buffer");
         }
-        this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
-        return false;
       }
-      shift() {
-        const data = this.queue.shift();
-        this.buffered -= this.byteLength(data);
-        if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
-        return data;
+      for (var i = 0; i < arguments.length; i++) {
+        var buf = arguments[i];
+        this.buffers.unshift(buf);
+        this.length += buf.length;
       }
-      end(data) {
-        if (typeof data === "function") this.stream.once("finish", data);
-        else if (data !== void 0 && data !== null) this.push(data);
-        this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
+      return this.length;
+    };
+    Buffers.prototype.copy = function(dst, dStart, start, end) {
+      return this.slice(start, end).copy(dst, dStart, 0, end - start);
+    };
+    Buffers.prototype.splice = function(i, howMany) {
+      var buffers = this.buffers;
+      var index = i >= 0 ? i : this.length - i;
+      var reps = [].slice.call(arguments, 2);
+      if (howMany === void 0) {
+        howMany = this.length - index;
+      } else if (howMany > this.length - index) {
+        howMany = this.length - index;
       }
-      autoBatch(data, cb) {
-        const buffer = [];
-        const stream = this.stream;
-        buffer.push(data);
-        while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
-          buffer.push(stream._writableState.shift());
-        }
-        if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
-        stream._writev(buffer, cb);
+      for (var i = 0; i < reps.length; i++) {
+        this.length += reps[i].length;
       }
-      update() {
-        const stream = this.stream;
-        stream._duplexState |= WRITE_UPDATING;
-        do {
-          while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
-            const data = this.shift();
-            stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
-            stream._write(data, this.afterWrite);
-          }
-          if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
-        } while (this.continueUpdate() === true);
-        stream._duplexState &= WRITE_NOT_UPDATING;
+      var removed = new Buffers();
+      var bytes = 0;
+      var startBytes = 0;
+      for (var ii = 0; ii < buffers.length && startBytes + buffers[ii].length < index; ii++) {
+        startBytes += buffers[ii].length;
       }
-      updateNonPrimary() {
-        const stream = this.stream;
-        if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
-          stream._duplexState = (stream._duplexState | WRITE_ACTIVE) & WRITE_NOT_FINISHING;
-          stream._final(afterFinal.bind(this));
-          return;
-        }
-        if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
-          if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
-            stream._duplexState |= ACTIVE;
-            stream._destroy(afterDestroy.bind(this));
+      if (index - startBytes > 0) {
+        var start = index - startBytes;
+        if (start + howMany < buffers[ii].length) {
+          removed.push(buffers[ii].slice(start, start + howMany));
+          var orig = buffers[ii];
+          var buf0 = new Buffer(start);
+          for (var i = 0; i < start; i++) {
+            buf0[i] = orig[i];
           }
-          return;
-        }
-        if ((stream._duplexState & IS_OPENING) === OPENING) {
-          stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
-          stream._open(afterOpen.bind(this));
+          var buf1 = new Buffer(orig.length - start - howMany);
+          for (var i = start + howMany; i < orig.length; i++) {
+            buf1[i - howMany - start] = orig[i];
+          }
+          if (reps.length > 0) {
+            var reps_ = reps.slice();
+            reps_.unshift(buf0);
+            reps_.push(buf1);
+            buffers.splice.apply(buffers, [ii, 1].concat(reps_));
+            ii += reps_.length;
+            reps = [];
+          } else {
+            buffers.splice(ii, 1, buf0, buf1);
+            ii += 2;
+          }
+        } else {
+          removed.push(buffers[ii].slice(start));
+          buffers[ii] = buffers[ii].slice(0, start);
+          ii++;
         }
       }
-      continueUpdate() {
-        if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
-        this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
-        return true;
-      }
-      updateCallback() {
-        if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update();
-        else this.updateNextTick();
+      if (reps.length > 0) {
+        buffers.splice.apply(buffers, [ii, 0].concat(reps));
+        ii += reps.length;
       }
-      updateNextTick() {
-        if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
-        this.stream._duplexState |= WRITE_NEXT_TICK;
-        if ((this.stream._duplexState & WRITE_UPDATING) === 0) queueTick(this.afterUpdateNextTick);
+      while (removed.length < howMany) {
+        var buf = buffers[ii];
+        var len = buf.length;
+        var take = Math.min(len, howMany - removed.length);
+        if (take === len) {
+          removed.push(buf);
+          buffers.splice(ii, 1);
+        } else {
+          removed.push(buf.slice(0, take));
+          buffers[ii] = buffers[ii].slice(take);
+        }
       }
+      this.length -= removed.length;
+      return removed;
     };
-    var ReadableState = class {
-      constructor(stream, { highWaterMark = 16384, map: map2 = null, mapReadable, byteLength, byteLengthReadable } = {}) {
-        this.stream = stream;
-        this.queue = new FIFO();
-        this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
-        this.buffered = 0;
-        this.readAhead = highWaterMark > 0;
-        this.error = null;
-        this.pipeline = null;
-        this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
-        this.map = mapReadable || map2;
-        this.pipeTo = null;
-        this.afterRead = afterRead.bind(this);
-        this.afterUpdateNextTick = updateReadNT.bind(this);
-      }
-      get ended() {
-        return (this.stream._duplexState & READ_DONE) !== 0;
+    Buffers.prototype.slice = function(i, j) {
+      var buffers = this.buffers;
+      if (j === void 0) j = this.length;
+      if (i === void 0) i = 0;
+      if (j > this.length) j = this.length;
+      var startBytes = 0;
+      for (var si = 0; si < buffers.length && startBytes + buffers[si].length <= i; si++) {
+        startBytes += buffers[si].length;
       }
-      pipe(pipeTo, cb) {
-        if (this.pipeTo !== null) throw new Error("Can only pipe to one destination");
-        if (typeof cb !== "function") cb = null;
-        this.stream._duplexState |= READ_PIPE_DRAINED;
-        this.pipeTo = pipeTo;
-        this.pipeline = new Pipeline(this.stream, pipeTo, cb);
-        if (cb) this.stream.on("error", noop);
-        if (isStreamx(pipeTo)) {
-          pipeTo._writableState.pipeline = this.pipeline;
-          if (cb) pipeTo.on("error", noop);
-          pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
-        } else {
-          const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
-          const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
-          pipeTo.on("error", onerror);
-          pipeTo.on("close", onclose);
-          pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
-        }
-        pipeTo.on("drain", afterDrain.bind(this));
-        this.stream.emit("piping", pipeTo);
-        pipeTo.emit("pipe", this.stream);
+      var target = new Buffer(j - i);
+      var ti = 0;
+      for (var ii = si; ti < j - i && ii < buffers.length; ii++) {
+        var len = buffers[ii].length;
+        var start = ti === 0 ? i - startBytes : 0;
+        var end = ti + len >= j - i ? Math.min(start + (j - i) - ti, len) : len;
+        buffers[ii].copy(target, ti, start, end);
+        ti += end - start;
       }
-      push(data) {
-        const stream = this.stream;
-        if (data === null) {
-          this.highWaterMark = 0;
-          stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
-          return false;
-        }
-        if (this.map !== null) {
-          data = this.map(data);
-          if (data === null) {
-            stream._duplexState &= READ_PUSHED;
-            return this.buffered < this.highWaterMark;
-          }
+      return target;
+    };
+    Buffers.prototype.pos = function(i) {
+      if (i < 0 || i >= this.length) throw new Error("oob");
+      var l = i, bi = 0, bu = null;
+      for (; ; ) {
+        bu = this.buffers[bi];
+        if (l < bu.length) {
+          return { buf: bi, offset: l };
+        } else {
+          l -= bu.length;
         }
-        this.buffered += this.byteLength(data);
-        this.queue.push(data);
-        stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
-        return this.buffered < this.highWaterMark;
+        bi++;
       }
-      shift() {
-        const data = this.queue.shift();
-        this.buffered -= this.byteLength(data);
-        if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED;
-        return data;
+    };
+    Buffers.prototype.get = function get(i) {
+      var pos = this.pos(i);
+      return this.buffers[pos.buf].get(pos.offset);
+    };
+    Buffers.prototype.set = function set2(i, b) {
+      var pos = this.pos(i);
+      return this.buffers[pos.buf].set(pos.offset, b);
+    };
+    Buffers.prototype.indexOf = function(needle, offset) {
+      if ("string" === typeof needle) {
+        needle = new Buffer(needle);
+      } else if (needle instanceof Buffer) {
+      } else {
+        throw new Error("Invalid type for a search string");
       }
-      unshift(data) {
-        const pending = [this.map !== null ? this.map(data) : data];
-        while (this.buffered > 0) pending.push(this.shift());
-        for (let i = 0; i < pending.length - 1; i++) {
-          const data2 = pending[i];
-          this.buffered += this.byteLength(data2);
-          this.queue.push(data2);
-        }
-        this.push(pending[pending.length - 1]);
+      if (!needle.length) {
+        return 0;
       }
-      read() {
-        const stream = this.stream;
-        if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
-          const data = this.shift();
-          if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
-          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
-          return data;
-        }
-        if (this.readAhead === false) {
-          stream._duplexState |= READ_READ_AHEAD;
-          this.updateNextTick();
-        }
-        return null;
+      if (!this.length) {
+        return -1;
       }
-      drain() {
-        const stream = this.stream;
-        while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
-          const data = this.shift();
-          if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
-          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
-        }
+      var i = 0, j = 0, match = 0, mstart, pos = 0;
+      if (offset) {
+        var p = this.pos(offset);
+        i = p.buf;
+        j = p.offset;
+        pos = offset;
       }
-      update() {
-        const stream = this.stream;
-        stream._duplexState |= READ_UPDATING;
-        do {
-          this.drain();
-          while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
-            stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
-            stream._read(this.afterRead);
-            this.drain();
-          }
-          if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
-            stream._duplexState |= READ_EMITTED_READABLE;
-            stream.emit("readable");
+      for (; ; ) {
+        while (j >= this.buffers[i].length) {
+          j = 0;
+          i++;
+          if (i >= this.buffers.length) {
+            return -1;
           }
-          if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
-        } while (this.continueUpdate() === true);
-        stream._duplexState &= READ_NOT_UPDATING;
-      }
-      updateNonPrimary() {
-        const stream = this.stream;
-        if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
-          stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
-          stream.emit("end");
-          if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING;
-          if (this.pipeTo !== null) this.pipeTo.end();
         }
-        if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
-          if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
-            stream._duplexState |= ACTIVE;
-            stream._destroy(afterDestroy.bind(this));
+        var char = this.buffers[i][j];
+        if (char == needle[match]) {
+          if (match == 0) {
+            mstart = {
+              i,
+              j,
+              pos
+            };
           }
-          return;
-        }
-        if ((stream._duplexState & IS_OPENING) === OPENING) {
-          stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
-          stream._open(afterOpen.bind(this));
+          match++;
+          if (match == needle.length) {
+            return mstart.pos;
+          }
+        } else if (match != 0) {
+          i = mstart.i;
+          j = mstart.j;
+          pos = mstart.pos;
+          match = 0;
         }
-      }
-      continueUpdate() {
-        if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
-        this.stream._duplexState &= READ_NOT_NEXT_TICK;
-        return true;
-      }
-      updateCallback() {
-        if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update();
-        else this.updateNextTick();
-      }
-      updateNextTick() {
-        if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return;
-        this.stream._duplexState |= READ_NEXT_TICK;
-        if ((this.stream._duplexState & READ_UPDATING) === 0) queueTick(this.afterUpdateNextTick);
+        j++;
+        pos++;
       }
     };
-    var TransformState = class {
-      constructor(stream) {
-        this.data = null;
-        this.afterTransform = afterTransform.bind(stream);
-        this.afterFinal = null;
+    Buffers.prototype.toBuffer = function() {
+      return this.slice();
+    };
+    Buffers.prototype.toString = function(encoding, start, end) {
+      return this.slice(start, end).toString(encoding);
+    };
+  }
+});
+
+// node_modules/binary/lib/vars.js
+var require_vars = __commonJS({
+  "node_modules/binary/lib/vars.js"(exports2, module2) {
+    module2.exports = function(store) {
+      function getset(name, value) {
+        var node = vars.store;
+        var keys = name.split(".");
+        keys.slice(0, -1).forEach(function(k) {
+          if (node[k] === void 0) node[k] = {};
+          node = node[k];
+        });
+        var key = keys[keys.length - 1];
+        if (arguments.length == 1) {
+          return node[key];
+        } else {
+          return node[key] = value;
+        }
       }
+      var vars = {
+        get: function(name) {
+          return getset(name);
+        },
+        set: function(name, value) {
+          return getset(name, value);
+        },
+        store: store || {}
+      };
+      return vars;
     };
-    var Pipeline = class {
-      constructor(src, dst, cb) {
-        this.from = src;
-        this.to = dst;
-        this.afterPipe = cb;
-        this.error = null;
-        this.pipeToFinished = false;
+  }
+});
+
+// node_modules/binary/index.js
+var require_binary = __commonJS({
+  "node_modules/binary/index.js"(exports2, module2) {
+    var Chainsaw = require_chainsaw();
+    var EventEmitter = require("events").EventEmitter;
+    var Buffers = require_buffers();
+    var Vars = require_vars();
+    var Stream = require("stream").Stream;
+    exports2 = module2.exports = function(bufOrEm, eventName) {
+      if (Buffer.isBuffer(bufOrEm)) {
+        return exports2.parse(bufOrEm);
       }
-      finished() {
-        this.pipeToFinished = true;
+      var s = exports2.stream();
+      if (bufOrEm && bufOrEm.pipe) {
+        bufOrEm.pipe(s);
+      } else if (bufOrEm) {
+        bufOrEm.on(eventName || "data", function(buf) {
+          s.write(buf);
+        });
+        bufOrEm.on("end", function() {
+          s.end();
+        });
       }
-      done(stream, err) {
-        if (err) this.error = err;
-        if (stream === this.to) {
-          this.to = null;
-          if (this.from !== null) {
-            if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
-              this.from.destroy(this.error || new Error("Writable stream closed prematurely"));
+      return s;
+    };
+    exports2.stream = function(input) {
+      if (input) return exports2.apply(null, arguments);
+      var pending = null;
+      function getBytes(bytes, cb, skip) {
+        pending = {
+          bytes,
+          skip,
+          cb: function(buf) {
+            pending = null;
+            cb(buf);
+          }
+        };
+        dispatch();
+      }
+      var offset = null;
+      function dispatch() {
+        if (!pending) {
+          if (caughtEnd) done = true;
+          return;
+        }
+        if (typeof pending === "function") {
+          pending();
+        } else {
+          var bytes = offset + pending.bytes;
+          if (buffers.length >= bytes) {
+            var buf;
+            if (offset == null) {
+              buf = buffers.splice(0, bytes);
+              if (!pending.skip) {
+                buf = buf.slice();
+              }
+            } else {
+              if (!pending.skip) {
+                buf = buffers.slice(offset, bytes);
+              }
+              offset = bytes;
+            }
+            if (pending.skip) {
+              pending.cb();
+            } else {
+              pending.cb(buf);
             }
-            return;
           }
         }
-        if (stream === this.from) {
-          this.from = null;
-          if (this.to !== null) {
-            if ((stream._duplexState & READ_DONE) === 0) {
-              this.to.destroy(this.error || new Error("Readable stream closed before ending"));
+      }
+      function builder(saw) {
+        function next() {
+          if (!done) saw.next();
+        }
+        var self2 = words(function(bytes, cb) {
+          return function(name) {
+            getBytes(bytes, function(buf) {
+              vars.set(name, cb(buf));
+              next();
+            });
+          };
+        });
+        self2.tap = function(cb) {
+          saw.nest(cb, vars.store);
+        };
+        self2.into = function(key, cb) {
+          if (!vars.get(key)) vars.set(key, {});
+          var parent = vars;
+          vars = Vars(parent.get(key));
+          saw.nest(function() {
+            cb.apply(this, arguments);
+            this.tap(function() {
+              vars = parent;
+            });
+          }, vars.store);
+        };
+        self2.flush = function() {
+          vars.store = {};
+          next();
+        };
+        self2.loop = function(cb) {
+          var end = false;
+          saw.nest(false, function loop() {
+            this.vars = vars.store;
+            cb.call(this, function() {
+              end = true;
+              next();
+            }, vars.store);
+            this.tap(function() {
+              if (end) saw.next();
+              else loop.call(this);
+            }.bind(this));
+          }, vars.store);
+        };
+        self2.buffer = function(name, bytes) {
+          if (typeof bytes === "string") {
+            bytes = vars.get(bytes);
+          }
+          getBytes(bytes, function(buf) {
+            vars.set(name, buf);
+            next();
+          });
+        };
+        self2.skip = function(bytes) {
+          if (typeof bytes === "string") {
+            bytes = vars.get(bytes);
+          }
+          getBytes(bytes, function() {
+            next();
+          });
+        };
+        self2.scan = function find2(name, search) {
+          if (typeof search === "string") {
+            search = new Buffer(search);
+          } else if (!Buffer.isBuffer(search)) {
+            throw new Error("search must be a Buffer or a string");
+          }
+          var taken = 0;
+          pending = function() {
+            var pos = buffers.indexOf(search, offset + taken);
+            var i = pos - offset - taken;
+            if (pos !== -1) {
+              pending = null;
+              if (offset != null) {
+                vars.set(
+                  name,
+                  buffers.slice(offset, offset + taken + i)
+                );
+                offset += taken + i + search.length;
+              } else {
+                vars.set(
+                  name,
+                  buffers.slice(0, taken + i)
+                );
+                buffers.splice(0, taken + i + search.length);
+              }
+              next();
+              dispatch();
+            } else {
+              i = Math.max(buffers.length - search.length - offset - taken, 0);
             }
-            return;
+            taken += i;
+          };
+          dispatch();
+        };
+        self2.peek = function(cb) {
+          offset = 0;
+          saw.nest(function() {
+            cb.call(this, vars.store);
+            this.tap(function() {
+              offset = null;
+            });
+          });
+        };
+        return self2;
+      }
+      ;
+      var stream = Chainsaw.light(builder);
+      stream.writable = true;
+      var buffers = Buffers();
+      stream.write = function(buf) {
+        buffers.push(buf);
+        dispatch();
+      };
+      var vars = Vars();
+      var done = false, caughtEnd = false;
+      stream.end = function() {
+        caughtEnd = true;
+      };
+      stream.pipe = Stream.prototype.pipe;
+      Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function(name) {
+        stream[name] = EventEmitter.prototype[name];
+      });
+      return stream;
+    };
+    exports2.parse = function parse(buffer) {
+      var self2 = words(function(bytes, cb) {
+        return function(name) {
+          if (offset + bytes <= buffer.length) {
+            var buf = buffer.slice(offset, offset + bytes);
+            offset += bytes;
+            vars.set(name, cb(buf));
+          } else {
+            vars.set(name, null);
           }
+          return self2;
+        };
+      });
+      var offset = 0;
+      var vars = Vars();
+      self2.vars = vars.store;
+      self2.tap = function(cb) {
+        cb.call(self2, vars.store);
+        return self2;
+      };
+      self2.into = function(key, cb) {
+        if (!vars.get(key)) {
+          vars.set(key, {});
         }
-        if (this.afterPipe !== null) this.afterPipe(this.error);
-        this.to = this.from = this.afterPipe = null;
+        var parent = vars;
+        vars = Vars(parent.get(key));
+        cb.call(self2, vars.store);
+        vars = parent;
+        return self2;
+      };
+      self2.loop = function(cb) {
+        var end = false;
+        var ender = function() {
+          end = true;
+        };
+        while (end === false) {
+          cb.call(self2, ender, vars.store);
+        }
+        return self2;
+      };
+      self2.buffer = function(name, size) {
+        if (typeof size === "string") {
+          size = vars.get(size);
+        }
+        var buf = buffer.slice(offset, Math.min(buffer.length, offset + size));
+        offset += size;
+        vars.set(name, buf);
+        return self2;
+      };
+      self2.skip = function(bytes) {
+        if (typeof bytes === "string") {
+          bytes = vars.get(bytes);
+        }
+        offset += bytes;
+        return self2;
+      };
+      self2.scan = function(name, search) {
+        if (typeof search === "string") {
+          search = new Buffer(search);
+        } else if (!Buffer.isBuffer(search)) {
+          throw new Error("search must be a Buffer or a string");
+        }
+        vars.set(name, null);
+        for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) {
+          for (var j = 0; j < search.length && buffer[offset + i + j] === search[j]; j++) ;
+          if (j === search.length) break;
+        }
+        vars.set(name, buffer.slice(offset, offset + i));
+        offset += i + search.length;
+        return self2;
+      };
+      self2.peek = function(cb) {
+        var was = offset;
+        cb.call(self2, vars.store);
+        offset = was;
+        return self2;
+      };
+      self2.flush = function() {
+        vars.store = {};
+        return self2;
+      };
+      self2.eof = function() {
+        return offset >= buffer.length;
+      };
+      return self2;
+    };
+    function decodeLEu(bytes) {
+      var acc = 0;
+      for (var i = 0; i < bytes.length; i++) {
+        acc += Math.pow(256, i) * bytes[i];
       }
-    };
-    function afterDrain() {
-      this.stream._duplexState |= READ_PIPE_DRAINED;
-      this.updateCallback();
+      return acc;
     }
-    function afterFinal(err) {
-      const stream = this.stream;
-      if (err) stream.destroy(err);
-      if ((stream._duplexState & DESTROY_STATUS) === 0) {
-        stream._duplexState |= WRITE_DONE;
-        stream.emit("finish");
-      }
-      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
-        stream._duplexState |= DESTROYING;
+    function decodeBEu(bytes) {
+      var acc = 0;
+      for (var i = 0; i < bytes.length; i++) {
+        acc += Math.pow(256, bytes.length - i - 1) * bytes[i];
       }
-      stream._duplexState &= WRITE_NOT_ACTIVE;
-      if ((stream._duplexState & WRITE_UPDATING) === 0) this.update();
-      else this.updateNextTick();
+      return acc;
     }
-    function afterDestroy(err) {
-      const stream = this.stream;
-      if (!err && this.error !== STREAM_DESTROYED) err = this.error;
-      if (err) stream.emit("error", err);
-      stream._duplexState |= DESTROYED;
-      stream.emit("close");
-      const rs = stream._readableState;
-      const ws = stream._writableState;
-      if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err);
-      if (ws !== null) {
-        while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false);
-        if (ws.pipeline !== null) ws.pipeline.done(stream, err);
+    function decodeBEs(bytes) {
+      var val2 = decodeBEu(bytes);
+      if ((bytes[0] & 128) == 128) {
+        val2 -= Math.pow(256, bytes.length);
       }
+      return val2;
     }
-    function afterWrite(err) {
-      const stream = this.stream;
-      if (err) stream.destroy(err);
-      stream._duplexState &= WRITE_NOT_ACTIVE;
-      if (this.drains !== null) tickDrains(this.drains);
-      if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
-        stream._duplexState &= WRITE_DRAINED;
-        if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
-          stream.emit("drain");
-        }
+    function decodeLEs(bytes) {
+      var val2 = decodeLEu(bytes);
+      if ((bytes[bytes.length - 1] & 128) == 128) {
+        val2 -= Math.pow(256, bytes.length);
       }
-      this.updateCallback();
+      return val2;
     }
-    function afterRead(err) {
-      if (err) this.stream.destroy(err);
-      this.stream._duplexState &= READ_NOT_ACTIVE;
-      if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) this.stream._duplexState &= READ_NO_READ_AHEAD;
-      this.updateCallback();
+    function words(decode) {
+      var self2 = {};
+      [1, 2, 4, 8].forEach(function(bytes) {
+        var bits = bytes * 8;
+        self2["word" + bits + "le"] = self2["word" + bits + "lu"] = decode(bytes, decodeLEu);
+        self2["word" + bits + "ls"] = decode(bytes, decodeLEs);
+        self2["word" + bits + "be"] = self2["word" + bits + "bu"] = decode(bytes, decodeBEu);
+        self2["word" + bits + "bs"] = decode(bytes, decodeBEs);
+      });
+      self2.word8 = self2.word8u = self2.word8be;
+      self2.word8s = self2.word8bs;
+      return self2;
     }
-    function updateReadNT() {
-      if ((this.stream._duplexState & READ_UPDATING) === 0) {
-        this.stream._duplexState &= READ_NOT_NEXT_TICK;
-        this.update();
+  }
+});
+
+// node_modules/unzip-stream/lib/matcher-stream.js
+var require_matcher_stream = __commonJS({
+  "node_modules/unzip-stream/lib/matcher-stream.js"(exports2, module2) {
+    var Transform = require("stream").Transform;
+    var util = require("util");
+    function MatcherStream(patternDesc, matchFn) {
+      if (!(this instanceof MatcherStream)) {
+        return new MatcherStream();
       }
+      Transform.call(this);
+      var p = typeof patternDesc === "object" ? patternDesc.pattern : patternDesc;
+      this.pattern = Buffer.isBuffer(p) ? p : Buffer.from(p);
+      this.requiredLength = this.pattern.length;
+      if (patternDesc.requiredExtraSize) this.requiredLength += patternDesc.requiredExtraSize;
+      this.data = new Buffer("");
+      this.bytesSoFar = 0;
+      this.matchFn = matchFn;
     }
-    function updateWriteNT() {
-      if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
-        this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
-        this.update();
+    util.inherits(MatcherStream, Transform);
+    MatcherStream.prototype.checkDataChunk = function(ignoreMatchZero) {
+      var enoughData = this.data.length >= this.requiredLength;
+      if (!enoughData) {
+        return;
       }
-    }
-    function tickDrains(drains) {
-      for (let i = 0; i < drains.length; i++) {
-        if (--drains[i].writes === 0) {
-          drains.shift().resolve(true);
-          i--;
+      var matchIndex = this.data.indexOf(this.pattern, ignoreMatchZero ? 1 : 0);
+      if (matchIndex >= 0 && matchIndex + this.requiredLength > this.data.length) {
+        if (matchIndex > 0) {
+          var packet = this.data.slice(0, matchIndex);
+          this.push(packet);
+          this.bytesSoFar += matchIndex;
+          this.data = this.data.slice(matchIndex);
         }
+        return;
       }
-    }
-    function afterOpen(err) {
-      const stream = this.stream;
-      if (err) stream.destroy(err);
-      if ((stream._duplexState & DESTROYING) === 0) {
-        if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY;
-        if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY;
-        stream.emit("open");
-      }
-      stream._duplexState &= NOT_ACTIVE;
-      if (stream._writableState !== null) {
-        stream._writableState.updateCallback();
+      if (matchIndex === -1) {
+        var packetLen = this.data.length - this.requiredLength + 1;
+        var packet = this.data.slice(0, packetLen);
+        this.push(packet);
+        this.bytesSoFar += packetLen;
+        this.data = this.data.slice(packetLen);
+        return;
       }
-      if (stream._readableState !== null) {
-        stream._readableState.updateCallback();
+      if (matchIndex > 0) {
+        var packet = this.data.slice(0, matchIndex);
+        this.data = this.data.slice(matchIndex);
+        this.push(packet);
+        this.bytesSoFar += matchIndex;
       }
-    }
-    function afterTransform(err, data) {
-      if (data !== void 0 && data !== null) this.push(data);
-      this._writableState.afterWrite(err);
-    }
-    function newListener(name) {
-      if (this._readableState !== null) {
-        if (name === "data") {
-          this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
-          this._readableState.updateNextTick();
-        }
-        if (name === "readable") {
-          this._duplexState |= READ_EMIT_READABLE;
-          this._readableState.updateNextTick();
-        }
+      var finished = this.matchFn ? this.matchFn(this.data, this.bytesSoFar) : true;
+      if (finished) {
+        this.data = new Buffer("");
+        return;
       }
-      if (this._writableState !== null) {
-        if (name === "drain") {
-          this._duplexState |= WRITE_EMIT_DRAIN;
-          this._writableState.updateNextTick();
-        }
+      return true;
+    };
+    MatcherStream.prototype._transform = function(chunk, encoding, cb) {
+      this.data = Buffer.concat([this.data, chunk]);
+      var firstIteration = true;
+      while (this.checkDataChunk(!firstIteration)) {
+        firstIteration = false;
       }
-    }
-    var Stream = class extends EventEmitter {
-      constructor(opts) {
-        super();
-        this._duplexState = 0;
-        this._readableState = null;
-        this._writableState = null;
-        if (opts) {
-          if (opts.open) this._open = opts.open;
-          if (opts.destroy) this._destroy = opts.destroy;
-          if (opts.predestroy) this._predestroy = opts.predestroy;
-          if (opts.signal) {
-            opts.signal.addEventListener("abort", abort.bind(this));
-          }
+      cb();
+    };
+    MatcherStream.prototype._flush = function(cb) {
+      if (this.data.length > 0) {
+        var firstIteration = true;
+        while (this.checkDataChunk(!firstIteration)) {
+          firstIteration = false;
         }
-        this.on("newListener", newListener);
-      }
-      _open(cb) {
-        cb(null);
       }
-      _destroy(cb) {
-        cb(null);
-      }
-      _predestroy() {
+      if (this.data.length > 0) {
+        this.push(this.data);
+        this.data = null;
       }
-      get readable() {
-        return this._readableState !== null ? true : void 0;
+      cb();
+    };
+    module2.exports = MatcherStream;
+  }
+});
+
+// node_modules/unzip-stream/lib/entry.js
+var require_entry = __commonJS({
+  "node_modules/unzip-stream/lib/entry.js"(exports2, module2) {
+    "use strict";
+    var stream = require("stream");
+    var inherits = require("util").inherits;
+    function Entry() {
+      if (!(this instanceof Entry)) {
+        return new Entry();
       }
-      get writable() {
-        return this._writableState !== null ? true : void 0;
+      stream.PassThrough.call(this);
+      this.path = null;
+      this.type = null;
+      this.isDirectory = false;
+    }
+    inherits(Entry, stream.PassThrough);
+    Entry.prototype.autodrain = function() {
+      return this.pipe(new stream.Transform({ transform: function(d, e, cb) {
+        cb();
+      } }));
+    };
+    module2.exports = Entry;
+  }
+});
+
+// node_modules/unzip-stream/lib/unzip-stream.js
+var require_unzip_stream = __commonJS({
+  "node_modules/unzip-stream/lib/unzip-stream.js"(exports2, module2) {
+    "use strict";
+    var binary2 = require_binary();
+    var stream = require("stream");
+    var util = require("util");
+    var zlib = require("zlib");
+    var MatcherStream = require_matcher_stream();
+    var Entry = require_entry();
+    var states = {
+      STREAM_START: 0,
+      START: 1,
+      LOCAL_FILE_HEADER: 2,
+      LOCAL_FILE_HEADER_SUFFIX: 3,
+      FILE_DATA: 4,
+      FILE_DATA_END: 5,
+      DATA_DESCRIPTOR: 6,
+      CENTRAL_DIRECTORY_FILE_HEADER: 7,
+      CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX: 8,
+      CDIR64_END: 9,
+      CDIR64_END_DATA_SECTOR: 10,
+      CDIR64_LOCATOR: 11,
+      CENTRAL_DIRECTORY_END: 12,
+      CENTRAL_DIRECTORY_END_COMMENT: 13,
+      TRAILING_JUNK: 14,
+      ERROR: 99
+    };
+    var FOUR_GIGS = 4294967296;
+    var SIG_LOCAL_FILE_HEADER = 67324752;
+    var SIG_DATA_DESCRIPTOR = 134695760;
+    var SIG_CDIR_RECORD = 33639248;
+    var SIG_CDIR64_RECORD_END = 101075792;
+    var SIG_CDIR64_LOCATOR_END = 117853008;
+    var SIG_CDIR_RECORD_END = 101010256;
+    function UnzipStream(options) {
+      if (!(this instanceof UnzipStream)) {
+        return new UnzipStream(options);
       }
-      get destroyed() {
-        return (this._duplexState & DESTROYED) !== 0;
+      stream.Transform.call(this);
+      this.options = options || {};
+      this.data = new Buffer("");
+      this.state = states.STREAM_START;
+      this.skippedBytes = 0;
+      this.parsedEntity = null;
+      this.outStreamInfo = {};
+    }
+    util.inherits(UnzipStream, stream.Transform);
+    UnzipStream.prototype.processDataChunk = function(chunk) {
+      var requiredLength;
+      switch (this.state) {
+        case states.STREAM_START:
+        case states.START:
+          requiredLength = 4;
+          break;
+        case states.LOCAL_FILE_HEADER:
+          requiredLength = 26;
+          break;
+        case states.LOCAL_FILE_HEADER_SUFFIX:
+          requiredLength = this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength;
+          break;
+        case states.DATA_DESCRIPTOR:
+          requiredLength = 12;
+          break;
+        case states.CENTRAL_DIRECTORY_FILE_HEADER:
+          requiredLength = 42;
+          break;
+        case states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:
+          requiredLength = this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength + this.parsedEntity.fileCommentLength;
+          break;
+        case states.CDIR64_END:
+          requiredLength = 52;
+          break;
+        case states.CDIR64_END_DATA_SECTOR:
+          requiredLength = this.parsedEntity.centralDirectoryRecordSize - 44;
+          break;
+        case states.CDIR64_LOCATOR:
+          requiredLength = 16;
+          break;
+        case states.CENTRAL_DIRECTORY_END:
+          requiredLength = 18;
+          break;
+        case states.CENTRAL_DIRECTORY_END_COMMENT:
+          requiredLength = this.parsedEntity.commentLength;
+          break;
+        case states.FILE_DATA:
+          return 0;
+        case states.FILE_DATA_END:
+          return 0;
+        case states.TRAILING_JUNK:
+          if (this.options.debug) console.log("found", chunk.length, "bytes of TRAILING_JUNK");
+          return chunk.length;
+        default:
+          return chunk.length;
       }
-      get destroying() {
-        return (this._duplexState & DESTROY_STATUS) !== 0;
+      var chunkLength = chunk.length;
+      if (chunkLength < requiredLength) {
+        return 0;
       }
-      destroy(err) {
-        if ((this._duplexState & DESTROY_STATUS) === 0) {
-          if (!err) err = STREAM_DESTROYED;
-          this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
-          if (this._readableState !== null) {
-            this._readableState.highWaterMark = 0;
-            this._readableState.error = err;
+      switch (this.state) {
+        case states.STREAM_START:
+        case states.START:
+          var signature = chunk.readUInt32LE(0);
+          switch (signature) {
+            case SIG_LOCAL_FILE_HEADER:
+              this.state = states.LOCAL_FILE_HEADER;
+              break;
+            case SIG_CDIR_RECORD:
+              this.state = states.CENTRAL_DIRECTORY_FILE_HEADER;
+              break;
+            case SIG_CDIR64_RECORD_END:
+              this.state = states.CDIR64_END;
+              break;
+            case SIG_CDIR64_LOCATOR_END:
+              this.state = states.CDIR64_LOCATOR;
+              break;
+            case SIG_CDIR_RECORD_END:
+              this.state = states.CENTRAL_DIRECTORY_END;
+              break;
+            default:
+              var isStreamStart = this.state === states.STREAM_START;
+              if (!isStreamStart && (signature & 65535) !== 19280 && this.skippedBytes < 26) {
+                var remaining = signature;
+                var toSkip = 4;
+                for (var i = 1; i < 4 && remaining !== 0; i++) {
+                  remaining = remaining >>> 8;
+                  if ((remaining & 255) === 80) {
+                    toSkip = i;
+                    break;
+                  }
+                }
+                this.skippedBytes += toSkip;
+                if (this.options.debug) console.log("Skipped", this.skippedBytes, "bytes");
+                return toSkip;
+              }
+              this.state = states.ERROR;
+              var errMsg = isStreamStart ? "Not a valid zip file" : "Invalid signature in zip file";
+              if (this.options.debug) {
+                var sig = chunk.readUInt32LE(0);
+                var asString;
+                try {
+                  asString = chunk.slice(0, 4).toString();
+                } catch (e) {
+                }
+                console.log("Unexpected signature in zip file: 0x" + sig.toString(16), '"' + asString + '", skipped', this.skippedBytes, "bytes");
+              }
+              this.emit("error", new Error(errMsg));
+              return chunk.length;
           }
-          if (this._writableState !== null) {
-            this._writableState.highWaterMark = 0;
-            this._writableState.error = err;
+          this.skippedBytes = 0;
+          return requiredLength;
+        case states.LOCAL_FILE_HEADER:
+          this.parsedEntity = this._readFile(chunk);
+          this.state = states.LOCAL_FILE_HEADER_SUFFIX;
+          return requiredLength;
+        case states.LOCAL_FILE_HEADER_SUFFIX:
+          var entry = new Entry();
+          var isUtf8 = (this.parsedEntity.flags & 2048) !== 0;
+          entry.path = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8);
+          var extraDataBuffer = chunk.slice(this.parsedEntity.fileNameLength, this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength);
+          var extra = this._readExtraFields(extraDataBuffer);
+          if (extra && extra.parsed) {
+            if (extra.parsed.path && !isUtf8) {
+              entry.path = extra.parsed.path;
+            }
+            if (Number.isFinite(extra.parsed.uncompressedSize) && this.parsedEntity.uncompressedSize === FOUR_GIGS - 1) {
+              this.parsedEntity.uncompressedSize = extra.parsed.uncompressedSize;
+            }
+            if (Number.isFinite(extra.parsed.compressedSize) && this.parsedEntity.compressedSize === FOUR_GIGS - 1) {
+              this.parsedEntity.compressedSize = extra.parsed.compressedSize;
+            }
           }
-          this._duplexState |= PREDESTROYING;
-          this._predestroy();
-          this._duplexState &= NOT_PREDESTROYING;
-          if (this._readableState !== null) this._readableState.updateNextTick();
-          if (this._writableState !== null) this._writableState.updateNextTick();
-        }
-      }
-    };
-    var Readable = class _Readable extends Stream {
-      constructor(opts) {
-        super(opts);
-        this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD;
-        this._readableState = new ReadableState(this, opts);
-        if (opts) {
-          if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD;
-          if (opts.read) this._read = opts.read;
-          if (opts.eagerOpen) this._readableState.updateNextTick();
-          if (opts.encoding) this.setEncoding(opts.encoding);
-        }
-      }
-      setEncoding(encoding) {
-        const dec = new TextDecoder2(encoding);
-        const map2 = this._readableState.map || echo;
-        this._readableState.map = mapOrSkip;
-        return this;
-        function mapOrSkip(data) {
-          const next = dec.push(data);
-          return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map2(next);
-        }
-      }
-      _read(cb) {
-        cb(null);
-      }
-      pipe(dest, cb) {
-        this._readableState.updateNextTick();
-        this._readableState.pipe(dest, cb);
-        return dest;
-      }
-      read() {
-        this._readableState.updateNextTick();
-        return this._readableState.read();
-      }
-      push(data) {
-        this._readableState.updateNextTick();
-        return this._readableState.push(data);
-      }
-      unshift(data) {
-        this._readableState.updateNextTick();
-        return this._readableState.unshift(data);
-      }
-      resume() {
-        this._duplexState |= READ_RESUMED_READ_AHEAD;
-        this._readableState.updateNextTick();
-        return this;
-      }
-      pause() {
-        this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
-        return this;
-      }
-      static _fromAsyncIterator(ite, opts) {
-        let destroy;
-        const rs = new _Readable({
-          ...opts,
-          read(cb) {
-            ite.next().then(push).then(cb.bind(null, null)).catch(cb);
-          },
-          predestroy() {
-            destroy = ite.return();
-          },
-          destroy(cb) {
-            if (!destroy) return cb(null);
-            destroy.then(cb.bind(null, null)).catch(cb);
+          this.parsedEntity.extra = extra.parsed || {};
+          if (this.options.debug) {
+            const debugObj = Object.assign({}, this.parsedEntity, {
+              path: entry.path,
+              flags: "0x" + this.parsedEntity.flags.toString(16),
+              extraFields: extra && extra.debug
+            });
+            console.log("decoded LOCAL_FILE_HEADER:", JSON.stringify(debugObj, null, 2));
+          }
+          this._prepareOutStream(this.parsedEntity, entry);
+          this.emit("entry", entry);
+          this.state = states.FILE_DATA;
+          return requiredLength;
+        case states.CENTRAL_DIRECTORY_FILE_HEADER:
+          this.parsedEntity = this._readCentralDirectoryEntry(chunk);
+          this.state = states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX;
+          return requiredLength;
+        case states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:
+          var isUtf8 = (this.parsedEntity.flags & 2048) !== 0;
+          var path2 = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8);
+          var extraDataBuffer = chunk.slice(this.parsedEntity.fileNameLength, this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength);
+          var extra = this._readExtraFields(extraDataBuffer);
+          if (extra && extra.parsed && extra.parsed.path && !isUtf8) {
+            path2 = extra.parsed.path;
           }
-        });
-        return rs;
-        function push(data) {
-          if (data.done) rs.push(null);
-          else rs.push(data.value);
-        }
-      }
-      static from(data, opts) {
-        if (isReadStreamx(data)) return data;
-        if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
-        if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
-        let i = 0;
-        return new _Readable({
-          ...opts,
-          read(cb) {
-            this.push(i === data.length ? null : data[i++]);
-            cb(null);
+          this.parsedEntity.extra = extra.parsed;
+          var isUnix = (this.parsedEntity.versionMadeBy & 65280) >> 8 === 3;
+          var unixAttrs, isSymlink;
+          if (isUnix) {
+            unixAttrs = this.parsedEntity.externalFileAttributes >>> 16;
+            var fileType = unixAttrs >>> 12;
+            isSymlink = (fileType & 10) === 10;
           }
-        });
-      }
-      static isBackpressured(rs) {
-        return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
-      }
-      static isPaused(rs) {
-        return (rs._duplexState & READ_RESUMED) === 0;
-      }
-      [asyncIterator]() {
-        const stream = this;
-        let error4 = null;
-        let promiseResolve = null;
-        let promiseReject = null;
-        this.on("error", (err) => {
-          error4 = err;
-        });
-        this.on("readable", onreadable);
-        this.on("close", onclose);
-        return {
-          [asyncIterator]() {
-            return this;
-          },
-          next() {
-            return new Promise(function(resolve2, reject) {
-              promiseResolve = resolve2;
-              promiseReject = reject;
-              const data = stream.read();
-              if (data !== null) ondata(data);
-              else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
+          if (this.options.debug) {
+            const debugObj = Object.assign({}, this.parsedEntity, {
+              path: path2,
+              flags: "0x" + this.parsedEntity.flags.toString(16),
+              unixAttrs: unixAttrs && "0" + unixAttrs.toString(8),
+              isSymlink,
+              extraFields: extra.debug
             });
-          },
-          return() {
-            return destroy(null);
-          },
-          throw(err) {
-            return destroy(err);
+            console.log("decoded CENTRAL_DIRECTORY_FILE_HEADER:", JSON.stringify(debugObj, null, 2));
           }
-        };
-        function onreadable() {
-          if (promiseResolve !== null) ondata(stream.read());
-        }
-        function onclose() {
-          if (promiseResolve !== null) ondata(null);
-        }
-        function ondata(data) {
-          if (promiseReject === null) return;
-          if (error4) promiseReject(error4);
-          else if (data === null && (stream._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED);
-          else promiseResolve({ value: data, done: data === null });
-          promiseReject = promiseResolve = null;
-        }
-        function destroy(err) {
-          stream.destroy(err);
-          return new Promise((resolve2, reject) => {
-            if (stream._duplexState & DESTROYED) return resolve2({ value: void 0, done: true });
-            stream.once("close", function() {
-              if (err) reject(err);
-              else resolve2({ value: void 0, done: true });
-            });
-          });
-        }
+          this.state = states.START;
+          return requiredLength;
+        case states.CDIR64_END:
+          this.parsedEntity = this._readEndOfCentralDirectory64(chunk);
+          if (this.options.debug) {
+            console.log("decoded CDIR64_END_RECORD:", this.parsedEntity);
+          }
+          this.state = states.CDIR64_END_DATA_SECTOR;
+          return requiredLength;
+        case states.CDIR64_END_DATA_SECTOR:
+          this.state = states.START;
+          return requiredLength;
+        case states.CDIR64_LOCATOR:
+          this.state = states.START;
+          return requiredLength;
+        case states.CENTRAL_DIRECTORY_END:
+          this.parsedEntity = this._readEndOfCentralDirectory(chunk);
+          if (this.options.debug) {
+            console.log("decoded CENTRAL_DIRECTORY_END:", this.parsedEntity);
+          }
+          this.state = states.CENTRAL_DIRECTORY_END_COMMENT;
+          return requiredLength;
+        case states.CENTRAL_DIRECTORY_END_COMMENT:
+          if (this.options.debug) {
+            console.log("decoded CENTRAL_DIRECTORY_END_COMMENT:", chunk.slice(0, requiredLength).toString());
+          }
+          this.state = states.TRAILING_JUNK;
+          return requiredLength;
+        case states.ERROR:
+          return chunk.length;
+        // discard
+        default:
+          console.log("didn't handle state #", this.state, "discarding");
+          return chunk.length;
       }
     };
-    var Writable = class extends Stream {
-      constructor(opts) {
-        super(opts);
-        this._duplexState |= OPENING | READ_DONE;
-        this._writableState = new WritableState(this, opts);
-        if (opts) {
-          if (opts.writev) this._writev = opts.writev;
-          if (opts.write) this._write = opts.write;
-          if (opts.final) this._final = opts.final;
-          if (opts.eagerOpen) this._writableState.updateNextTick();
-        }
-      }
-      cork() {
-        this._duplexState |= WRITE_CORKED;
-      }
-      uncork() {
-        this._duplexState &= WRITE_NOT_CORKED;
-        this._writableState.updateNextTick();
-      }
-      _writev(batch, cb) {
-        cb(null);
-      }
-      _write(data, cb) {
-        this._writableState.autoBatch(data, cb);
-      }
-      _final(cb) {
-        cb(null);
-      }
-      static isBackpressured(ws) {
-        return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
+    UnzipStream.prototype._prepareOutStream = function(vars, entry) {
+      var self2 = this;
+      var isDirectory = vars.uncompressedSize === 0 && /[\/\\]$/.test(entry.path);
+      entry.path = entry.path.replace(/(?<=^|[/\\]+)[.][.]+(?=[/\\]+|$)/g, ".");
+      entry.type = isDirectory ? "Directory" : "File";
+      entry.isDirectory = isDirectory;
+      var fileSizeKnown = !(vars.flags & 8);
+      if (fileSizeKnown) {
+        entry.size = vars.uncompressedSize;
       }
-      static drained(ws) {
-        if (ws.destroyed) return Promise.resolve(false);
-        const state = ws._writableState;
-        const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
-        const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
-        if (writes === 0) return Promise.resolve(true);
-        if (state.drains === null) state.drains = [];
-        return new Promise((resolve2) => {
-          state.drains.push({ writes, resolve: resolve2 });
+      var isVersionSupported = vars.versionsNeededToExtract <= 45;
+      this.outStreamInfo = {
+        stream: null,
+        limit: fileSizeKnown ? vars.compressedSize : -1,
+        written: 0
+      };
+      if (!fileSizeKnown) {
+        var pattern = new Buffer(4);
+        pattern.writeUInt32LE(SIG_DATA_DESCRIPTOR, 0);
+        var zip64Mode = vars.extra.zip64Mode;
+        var extraSize = zip64Mode ? 20 : 12;
+        var searchPattern = {
+          pattern,
+          requiredExtraSize: extraSize
+        };
+        var matcherStream = new MatcherStream(searchPattern, function(matchedChunk, sizeSoFar) {
+          var vars2 = self2._readDataDescriptor(matchedChunk, zip64Mode);
+          var compressedSizeMatches = vars2.compressedSize === sizeSoFar;
+          if (!zip64Mode && !compressedSizeMatches && sizeSoFar >= FOUR_GIGS) {
+            var overflown = sizeSoFar - FOUR_GIGS;
+            while (overflown >= 0) {
+              compressedSizeMatches = vars2.compressedSize === overflown;
+              if (compressedSizeMatches) break;
+              overflown -= FOUR_GIGS;
+            }
+          }
+          if (!compressedSizeMatches) {
+            return;
+          }
+          self2.state = states.FILE_DATA_END;
+          var sliceOffset = zip64Mode ? 24 : 16;
+          if (self2.data.length > 0) {
+            self2.data = Buffer.concat([matchedChunk.slice(sliceOffset), self2.data]);
+          } else {
+            self2.data = matchedChunk.slice(sliceOffset);
+          }
+          return true;
         });
+        this.outStreamInfo.stream = matcherStream;
+      } else {
+        this.outStreamInfo.stream = new stream.PassThrough();
       }
-      write(data) {
-        this._writableState.updateNextTick();
-        return this._writableState.push(data);
-      }
-      end(data) {
-        this._writableState.updateNextTick();
-        this._writableState.end(data);
-        return this;
-      }
-    };
-    var Duplex = class extends Readable {
-      // and Writable
-      constructor(opts) {
-        super(opts);
-        this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
-        this._writableState = new WritableState(this, opts);
-        if (opts) {
-          if (opts.writev) this._writev = opts.writev;
-          if (opts.write) this._write = opts.write;
-          if (opts.final) this._final = opts.final;
-        }
-      }
-      cork() {
-        this._duplexState |= WRITE_CORKED;
-      }
-      uncork() {
-        this._duplexState &= WRITE_NOT_CORKED;
-        this._writableState.updateNextTick();
-      }
-      _writev(batch, cb) {
-        cb(null);
-      }
-      _write(data, cb) {
-        this._writableState.autoBatch(data, cb);
-      }
-      _final(cb) {
-        cb(null);
-      }
-      write(data) {
-        this._writableState.updateNextTick();
-        return this._writableState.push(data);
-      }
-      end(data) {
-        this._writableState.updateNextTick();
-        this._writableState.end(data);
-        return this;
-      }
-    };
-    var Transform = class extends Duplex {
-      constructor(opts) {
-        super(opts);
-        this._transformState = new TransformState(this);
-        if (opts) {
-          if (opts.transform) this._transform = opts.transform;
-          if (opts.flush) this._flush = opts.flush;
-        }
-      }
-      _write(data, cb) {
-        if (this._readableState.buffered >= this._readableState.highWaterMark) {
-          this._transformState.data = data;
-        } else {
-          this._transform(data, this._transformState.afterTransform);
-        }
-      }
-      _read(cb) {
-        if (this._transformState.data !== null) {
-          const data = this._transformState.data;
-          this._transformState.data = null;
-          cb(null);
-          this._transform(data, this._transformState.afterTransform);
-        } else {
-          cb(null);
-        }
-      }
-      destroy(err) {
-        super.destroy(err);
-        if (this._transformState.data !== null) {
-          this._transformState.data = null;
-          this._transformState.afterTransform();
-        }
-      }
-      _transform(data, cb) {
-        cb(null, data);
+      var isEncrypted = vars.flags & 1 || vars.flags & 64;
+      if (isEncrypted || !isVersionSupported) {
+        var message = isEncrypted ? "Encrypted files are not supported!" : "Zip version " + Math.floor(vars.versionsNeededToExtract / 10) + "." + vars.versionsNeededToExtract % 10 + " is not supported";
+        entry.skip = true;
+        setImmediate(() => {
+          self2.emit("error", new Error(message));
+        });
+        this.outStreamInfo.stream.pipe(new Entry().autodrain());
+        return;
       }
-      _flush(cb) {
-        cb(null);
+      var isCompressed = vars.compressionMethod > 0;
+      if (isCompressed) {
+        var inflater = zlib.createInflateRaw();
+        inflater.on("error", function(err) {
+          self2.state = states.ERROR;
+          self2.emit("error", err);
+        });
+        this.outStreamInfo.stream.pipe(inflater).pipe(entry);
+      } else {
+        this.outStreamInfo.stream.pipe(entry);
       }
-      _final(cb) {
-        this._transformState.afterFinal = cb;
-        this._flush(transformAfterFlush.bind(this));
+      if (this._drainAllEntries) {
+        entry.autodrain();
       }
     };
-    var PassThrough = class extends Transform {
+    UnzipStream.prototype._readFile = function(data) {
+      var vars = binary2.parse(data).word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars;
+      return vars;
     };
-    function transformAfterFlush(err, data) {
-      const cb = this._transformState.afterFinal;
-      if (err) return cb(err);
-      if (data !== null && data !== void 0) this.push(data);
-      this.push(null);
-      cb(null);
-    }
-    function pipelinePromise(...streams) {
-      return new Promise((resolve2, reject) => {
-        return pipeline(...streams, (err) => {
-          if (err) return reject(err);
-          resolve2();
-        });
-      });
-    }
-    function pipeline(stream, ...streams) {
-      const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
-      const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
-      if (all.length < 2) throw new Error("Pipeline requires at least 2 streams");
-      let src = all[0];
-      let dest = null;
-      let error4 = null;
-      for (let i = 1; i < all.length; i++) {
-        dest = all[i];
-        if (isStreamx(src)) {
-          src.pipe(dest, onerror);
-        } else {
-          errorHandle(src, true, i > 1, onerror);
-          src.pipe(dest);
-        }
-        src = dest;
-      }
-      if (done) {
-        let fin = false;
-        const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
-        dest.on("error", (err) => {
-          if (error4 === null) error4 = err;
-        });
-        dest.on("finish", () => {
-          fin = true;
-          if (!autoDestroy) done(error4);
-        });
-        if (autoDestroy) {
-          dest.on("close", () => done(error4 || (fin ? null : PREMATURE_CLOSE)));
-        }
+    UnzipStream.prototype._readExtraFields = function(data) {
+      var extra = {};
+      var result = { parsed: extra };
+      if (this.options.debug) {
+        result.debug = [];
       }
-      return dest;
-      function errorHandle(s, rd, wr, onerror2) {
-        s.on("error", onerror2);
-        s.on("close", onclose);
-        function onclose() {
-          if (rd && s._readableState && !s._readableState.ended) return onerror2(PREMATURE_CLOSE);
-          if (wr && s._writableState && !s._writableState.ended) return onerror2(PREMATURE_CLOSE);
+      var index = 0;
+      while (index < data.length) {
+        var vars = binary2.parse(data).skip(index).word16lu("extraId").word16lu("extraSize").vars;
+        index += 4;
+        var fieldType = void 0;
+        switch (vars.extraId) {
+          case 1:
+            fieldType = "Zip64 extended information extra field";
+            var z64vars = binary2.parse(data.slice(index, index + vars.extraSize)).word64lu("uncompressedSize").word64lu("compressedSize").word64lu("offsetToLocalHeader").word32lu("diskStartNumber").vars;
+            if (z64vars.uncompressedSize !== null) {
+              extra.uncompressedSize = z64vars.uncompressedSize;
+            }
+            if (z64vars.compressedSize !== null) {
+              extra.compressedSize = z64vars.compressedSize;
+            }
+            extra.zip64Mode = true;
+            break;
+          case 10:
+            fieldType = "NTFS extra field";
+            break;
+          case 21589:
+            fieldType = "extended timestamp";
+            var timestampFields = data.readUInt8(index);
+            var offset = 1;
+            if (vars.extraSize >= offset + 4 && timestampFields & 1) {
+              extra.mtime = new Date(data.readUInt32LE(index + offset) * 1e3);
+              offset += 4;
+            }
+            if (vars.extraSize >= offset + 4 && timestampFields & 2) {
+              extra.atime = new Date(data.readUInt32LE(index + offset) * 1e3);
+              offset += 4;
+            }
+            if (vars.extraSize >= offset + 4 && timestampFields & 4) {
+              extra.ctime = new Date(data.readUInt32LE(index + offset) * 1e3);
+            }
+            break;
+          case 28789:
+            fieldType = "Info-ZIP Unicode Path Extra Field";
+            var fieldVer = data.readUInt8(index);
+            if (fieldVer === 1) {
+              var offset = 1;
+              var nameCrc32 = data.readUInt32LE(index + offset);
+              offset += 4;
+              var pathBuffer = data.slice(index + offset);
+              extra.path = pathBuffer.toString();
+            }
+            break;
+          case 13:
+          case 22613:
+            fieldType = vars.extraId === 13 ? "PKWARE Unix" : "Info-ZIP UNIX (type 1)";
+            var offset = 0;
+            if (vars.extraSize >= 8) {
+              var atime = new Date(data.readUInt32LE(index + offset) * 1e3);
+              offset += 4;
+              var mtime = new Date(data.readUInt32LE(index + offset) * 1e3);
+              offset += 4;
+              extra.atime = atime;
+              extra.mtime = mtime;
+              if (vars.extraSize >= 12) {
+                var uid = data.readUInt16LE(index + offset);
+                offset += 2;
+                var gid = data.readUInt16LE(index + offset);
+                offset += 2;
+                extra.uid = uid;
+                extra.gid = gid;
+              }
+            }
+            break;
+          case 30805:
+            fieldType = "Info-ZIP UNIX (type 2)";
+            var offset = 0;
+            if (vars.extraSize >= 4) {
+              var uid = data.readUInt16LE(index + offset);
+              offset += 2;
+              var gid = data.readUInt16LE(index + offset);
+              offset += 2;
+              extra.uid = uid;
+              extra.gid = gid;
+            }
+            break;
+          case 30837:
+            fieldType = "Info-ZIP New Unix";
+            var offset = 0;
+            var extraVer = data.readUInt8(index);
+            offset += 1;
+            if (extraVer === 1) {
+              var uidSize = data.readUInt8(index + offset);
+              offset += 1;
+              if (uidSize <= 6) {
+                extra.uid = data.readUIntLE(index + offset, uidSize);
+              }
+              offset += uidSize;
+              var gidSize = data.readUInt8(index + offset);
+              offset += 1;
+              if (gidSize <= 6) {
+                extra.gid = data.readUIntLE(index + offset, gidSize);
+              }
+            }
+            break;
+          case 30062:
+            fieldType = "ASi Unix";
+            var offset = 0;
+            if (vars.extraSize >= 14) {
+              var crc = data.readUInt32LE(index + offset);
+              offset += 4;
+              var mode = data.readUInt16LE(index + offset);
+              offset += 2;
+              var sizdev = data.readUInt32LE(index + offset);
+              offset += 4;
+              var uid = data.readUInt16LE(index + offset);
+              offset += 2;
+              var gid = data.readUInt16LE(index + offset);
+              offset += 2;
+              extra.mode = mode;
+              extra.uid = uid;
+              extra.gid = gid;
+              if (vars.extraSize > 14) {
+                var start = index + offset;
+                var end = index + vars.extraSize - 14;
+                var symlinkName = this._decodeString(data.slice(start, end));
+                extra.symlink = symlinkName;
+              }
+            }
+            break;
         }
-      }
-      function onerror(err) {
-        if (!err || error4) return;
-        error4 = err;
-        for (const s of all) {
-          s.destroy(err);
+        if (this.options.debug) {
+          result.debug.push({
+            extraId: "0x" + vars.extraId.toString(16),
+            description: fieldType,
+            data: data.slice(index, index + vars.extraSize).inspect()
+          });
         }
+        index += vars.extraSize;
       }
-    }
-    function echo(s) {
-      return s;
-    }
-    function isStream(stream) {
-      return !!stream._readableState || !!stream._writableState;
-    }
-    function isStreamx(stream) {
-      return typeof stream._duplexState === "number" && isStream(stream);
-    }
-    function isEnded(stream) {
-      return !!stream._readableState && stream._readableState.ended;
-    }
-    function isFinished(stream) {
-      return !!stream._writableState && stream._writableState.ended;
-    }
-    function getStreamError(stream, opts = {}) {
-      const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
-      return !opts.all && err === STREAM_DESTROYED ? null : err;
-    }
-    function isReadStreamx(stream) {
-      return isStreamx(stream) && stream.readable;
-    }
-    function isTypedArray(data) {
-      return typeof data === "object" && data !== null && typeof data.byteLength === "number";
-    }
-    function defaultByteLength(data) {
-      return isTypedArray(data) ? data.byteLength : 1024;
-    }
-    function noop() {
-    }
-    function abort() {
-      this.destroy(new Error("Stream aborted."));
-    }
-    function isWritev(s) {
-      return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
-    }
-    module2.exports = {
-      pipeline,
-      pipelinePromise,
-      isStream,
-      isStreamx,
-      isEnded,
-      isFinished,
-      getStreamError,
-      Stream,
-      Writable,
-      Readable,
-      Duplex,
-      Transform,
-      // Export PassThrough for compatibility with Node.js core's stream module
-      PassThrough
-    };
-  }
-});
-
-// node_modules/tar-stream/headers.js
-var require_headers2 = __commonJS({
-  "node_modules/tar-stream/headers.js"(exports2) {
-    var b4a = require_b4a();
-    var ZEROS = "0000000000000000000";
-    var SEVENS = "7777777777777777777";
-    var ZERO_OFFSET = "0".charCodeAt(0);
-    var USTAR_MAGIC = b4a.from([117, 115, 116, 97, 114, 0]);
-    var USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]);
-    var GNU_MAGIC = b4a.from([117, 115, 116, 97, 114, 32]);
-    var GNU_VER = b4a.from([32, 0]);
-    var MASK = 4095;
-    var MAGIC_OFFSET = 257;
-    var VERSION_OFFSET = 263;
-    exports2.decodeLongPath = function decodeLongPath(buf, encoding) {
-      return decodeStr(buf, 0, buf.length, encoding);
+      return result;
     };
-    exports2.encodePax = function encodePax(opts) {
-      let result = "";
-      if (opts.name) result += addLength(" path=" + opts.name + "\n");
-      if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n");
-      const pax = opts.pax;
-      if (pax) {
-        for (const key in pax) {
-          result += addLength(" " + key + "=" + pax[key] + "\n");
-        }
+    UnzipStream.prototype._readDataDescriptor = function(data, zip64Mode) {
+      if (zip64Mode) {
+        var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word64lu("compressedSize").word64lu("uncompressedSize").vars;
+        return vars;
       }
-      return b4a.from(result);
+      var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").vars;
+      return vars;
     };
-    exports2.decodePax = function decodePax(buf) {
-      const result = {};
-      while (buf.length) {
-        let i = 0;
-        while (i < buf.length && buf[i] !== 32) i++;
-        const len = parseInt(b4a.toString(buf.subarray(0, i)), 10);
-        if (!len) return result;
-        const b = b4a.toString(buf.subarray(i + 1, len - 1));
-        const keyIndex = b.indexOf("=");
-        if (keyIndex === -1) return result;
-        result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1);
-        buf = buf.subarray(len);
+    UnzipStream.prototype._readCentralDirectoryEntry = function(data) {
+      var vars = binary2.parse(data).word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars;
+      return vars;
+    };
+    UnzipStream.prototype._readEndOfCentralDirectory64 = function(data) {
+      var vars = binary2.parse(data).word64lu("centralDirectoryRecordSize").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskNumberWithCentralDirectoryStart").word64lu("centralDirectoryEntries").word64lu("totalCentralDirectoryEntries").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars;
+      return vars;
+    };
+    UnzipStream.prototype._readEndOfCentralDirectory = function(data) {
+      var vars = binary2.parse(data).word16lu("diskNumber").word16lu("diskStart").word16lu("centralDirectoryEntries").word16lu("totalCentralDirectoryEntries").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars;
+      return vars;
+    };
+    var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 ";
+    UnzipStream.prototype._decodeString = function(buffer, isUtf8) {
+      if (isUtf8) {
+        return buffer.toString("utf8");
+      }
+      if (this.options.decodeString) {
+        return this.options.decodeString(buffer);
+      }
+      let result = "";
+      for (var i = 0; i < buffer.length; i++) {
+        result += cp437[buffer[i]];
       }
       return result;
     };
-    exports2.encode = function encode(opts) {
-      const buf = b4a.alloc(512);
-      let name = opts.name;
-      let prefix = "";
-      if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/";
-      if (b4a.byteLength(name) !== name.length) return null;
-      while (b4a.byteLength(name) > 100) {
-        const i = name.indexOf("/");
-        if (i === -1) return null;
-        prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i);
-        name = name.slice(i + 1);
+    UnzipStream.prototype._parseOrOutput = function(encoding, cb) {
+      var consume;
+      while ((consume = this.processDataChunk(this.data)) > 0) {
+        this.data = this.data.slice(consume);
+        if (this.data.length === 0) break;
       }
-      if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null;
-      if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null;
-      b4a.write(buf, name);
-      b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100);
-      b4a.write(buf, encodeOct(opts.uid, 6), 108);
-      b4a.write(buf, encodeOct(opts.gid, 6), 116);
-      encodeSize(opts.size, buf, 124);
-      b4a.write(buf, encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136);
-      buf[156] = ZERO_OFFSET + toTypeflag(opts.type);
-      if (opts.linkname) b4a.write(buf, opts.linkname, 157);
-      b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET);
-      b4a.copy(USTAR_VER, buf, VERSION_OFFSET);
-      if (opts.uname) b4a.write(buf, opts.uname, 265);
-      if (opts.gname) b4a.write(buf, opts.gname, 297);
-      b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329);
-      b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337);
-      if (prefix) b4a.write(buf, prefix, 345);
-      b4a.write(buf, encodeOct(cksum(buf), 6), 148);
-      return buf;
+      if (this.state === states.FILE_DATA) {
+        if (this.outStreamInfo.limit >= 0) {
+          var remaining = this.outStreamInfo.limit - this.outStreamInfo.written;
+          var packet;
+          if (remaining < this.data.length) {
+            packet = this.data.slice(0, remaining);
+            this.data = this.data.slice(remaining);
+          } else {
+            packet = this.data;
+            this.data = new Buffer("");
+          }
+          this.outStreamInfo.written += packet.length;
+          if (this.outStreamInfo.limit === this.outStreamInfo.written) {
+            this.state = states.START;
+            this.outStreamInfo.stream.end(packet, encoding, cb);
+          } else {
+            this.outStreamInfo.stream.write(packet, encoding, cb);
+          }
+        } else {
+          var packet = this.data;
+          this.data = new Buffer("");
+          this.outStreamInfo.written += packet.length;
+          var outputStream = this.outStreamInfo.stream;
+          outputStream.write(packet, encoding, () => {
+            if (this.state === states.FILE_DATA_END) {
+              this.state = states.START;
+              return outputStream.end(cb);
+            }
+            cb();
+          });
+        }
+        return;
+      }
+      cb();
     };
-    exports2.decode = function decode(buf, filenameEncoding, allowUnknownFormat) {
-      let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET;
-      let name = decodeStr(buf, 0, 100, filenameEncoding);
-      const mode = decodeOct(buf, 100, 8);
-      const uid = decodeOct(buf, 108, 8);
-      const gid = decodeOct(buf, 116, 8);
-      const size = decodeOct(buf, 124, 12);
-      const mtime = decodeOct(buf, 136, 12);
-      const type2 = toType(typeflag);
-      const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding);
-      const uname = decodeStr(buf, 265, 32);
-      const gname = decodeStr(buf, 297, 32);
-      const devmajor = decodeOct(buf, 329, 8);
-      const devminor = decodeOct(buf, 337, 8);
-      const c = cksum(buf);
-      if (c === 8 * 32) return null;
-      if (c !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");
-      if (isUSTAR(buf)) {
-        if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name;
-      } else if (isGNU(buf)) {
+    UnzipStream.prototype.drainAll = function() {
+      this._drainAllEntries = true;
+    };
+    UnzipStream.prototype._transform = function(chunk, encoding, cb) {
+      var self2 = this;
+      if (self2.data.length > 0) {
+        self2.data = Buffer.concat([self2.data, chunk]);
       } else {
-        if (!allowUnknownFormat) {
-          throw new Error("Invalid tar header: unknown format.");
-        }
+        self2.data = chunk;
       }
-      if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5;
-      return {
-        name,
-        mode,
-        uid,
-        gid,
-        size,
-        mtime: new Date(1e3 * mtime),
-        type: type2,
-        linkname,
-        uname,
-        gname,
-        devmajor,
-        devminor,
-        pax: null
+      var startDataLength = self2.data.length;
+      var done = function() {
+        if (self2.data.length > 0 && self2.data.length < startDataLength) {
+          startDataLength = self2.data.length;
+          self2._parseOrOutput(encoding, done);
+          return;
+        }
+        cb();
       };
+      self2._parseOrOutput(encoding, done);
     };
-    function isUSTAR(buf) {
-      return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6));
-    }
-    function isGNU(buf) {
-      return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2));
-    }
-    function clamp(index, len, defaultValue) {
-      if (typeof index !== "number") return defaultValue;
-      index = ~~index;
-      if (index >= len) return len;
-      if (index >= 0) return index;
-      index += len;
-      if (index >= 0) return index;
-      return 0;
-    }
-    function toType(flag) {
-      switch (flag) {
-        case 0:
-          return "file";
-        case 1:
-          return "link";
-        case 2:
-          return "symlink";
-        case 3:
-          return "character-device";
-        case 4:
-          return "block-device";
-        case 5:
-          return "directory";
-        case 6:
-          return "fifo";
-        case 7:
-          return "contiguous-file";
-        case 72:
-          return "pax-header";
-        case 55:
-          return "pax-global-header";
-        case 27:
-          return "gnu-long-link-path";
-        case 28:
-        case 30:
-          return "gnu-long-path";
-      }
-      return null;
-    }
-    function toTypeflag(flag) {
-      switch (flag) {
-        case "file":
-          return 0;
-        case "link":
-          return 1;
-        case "symlink":
-          return 2;
-        case "character-device":
-          return 3;
-        case "block-device":
-          return 4;
-        case "directory":
-          return 5;
-        case "fifo":
-          return 6;
-        case "contiguous-file":
-          return 7;
-        case "pax-header":
-          return 72;
-      }
-      return 0;
-    }
-    function indexOf(block, num, offset, end) {
-      for (; offset < end; offset++) {
-        if (block[offset] === num) return offset;
-      }
-      return end;
-    }
-    function cksum(block) {
-      let sum = 8 * 32;
-      for (let i = 0; i < 148; i++) sum += block[i];
-      for (let j = 156; j < 512; j++) sum += block[j];
-      return sum;
-    }
-    function encodeOct(val2, n) {
-      val2 = val2.toString(8);
-      if (val2.length > n) return SEVENS.slice(0, n) + " ";
-      return ZEROS.slice(0, n - val2.length) + val2 + " ";
-    }
-    function encodeSizeBin(num, buf, off) {
-      buf[off] = 128;
-      for (let i = 11; i > 0; i--) {
-        buf[off + i] = num & 255;
-        num = Math.floor(num / 256);
-      }
-    }
-    function encodeSize(num, buf, off) {
-      if (num.toString(8).length > 11) {
-        encodeSizeBin(num, buf, off);
-      } else {
-        b4a.write(buf, encodeOct(num, 11), off);
+    UnzipStream.prototype._flush = function(cb) {
+      var self2 = this;
+      if (self2.data.length > 0) {
+        self2._parseOrOutput("buffer", function() {
+          if (self2.data.length > 0) return setImmediate(function() {
+            self2._flush(cb);
+          });
+          cb();
+        });
+        return;
       }
-    }
-    function parse256(buf) {
-      let positive;
-      if (buf[0] === 128) positive = true;
-      else if (buf[0] === 255) positive = false;
-      else return null;
-      const tuple = [];
-      let i;
-      for (i = buf.length - 1; i > 0; i--) {
-        const byte = buf[i];
-        if (positive) tuple.push(byte);
-        else tuple.push(255 - byte);
+      if (self2.state === states.FILE_DATA) {
+        return cb(new Error("Stream finished in an invalid state, uncompression failed"));
       }
-      let sum = 0;
-      const l = tuple.length;
-      for (i = 0; i < l; i++) {
-        sum += tuple[i] * Math.pow(256, i);
+      setImmediate(cb);
+    };
+    module2.exports = UnzipStream;
+  }
+});
+
+// node_modules/unzip-stream/lib/parser-stream.js
+var require_parser_stream = __commonJS({
+  "node_modules/unzip-stream/lib/parser-stream.js"(exports2, module2) {
+    var Transform = require("stream").Transform;
+    var util = require("util");
+    var UnzipStream = require_unzip_stream();
+    function ParserStream(opts) {
+      if (!(this instanceof ParserStream)) {
+        return new ParserStream(opts);
       }
-      return positive ? sum : -1 * sum;
+      var transformOpts = opts || {};
+      Transform.call(this, { readableObjectMode: true });
+      this.opts = opts || {};
+      this.unzipStream = new UnzipStream(this.opts);
+      var self2 = this;
+      this.unzipStream.on("entry", function(entry) {
+        self2.push(entry);
+      });
+      this.unzipStream.on("error", function(error4) {
+        self2.emit("error", error4);
+      });
     }
-    function decodeOct(val2, offset, length) {
-      val2 = val2.subarray(offset, offset + length);
-      offset = 0;
-      if (val2[offset] & 128) {
-        return parse256(val2);
-      } else {
-        while (offset < val2.length && val2[offset] === 32) offset++;
-        const end = clamp(indexOf(val2, 32, offset, val2.length), val2.length, val2.length);
-        while (offset < end && val2[offset] === 0) offset++;
-        if (end === offset) return 0;
-        return parseInt(b4a.toString(val2.subarray(offset, end)), 8);
+    util.inherits(ParserStream, Transform);
+    ParserStream.prototype._transform = function(chunk, encoding, cb) {
+      this.unzipStream.write(chunk, encoding, cb);
+    };
+    ParserStream.prototype._flush = function(cb) {
+      var self2 = this;
+      this.unzipStream.end(function() {
+        process.nextTick(function() {
+          self2.emit("close");
+        });
+        cb();
+      });
+    };
+    ParserStream.prototype.on = function(eventName, fn) {
+      if (eventName === "entry") {
+        return Transform.prototype.on.call(this, "data", fn);
       }
-    }
-    function decodeStr(val2, offset, length, encoding) {
-      return b4a.toString(val2.subarray(offset, indexOf(val2, 0, offset, offset + length)), encoding);
-    }
-    function addLength(str2) {
-      const len = b4a.byteLength(str2);
-      let digits = Math.floor(Math.log(len) / Math.log(10)) + 1;
-      if (len + digits >= Math.pow(10, digits)) digits++;
-      return len + digits + str2;
-    }
+      return Transform.prototype.on.call(this, eventName, fn);
+    };
+    ParserStream.prototype.drainAll = function() {
+      this.unzipStream.drainAll();
+      return this.pipe(new Transform({ objectMode: true, transform: function(d, e, cb) {
+        cb();
+      } }));
+    };
+    module2.exports = ParserStream;
   }
 });
 
-// node_modules/tar-stream/extract.js
-var require_extract = __commonJS({
-  "node_modules/tar-stream/extract.js"(exports2, module2) {
-    var { Writable, Readable, getStreamError } = require_streamx();
-    var FIFO = require_fast_fifo();
-    var b4a = require_b4a();
-    var headers = require_headers2();
-    var EMPTY = b4a.alloc(0);
-    var BufferList = class {
-      constructor() {
-        this.buffered = 0;
-        this.shifted = 0;
-        this.queue = new FIFO();
-        this._offset = 0;
-      }
-      push(buffer) {
-        this.buffered += buffer.byteLength;
-        this.queue.push(buffer);
-      }
-      shiftFirst(size) {
-        return this._buffered === 0 ? null : this._next(size);
-      }
-      shift(size) {
-        if (size > this.buffered) return null;
-        if (size === 0) return EMPTY;
-        let chunk = this._next(size);
-        if (size === chunk.byteLength) return chunk;
-        const chunks = [chunk];
-        while ((size -= chunk.byteLength) > 0) {
-          chunk = this._next(size);
-          chunks.push(chunk);
-        }
-        return b4a.concat(chunks);
-      }
-      _next(size) {
-        const buf = this.queue.peek();
-        const rem = buf.byteLength - this._offset;
-        if (size >= rem) {
-          const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf;
-          this.queue.shift();
-          this._offset = 0;
-          this.buffered -= rem;
-          this.shifted += rem;
-          return sub;
-        }
-        this.buffered -= size;
-        this.shifted += size;
-        return buf.subarray(this._offset, this._offset += size);
+// node_modules/mkdirp/index.js
+var require_mkdirp = __commonJS({
+  "node_modules/mkdirp/index.js"(exports2, module2) {
+    var path2 = require("path");
+    var fs2 = require("fs");
+    var _0777 = parseInt("0777", 8);
+    module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
+    function mkdirP(p, opts, f, made) {
+      if (typeof opts === "function") {
+        f = opts;
+        opts = {};
+      } else if (!opts || typeof opts !== "object") {
+        opts = { mode: opts };
       }
-    };
-    var Source = class extends Readable {
-      constructor(self2, header, offset) {
-        super();
-        this.header = header;
-        this.offset = offset;
-        this._parent = self2;
+      var mode = opts.mode;
+      var xfs = opts.fs || fs2;
+      if (mode === void 0) {
+        mode = _0777;
       }
-      _read(cb) {
-        if (this.header.size === 0) {
-          this.push(null);
+      if (!made) made = null;
+      var cb = f || /* istanbul ignore next */
+      function() {
+      };
+      p = path2.resolve(p);
+      xfs.mkdir(p, mode, function(er) {
+        if (!er) {
+          made = made || p;
+          return cb(null, made);
         }
-        if (this._parent._stream === this) {
-          this._parent._update();
+        switch (er.code) {
+          case "ENOENT":
+            if (path2.dirname(p) === p) return cb(er);
+            mkdirP(path2.dirname(p), opts, function(er2, made2) {
+              if (er2) cb(er2, made2);
+              else mkdirP(p, opts, cb, made2);
+            });
+            break;
+          // In the case of any other error, just see if there's a dir
+          // there already.  If so, then hooray!  If not, then something
+          // is borked.
+          default:
+            xfs.stat(p, function(er2, stat) {
+              if (er2 || !stat.isDirectory()) cb(er, made);
+              else cb(null, made);
+            });
+            break;
         }
-        cb(null);
+      });
+    }
+    mkdirP.sync = function sync(p, opts, made) {
+      if (!opts || typeof opts !== "object") {
+        opts = { mode: opts };
       }
-      _predestroy() {
-        this._parent.destroy(getStreamError(this));
+      var mode = opts.mode;
+      var xfs = opts.fs || fs2;
+      if (mode === void 0) {
+        mode = _0777;
       }
-      _detach() {
-        if (this._parent._stream === this) {
-          this._parent._stream = null;
-          this._parent._missing = overflow(this.header.size);
-          this._parent._update();
+      if (!made) made = null;
+      p = path2.resolve(p);
+      try {
+        xfs.mkdirSync(p, mode);
+        made = made || p;
+      } catch (err0) {
+        switch (err0.code) {
+          case "ENOENT":
+            made = sync(path2.dirname(p), opts, made);
+            sync(p, opts, made);
+            break;
+          // In the case of any other error, just see if there's a dir
+          // there already.  If so, then hooray!  If not, then something
+          // is borked.
+          default:
+            var stat;
+            try {
+              stat = xfs.statSync(p);
+            } catch (err1) {
+              throw err0;
+            }
+            if (!stat.isDirectory()) throw err0;
+            break;
         }
       }
-      _destroy(cb) {
-        this._detach();
-        cb(null);
-      }
+      return made;
     };
-    var Extract = class extends Writable {
-      constructor(opts) {
-        super(opts);
-        if (!opts) opts = {};
-        this._buffer = new BufferList();
-        this._offset = 0;
-        this._header = null;
-        this._stream = null;
-        this._missing = 0;
-        this._longHeader = false;
-        this._callback = noop;
-        this._locked = false;
-        this._finished = false;
-        this._pax = null;
-        this._paxGlobal = null;
-        this._gnuLongPath = null;
-        this._gnuLongLinkPath = null;
-        this._filenameEncoding = opts.filenameEncoding || "utf-8";
-        this._allowUnknownFormat = !!opts.allowUnknownFormat;
-        this._unlockBound = this._unlock.bind(this);
+  }
+});
+
+// node_modules/unzip-stream/lib/extract.js
+var require_extract2 = __commonJS({
+  "node_modules/unzip-stream/lib/extract.js"(exports2, module2) {
+    var fs2 = require("fs");
+    var path2 = require("path");
+    var util = require("util");
+    var mkdirp = require_mkdirp();
+    var Transform = require("stream").Transform;
+    var UnzipStream = require_unzip_stream();
+    function Extract(opts) {
+      if (!(this instanceof Extract))
+        return new Extract(opts);
+      Transform.call(this);
+      this.opts = opts || {};
+      this.unzipStream = new UnzipStream(this.opts);
+      this.unfinishedEntries = 0;
+      this.afterFlushWait = false;
+      this.createdDirectories = {};
+      var self2 = this;
+      this.unzipStream.on("entry", this._processEntry.bind(this));
+      this.unzipStream.on("error", function(error4) {
+        self2.emit("error", error4);
+      });
+    }
+    util.inherits(Extract, Transform);
+    Extract.prototype._transform = function(chunk, encoding, cb) {
+      this.unzipStream.write(chunk, encoding, cb);
+    };
+    Extract.prototype._flush = function(cb) {
+      var self2 = this;
+      var allDone = function() {
+        process.nextTick(function() {
+          self2.emit("close");
+        });
+        cb();
+      };
+      this.unzipStream.end(function() {
+        if (self2.unfinishedEntries > 0) {
+          self2.afterFlushWait = true;
+          return self2.on("await-finished", allDone);
+        }
+        allDone();
+      });
+    };
+    Extract.prototype._processEntry = function(entry) {
+      var self2 = this;
+      var destPath = path2.join(this.opts.path, entry.path);
+      var directory = entry.isDirectory ? destPath : path2.dirname(destPath);
+      this.unfinishedEntries++;
+      var writeFileFn = function() {
+        var pipedStream = fs2.createWriteStream(destPath);
+        pipedStream.on("close", function() {
+          self2.unfinishedEntries--;
+          self2._notifyAwaiter();
+        });
+        pipedStream.on("error", function(error4) {
+          self2.emit("error", error4);
+        });
+        entry.pipe(pipedStream);
+      };
+      if (this.createdDirectories[directory] || directory === ".") {
+        return writeFileFn();
       }
-      _unlock(err) {
-        this._locked = false;
-        if (err) {
-          this.destroy(err);
-          this._continueWrite(err);
+      mkdirp(directory, function(err) {
+        if (err) return self2.emit("error", err);
+        self2.createdDirectories[directory] = true;
+        if (entry.isDirectory) {
+          self2.unfinishedEntries--;
+          self2._notifyAwaiter();
           return;
         }
-        this._update();
+        writeFileFn();
+      });
+    };
+    Extract.prototype._notifyAwaiter = function() {
+      if (this.afterFlushWait && this.unfinishedEntries === 0) {
+        this.emit("await-finished");
+        this.afterFlushWait = false;
       }
-      _consumeHeader() {
-        if (this._locked) return false;
-        this._offset = this._buffer.shifted;
-        try {
-          this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat);
-        } catch (err) {
-          this._continueWrite(err);
-          return false;
-        }
-        if (!this._header) return true;
-        switch (this._header.type) {
-          case "gnu-long-path":
-          case "gnu-long-link-path":
-          case "pax-global-header":
-          case "pax-header":
-            this._longHeader = true;
-            this._missing = this._header.size;
-            return true;
-        }
-        this._locked = true;
-        this._applyLongHeaders();
-        if (this._header.size === 0 || this._header.type === "directory") {
-          this.emit("entry", this._header, this._createStream(), this._unlockBound);
-          return true;
-        }
-        this._stream = this._createStream();
-        this._missing = this._header.size;
-        this.emit("entry", this._header, this._stream, this._unlockBound);
-        return true;
+    };
+    module2.exports = Extract;
+  }
+});
+
+// node_modules/unzip-stream/unzip.js
+var require_unzip = __commonJS({
+  "node_modules/unzip-stream/unzip.js"(exports2) {
+    "use strict";
+    exports2.Parse = require_parser_stream();
+    exports2.Extract = require_extract2();
+  }
+});
+
+// node_modules/@actions/artifact/lib/internal/download/download-artifact.js
+var require_download_artifact = __commonJS({
+  "node_modules/@actions/artifact/lib/internal/download/download-artifact.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      _applyLongHeaders() {
-        if (this._gnuLongPath) {
-          this._header.name = this._gnuLongPath;
-          this._gnuLongPath = null;
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
+      var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function(o2) {
+          var ar = [];
+          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
+          return ar;
+        };
+        return ownKeys(o);
+      };
+      return function(mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) {
+          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
         }
-        if (this._gnuLongLinkPath) {
-          this._header.linkname = this._gnuLongLinkPath;
-          this._gnuLongLinkPath = null;
+        __setModuleDefault4(result, mod);
+        return result;
+      };
+    })();
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        if (this._pax) {
-          if (this._pax.path) this._header.name = this._pax.path;
-          if (this._pax.linkpath) this._header.linkname = this._pax.linkpath;
-          if (this._pax.size) this._header.size = parseInt(this._pax.size, 10);
-          this._header.pax = this._pax;
-          this._pax = null;
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
         }
-      }
-      _decodeLongHeader(buf) {
-        switch (this._header.type) {
-          case "gnu-long-path":
-            this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding);
-            break;
-          case "gnu-long-link-path":
-            this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding);
-            break;
-          case "pax-global-header":
-            this._paxGlobal = headers.decodePax(buf);
-            break;
-          case "pax-header":
-            this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf));
-            break;
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
         }
-      }
-      _consumeLongHeader() {
-        this._longHeader = false;
-        this._missing = overflow(this._header.size);
-        const buf = this._buffer.shift(this._header.size);
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
+      return mod && mod.__esModule ? mod : { "default": mod };
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.streamExtractExternal = streamExtractExternal;
+    exports2.downloadArtifactPublic = downloadArtifactPublic;
+    exports2.downloadArtifactInternal = downloadArtifactInternal;
+    var promises_1 = __importDefault4(require("fs/promises"));
+    var crypto = __importStar4(require("crypto"));
+    var stream = __importStar4(require("stream"));
+    var github2 = __importStar4(require_github());
+    var core14 = __importStar4(require_core());
+    var httpClient = __importStar4(require_lib3());
+    var unzip_stream_1 = __importDefault4(require_unzip());
+    var user_agent_1 = require_user_agent();
+    var config_1 = require_config();
+    var artifact_twirp_client_1 = require_artifact_twirp_client2();
+    var generated_1 = require_generated();
+    var util_1 = require_util8();
+    var errors_1 = require_errors2();
+    var scrubQueryParameters = (url) => {
+      const parsed = new URL(url);
+      parsed.search = "";
+      return parsed.toString();
+    };
+    function exists(path2) {
+      return __awaiter4(this, void 0, void 0, function* () {
         try {
-          this._decodeLongHeader(buf);
-        } catch (err) {
-          this._continueWrite(err);
-          return false;
-        }
-        return true;
-      }
-      _consumeStream() {
-        const buf = this._buffer.shiftFirst(this._missing);
-        if (buf === null) return false;
-        this._missing -= buf.byteLength;
-        const drained = this._stream.push(buf);
-        if (this._missing === 0) {
-          this._stream.push(null);
-          if (drained) this._stream._detach();
-          return drained && this._locked === false;
+          yield promises_1.default.access(path2);
+          return true;
+        } catch (error4) {
+          if (error4.code === "ENOENT") {
+            return false;
+          } else {
+            throw error4;
+          }
         }
-        return drained;
-      }
-      _createStream() {
-        return new Source(this, this._header, this._offset);
-      }
-      _update() {
-        while (this._buffer.buffered > 0 && !this.destroying) {
-          if (this._missing > 0) {
-            if (this._stream !== null) {
-              if (this._consumeStream() === false) return;
-              continue;
-            }
-            if (this._longHeader === true) {
-              if (this._missing > this._buffer.buffered) break;
-              if (this._consumeLongHeader() === false) return false;
-              continue;
-            }
-            const ignore = this._buffer.shiftFirst(this._missing);
-            if (ignore !== null) this._missing -= ignore.byteLength;
-            continue;
+      });
+    }
+    function streamExtract(url, directory) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        let retryCount = 0;
+        while (retryCount < 5) {
+          try {
+            return yield streamExtractExternal(url, directory);
+          } catch (error4) {
+            retryCount++;
+            core14.debug(`Failed to download artifact after ${retryCount} retries due to ${error4.message}. Retrying in 5 seconds...`);
+            yield new Promise((resolve2) => setTimeout(resolve2, 5e3));
           }
-          if (this._buffer.buffered < 512) break;
-          if (this._stream !== null || this._consumeHeader() === false) return;
         }
-        this._continueWrite(null);
-      }
-      _continueWrite(err) {
-        const cb = this._callback;
-        this._callback = noop;
-        cb(err);
-      }
-      _write(data, cb) {
-        this._callback = cb;
-        this._buffer.push(data);
-        this._update();
-      }
-      _final(cb) {
-        this._finished = this._missing === 0 && this._buffer.buffered === 0;
-        cb(this._finished ? null : new Error("Unexpected end of data"));
-      }
-      _predestroy() {
-        this._continueWrite(null);
-      }
-      _destroy(cb) {
-        if (this._stream) this._stream.destroy(getStreamError(this));
-        cb(null);
-      }
-      [Symbol.asyncIterator]() {
-        let error4 = null;
-        let promiseResolve = null;
-        let promiseReject = null;
-        let entryStream = null;
-        let entryCallback = null;
-        const extract2 = this;
-        this.on("entry", onentry);
-        this.on("error", (err) => {
-          error4 = err;
+        throw new Error(`Artifact download failed after ${retryCount} retries.`);
+      });
+    }
+    function streamExtractExternal(url_1, directory_1) {
+      return __awaiter4(this, arguments, void 0, function* (url, directory, opts = { timeout: 30 * 1e3 }) {
+        const client = new httpClient.HttpClient((0, user_agent_1.getUserAgentString)());
+        const response = yield client.get(url);
+        if (response.message.statusCode !== 200) {
+          throw new Error(`Unexpected HTTP response from blob storage: ${response.message.statusCode} ${response.message.statusMessage}`);
+        }
+        let sha256Digest = void 0;
+        return new Promise((resolve2, reject) => {
+          const timerFn = () => {
+            const timeoutError = new Error(`Blob storage chunk did not respond in ${opts.timeout}ms`);
+            response.message.destroy(timeoutError);
+            reject(timeoutError);
+          };
+          const timer = setTimeout(timerFn, opts.timeout);
+          const hashStream = crypto.createHash("sha256").setEncoding("hex");
+          const passThrough = new stream.PassThrough();
+          response.message.pipe(passThrough);
+          passThrough.pipe(hashStream);
+          const extractStream = passThrough;
+          extractStream.on("data", () => {
+            timer.refresh();
+          }).on("error", (error4) => {
+            core14.debug(`response.message: Artifact download failed: ${error4.message}`);
+            clearTimeout(timer);
+            reject(error4);
+          }).pipe(unzip_stream_1.default.Extract({ path: directory })).on("close", () => {
+            clearTimeout(timer);
+            if (hashStream) {
+              hashStream.end();
+              sha256Digest = hashStream.read();
+              core14.info(`SHA256 digest of downloaded artifact is ${sha256Digest}`);
+            }
+            resolve2({ sha256Digest: `sha256:${sha256Digest}` });
+          }).on("error", (error4) => {
+            reject(error4);
+          });
+        });
+      });
+    }
+    function downloadArtifactPublic(artifactId, repositoryOwner, repositoryName, token, options) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path);
+        const api = github2.getOctokit(token);
+        let digestMismatch = false;
+        core14.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`);
+        const { headers, status } = yield api.rest.actions.downloadArtifact({
+          owner: repositoryOwner,
+          repo: repositoryName,
+          artifact_id: artifactId,
+          archive_format: "zip",
+          request: {
+            redirect: "manual"
+          }
         });
-        this.on("close", onclose);
-        return {
-          [Symbol.asyncIterator]() {
-            return this;
-          },
-          next() {
-            return new Promise(onnext);
-          },
-          return() {
-            return destroy(null);
-          },
-          throw(err) {
-            return destroy(err);
+        if (status !== 302) {
+          throw new Error(`Unable to download artifact. Unexpected status: ${status}`);
+        }
+        const { location } = headers;
+        if (!location) {
+          throw new Error(`Unable to redirect to artifact download url`);
+        }
+        core14.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`);
+        try {
+          core14.info(`Starting download of artifact to: ${downloadPath}`);
+          const extractResponse = yield streamExtract(location, downloadPath);
+          core14.info(`Artifact download completed successfully.`);
+          if (options === null || options === void 0 ? void 0 : options.expectedHash) {
+            if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) {
+              digestMismatch = true;
+              core14.debug(`Computed digest: ${extractResponse.sha256Digest}`);
+              core14.debug(`Expected digest: ${options.expectedHash}`);
+            }
           }
+        } catch (error4) {
+          throw new Error(`Unable to download and extract artifact: ${error4.message}`);
+        }
+        return { downloadPath, digestMismatch };
+      });
+    }
+    function downloadArtifactInternal(artifactId, options) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path);
+        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
+        let digestMismatch = false;
+        const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)();
+        const listReq = {
+          workflowRunBackendId,
+          workflowJobRunBackendId,
+          idFilter: generated_1.Int64Value.create({ value: artifactId.toString() })
         };
-        function consumeCallback(err) {
-          if (!entryCallback) return;
-          const cb = entryCallback;
-          entryCallback = null;
-          cb(err);
+        const { artifacts } = yield artifactClient.ListArtifacts(listReq);
+        if (artifacts.length === 0) {
+          throw new errors_1.ArtifactNotFoundError(`No artifacts found for ID: ${artifactId}
+Are you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`);
         }
-        function onnext(resolve2, reject) {
-          if (error4) {
-            return reject(error4);
-          }
-          if (entryStream) {
-            resolve2({ value: entryStream, done: false });
-            entryStream = null;
-            return;
-          }
-          promiseResolve = resolve2;
-          promiseReject = reject;
-          consumeCallback(null);
-          if (extract2._finished && promiseResolve) {
-            promiseResolve({ value: void 0, done: true });
-            promiseResolve = promiseReject = null;
-          }
+        if (artifacts.length > 1) {
+          core14.warning("Multiple artifacts found, defaulting to first.");
         }
-        function onentry(header, stream, callback) {
-          entryCallback = callback;
-          stream.on("error", noop);
-          if (promiseResolve) {
-            promiseResolve({ value: stream, done: false });
-            promiseResolve = promiseReject = null;
-          } else {
-            entryStream = stream;
+        const signedReq = {
+          workflowRunBackendId: artifacts[0].workflowRunBackendId,
+          workflowJobRunBackendId: artifacts[0].workflowJobRunBackendId,
+          name: artifacts[0].name
+        };
+        const { signedUrl } = yield artifactClient.GetSignedArtifactURL(signedReq);
+        core14.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`);
+        try {
+          core14.info(`Starting download of artifact to: ${downloadPath}`);
+          const extractResponse = yield streamExtract(signedUrl, downloadPath);
+          core14.info(`Artifact download completed successfully.`);
+          if (options === null || options === void 0 ? void 0 : options.expectedHash) {
+            if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) {
+              digestMismatch = true;
+              core14.debug(`Computed digest: ${extractResponse.sha256Digest}`);
+              core14.debug(`Expected digest: ${options.expectedHash}`);
+            }
           }
+        } catch (error4) {
+          throw new Error(`Unable to download and extract artifact: ${error4.message}`);
         }
-        function onclose() {
-          consumeCallback(error4);
-          if (!promiseResolve) return;
-          if (error4) promiseReject(error4);
-          else promiseResolve({ value: void 0, done: true });
-          promiseResolve = promiseReject = null;
+        return { downloadPath, digestMismatch };
+      });
+    }
+    function resolveOrCreateDirectory() {
+      return __awaiter4(this, arguments, void 0, function* (downloadPath = (0, config_1.getGitHubWorkspaceDir)()) {
+        if (!(yield exists(downloadPath))) {
+          core14.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`);
+          yield promises_1.default.mkdir(downloadPath, { recursive: true });
+        } else {
+          core14.debug(`Artifact destination folder already exists: ${downloadPath}`);
         }
-        function destroy(err) {
-          extract2.destroy(err);
-          consumeCallback(err);
-          return new Promise((resolve2, reject) => {
-            if (extract2.destroyed) return resolve2({ value: void 0, done: true });
-            extract2.once("close", function() {
-              if (err) reject(err);
-              else resolve2({ value: void 0, done: true });
-            });
-          });
+        return downloadPath;
+      });
+    }
+  }
+});
+
+// node_modules/@actions/artifact/lib/internal/find/retry-options.js
+var require_retry_options = __commonJS({
+  "node_modules/@actions/artifact/lib/internal/find/retry-options.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
+      var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function(o2) {
+          var ar = [];
+          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
+          return ar;
+        };
+        return ownKeys(o);
+      };
+      return function(mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) {
+          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
         }
+        __setModuleDefault4(result, mod);
+        return result;
+      };
+    })();
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getRetryOptions = getRetryOptions;
+    var core14 = __importStar4(require_core());
+    var defaultMaxRetryNumber = 5;
+    var defaultExemptStatusCodes = [400, 401, 403, 404, 422];
+    function getRetryOptions(defaultOptions, retries = defaultMaxRetryNumber, exemptStatusCodes = defaultExemptStatusCodes) {
+      var _a;
+      if (retries <= 0) {
+        return [{ enabled: false }, defaultOptions.request];
       }
-    };
-    module2.exports = function extract2(opts) {
-      return new Extract(opts);
-    };
-    function noop() {
-    }
-    function overflow(size) {
-      size &= 511;
-      return size && 512 - size;
+      const retryOptions = {
+        enabled: true
+      };
+      if (exemptStatusCodes.length > 0) {
+        retryOptions.doNotRetry = exemptStatusCodes;
+      }
+      const requestOptions = Object.assign(Object.assign({}, defaultOptions.request), { retries });
+      core14.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a = retryOptions.doNotRetry) !== null && _a !== void 0 ? _a : "octokit default: [400, 401, 403, 404, 422]"})`);
+      return [retryOptions, requestOptions];
     }
   }
 });
 
-// node_modules/tar-stream/constants.js
-var require_constants9 = __commonJS({
-  "node_modules/tar-stream/constants.js"(exports2, module2) {
-    var constants = {
-      // just for envs without fs
-      S_IFMT: 61440,
-      S_IFDIR: 16384,
-      S_IFCHR: 8192,
-      S_IFBLK: 24576,
-      S_IFIFO: 4096,
-      S_IFLNK: 40960
-    };
-    try {
-      module2.exports = require("fs").constants || constants;
-    } catch {
-      module2.exports = constants;
+// node_modules/@octokit/plugin-request-log/dist-node/index.js
+var require_dist_node16 = __commonJS({
+  "node_modules/@octokit/plugin-request-log/dist-node/index.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    var VERSION = "1.0.4";
+    function requestLog(octokit) {
+      octokit.hook.wrap("request", (request, 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 request(options).then((response) => {
+          octokit.log.info(`${requestOptions.method} ${path2} - ${response.status} in ${Date.now() - start}ms`);
+          return response;
+        }).catch((error4) => {
+          octokit.log.info(`${requestOptions.method} ${path2} - ${error4.status} in ${Date.now() - start}ms`);
+          throw error4;
+        });
+      });
     }
+    requestLog.VERSION = VERSION;
+    exports2.requestLog = requestLog;
   }
 });
 
-// node_modules/tar-stream/pack.js
-var require_pack = __commonJS({
-  "node_modules/tar-stream/pack.js"(exports2, module2) {
-    var { Readable, Writable, getStreamError } = require_streamx();
-    var b4a = require_b4a();
-    var constants = require_constants9();
-    var headers = require_headers2();
-    var DMODE = 493;
-    var FMODE = 420;
-    var END_OF_TAR = b4a.alloc(1024);
-    var Sink = class extends Writable {
-      constructor(pack, header, callback) {
-        super({ mapWritable, eagerOpen: true });
-        this.written = 0;
-        this.header = header;
-        this._callback = callback;
-        this._linkname = null;
-        this._isLinkname = header.type === "symlink" && !header.linkname;
-        this._isVoid = header.type !== "file" && header.type !== "contiguous-file";
-        this._finished = false;
-        this._pack = pack;
-        this._openCallback = null;
-        if (this._pack._stream === null) this._pack._stream = this;
-        else this._pack._pending.push(this);
-      }
-      _open(cb) {
-        this._openCallback = cb;
-        if (this._pack._stream === this) this._continueOpen();
-      }
-      _continuePack(err) {
-        if (this._callback === null) return;
-        const callback = this._callback;
-        this._callback = null;
-        callback(err);
-      }
-      _continueOpen() {
-        if (this._pack._stream === null) this._pack._stream = this;
-        const cb = this._openCallback;
-        this._openCallback = null;
-        if (cb === null) return;
-        if (this._pack.destroying) return cb(new Error("pack stream destroyed"));
-        if (this._pack._finalized) return cb(new Error("pack stream is already finalized"));
-        this._pack._stream = this;
-        if (!this._isLinkname) {
-          this._pack._encode(this.header);
-        }
-        if (this._isVoid) {
-          this._finish();
-          this._continuePack(null);
-        }
-        cb(null);
-      }
-      _write(data, cb) {
-        if (this._isLinkname) {
-          this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data;
-          return cb(null);
-        }
-        if (this._isVoid) {
-          if (data.byteLength > 0) {
-            return cb(new Error("No body allowed for this entry"));
-          }
-          return cb();
-        }
-        this.written += data.byteLength;
-        if (this._pack.push(data)) return cb();
-        this._pack._drain = cb;
-      }
-      _finish() {
-        if (this._finished) return;
-        this._finished = true;
-        if (this._isLinkname) {
-          this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : "";
-          this._pack._encode(this.header);
-        }
-        overflow(this._pack, this.header.size);
-        this._pack._done(this);
-      }
-      _final(cb) {
-        if (this.written !== this.header.size) {
-          return cb(new Error("Size mismatch"));
-        }
-        this._finish();
-        cb(null);
-      }
-      _getError() {
-        return getStreamError(this) || new Error("tar entry destroyed");
-      }
-      _predestroy() {
-        this._pack.destroy(this._getError());
-      }
-      _destroy(cb) {
-        this._pack._done(this);
-        this._continuePack(this._finished ? null : this._getError());
-        cb();
-      }
-    };
-    var Pack = class extends Readable {
-      constructor(opts) {
-        super(opts);
-        this._drain = noop;
-        this._finalized = false;
-        this._finalizing = false;
-        this._pending = [];
-        this._stream = null;
+// node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js
+var require_dist_node17 = __commonJS({
+  "node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    function _interopDefault(ex) {
+      return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
+    }
+    var Bottleneck = _interopDefault(require_light());
+    async function errorRequest(octokit, state, error4, options) {
+      if (!error4.request || !error4.request.request) {
+        throw error4;
       }
-      entry(header, buffer, callback) {
-        if (this._finalized || this.destroying) throw new Error("already finalized or destroyed");
-        if (typeof buffer === "function") {
-          callback = buffer;
-          buffer = null;
-        }
-        if (!callback) callback = noop;
-        if (!header.size || header.type === "symlink") header.size = 0;
-        if (!header.type) header.type = modeToType(header.mode);
-        if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE;
-        if (!header.uid) header.uid = 0;
-        if (!header.gid) header.gid = 0;
-        if (!header.mtime) header.mtime = /* @__PURE__ */ new Date();
-        if (typeof buffer === "string") buffer = b4a.from(buffer);
-        const sink = new Sink(this, header, callback);
-        if (b4a.isBuffer(buffer)) {
-          header.size = buffer.byteLength;
-          sink.write(buffer);
-          sink.end();
-          return sink;
-        }
-        if (sink._isVoid) {
-          return sink;
-        }
-        return sink;
+      if (error4.status >= 400 && !state.doNotRetry.includes(error4.status)) {
+        const retries = options.request.retries != null ? options.request.retries : state.retries;
+        const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2);
+        throw octokit.retry.retryRequest(error4, retries, retryAfter);
       }
-      finalize() {
-        if (this._stream || this._pending.length > 0) {
-          this._finalizing = true;
-          return;
+      throw error4;
+    }
+    async function wrapRequest(state, request, options) {
+      const limiter = new Bottleneck();
+      limiter.on("failed", function(error4, info7) {
+        const maxRetries = ~~error4.request.request.retries;
+        const after = ~~error4.request.request.retryAfter;
+        options.request.retryCount = info7.retryCount + 1;
+        if (maxRetries > info7.retryCount) {
+          return after * state.retryAfterBaseValue;
         }
-        if (this._finalized) return;
-        this._finalized = true;
-        this.push(END_OF_TAR);
-        this.push(null);
-      }
-      _done(stream) {
-        if (stream !== this._stream) return;
-        this._stream = null;
-        if (this._finalizing) this.finalize();
-        if (this._pending.length) this._pending.shift()._continueOpen();
+      });
+      return limiter.schedule(request, options);
+    }
+    var VERSION = "3.0.9";
+    function retry3(octokit, octokitOptions) {
+      const state = Object.assign({
+        enabled: true,
+        retryAfterBaseValue: 1e3,
+        doNotRetry: [400, 401, 403, 404, 422],
+        retries: 3
+      }, octokitOptions.retry);
+      if (state.enabled) {
+        octokit.hook.error("request", errorRequest.bind(null, octokit, state));
+        octokit.hook.wrap("request", wrapRequest.bind(null, state));
       }
-      _encode(header) {
-        if (!header.pax) {
-          const buf = headers.encode(header);
-          if (buf) {
-            this.push(buf);
-            return;
+      return {
+        retry: {
+          retryRequest: (error4, retries, retryAfter) => {
+            error4.request.request = Object.assign({}, error4.request.request, {
+              retries,
+              retryAfter
+            });
+            return error4;
           }
-        }
-        this._encodePax(header);
-      }
-      _encodePax(header) {
-        const paxHeader = headers.encodePax({
-          name: header.name,
-          linkname: header.linkname,
-          pax: header.pax
-        });
-        const newHeader = {
-          name: "PaxHeader",
-          mode: header.mode,
-          uid: header.uid,
-          gid: header.gid,
-          size: paxHeader.byteLength,
-          mtime: header.mtime,
-          type: "pax-header",
-          linkname: header.linkname && "PaxHeader",
-          uname: header.uname,
-          gname: header.gname,
-          devmajor: header.devmajor,
-          devminor: header.devminor
-        };
-        this.push(headers.encode(newHeader));
-        this.push(paxHeader);
-        overflow(this, paxHeader.byteLength);
-        newHeader.size = header.size;
-        newHeader.type = header.type;
-        this.push(headers.encode(newHeader));
-      }
-      _doDrain() {
-        const drain = this._drain;
-        this._drain = noop;
-        drain();
-      }
-      _predestroy() {
-        const err = getStreamError(this);
-        if (this._stream) this._stream.destroy(err);
-        while (this._pending.length) {
-          const stream = this._pending.shift();
-          stream.destroy(err);
-          stream._continueOpen();
-        }
-        this._doDrain();
-      }
-      _read(cb) {
-        this._doDrain();
-        cb();
-      }
-    };
-    module2.exports = function pack(opts) {
-      return new Pack(opts);
-    };
-    function modeToType(mode) {
-      switch (mode & constants.S_IFMT) {
-        case constants.S_IFBLK:
-          return "block-device";
-        case constants.S_IFCHR:
-          return "character-device";
-        case constants.S_IFDIR:
-          return "directory";
-        case constants.S_IFIFO:
-          return "fifo";
-        case constants.S_IFLNK:
-          return "symlink";
-      }
-      return "file";
-    }
-    function noop() {
-    }
-    function overflow(self2, size) {
-      size &= 511;
-      if (size) self2.push(END_OF_TAR.subarray(0, 512 - size));
-    }
-    function mapWritable(buf) {
-      return b4a.isBuffer(buf) ? buf : b4a.from(buf);
+        }
+      };
     }
+    retry3.VERSION = VERSION;
+    exports2.VERSION = VERSION;
+    exports2.retry = retry3;
   }
 });
 
-// node_modules/tar-stream/index.js
-var require_tar_stream = __commonJS({
-  "node_modules/tar-stream/index.js"(exports2) {
-    exports2.extract = require_extract();
-    exports2.pack = require_pack();
-  }
-});
-
-// node_modules/archiver/lib/plugins/tar.js
-var require_tar = __commonJS({
-  "node_modules/archiver/lib/plugins/tar.js"(exports2, module2) {
-    var zlib = require("zlib");
-    var engine = require_tar_stream();
-    var util = require_archiver_utils();
-    var Tar = function(options) {
-      if (!(this instanceof Tar)) {
-        return new Tar(options);
-      }
-      options = this.options = util.defaults(options, {
-        gzip: false
-      });
-      if (typeof options.gzipOptions !== "object") {
-        options.gzipOptions = {};
+// node_modules/@actions/artifact/lib/internal/find/get-artifact.js
+var require_get_artifact = __commonJS({
+  "node_modules/@actions/artifact/lib/internal/find/get-artifact.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      this.supports = {
-        directory: true,
-        symlink: true
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
+      var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function(o2) {
+          var ar = [];
+          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
+          return ar;
+        };
+        return ownKeys(o);
       };
-      this.engine = engine.pack(options);
-      this.compressor = false;
-      if (options.gzip) {
-        this.compressor = zlib.createGzip(options.gzipOptions);
-        this.compressor.on("error", this._onCompressorError.bind(this));
-      }
-    };
-    Tar.prototype._onCompressorError = function(err) {
-      this.engine.emit("error", err);
-    };
-    Tar.prototype.append = function(source, data, callback) {
-      var self2 = this;
-      data.mtime = data.date;
-      function append(err, sourceBuffer) {
-        if (err) {
-          callback(err);
-          return;
+      return function(mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) {
+          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
         }
-        self2.engine.entry(data, sourceBuffer, function(err2) {
-          callback(err2, data);
-        });
-      }
-      if (data.sourceType === "buffer") {
-        append(null, source);
-      } else if (data.sourceType === "stream" && data.stats) {
-        data.size = data.stats.size;
-        var entry = self2.engine.entry(data, function(err) {
-          callback(err, data);
+        __setModuleDefault4(result, mod);
+        return result;
+      };
+    })();
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
         });
-        source.pipe(entry);
-      } else if (data.sourceType === "stream") {
-        util.collectStream(source, append);
-      }
-    };
-    Tar.prototype.finalize = function() {
-      this.engine.finalize();
-    };
-    Tar.prototype.on = function() {
-      return this.engine.on.apply(this.engine, arguments);
-    };
-    Tar.prototype.pipe = function(destination, options) {
-      if (this.compressor) {
-        return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options);
-      } else {
-        return this.engine.pipe.apply(this.engine, arguments);
-      }
-    };
-    Tar.prototype.unpipe = function() {
-      if (this.compressor) {
-        return this.compressor.unpipe.apply(this.compressor, arguments);
-      } else {
-        return this.engine.unpipe.apply(this.engine, arguments);
       }
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    module2.exports = Tar;
-  }
-});
-
-// node_modules/buffer-crc32/dist/index.cjs
-var require_dist8 = __commonJS({
-  "node_modules/buffer-crc32/dist/index.cjs"(exports2, module2) {
-    "use strict";
-    function getDefaultExportFromCjs(x) {
-      return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
-    }
-    var CRC_TABLE = new Int32Array([
-      0,
-      1996959894,
-      3993919788,
-      2567524794,
-      124634137,
-      1886057615,
-      3915621685,
-      2657392035,
-      249268274,
-      2044508324,
-      3772115230,
-      2547177864,
-      162941995,
-      2125561021,
-      3887607047,
-      2428444049,
-      498536548,
-      1789927666,
-      4089016648,
-      2227061214,
-      450548861,
-      1843258603,
-      4107580753,
-      2211677639,
-      325883990,
-      1684777152,
-      4251122042,
-      2321926636,
-      335633487,
-      1661365465,
-      4195302755,
-      2366115317,
-      997073096,
-      1281953886,
-      3579855332,
-      2724688242,
-      1006888145,
-      1258607687,
-      3524101629,
-      2768942443,
-      901097722,
-      1119000684,
-      3686517206,
-      2898065728,
-      853044451,
-      1172266101,
-      3705015759,
-      2882616665,
-      651767980,
-      1373503546,
-      3369554304,
-      3218104598,
-      565507253,
-      1454621731,
-      3485111705,
-      3099436303,
-      671266974,
-      1594198024,
-      3322730930,
-      2970347812,
-      795835527,
-      1483230225,
-      3244367275,
-      3060149565,
-      1994146192,
-      31158534,
-      2563907772,
-      4023717930,
-      1907459465,
-      112637215,
-      2680153253,
-      3904427059,
-      2013776290,
-      251722036,
-      2517215374,
-      3775830040,
-      2137656763,
-      141376813,
-      2439277719,
-      3865271297,
-      1802195444,
-      476864866,
-      2238001368,
-      4066508878,
-      1812370925,
-      453092731,
-      2181625025,
-      4111451223,
-      1706088902,
-      314042704,
-      2344532202,
-      4240017532,
-      1658658271,
-      366619977,
-      2362670323,
-      4224994405,
-      1303535960,
-      984961486,
-      2747007092,
-      3569037538,
-      1256170817,
-      1037604311,
-      2765210733,
-      3554079995,
-      1131014506,
-      879679996,
-      2909243462,
-      3663771856,
-      1141124467,
-      855842277,
-      2852801631,
-      3708648649,
-      1342533948,
-      654459306,
-      3188396048,
-      3373015174,
-      1466479909,
-      544179635,
-      3110523913,
-      3462522015,
-      1591671054,
-      702138776,
-      2966460450,
-      3352799412,
-      1504918807,
-      783551873,
-      3082640443,
-      3233442989,
-      3988292384,
-      2596254646,
-      62317068,
-      1957810842,
-      3939845945,
-      2647816111,
-      81470997,
-      1943803523,
-      3814918930,
-      2489596804,
-      225274430,
-      2053790376,
-      3826175755,
-      2466906013,
-      167816743,
-      2097651377,
-      4027552580,
-      2265490386,
-      503444072,
-      1762050814,
-      4150417245,
-      2154129355,
-      426522225,
-      1852507879,
-      4275313526,
-      2312317920,
-      282753626,
-      1742555852,
-      4189708143,
-      2394877945,
-      397917763,
-      1622183637,
-      3604390888,
-      2714866558,
-      953729732,
-      1340076626,
-      3518719985,
-      2797360999,
-      1068828381,
-      1219638859,
-      3624741850,
-      2936675148,
-      906185462,
-      1090812512,
-      3747672003,
-      2825379669,
-      829329135,
-      1181335161,
-      3412177804,
-      3160834842,
-      628085408,
-      1382605366,
-      3423369109,
-      3138078467,
-      570562233,
-      1426400815,
-      3317316542,
-      2998733608,
-      733239954,
-      1555261956,
-      3268935591,
-      3050360625,
-      752459403,
-      1541320221,
-      2607071920,
-      3965973030,
-      1969922972,
-      40735498,
-      2617837225,
-      3943577151,
-      1913087877,
-      83908371,
-      2512341634,
-      3803740692,
-      2075208622,
-      213261112,
-      2463272603,
-      3855990285,
-      2094854071,
-      198958881,
-      2262029012,
-      4057260610,
-      1759359992,
-      534414190,
-      2176718541,
-      4139329115,
-      1873836001,
-      414664567,
-      2282248934,
-      4279200368,
-      1711684554,
-      285281116,
-      2405801727,
-      4167216745,
-      1634467795,
-      376229701,
-      2685067896,
-      3608007406,
-      1308918612,
-      956543938,
-      2808555105,
-      3495958263,
-      1231636301,
-      1047427035,
-      2932959818,
-      3654703836,
-      1088359270,
-      936918e3,
-      2847714899,
-      3736837829,
-      1202900863,
-      817233897,
-      3183342108,
-      3401237130,
-      1404277552,
-      615818150,
-      3134207493,
-      3453421203,
-      1423857449,
-      601450431,
-      3009837614,
-      3294710456,
-      1567103746,
-      711928724,
-      3020668471,
-      3272380065,
-      1510334235,
-      755167117
-    ]);
-    function ensureBuffer(input) {
-      if (Buffer.isBuffer(input)) {
-        return input;
-      }
-      if (typeof input === "number") {
-        return Buffer.alloc(input);
-      } else if (typeof input === "string") {
-        return Buffer.from(input);
-      } else {
-        throw new Error("input must be buffer, number, or string, received " + typeof input);
-      }
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getArtifactPublic = getArtifactPublic;
+    exports2.getArtifactInternal = getArtifactInternal;
+    var github_1 = require_github();
+    var plugin_retry_1 = require_dist_node17();
+    var core14 = __importStar4(require_core());
+    var utils_1 = require_utils4();
+    var retry_options_1 = require_retry_options();
+    var plugin_request_log_1 = require_dist_node16();
+    var util_1 = require_util8();
+    var user_agent_1 = require_user_agent();
+    var artifact_twirp_client_1 = require_artifact_twirp_client2();
+    var generated_1 = require_generated();
+    var errors_1 = require_errors2();
+    function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        var _a;
+        const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults);
+        const opts = {
+          log: void 0,
+          userAgent: (0, user_agent_1.getUserAgentString)(),
+          previews: void 0,
+          retry: retryOpts,
+          request: requestOpts
+        };
+        const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog);
+        const getArtifactResp = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}", {
+          owner: repositoryOwner,
+          repo: repositoryName,
+          run_id: workflowRunId,
+          name: artifactName
+        });
+        if (getArtifactResp.status !== 200) {
+          throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`);
+        }
+        if (getArtifactResp.data.artifacts.length === 0) {
+          throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}
+        Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.
+        For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`);
+        }
+        let artifact2 = getArtifactResp.data.artifacts[0];
+        if (getArtifactResp.data.artifacts.length > 1) {
+          artifact2 = getArtifactResp.data.artifacts.sort((a, b) => b.id - a.id)[0];
+          core14.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.id})`);
+        }
+        return {
+          artifact: {
+            name: artifact2.name,
+            id: artifact2.id,
+            size: artifact2.size_in_bytes,
+            createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0,
+            digest: artifact2.digest
+          }
+        };
+      });
     }
-    function bufferizeInt(num) {
-      const tmp = ensureBuffer(4);
-      tmp.writeInt32BE(num, 0);
-      return tmp;
+    function getArtifactInternal(artifactName) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        var _a;
+        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
+        const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)();
+        const req = {
+          workflowRunBackendId,
+          workflowJobRunBackendId,
+          nameFilter: generated_1.StringValue.create({ value: artifactName })
+        };
+        const res = yield artifactClient.ListArtifacts(req);
+        if (res.artifacts.length === 0) {
+          throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}
+        Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.
+        For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`);
+        }
+        let artifact2 = res.artifacts[0];
+        if (res.artifacts.length > 1) {
+          artifact2 = res.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0];
+          core14.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`);
+        }
+        return {
+          artifact: {
+            name: artifact2.name,
+            id: Number(artifact2.databaseId),
+            size: Number(artifact2.size),
+            createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0,
+            digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value
+          }
+        };
+      });
     }
-    function _crc32(buf, previous) {
-      buf = ensureBuffer(buf);
-      if (Buffer.isBuffer(previous)) {
-        previous = previous.readUInt32BE(0);
-      }
-      let crc = ~~previous ^ -1;
-      for (var n = 0; n < buf.length; n++) {
-        crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8;
+  }
+});
+
+// node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js
+var require_delete_artifact = __commonJS({
+  "node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      return crc ^ -1;
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.deleteArtifactPublic = deleteArtifactPublic;
+    exports2.deleteArtifactInternal = deleteArtifactInternal;
+    var core_1 = require_core();
+    var github_1 = require_github();
+    var user_agent_1 = require_user_agent();
+    var retry_options_1 = require_retry_options();
+    var utils_1 = require_utils4();
+    var plugin_request_log_1 = require_dist_node16();
+    var plugin_retry_1 = require_dist_node17();
+    var artifact_twirp_client_1 = require_artifact_twirp_client2();
+    var util_1 = require_util8();
+    var generated_1 = require_generated();
+    var get_artifact_1 = require_get_artifact();
+    var errors_1 = require_errors2();
+    function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        var _a;
+        const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults);
+        const opts = {
+          log: void 0,
+          userAgent: (0, user_agent_1.getUserAgentString)(),
+          previews: void 0,
+          retry: retryOpts,
+          request: requestOpts
+        };
+        const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog);
+        const getArtifactResp = yield (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token);
+        const deleteArtifactResp = yield github2.rest.actions.deleteArtifact({
+          owner: repositoryOwner,
+          repo: repositoryName,
+          artifact_id: getArtifactResp.artifact.id
+        });
+        if (deleteArtifactResp.status !== 204) {
+          throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`);
+        }
+        return {
+          id: getArtifactResp.artifact.id
+        };
+      });
     }
-    function crc32() {
-      return bufferizeInt(_crc32.apply(null, arguments));
+    function deleteArtifactInternal(artifactName) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
+        const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)();
+        const listReq = {
+          workflowRunBackendId,
+          workflowJobRunBackendId,
+          nameFilter: generated_1.StringValue.create({ value: artifactName })
+        };
+        const listRes = yield artifactClient.ListArtifacts(listReq);
+        if (listRes.artifacts.length === 0) {
+          throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`);
+        }
+        let artifact2 = listRes.artifacts[0];
+        if (listRes.artifacts.length > 1) {
+          artifact2 = listRes.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0];
+          (0, core_1.debug)(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`);
+        }
+        const req = {
+          workflowRunBackendId: artifact2.workflowRunBackendId,
+          workflowJobRunBackendId: artifact2.workflowJobRunBackendId,
+          name: artifact2.name
+        };
+        const res = yield artifactClient.DeleteArtifact(req);
+        (0, core_1.info)(`Artifact '${artifactName}' (ID: ${res.artifactId}) deleted`);
+        return {
+          id: Number(res.artifactId)
+        };
+      });
     }
-    crc32.signed = function() {
-      return _crc32.apply(null, arguments);
-    };
-    crc32.unsigned = function() {
-      return _crc32.apply(null, arguments) >>> 0;
-    };
-    var bufferCrc32 = crc32;
-    var index = /* @__PURE__ */ getDefaultExportFromCjs(bufferCrc32);
-    module2.exports = index;
   }
 });
 
-// node_modules/archiver/lib/plugins/json.js
-var require_json = __commonJS({
-  "node_modules/archiver/lib/plugins/json.js"(exports2, module2) {
-    var inherits = require("util").inherits;
-    var Transform = require_ours().Transform;
-    var crc32 = require_dist8();
-    var util = require_archiver_utils();
-    var Json = function(options) {
-      if (!(this instanceof Json)) {
-        return new Json(options);
+// node_modules/@actions/artifact/lib/internal/find/list-artifacts.js
+var require_list_artifacts = __commonJS({
+  "node_modules/@actions/artifact/lib/internal/find/list-artifacts.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      options = this.options = util.defaults(options, {});
-      Transform.call(this, options);
-      this.supports = {
-        directory: true,
-        symlink: true
-      };
-      this.files = [];
-    };
-    inherits(Json, Transform);
-    Json.prototype._transform = function(chunk, encoding, callback) {
-      callback(null, chunk);
-    };
-    Json.prototype._writeStringified = function() {
-      var fileString = JSON.stringify(this.files);
-      this.write(fileString);
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    Json.prototype.append = function(source, data, callback) {
-      var self2 = this;
-      data.crc32 = 0;
-      function onend(err, sourceBuffer) {
-        if (err) {
-          callback(err);
-          return;
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.listArtifactsPublic = listArtifactsPublic;
+    exports2.listArtifactsInternal = listArtifactsInternal;
+    var core_1 = require_core();
+    var github_1 = require_github();
+    var user_agent_1 = require_user_agent();
+    var retry_options_1 = require_retry_options();
+    var utils_1 = require_utils4();
+    var plugin_request_log_1 = require_dist_node16();
+    var plugin_retry_1 = require_dist_node17();
+    var artifact_twirp_client_1 = require_artifact_twirp_client2();
+    var util_1 = require_util8();
+    var config_1 = require_config();
+    var generated_1 = require_generated();
+    var maximumArtifactCount = (0, config_1.getMaxArtifactListCount)();
+    var paginationCount = 100;
+    var maxNumberOfPages = Math.ceil(maximumArtifactCount / paginationCount);
+    function listArtifactsPublic(workflowRunId_1, repositoryOwner_1, repositoryName_1, token_1) {
+      return __awaiter4(this, arguments, void 0, function* (workflowRunId, repositoryOwner, repositoryName, token, latest = false) {
+        (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`);
+        let artifacts = [];
+        const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults);
+        const opts = {
+          log: void 0,
+          userAgent: (0, user_agent_1.getUserAgentString)(),
+          previews: void 0,
+          retry: retryOpts,
+          request: requestOpts
+        };
+        const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog);
+        let currentPageNumber = 1;
+        const { data: listArtifactResponse } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", {
+          owner: repositoryOwner,
+          repo: repositoryName,
+          run_id: workflowRunId,
+          per_page: paginationCount,
+          page: currentPageNumber
+        });
+        let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount);
+        const totalArtifactCount = listArtifactResponse.total_count;
+        if (totalArtifactCount > maximumArtifactCount) {
+          (0, core_1.warning)(`Workflow run ${workflowRunId} has ${totalArtifactCount} artifacts, exceeding the limit of ${maximumArtifactCount}. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`);
+          numberOfPages = maxNumberOfPages;
+        }
+        for (const artifact2 of listArtifactResponse.artifacts) {
+          artifacts.push({
+            name: artifact2.name,
+            id: artifact2.id,
+            size: artifact2.size_in_bytes,
+            createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0,
+            digest: artifact2.digest
+          });
+        }
+        currentPageNumber++;
+        for (currentPageNumber; currentPageNumber <= numberOfPages; currentPageNumber++) {
+          (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`);
+          const { data: listArtifactResponse2 } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", {
+            owner: repositoryOwner,
+            repo: repositoryName,
+            run_id: workflowRunId,
+            per_page: paginationCount,
+            page: currentPageNumber
+          });
+          for (const artifact2 of listArtifactResponse2.artifacts) {
+            artifacts.push({
+              name: artifact2.name,
+              id: artifact2.id,
+              size: artifact2.size_in_bytes,
+              createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0,
+              digest: artifact2.digest
+            });
+          }
+        }
+        if (latest) {
+          artifacts = filterLatest(artifacts);
+        }
+        (0, core_1.info)(`Found ${artifacts.length} artifact(s)`);
+        return {
+          artifacts
+        };
+      });
+    }
+    function listArtifactsInternal() {
+      return __awaiter4(this, arguments, void 0, function* (latest = false) {
+        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
+        const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)();
+        const req = {
+          workflowRunBackendId,
+          workflowJobRunBackendId
+        };
+        const res = yield artifactClient.ListArtifacts(req);
+        let artifacts = res.artifacts.map((artifact2) => {
+          var _a;
+          return {
+            name: artifact2.name,
+            id: Number(artifact2.databaseId),
+            size: Number(artifact2.size),
+            createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0,
+            digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value
+          };
+        });
+        if (latest) {
+          artifacts = filterLatest(artifacts);
+        }
+        (0, core_1.info)(`Found ${artifacts.length} artifact(s)`);
+        return {
+          artifacts
+        };
+      });
+    }
+    function filterLatest(artifacts) {
+      artifacts.sort((a, b) => b.id - a.id);
+      const latestArtifacts = [];
+      const seenArtifactNames = /* @__PURE__ */ new Set();
+      for (const artifact2 of artifacts) {
+        if (!seenArtifactNames.has(artifact2.name)) {
+          latestArtifacts.push(artifact2);
+          seenArtifactNames.add(artifact2.name);
         }
-        data.size = sourceBuffer.length || 0;
-        data.crc32 = crc32.unsigned(sourceBuffer);
-        self2.files.push(data);
-        callback(null, data);
-      }
-      if (data.sourceType === "buffer") {
-        onend(null, source);
-      } else if (data.sourceType === "stream") {
-        util.collectStream(source, onend);
       }
-    };
-    Json.prototype.finalize = function() {
-      this._writeStringified();
-      this.end();
-    };
-    module2.exports = Json;
+      return latestArtifacts;
+    }
   }
 });
 
-// node_modules/archiver/index.js
-var require_archiver = __commonJS({
-  "node_modules/archiver/index.js"(exports2, module2) {
-    var Archiver = require_core2();
-    var formats = {};
-    var vending = function(format, options) {
-      return vending.create(format, options);
-    };
-    vending.create = function(format, options) {
-      if (formats[format]) {
-        var instance = new Archiver(format, options);
-        instance.setFormat(format);
-        instance.setModule(new formats[format](options));
-        return instance;
-      } else {
-        throw new Error("create(" + format + "): format not registered");
+// node_modules/@actions/artifact/lib/internal/client.js
+var require_client2 = __commonJS({
+  "node_modules/@actions/artifact/lib/internal/client.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    vending.registerFormat = function(format, module3) {
-      if (formats[format]) {
-        throw new Error("register(" + format + "): format already registered");
+    var __rest4 = exports2 && exports2.__rest || function(s, e) {
+      var t = {};
+      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+        t[p] = s[p];
+      if (s != null && typeof Object.getOwnPropertySymbols === "function")
+        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+            t[p[i]] = s[p[i]];
+        }
+      return t;
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.DefaultArtifactClient = void 0;
+    var core_1 = require_core();
+    var config_1 = require_config();
+    var upload_artifact_1 = require_upload_artifact();
+    var download_artifact_1 = require_download_artifact();
+    var delete_artifact_1 = require_delete_artifact();
+    var get_artifact_1 = require_get_artifact();
+    var list_artifacts_1 = require_list_artifacts();
+    var errors_1 = require_errors2();
+    var DefaultArtifactClient2 = class {
+      uploadArtifact(name, files, rootDirectory, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          try {
+            if ((0, config_1.isGhes)()) {
+              throw new errors_1.GHESNotSupportedError();
+            }
+            return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options);
+          } catch (error4) {
+            (0, core_1.warning)(`Artifact upload failed with error: ${error4}.
+
+Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
+
+If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
+            throw error4;
+          }
+        });
       }
-      if (typeof module3 !== "function") {
-        throw new Error("register(" + format + "): format module invalid");
+      downloadArtifact(artifactId, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          try {
+            if ((0, config_1.isGhes)()) {
+              throw new errors_1.GHESNotSupportedError();
+            }
+            if (options === null || options === void 0 ? void 0 : options.findBy) {
+              const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest4(options, ["findBy"]);
+              return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions);
+            }
+            return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options);
+          } catch (error4) {
+            (0, core_1.warning)(`Download Artifact failed with error: ${error4}.
+
+Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
+
+If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
+            throw error4;
+          }
+        });
       }
-      if (typeof module3.prototype.append !== "function" || typeof module3.prototype.finalize !== "function") {
-        throw new Error("register(" + format + "): format module missing methods");
+      listArtifacts(options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          try {
+            if ((0, config_1.isGhes)()) {
+              throw new errors_1.GHESNotSupportedError();
+            }
+            if (options === null || options === void 0 ? void 0 : options.findBy) {
+              const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options;
+              return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest);
+            }
+            return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest);
+          } catch (error4) {
+            (0, core_1.warning)(`Listing Artifacts failed with error: ${error4}.
+
+Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
+
+If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
+            throw error4;
+          }
+        });
       }
-      formats[format] = module3;
-    };
-    vending.isRegisteredFormat = function(format) {
-      if (formats[format]) {
-        return true;
+      getArtifact(artifactName, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          try {
+            if ((0, config_1.isGhes)()) {
+              throw new errors_1.GHESNotSupportedError();
+            }
+            if (options === null || options === void 0 ? void 0 : options.findBy) {
+              const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options;
+              return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token);
+            }
+            return (0, get_artifact_1.getArtifactInternal)(artifactName);
+          } catch (error4) {
+            (0, core_1.warning)(`Get Artifact failed with error: ${error4}.
+
+Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
+
+If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
+            throw error4;
+          }
+        });
+      }
+      deleteArtifact(artifactName, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          try {
+            if ((0, config_1.isGhes)()) {
+              throw new errors_1.GHESNotSupportedError();
+            }
+            if (options === null || options === void 0 ? void 0 : options.findBy) {
+              const { findBy: { repositoryOwner, repositoryName, workflowRunId, token } } = options;
+              return (0, delete_artifact_1.deleteArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token);
+            }
+            return (0, delete_artifact_1.deleteArtifactInternal)(artifactName);
+          } catch (error4) {
+            (0, core_1.warning)(`Delete Artifact failed with error: ${error4}.
+
+Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
+
+If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
+            throw error4;
+          }
+        });
       }
-      return false;
     };
-    vending.registerFormat("zip", require_zip());
-    vending.registerFormat("tar", require_tar());
-    vending.registerFormat("json", require_json());
-    module2.exports = vending;
+    exports2.DefaultArtifactClient = DefaultArtifactClient2;
   }
 });
 
-// node_modules/@actions/artifact/lib/internal/upload/zip.js
-var require_zip2 = __commonJS({
-  "node_modules/@actions/artifact/lib/internal/upload/zip.js"(exports2) {
+// node_modules/@actions/artifact/lib/internal/shared/interfaces.js
+var require_interfaces2 = __commonJS({
+  "node_modules/@actions/artifact/lib/internal/shared/interfaces.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+  }
+});
+
+// node_modules/@actions/artifact/lib/artifact.js
+var require_artifact2 = __commonJS({
+  "node_modules/@actions/artifact/lib/artifact.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -95261,137 +99919,80 @@ var require_zip2 = __commonJS({
       if (k2 === void 0) k2 = k;
       o[k2] = m[k];
     }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
-      var ownKeys = function(o) {
-        ownKeys = Object.getOwnPropertyNames || function(o2) {
-          var ar = [];
-          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
-          return ar;
-        };
-        return ownKeys(o);
-      };
-      return function(mod) {
-        if (mod && mod.__esModule) return mod;
-        var result = {};
-        if (mod != null) {
-          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
-        }
-        __setModuleDefault4(result, mod);
-        return result;
-      };
-    })();
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
+    var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) {
+      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p);
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ZipUploadStream = exports2.DEFAULT_COMPRESSION_LEVEL = void 0;
-    exports2.createZipUploadStream = createZipUploadStream;
-    var stream = __importStar4(require("stream"));
-    var promises_1 = require("fs/promises");
-    var archiver2 = __importStar4(require_archiver());
-    var core14 = __importStar4(require_core());
-    var config_1 = require_config();
-    exports2.DEFAULT_COMPRESSION_LEVEL = 6;
-    var ZipUploadStream = class extends stream.Transform {
-      constructor(bufferSize) {
-        super({
-          highWaterMark: bufferSize
-        });
-      }
-      // eslint-disable-next-line @typescript-eslint/no-explicit-any
-      _transform(chunk, enc, cb) {
-        cb(null, chunk);
+    var client_1 = require_client2();
+    __exportStar4(require_interfaces2(), exports2);
+    __exportStar4(require_errors2(), exports2);
+    __exportStar4(require_client2(), exports2);
+    var client = new client_1.DefaultArtifactClient();
+    exports2.default = client;
+  }
+});
+
+// node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js
+var require_path_and_artifact_name_validation2 = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.checkArtifactFilePath = exports2.checkArtifactName = void 0;
+    var core_1 = require_core();
+    var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([
+      ['"', ' Double quote "'],
+      [":", " Colon :"],
+      ["<", " Less than <"],
+      [">", " Greater than >"],
+      ["|", " Vertical bar |"],
+      ["*", " Asterisk *"],
+      ["?", " Question mark ?"],
+      ["\r", " Carriage return \\r"],
+      ["\n", " Line feed \\n"]
+    ]);
+    var invalidArtifactNameCharacters = new Map([
+      ...invalidArtifactFilePathCharacters,
+      ["\\", " Backslash \\"],
+      ["/", " Forward slash /"]
+    ]);
+    function checkArtifactName(name) {
+      if (!name) {
+        throw new Error(`Artifact name: ${name}, is incorrectly provided`);
       }
-    };
-    exports2.ZipUploadStream = ZipUploadStream;
-    function createZipUploadStream(uploadSpecification_1) {
-      return __awaiter4(this, arguments, void 0, function* (uploadSpecification, compressionLevel = exports2.DEFAULT_COMPRESSION_LEVEL) {
-        core14.debug(`Creating Artifact archive with compressionLevel: ${compressionLevel}`);
-        const zip = archiver2.create("zip", {
-          highWaterMark: (0, config_1.getUploadChunkSize)(),
-          zlib: { level: compressionLevel }
-        });
-        zip.on("error", zipErrorCallback);
-        zip.on("warning", zipWarningCallback);
-        zip.on("finish", zipFinishCallback);
-        zip.on("end", zipEndCallback);
-        for (const file of uploadSpecification) {
-          if (file.sourcePath !== null) {
-            let sourcePath = file.sourcePath;
-            if (file.stats.isSymbolicLink()) {
-              sourcePath = yield (0, promises_1.realpath)(file.sourcePath);
-            }
-            zip.file(sourcePath, {
-              name: file.destinationPath
-            });
-          } else {
-            zip.append("", { name: file.destinationPath });
-          }
+      for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) {
+        if (name.includes(invalidCharacterKey)) {
+          throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter}
+          
+Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()}
+          
+These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`);
         }
-        const bufferSize = (0, config_1.getUploadChunkSize)();
-        const zipUploadStream = new ZipUploadStream(bufferSize);
-        core14.debug(`Zip write high watermark value ${zipUploadStream.writableHighWaterMark}`);
-        core14.debug(`Zip read high watermark value ${zipUploadStream.readableHighWaterMark}`);
-        zip.pipe(zipUploadStream);
-        zip.finalize();
-        return zipUploadStream;
-      });
+      }
+      (0, core_1.info)(`Artifact name is valid!`);
     }
-    var zipErrorCallback = (error4) => {
-      core14.error("An error has occurred while creating the zip file for upload");
-      core14.info(error4);
-      throw new Error("An error has occurred during zip creation for the artifact");
-    };
-    var zipWarningCallback = (error4) => {
-      if (error4.code === "ENOENT") {
-        core14.warning("ENOENT warning during artifact zip creation. No such file or directory");
-        core14.info(error4);
-      } else {
-        core14.warning(`A non-blocking warning has occurred during artifact zip creation: ${error4.code}`);
-        core14.info(error4);
+    exports2.checkArtifactName = checkArtifactName;
+    function checkArtifactFilePath(path2) {
+      if (!path2) {
+        throw new Error(`Artifact path: ${path2}, is incorrectly provided`);
       }
-    };
-    var zipFinishCallback = () => {
-      core14.debug("Zip stream for upload has finished.");
-    };
-    var zipEndCallback = () => {
-      core14.debug("Zip stream for upload has ended.");
-    };
+      for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) {
+        if (path2.includes(invalidCharacterKey)) {
+          throw new Error(`Artifact path is not valid: ${path2}. Contains the following character: ${errorMessageForCharacter}
+          
+Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()}
+          
+The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.
+          `);
+        }
+      }
+    }
+    exports2.checkArtifactFilePath = checkArtifactFilePath;
   }
 });
 
-// node_modules/@actions/artifact/lib/internal/upload/upload-artifact.js
-var require_upload_artifact = __commonJS({
-  "node_modules/@actions/artifact/lib/internal/upload/upload-artifact.js"(exports2) {
+// node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js
+var require_upload_specification = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -95411,1996 +100012,1978 @@ var require_upload_artifact = __commonJS({
     }) : function(o, v) {
       o["default"] = v;
     });
-    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
-      var ownKeys = function(o) {
-        ownKeys = Object.getOwnPropertyNames || function(o2) {
-          var ar = [];
-          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
-          return ar;
-        };
-        return ownKeys(o);
-      };
-      return function(mod) {
-        if (mod && mod.__esModule) return mod;
-        var result = {};
-        if (mod != null) {
-          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
-        }
-        __setModuleDefault4(result, mod);
-        return result;
-      };
-    })();
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
+      __setModuleDefault4(result, mod);
+      return result;
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.uploadArtifact = uploadArtifact;
-    var core14 = __importStar4(require_core());
-    var retention_1 = require_retention();
-    var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation();
-    var artifact_twirp_client_1 = require_artifact_twirp_client2();
-    var upload_zip_specification_1 = require_upload_zip_specification();
-    var util_1 = require_util8();
-    var blob_upload_1 = require_blob_upload();
-    var zip_1 = require_zip2();
-    var generated_1 = require_generated();
-    var errors_1 = require_errors2();
-    function uploadArtifact(name, files, rootDirectory, options) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        (0, path_and_artifact_name_validation_1.validateArtifactName)(name);
-        (0, upload_zip_specification_1.validateRootDirectory)(rootDirectory);
-        const zipSpecification = (0, upload_zip_specification_1.getUploadZipSpecification)(files, rootDirectory);
-        if (zipSpecification.length === 0) {
-          throw new errors_1.FilesNotFoundError(zipSpecification.flatMap((s) => s.sourcePath ? [s.sourcePath] : []));
-        }
-        const backendIds = (0, util_1.getBackendIdsFromToken)();
-        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
-        const createArtifactReq = {
-          workflowRunBackendId: backendIds.workflowRunBackendId,
-          workflowJobRunBackendId: backendIds.workflowJobRunBackendId,
-          name,
-          version: 4
-        };
-        const expiresAt = (0, retention_1.getExpiration)(options === null || options === void 0 ? void 0 : options.retentionDays);
-        if (expiresAt) {
-          createArtifactReq.expiresAt = expiresAt;
-        }
-        const createArtifactResp = yield artifactClient.CreateArtifact(createArtifactReq);
-        if (!createArtifactResp.ok) {
-          throw new errors_1.InvalidResponseError("CreateArtifact: response from backend was not ok");
-        }
-        const zipUploadStream = yield (0, zip_1.createZipUploadStream)(zipSpecification, options === null || options === void 0 ? void 0 : options.compressionLevel);
-        const uploadResult = yield (0, blob_upload_1.uploadZipToBlobStorage)(createArtifactResp.signedUploadUrl, zipUploadStream);
-        const finalizeArtifactReq = {
-          workflowRunBackendId: backendIds.workflowRunBackendId,
-          workflowJobRunBackendId: backendIds.workflowJobRunBackendId,
-          name,
-          size: uploadResult.uploadSize ? uploadResult.uploadSize.toString() : "0"
-        };
-        if (uploadResult.sha256Hash) {
-          finalizeArtifactReq.hash = generated_1.StringValue.create({
-            value: `sha256:${uploadResult.sha256Hash}`
-          });
-        }
-        core14.info(`Finalizing artifact upload`);
-        const finalizeArtifactResp = yield artifactClient.FinalizeArtifact(finalizeArtifactReq);
-        if (!finalizeArtifactResp.ok) {
-          throw new errors_1.InvalidResponseError("FinalizeArtifact: response from backend was not ok");
-        }
-        const artifactId = BigInt(finalizeArtifactResp.artifactId);
-        core14.info(`Artifact ${name}.zip successfully finalized. Artifact ID ${artifactId}`);
-        return {
-          size: uploadResult.uploadSize,
-          digest: uploadResult.sha256Hash,
-          id: Number(artifactId)
-        };
-      });
-    }
-  }
-});
-
-// node_modules/traverse/index.js
-var require_traverse = __commonJS({
-  "node_modules/traverse/index.js"(exports2, module2) {
-    module2.exports = Traverse;
-    function Traverse(obj) {
-      if (!(this instanceof Traverse)) return new Traverse(obj);
-      this.value = obj;
-    }
-    Traverse.prototype.get = function(ps) {
-      var node = this.value;
-      for (var i = 0; i < ps.length; i++) {
-        var key = ps[i];
-        if (!Object.hasOwnProperty.call(node, key)) {
-          node = void 0;
-          break;
-        }
-        node = node[key];
-      }
-      return node;
-    };
-    Traverse.prototype.set = function(ps, value) {
-      var node = this.value;
-      for (var i = 0; i < ps.length - 1; i++) {
-        var key = ps[i];
-        if (!Object.hasOwnProperty.call(node, key)) node[key] = {};
-        node = node[key];
-      }
-      node[ps[i]] = value;
-      return value;
-    };
-    Traverse.prototype.map = function(cb) {
-      return walk(this.value, cb, true);
-    };
-    Traverse.prototype.forEach = function(cb) {
-      this.value = walk(this.value, cb, false);
-      return this.value;
-    };
-    Traverse.prototype.reduce = function(cb, init) {
-      var skip = arguments.length === 1;
-      var acc = skip ? this.value : init;
-      this.forEach(function(x) {
-        if (!this.isRoot || !skip) {
-          acc = cb.call(this, acc, x);
-        }
-      });
-      return acc;
-    };
-    Traverse.prototype.deepEqual = function(obj) {
-      if (arguments.length !== 1) {
-        throw new Error(
-          "deepEqual requires exactly one object to compare against"
-        );
-      }
-      var equal = true;
-      var node = obj;
-      this.forEach(function(y) {
-        var notEqual = (function() {
-          equal = false;
-          return void 0;
-        }).bind(this);
-        if (!this.isRoot) {
-          if (typeof node !== "object") return notEqual();
-          node = node[this.key];
-        }
-        var x = node;
-        this.post(function() {
-          node = x;
-        });
-        var toS = function(o) {
-          return Object.prototype.toString.call(o);
-        };
-        if (this.circular) {
-          if (Traverse(obj).get(this.circular.path) !== x) notEqual();
-        } else if (typeof x !== typeof y) {
-          notEqual();
-        } else if (x === null || y === null || x === void 0 || y === void 0) {
-          if (x !== y) notEqual();
-        } else if (x.__proto__ !== y.__proto__) {
-          notEqual();
-        } else if (x === y) {
-        } else if (typeof x === "function") {
-          if (x instanceof RegExp) {
-            if (x.toString() != y.toString()) notEqual();
-          } else if (x !== y) notEqual();
-        } else if (typeof x === "object") {
-          if (toS(y) === "[object Arguments]" || toS(x) === "[object Arguments]") {
-            if (toS(x) !== toS(y)) {
-              notEqual();
-            }
-          } else if (x instanceof Date || y instanceof Date) {
-            if (!(x instanceof Date) || !(y instanceof Date) || x.getTime() !== y.getTime()) {
-              notEqual();
-            }
-          } else {
-            var kx = Object.keys(x);
-            var ky = Object.keys(y);
-            if (kx.length !== ky.length) return notEqual();
-            for (var i = 0; i < kx.length; i++) {
-              var k = kx[i];
-              if (!Object.hasOwnProperty.call(y, k)) {
-                notEqual();
-              }
-            }
-          }
-        }
-      });
-      return equal;
-    };
-    Traverse.prototype.paths = function() {
-      var acc = [];
-      this.forEach(function(x) {
-        acc.push(this.path);
-      });
-      return acc;
-    };
-    Traverse.prototype.nodes = function() {
-      var acc = [];
-      this.forEach(function(x) {
-        acc.push(this.node);
-      });
-      return acc;
-    };
-    Traverse.prototype.clone = function() {
-      var parents = [], nodes = [];
-      return (function clone(src) {
-        for (var i = 0; i < parents.length; i++) {
-          if (parents[i] === src) {
-            return nodes[i];
-          }
-        }
-        if (typeof src === "object" && src !== null) {
-          var dst = copy(src);
-          parents.push(src);
-          nodes.push(dst);
-          Object.keys(src).forEach(function(key) {
-            dst[key] = clone(src[key]);
-          });
-          parents.pop();
-          nodes.pop();
-          return dst;
-        } else {
-          return src;
-        }
-      })(this.value);
-    };
-    function walk(root, cb, immutable) {
-      var path2 = [];
-      var parents = [];
-      var alive = true;
-      return (function walker(node_) {
-        var node = immutable ? copy(node_) : node_;
-        var modifiers = {};
-        var state = {
-          node,
-          node_,
-          path: [].concat(path2),
-          parent: parents.slice(-1)[0],
-          key: path2.slice(-1)[0],
-          isRoot: path2.length === 0,
-          level: path2.length,
-          circular: null,
-          update: function(x) {
-            if (!state.isRoot) {
-              state.parent.node[state.key] = x;
-            }
-            state.node = x;
-          },
-          "delete": function() {
-            delete state.parent.node[state.key];
-          },
-          remove: function() {
-            if (Array.isArray(state.parent.node)) {
-              state.parent.node.splice(state.key, 1);
-            } else {
-              delete state.parent.node[state.key];
-            }
-          },
-          before: function(f) {
-            modifiers.before = f;
-          },
-          after: function(f) {
-            modifiers.after = f;
-          },
-          pre: function(f) {
-            modifiers.pre = f;
-          },
-          post: function(f) {
-            modifiers.post = f;
-          },
-          stop: function() {
-            alive = false;
-          }
-        };
-        if (!alive) return state;
-        if (typeof node === "object" && node !== null) {
-          state.isLeaf = Object.keys(node).length == 0;
-          for (var i = 0; i < parents.length; i++) {
-            if (parents[i].node_ === node_) {
-              state.circular = parents[i];
-              break;
-            }
-          }
-        } else {
-          state.isLeaf = true;
+    exports2.getUploadSpecification = void 0;
+    var fs2 = __importStar4(require("fs"));
+    var core_1 = require_core();
+    var path_1 = require("path");
+    var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2();
+    function getUploadSpecification(artifactName, rootDirectory, artifactFiles) {
+      const specifications = [];
+      if (!fs2.existsSync(rootDirectory)) {
+        throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`);
+      }
+      if (!fs2.statSync(rootDirectory).isDirectory()) {
+        throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`);
+      }
+      rootDirectory = (0, path_1.normalize)(rootDirectory);
+      rootDirectory = (0, path_1.resolve)(rootDirectory);
+      for (let file of artifactFiles) {
+        if (!fs2.existsSync(file)) {
+          throw new Error(`File ${file} does not exist`);
         }
-        state.notLeaf = !state.isLeaf;
-        state.notRoot = !state.isRoot;
-        var ret = cb.call(state, state.node);
-        if (ret !== void 0 && state.update) state.update(ret);
-        if (modifiers.before) modifiers.before.call(state, state.node);
-        if (typeof state.node == "object" && state.node !== null && !state.circular) {
-          parents.push(state);
-          var keys = Object.keys(state.node);
-          keys.forEach(function(key, i2) {
-            path2.push(key);
-            if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);
-            var child = walker(state.node[key]);
-            if (immutable && Object.hasOwnProperty.call(state.node, key)) {
-              state.node[key] = child.node;
-            }
-            child.isLast = i2 == keys.length - 1;
-            child.isFirst = i2 == 0;
-            if (modifiers.post) modifiers.post.call(state, child);
-            path2.pop();
+        if (!fs2.statSync(file).isDirectory()) {
+          file = (0, path_1.normalize)(file);
+          file = (0, path_1.resolve)(file);
+          if (!file.startsWith(rootDirectory)) {
+            throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`);
+          }
+          const uploadPath = file.replace(rootDirectory, "");
+          (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath);
+          specifications.push({
+            absoluteFilePath: file,
+            uploadFilePath: (0, path_1.join)(artifactName, uploadPath)
           });
-          parents.pop();
-        }
-        if (modifiers.after) modifiers.after.call(state, state.node);
-        return state;
-      })(root).node;
-    }
-    Object.keys(Traverse.prototype).forEach(function(key) {
-      Traverse[key] = function(obj) {
-        var args = [].slice.call(arguments, 1);
-        var t = Traverse(obj);
-        return t[key].apply(t, args);
-      };
-    });
-    function copy(src) {
-      if (typeof src === "object" && src !== null) {
-        var dst;
-        if (Array.isArray(src)) {
-          dst = [];
-        } else if (src instanceof Date) {
-          dst = new Date(src);
-        } else if (src instanceof Boolean) {
-          dst = new Boolean(src);
-        } else if (src instanceof Number) {
-          dst = new Number(src);
-        } else if (src instanceof String) {
-          dst = new String(src);
         } else {
-          dst = Object.create(Object.getPrototypeOf(src));
+          (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`);
         }
-        Object.keys(src).forEach(function(key) {
-          dst[key] = src[key];
-        });
-        return dst;
-      } else return src;
+      }
+      return specifications;
     }
+    exports2.getUploadSpecification = getUploadSpecification;
   }
 });
 
-// node_modules/chainsaw/index.js
-var require_chainsaw = __commonJS({
-  "node_modules/chainsaw/index.js"(exports2, module2) {
-    var Traverse = require_traverse();
-    var EventEmitter = require("events").EventEmitter;
-    module2.exports = Chainsaw;
-    function Chainsaw(builder) {
-      var saw = Chainsaw.saw(builder, {});
-      var r = builder.call(saw.handlers, saw);
-      if (r !== void 0) saw.handlers = r;
-      saw.record();
-      return saw.chain();
+// node_modules/tmp/lib/tmp.js
+var require_tmp = __commonJS({
+  "node_modules/tmp/lib/tmp.js"(exports2, module2) {
+    var fs2 = require("fs");
+    var os = require("os");
+    var path2 = require("path");
+    var crypto = require("crypto");
+    var _c = { fs: fs2.constants, os: os.constants };
+    var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+    var TEMPLATE_PATTERN = /XXXXXX/;
+    var DEFAULT_TRIES = 3;
+    var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR);
+    var IS_WIN32 = os.platform() === "win32";
+    var EBADF = _c.EBADF || _c.os.errno.EBADF;
+    var ENOENT = _c.ENOENT || _c.os.errno.ENOENT;
+    var DIR_MODE = 448;
+    var FILE_MODE = 384;
+    var EXIT = "exit";
+    var _removeObjects = [];
+    var FN_RMDIR_SYNC = fs2.rmdirSync.bind(fs2);
+    var _gracefulCleanup = false;
+    function rimraf(dirPath, callback) {
+      return fs2.rm(dirPath, { recursive: true }, callback);
     }
-    Chainsaw.light = function ChainsawLight(builder) {
-      var saw = Chainsaw.saw(builder, {});
-      var r = builder.call(saw.handlers, saw);
-      if (r !== void 0) saw.handlers = r;
-      return saw.chain();
-    };
-    Chainsaw.saw = function(builder, handlers) {
-      var saw = new EventEmitter();
-      saw.handlers = handlers;
-      saw.actions = [];
-      saw.chain = function() {
-        var ch = Traverse(saw.handlers).map(function(node) {
-          if (this.isRoot) return node;
-          var ps = this.path;
-          if (typeof node === "function") {
-            this.update(function() {
-              saw.actions.push({
-                path: ps,
-                args: [].slice.call(arguments)
-              });
-              return ch;
+    function FN_RIMRAF_SYNC(dirPath) {
+      return fs2.rmSync(dirPath, { recursive: true });
+    }
+    function tmpName(options, callback) {
+      const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
+      _assertAndSanitizeOptions(opts, function(err, sanitizedOptions) {
+        if (err) return cb(err);
+        let tries = sanitizedOptions.tries;
+        (function _getUniqueName() {
+          try {
+            const name = _generateTmpName(sanitizedOptions);
+            fs2.stat(name, function(err2) {
+              if (!err2) {
+                if (tries-- > 0) return _getUniqueName();
+                return cb(new Error("Could not get a unique tmp filename, max tries reached " + name));
+              }
+              cb(null, name);
             });
+          } catch (err2) {
+            cb(err2);
+          }
+        })();
+      });
+    }
+    function tmpNameSync(options) {
+      const args = _parseArguments(options), opts = args[0];
+      const sanitizedOptions = _assertAndSanitizeOptionsSync(opts);
+      let tries = sanitizedOptions.tries;
+      do {
+        const name = _generateTmpName(sanitizedOptions);
+        try {
+          fs2.statSync(name);
+        } catch (e) {
+          return name;
+        }
+      } while (tries-- > 0);
+      throw new Error("Could not get a unique tmp filename, max tries reached");
+    }
+    function file(options, callback) {
+      const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
+      tmpName(opts, function _tmpNameCreated(err, name) {
+        if (err) return cb(err);
+        fs2.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) {
+          if (err2) return cb(err2);
+          if (opts.discardDescriptor) {
+            return fs2.close(fd, function _discardCallback(possibleErr) {
+              return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false));
+            });
+          } else {
+            const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
+            cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false));
           }
         });
-        process.nextTick(function() {
-          saw.emit("begin");
-          saw.next();
-        });
-        return ch;
+      });
+    }
+    function fileSync(options) {
+      const args = _parseArguments(options), opts = args[0];
+      const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
+      const name = tmpNameSync(opts);
+      let fd = fs2.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
+      if (opts.discardDescriptor) {
+        fs2.closeSync(fd);
+        fd = void 0;
+      }
+      return {
+        name,
+        fd,
+        removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true)
       };
-      saw.pop = function() {
-        return saw.actions.shift();
+    }
+    function dir(options, callback) {
+      const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
+      tmpName(opts, function _tmpNameCreated(err, name) {
+        if (err) return cb(err);
+        fs2.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) {
+          if (err2) return cb(err2);
+          cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false));
+        });
+      });
+    }
+    function dirSync(options) {
+      const args = _parseArguments(options), opts = args[0];
+      const name = tmpNameSync(opts);
+      fs2.mkdirSync(name, opts.mode || DIR_MODE);
+      return {
+        name,
+        removeCallback: _prepareTmpDirRemoveCallback(name, opts, true)
       };
-      saw.next = function() {
-        var action = saw.pop();
-        if (!action) {
-          saw.emit("end");
-        } else if (!action.trap) {
-          var node = saw.handlers;
-          action.path.forEach(function(key) {
-            node = node[key];
-          });
-          node.apply(saw.handlers, action.args);
+    }
+    function _removeFileAsync(fdPath, next) {
+      const _handler = function(err) {
+        if (err && !_isENOENT(err)) {
+          return next(err);
         }
+        next();
       };
-      saw.nest = function(cb) {
-        var args = [].slice.call(arguments, 1);
-        var autonext = true;
-        if (typeof cb === "boolean") {
-          var autonext = cb;
-          cb = args.shift();
+      if (0 <= fdPath[0])
+        fs2.close(fdPath[0], function() {
+          fs2.unlink(fdPath[1], _handler);
+        });
+      else fs2.unlink(fdPath[1], _handler);
+    }
+    function _removeFileSync(fdPath) {
+      let rethrownException = null;
+      try {
+        if (0 <= fdPath[0]) fs2.closeSync(fdPath[0]);
+      } catch (e) {
+        if (!_isEBADF(e) && !_isENOENT(e)) throw e;
+      } finally {
+        try {
+          fs2.unlinkSync(fdPath[1]);
+        } catch (e) {
+          if (!_isENOENT(e)) rethrownException = e;
         }
-        var s = Chainsaw.saw(builder, {});
-        var r = builder.call(s.handlers, s);
-        if (r !== void 0) s.handlers = r;
-        if ("undefined" !== typeof saw.step) {
-          s.record();
+      }
+      if (rethrownException !== null) {
+        throw rethrownException;
+      }
+    }
+    function _prepareTmpFileRemoveCallback(name, fd, opts, sync) {
+      const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync);
+      const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync);
+      if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
+      return sync ? removeCallbackSync : removeCallback;
+    }
+    function _prepareTmpDirRemoveCallback(name, opts, sync) {
+      const removeFunction = opts.unsafeCleanup ? rimraf : fs2.rmdir.bind(fs2);
+      const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC;
+      const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync);
+      const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync);
+      if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
+      return sync ? removeCallbackSync : removeCallback;
+    }
+    function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) {
+      let called = false;
+      return function _cleanupCallback(next) {
+        if (!called) {
+          const toRemove = cleanupCallbackSync || _cleanupCallback;
+          const index = _removeObjects.indexOf(toRemove);
+          if (index >= 0) _removeObjects.splice(index, 1);
+          called = true;
+          if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) {
+            return removeFunction(fileOrDirName);
+          } else {
+            return removeFunction(fileOrDirName, next || function() {
+            });
+          }
         }
-        cb.apply(s.chain(), args);
-        if (autonext !== false) s.on("end", saw.next);
-      };
-      saw.record = function() {
-        upgradeChainsaw(saw);
       };
-      ["trap", "down", "jump"].forEach(function(method) {
-        saw[method] = function() {
-          throw new Error("To use the trap, down and jump features, please call record() first to start recording actions.");
-        };
+    }
+    function _garbageCollector() {
+      if (!_gracefulCleanup) return;
+      while (_removeObjects.length) {
+        try {
+          _removeObjects[0]();
+        } catch (e) {
+        }
+      }
+    }
+    function _randomChars(howMany) {
+      let value = [], rnd = null;
+      try {
+        rnd = crypto.randomBytes(howMany);
+      } catch (e) {
+        rnd = crypto.pseudoRandomBytes(howMany);
+      }
+      for (let i = 0; i < howMany; i++) {
+        value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);
+      }
+      return value.join("");
+    }
+    function _isUndefined(obj) {
+      return typeof obj === "undefined";
+    }
+    function _parseArguments(options, callback) {
+      if (typeof options === "function") {
+        return [{}, options];
+      }
+      if (_isUndefined(options)) {
+        return [{}, callback];
+      }
+      const actualOptions = {};
+      for (const key of Object.getOwnPropertyNames(options)) {
+        actualOptions[key] = options[key];
+      }
+      return [actualOptions, callback];
+    }
+    function _resolvePath(name, tmpDir, cb) {
+      const pathToResolve = path2.isAbsolute(name) ? name : path2.join(tmpDir, name);
+      fs2.stat(pathToResolve, function(err) {
+        if (err) {
+          fs2.realpath(path2.dirname(pathToResolve), function(err2, parentDir) {
+            if (err2) return cb(err2);
+            cb(null, path2.join(parentDir, path2.basename(pathToResolve)));
+          });
+        } else {
+          fs2.realpath(path2, cb);
+        }
       });
-      return saw;
-    };
-    function upgradeChainsaw(saw) {
-      saw.step = 0;
-      saw.pop = function() {
-        return saw.actions[saw.step++];
-      };
-      saw.trap = function(name, cb) {
-        var ps = Array.isArray(name) ? name : [name];
-        saw.actions.push({
-          path: ps,
-          step: saw.step,
-          cb,
-          trap: true
+    }
+    function _resolvePathSync(name, tmpDir) {
+      const pathToResolve = path2.isAbsolute(name) ? name : path2.join(tmpDir, name);
+      try {
+        fs2.statSync(pathToResolve);
+        return fs2.realpathSync(pathToResolve);
+      } catch (_err) {
+        const parentDir = fs2.realpathSync(path2.dirname(pathToResolve));
+        return path2.join(parentDir, path2.basename(pathToResolve));
+      }
+    }
+    function _generateTmpName(opts) {
+      const tmpDir = opts.tmpdir;
+      if (!_isUndefined(opts.name)) {
+        return path2.join(tmpDir, opts.dir, opts.name);
+      }
+      if (!_isUndefined(opts.template)) {
+        return path2.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6));
+      }
+      const name = [
+        opts.prefix ? opts.prefix : "tmp",
+        "-",
+        process.pid,
+        "-",
+        _randomChars(12),
+        opts.postfix ? "-" + opts.postfix : ""
+      ].join("");
+      return path2.join(tmpDir, opts.dir, name);
+    }
+    function _assertOptionsBase(options) {
+      if (!_isUndefined(options.name)) {
+        const name = options.name;
+        if (path2.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`);
+        const basename = path2.basename(name);
+        if (basename === ".." || basename === "." || basename !== name)
+          throw new Error(`name option must not contain a path, found "${name}".`);
+      }
+      if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) {
+        throw new Error(`Invalid template, found "${options.template}".`);
+      }
+      if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) {
+        throw new Error(`Invalid tries, found "${options.tries}".`);
+      }
+      options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1;
+      options.keep = !!options.keep;
+      options.detachDescriptor = !!options.detachDescriptor;
+      options.discardDescriptor = !!options.discardDescriptor;
+      options.unsafeCleanup = !!options.unsafeCleanup;
+      options.prefix = _isUndefined(options.prefix) ? "" : options.prefix;
+      options.postfix = _isUndefined(options.postfix) ? "" : options.postfix;
+    }
+    function _getRelativePath(option, name, tmpDir, cb) {
+      if (_isUndefined(name)) return cb(null);
+      _resolvePath(name, tmpDir, function(err, resolvedPath) {
+        if (err) return cb(err);
+        const relativePath = path2.relative(tmpDir, resolvedPath);
+        if (!resolvedPath.startsWith(tmpDir)) {
+          return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`));
+        }
+        cb(null, relativePath);
+      });
+    }
+    function _getRelativePathSync(option, name, tmpDir) {
+      if (_isUndefined(name)) return;
+      const resolvedPath = _resolvePathSync(name, tmpDir);
+      const relativePath = path2.relative(tmpDir, resolvedPath);
+      if (!resolvedPath.startsWith(tmpDir)) {
+        throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`);
+      }
+      return relativePath;
+    }
+    function _assertAndSanitizeOptions(options, cb) {
+      _getTmpDir(options, function(err, tmpDir) {
+        if (err) return cb(err);
+        options.tmpdir = tmpDir;
+        try {
+          _assertOptionsBase(options, tmpDir);
+        } catch (err2) {
+          return cb(err2);
+        }
+        _getRelativePath("dir", options.dir, tmpDir, function(err2, dir2) {
+          if (err2) return cb(err2);
+          options.dir = _isUndefined(dir2) ? "" : dir2;
+          _getRelativePath("template", options.template, tmpDir, function(err3, template) {
+            if (err3) return cb(err3);
+            options.template = template;
+            cb(null, options);
+          });
         });
-      };
-      saw.down = function(name) {
-        var ps = (Array.isArray(name) ? name : [name]).join("/");
-        var i = saw.actions.slice(saw.step).map(function(x) {
-          if (x.trap && x.step <= saw.step) return false;
-          return x.path.join("/") == ps;
-        }).indexOf(true);
-        if (i >= 0) saw.step += i;
-        else saw.step = saw.actions.length;
-        var act = saw.actions[saw.step - 1];
-        if (act && act.trap) {
-          saw.step = act.step;
-          act.cb();
-        } else saw.next();
-      };
-      saw.jump = function(step) {
-        saw.step = step;
-        saw.next();
-      };
+      });
+    }
+    function _assertAndSanitizeOptionsSync(options) {
+      const tmpDir = options.tmpdir = _getTmpDirSync(options);
+      _assertOptionsBase(options, tmpDir);
+      const dir2 = _getRelativePathSync("dir", options.dir, tmpDir);
+      options.dir = _isUndefined(dir2) ? "" : dir2;
+      options.template = _getRelativePathSync("template", options.template, tmpDir);
+      return options;
+    }
+    function _isEBADF(error4) {
+      return _isExpectedError(error4, -EBADF, "EBADF");
     }
+    function _isENOENT(error4) {
+      return _isExpectedError(error4, -ENOENT, "ENOENT");
+    }
+    function _isExpectedError(error4, errno, code) {
+      return IS_WIN32 ? error4.code === code : error4.code === code && error4.errno === errno;
+    }
+    function setGracefulCleanup() {
+      _gracefulCleanup = true;
+    }
+    function _getTmpDir(options, cb) {
+      return fs2.realpath(options && options.tmpdir || os.tmpdir(), cb);
+    }
+    function _getTmpDirSync(options) {
+      return fs2.realpathSync(options && options.tmpdir || os.tmpdir());
+    }
+    process.addListener(EXIT, _garbageCollector);
+    Object.defineProperty(module2.exports, "tmpdir", {
+      enumerable: true,
+      configurable: false,
+      get: function() {
+        return _getTmpDirSync();
+      }
+    });
+    module2.exports.dir = dir;
+    module2.exports.dirSync = dirSync;
+    module2.exports.file = file;
+    module2.exports.fileSync = fileSync;
+    module2.exports.tmpName = tmpName;
+    module2.exports.tmpNameSync = tmpNameSync;
+    module2.exports.setGracefulCleanup = setGracefulCleanup;
   }
 });
 
-// node_modules/buffers/index.js
-var require_buffers = __commonJS({
-  "node_modules/buffers/index.js"(exports2, module2) {
-    module2.exports = Buffers;
-    function Buffers(bufs) {
-      if (!(this instanceof Buffers)) return new Buffers(bufs);
-      this.buffers = bufs || [];
-      this.length = this.buffers.reduce(function(size, buf) {
-        return size + buf.length;
-      }, 0);
-    }
-    Buffers.prototype.push = function() {
-      for (var i = 0; i < arguments.length; i++) {
-        if (!Buffer.isBuffer(arguments[i])) {
-          throw new TypeError("Tried to push a non-buffer");
-        }
+// node_modules/tmp-promise/index.js
+var require_tmp_promise = __commonJS({
+  "node_modules/tmp-promise/index.js"(exports2, module2) {
+    "use strict";
+    var { promisify } = require("util");
+    var tmp = require_tmp();
+    module2.exports.fileSync = tmp.fileSync;
+    var fileWithOptions = promisify(
+      (options, cb) => tmp.file(
+        options,
+        (err, path2, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path2, fd, cleanup: promisify(cleanup) })
+      )
+    );
+    module2.exports.file = async (options) => fileWithOptions(options);
+    module2.exports.withFile = async function withFile(fn, options) {
+      const { path: path2, fd, cleanup } = await module2.exports.file(options);
+      try {
+        return await fn({ path: path2, fd });
+      } finally {
+        await cleanup();
       }
-      for (var i = 0; i < arguments.length; i++) {
-        var buf = arguments[i];
-        this.buffers.push(buf);
-        this.length += buf.length;
+    };
+    module2.exports.dirSync = tmp.dirSync;
+    var dirWithOptions = promisify(
+      (options, cb) => tmp.dir(
+        options,
+        (err, path2, cleanup) => err ? cb(err) : cb(void 0, { path: path2, cleanup: promisify(cleanup) })
+      )
+    );
+    module2.exports.dir = async (options) => dirWithOptions(options);
+    module2.exports.withDir = async function withDir(fn, options) {
+      const { path: path2, cleanup } = await module2.exports.dir(options);
+      try {
+        return await fn({ path: path2 });
+      } finally {
+        await cleanup();
       }
-      return this.length;
     };
-    Buffers.prototype.unshift = function() {
-      for (var i = 0; i < arguments.length; i++) {
-        if (!Buffer.isBuffer(arguments[i])) {
-          throw new TypeError("Tried to unshift a non-buffer");
-        }
+    module2.exports.tmpNameSync = tmp.tmpNameSync;
+    module2.exports.tmpName = promisify(tmp.tmpName);
+    module2.exports.tmpdir = tmp.tmpdir;
+    module2.exports.setGracefulCleanup = tmp.setGracefulCleanup;
+  }
+});
+
+// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/proxy.js
+var require_proxy4 = __commonJS({
+  "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/proxy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.checkBypass = exports2.getProxyUrl = void 0;
+    function getProxyUrl(reqUrl) {
+      const usingSsl = reqUrl.protocol === "https:";
+      if (checkBypass(reqUrl)) {
+        return void 0;
       }
-      for (var i = 0; i < arguments.length; i++) {
-        var buf = arguments[i];
-        this.buffers.unshift(buf);
-        this.length += buf.length;
+      const proxyVar = (() => {
+        if (usingSsl) {
+          return process.env["https_proxy"] || process.env["HTTPS_PROXY"];
+        } else {
+          return process.env["http_proxy"] || process.env["HTTP_PROXY"];
+        }
+      })();
+      if (proxyVar) {
+        try {
+          return new DecodedURL(proxyVar);
+        } catch (_a) {
+          if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://"))
+            return new DecodedURL(`http://${proxyVar}`);
+        }
+      } else {
+        return void 0;
       }
-      return this.length;
-    };
-    Buffers.prototype.copy = function(dst, dStart, start, end) {
-      return this.slice(start, end).copy(dst, dStart, 0, end - start);
-    };
-    Buffers.prototype.splice = function(i, howMany) {
-      var buffers = this.buffers;
-      var index = i >= 0 ? i : this.length - i;
-      var reps = [].slice.call(arguments, 2);
-      if (howMany === void 0) {
-        howMany = this.length - index;
-      } else if (howMany > this.length - index) {
-        howMany = this.length - index;
+    }
+    exports2.getProxyUrl = getProxyUrl;
+    function checkBypass(reqUrl) {
+      if (!reqUrl.hostname) {
+        return false;
       }
-      for (var i = 0; i < reps.length; i++) {
-        this.length += reps[i].length;
+      const reqHost = reqUrl.hostname;
+      if (isLoopbackAddress(reqHost)) {
+        return true;
       }
-      var removed = new Buffers();
-      var bytes = 0;
-      var startBytes = 0;
-      for (var ii = 0; ii < buffers.length && startBytes + buffers[ii].length < index; ii++) {
-        startBytes += buffers[ii].length;
+      const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || "";
+      if (!noProxy) {
+        return false;
       }
-      if (index - startBytes > 0) {
-        var start = index - startBytes;
-        if (start + howMany < buffers[ii].length) {
-          removed.push(buffers[ii].slice(start, start + howMany));
-          var orig = buffers[ii];
-          var buf0 = new Buffer(start);
-          for (var i = 0; i < start; i++) {
-            buf0[i] = orig[i];
-          }
-          var buf1 = new Buffer(orig.length - start - howMany);
-          for (var i = start + howMany; i < orig.length; i++) {
-            buf1[i - howMany - start] = orig[i];
-          }
-          if (reps.length > 0) {
-            var reps_ = reps.slice();
-            reps_.unshift(buf0);
-            reps_.push(buf1);
-            buffers.splice.apply(buffers, [ii, 1].concat(reps_));
-            ii += reps_.length;
-            reps = [];
-          } else {
-            buffers.splice(ii, 1, buf0, buf1);
-            ii += 2;
-          }
-        } else {
-          removed.push(buffers[ii].slice(start));
-          buffers[ii] = buffers[ii].slice(0, start);
-          ii++;
-        }
+      let reqPort;
+      if (reqUrl.port) {
+        reqPort = Number(reqUrl.port);
+      } else if (reqUrl.protocol === "http:") {
+        reqPort = 80;
+      } else if (reqUrl.protocol === "https:") {
+        reqPort = 443;
       }
-      if (reps.length > 0) {
-        buffers.splice.apply(buffers, [ii, 0].concat(reps));
-        ii += reps.length;
+      const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+      if (typeof reqPort === "number") {
+        upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
       }
-      while (removed.length < howMany) {
-        var buf = buffers[ii];
-        var len = buf.length;
-        var take = Math.min(len, howMany - removed.length);
-        if (take === len) {
-          removed.push(buf);
-          buffers.splice(ii, 1);
-        } else {
-          removed.push(buf.slice(0, take));
-          buffers[ii] = buffers[ii].slice(take);
+      for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) {
+        if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) {
+          return true;
         }
       }
-      this.length -= removed.length;
-      return removed;
-    };
-    Buffers.prototype.slice = function(i, j) {
-      var buffers = this.buffers;
-      if (j === void 0) j = this.length;
-      if (i === void 0) i = 0;
-      if (j > this.length) j = this.length;
-      var startBytes = 0;
-      for (var si = 0; si < buffers.length && startBytes + buffers[si].length <= i; si++) {
-        startBytes += buffers[si].length;
+      return false;
+    }
+    exports2.checkBypass = checkBypass;
+    function isLoopbackAddress(host) {
+      const hostLower = host.toLowerCase();
+      return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]");
+    }
+    var DecodedURL = class extends URL {
+      constructor(url, base) {
+        super(url, base);
+        this._decodedUsername = decodeURIComponent(super.username);
+        this._decodedPassword = decodeURIComponent(super.password);
       }
-      var target = new Buffer(j - i);
-      var ti = 0;
-      for (var ii = si; ti < j - i && ii < buffers.length; ii++) {
-        var len = buffers[ii].length;
-        var start = ti === 0 ? i - startBytes : 0;
-        var end = ti + len >= j - i ? Math.min(start + (j - i) - ti, len) : len;
-        buffers[ii].copy(target, ti, start, end);
-        ti += end - start;
+      get username() {
+        return this._decodedUsername;
       }
-      return target;
-    };
-    Buffers.prototype.pos = function(i) {
-      if (i < 0 || i >= this.length) throw new Error("oob");
-      var l = i, bi = 0, bu = null;
-      for (; ; ) {
-        bu = this.buffers[bi];
-        if (l < bu.length) {
-          return { buf: bi, offset: l };
-        } else {
-          l -= bu.length;
-        }
-        bi++;
+      get password() {
+        return this._decodedPassword;
       }
     };
-    Buffers.prototype.get = function get(i) {
-      var pos = this.pos(i);
-      return this.buffers[pos.buf].get(pos.offset);
-    };
-    Buffers.prototype.set = function set2(i, b) {
-      var pos = this.pos(i);
-      return this.buffers[pos.buf].set(pos.offset, b);
-    };
-    Buffers.prototype.indexOf = function(needle, offset) {
-      if ("string" === typeof needle) {
-        needle = new Buffer(needle);
-      } else if (needle instanceof Buffer) {
-      } else {
-        throw new Error("Invalid type for a search string");
-      }
-      if (!needle.length) {
-        return 0;
+  }
+});
+
+// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/index.js
+var require_lib5 = __commonJS({
+  "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/index.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      if (!this.length) {
-        return -1;
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-      var i = 0, j = 0, match = 0, mstart, pos = 0;
-      if (offset) {
-        var p = this.pos(offset);
-        i = p.buf;
-        j = p.offset;
-        pos = offset;
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      for (; ; ) {
-        while (j >= this.buffers[i].length) {
-          j = 0;
-          i++;
-          if (i >= this.buffers.length) {
-            return -1;
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
           }
         }
-        var char = this.buffers[i][j];
-        if (char == needle[match]) {
-          if (match == 0) {
-            mstart = {
-              i,
-              j,
-              pos
-            };
-          }
-          match++;
-          if (match == needle.length) {
-            return mstart.pos;
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
           }
-        } else if (match != 0) {
-          i = mstart.i;
-          j = mstart.j;
-          pos = mstart.pos;
-          match = 0;
         }
-        j++;
-        pos++;
-      }
-    };
-    Buffers.prototype.toBuffer = function() {
-      return this.slice();
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    Buffers.prototype.toString = function(encoding, start, end) {
-      return this.slice(start, end).toString(encoding);
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0;
+    var http = __importStar4(require("http"));
+    var https2 = __importStar4(require("https"));
+    var pm = __importStar4(require_proxy4());
+    var tunnel = __importStar4(require_tunnel2());
+    var undici_1 = require_undici();
+    var HttpCodes;
+    (function(HttpCodes2) {
+      HttpCodes2[HttpCodes2["OK"] = 200] = "OK";
+      HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices";
+      HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently";
+      HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved";
+      HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther";
+      HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified";
+      HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy";
+      HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy";
+      HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+      HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect";
+      HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest";
+      HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized";
+      HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired";
+      HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden";
+      HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound";
+      HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+      HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable";
+      HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+      HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout";
+      HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict";
+      HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone";
+      HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests";
+      HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError";
+      HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented";
+      HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway";
+      HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+      HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout";
+    })(HttpCodes || (exports2.HttpCodes = HttpCodes = {}));
+    var Headers;
+    (function(Headers2) {
+      Headers2["Accept"] = "accept";
+      Headers2["ContentType"] = "content-type";
+    })(Headers || (exports2.Headers = Headers = {}));
+    var MediaTypes;
+    (function(MediaTypes2) {
+      MediaTypes2["ApplicationJson"] = "application/json";
+    })(MediaTypes || (exports2.MediaTypes = MediaTypes = {}));
+    function getProxyUrl(serverUrl) {
+      const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+      return proxyUrl ? proxyUrl.href : "";
+    }
+    exports2.getProxyUrl = getProxyUrl;
+    var HttpRedirectCodes = [
+      HttpCodes.MovedPermanently,
+      HttpCodes.ResourceMoved,
+      HttpCodes.SeeOther,
+      HttpCodes.TemporaryRedirect,
+      HttpCodes.PermanentRedirect
+    ];
+    var HttpResponseRetryCodes = [
+      HttpCodes.BadGateway,
+      HttpCodes.ServiceUnavailable,
+      HttpCodes.GatewayTimeout
+    ];
+    var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"];
+    var ExponentialBackoffCeiling = 10;
+    var ExponentialBackoffTimeSlice = 5;
+    var HttpClientError = class _HttpClientError extends Error {
+      constructor(message, statusCode) {
+        super(message);
+        this.name = "HttpClientError";
+        this.statusCode = statusCode;
+        Object.setPrototypeOf(this, _HttpClientError.prototype);
+      }
     };
-  }
-});
-
-// node_modules/binary/lib/vars.js
-var require_vars = __commonJS({
-  "node_modules/binary/lib/vars.js"(exports2, module2) {
-    module2.exports = function(store) {
-      function getset(name, value) {
-        var node = vars.store;
-        var keys = name.split(".");
-        keys.slice(0, -1).forEach(function(k) {
-          if (node[k] === void 0) node[k] = {};
-          node = node[k];
+    exports2.HttpClientError = HttpClientError;
+    var HttpClientResponse = class {
+      constructor(message) {
+        this.message = message;
+      }
+      readBody() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
+            let output = Buffer.alloc(0);
+            this.message.on("data", (chunk) => {
+              output = Buffer.concat([output, chunk]);
+            });
+            this.message.on("end", () => {
+              resolve2(output.toString());
+            });
+          }));
         });
-        var key = keys[keys.length - 1];
-        if (arguments.length == 1) {
-          return node[key];
-        } else {
-          return node[key] = value;
+      }
+      readBodyBuffer() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
+            const chunks = [];
+            this.message.on("data", (chunk) => {
+              chunks.push(chunk);
+            });
+            this.message.on("end", () => {
+              resolve2(Buffer.concat(chunks));
+            });
+          }));
+        });
+      }
+    };
+    exports2.HttpClientResponse = HttpClientResponse;
+    function isHttps(requestUrl) {
+      const parsedUrl = new URL(requestUrl);
+      return parsedUrl.protocol === "https:";
+    }
+    exports2.isHttps = isHttps;
+    var HttpClient2 = class {
+      constructor(userAgent, handlers, requestOptions) {
+        this._ignoreSslError = false;
+        this._allowRedirects = true;
+        this._allowRedirectDowngrade = false;
+        this._maxRedirects = 50;
+        this._allowRetries = false;
+        this._maxRetries = 1;
+        this._keepAlive = false;
+        this._disposed = false;
+        this.userAgent = userAgent;
+        this.handlers = handlers || [];
+        this.requestOptions = requestOptions;
+        if (requestOptions) {
+          if (requestOptions.ignoreSslError != null) {
+            this._ignoreSslError = requestOptions.ignoreSslError;
+          }
+          this._socketTimeout = requestOptions.socketTimeout;
+          if (requestOptions.allowRedirects != null) {
+            this._allowRedirects = requestOptions.allowRedirects;
+          }
+          if (requestOptions.allowRedirectDowngrade != null) {
+            this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+          }
+          if (requestOptions.maxRedirects != null) {
+            this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+          }
+          if (requestOptions.keepAlive != null) {
+            this._keepAlive = requestOptions.keepAlive;
+          }
+          if (requestOptions.allowRetries != null) {
+            this._allowRetries = requestOptions.allowRetries;
+          }
+          if (requestOptions.maxRetries != null) {
+            this._maxRetries = requestOptions.maxRetries;
+          }
         }
       }
-      var vars = {
-        get: function(name) {
-          return getset(name);
-        },
-        set: function(name, value) {
-          return getset(name, value);
-        },
-        store: store || {}
-      };
-      return vars;
-    };
-  }
-});
-
-// node_modules/binary/index.js
-var require_binary = __commonJS({
-  "node_modules/binary/index.js"(exports2, module2) {
-    var Chainsaw = require_chainsaw();
-    var EventEmitter = require("events").EventEmitter;
-    var Buffers = require_buffers();
-    var Vars = require_vars();
-    var Stream = require("stream").Stream;
-    exports2 = module2.exports = function(bufOrEm, eventName) {
-      if (Buffer.isBuffer(bufOrEm)) {
-        return exports2.parse(bufOrEm);
+      options(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("OPTIONS", requestUrl, null, additionalHeaders || {});
+        });
       }
-      var s = exports2.stream();
-      if (bufOrEm && bufOrEm.pipe) {
-        bufOrEm.pipe(s);
-      } else if (bufOrEm) {
-        bufOrEm.on(eventName || "data", function(buf) {
-          s.write(buf);
+      get(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("GET", requestUrl, null, additionalHeaders || {});
         });
-        bufOrEm.on("end", function() {
-          s.end();
+      }
+      del(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("DELETE", requestUrl, null, additionalHeaders || {});
         });
       }
-      return s;
-    };
-    exports2.stream = function(input) {
-      if (input) return exports2.apply(null, arguments);
-      var pending = null;
-      function getBytes(bytes, cb, skip) {
-        pending = {
-          bytes,
-          skip,
-          cb: function(buf) {
-            pending = null;
-            cb(buf);
-          }
-        };
-        dispatch();
+      post(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("POST", requestUrl, data, additionalHeaders || {});
+        });
       }
-      var offset = null;
-      function dispatch() {
-        if (!pending) {
-          if (caughtEnd) done = true;
-          return;
-        }
-        if (typeof pending === "function") {
-          pending();
-        } else {
-          var bytes = offset + pending.bytes;
-          if (buffers.length >= bytes) {
-            var buf;
-            if (offset == null) {
-              buf = buffers.splice(0, bytes);
-              if (!pending.skip) {
-                buf = buf.slice();
-              }
-            } else {
-              if (!pending.skip) {
-                buf = buffers.slice(offset, bytes);
-              }
-              offset = bytes;
-            }
-            if (pending.skip) {
-              pending.cb();
-            } else {
-              pending.cb(buf);
-            }
-          }
-        }
+      patch(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PATCH", requestUrl, data, additionalHeaders || {});
+        });
       }
-      function builder(saw) {
-        function next() {
-          if (!done) saw.next();
-        }
-        var self2 = words(function(bytes, cb) {
-          return function(name) {
-            getBytes(bytes, function(buf) {
-              vars.set(name, cb(buf));
-              next();
-            });
-          };
+      put(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PUT", requestUrl, data, additionalHeaders || {});
         });
-        self2.tap = function(cb) {
-          saw.nest(cb, vars.store);
-        };
-        self2.into = function(key, cb) {
-          if (!vars.get(key)) vars.set(key, {});
-          var parent = vars;
-          vars = Vars(parent.get(key));
-          saw.nest(function() {
-            cb.apply(this, arguments);
-            this.tap(function() {
-              vars = parent;
-            });
-          }, vars.store);
-        };
-        self2.flush = function() {
-          vars.store = {};
-          next();
-        };
-        self2.loop = function(cb) {
-          var end = false;
-          saw.nest(false, function loop() {
-            this.vars = vars.store;
-            cb.call(this, function() {
-              end = true;
-              next();
-            }, vars.store);
-            this.tap(function() {
-              if (end) saw.next();
-              else loop.call(this);
-            }.bind(this));
-          }, vars.store);
-        };
-        self2.buffer = function(name, bytes) {
-          if (typeof bytes === "string") {
-            bytes = vars.get(bytes);
-          }
-          getBytes(bytes, function(buf) {
-            vars.set(name, buf);
-            next();
-          });
-        };
-        self2.skip = function(bytes) {
-          if (typeof bytes === "string") {
-            bytes = vars.get(bytes);
-          }
-          getBytes(bytes, function() {
-            next();
-          });
-        };
-        self2.scan = function find2(name, search) {
-          if (typeof search === "string") {
-            search = new Buffer(search);
-          } else if (!Buffer.isBuffer(search)) {
-            throw new Error("search must be a Buffer or a string");
-          }
-          var taken = 0;
-          pending = function() {
-            var pos = buffers.indexOf(search, offset + taken);
-            var i = pos - offset - taken;
-            if (pos !== -1) {
-              pending = null;
-              if (offset != null) {
-                vars.set(
-                  name,
-                  buffers.slice(offset, offset + taken + i)
-                );
-                offset += taken + i + search.length;
-              } else {
-                vars.set(
-                  name,
-                  buffers.slice(0, taken + i)
-                );
-                buffers.splice(0, taken + i + search.length);
-              }
-              next();
-              dispatch();
-            } else {
-              i = Math.max(buffers.length - search.length - offset - taken, 0);
-            }
-            taken += i;
-          };
-          dispatch();
-        };
-        self2.peek = function(cb) {
-          offset = 0;
-          saw.nest(function() {
-            cb.call(this, vars.store);
-            this.tap(function() {
-              offset = null;
-            });
-          });
-        };
-        return self2;
       }
-      ;
-      var stream = Chainsaw.light(builder);
-      stream.writable = true;
-      var buffers = Buffers();
-      stream.write = function(buf) {
-        buffers.push(buf);
-        dispatch();
-      };
-      var vars = Vars();
-      var done = false, caughtEnd = false;
-      stream.end = function() {
-        caughtEnd = true;
-      };
-      stream.pipe = Stream.prototype.pipe;
-      Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function(name) {
-        stream[name] = EventEmitter.prototype[name];
-      });
-      return stream;
-    };
-    exports2.parse = function parse(buffer) {
-      var self2 = words(function(bytes, cb) {
-        return function(name) {
-          if (offset + bytes <= buffer.length) {
-            var buf = buffer.slice(offset, offset + bytes);
-            offset += bytes;
-            vars.set(name, cb(buf));
-          } else {
-            vars.set(name, null);
-          }
-          return self2;
-        };
-      });
-      var offset = 0;
-      var vars = Vars();
-      self2.vars = vars.store;
-      self2.tap = function(cb) {
-        cb.call(self2, vars.store);
-        return self2;
-      };
-      self2.into = function(key, cb) {
-        if (!vars.get(key)) {
-          vars.set(key, {});
-        }
-        var parent = vars;
-        vars = Vars(parent.get(key));
-        cb.call(self2, vars.store);
-        vars = parent;
-        return self2;
-      };
-      self2.loop = function(cb) {
-        var end = false;
-        var ender = function() {
-          end = true;
-        };
-        while (end === false) {
-          cb.call(self2, ender, vars.store);
-        }
-        return self2;
-      };
-      self2.buffer = function(name, size) {
-        if (typeof size === "string") {
-          size = vars.get(size);
-        }
-        var buf = buffer.slice(offset, Math.min(buffer.length, offset + size));
-        offset += size;
-        vars.set(name, buf);
-        return self2;
-      };
-      self2.skip = function(bytes) {
-        if (typeof bytes === "string") {
-          bytes = vars.get(bytes);
-        }
-        offset += bytes;
-        return self2;
-      };
-      self2.scan = function(name, search) {
-        if (typeof search === "string") {
-          search = new Buffer(search);
-        } else if (!Buffer.isBuffer(search)) {
-          throw new Error("search must be a Buffer or a string");
-        }
-        vars.set(name, null);
-        for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) {
-          for (var j = 0; j < search.length && buffer[offset + i + j] === search[j]; j++) ;
-          if (j === search.length) break;
-        }
-        vars.set(name, buffer.slice(offset, offset + i));
-        offset += i + search.length;
-        return self2;
-      };
-      self2.peek = function(cb) {
-        var was = offset;
-        cb.call(self2, vars.store);
-        offset = was;
-        return self2;
-      };
-      self2.flush = function() {
-        vars.store = {};
-        return self2;
-      };
-      self2.eof = function() {
-        return offset >= buffer.length;
-      };
-      return self2;
-    };
-    function decodeLEu(bytes) {
-      var acc = 0;
-      for (var i = 0; i < bytes.length; i++) {
-        acc += Math.pow(256, i) * bytes[i];
+      head(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("HEAD", requestUrl, null, additionalHeaders || {});
+        });
       }
-      return acc;
-    }
-    function decodeBEu(bytes) {
-      var acc = 0;
-      for (var i = 0; i < bytes.length; i++) {
-        acc += Math.pow(256, bytes.length - i - 1) * bytes[i];
+      sendStream(verb, requestUrl, stream, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request(verb, requestUrl, stream, additionalHeaders);
+        });
       }
-      return acc;
-    }
-    function decodeBEs(bytes) {
-      var val2 = decodeBEu(bytes);
-      if ((bytes[0] & 128) == 128) {
-        val2 -= Math.pow(256, bytes.length);
+      /**
+       * Gets a typed object from an endpoint
+       * Be aware that not found returns a null.  Other errors (4xx, 5xx) reject the promise
+       */
+      getJson(requestUrl, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          const res = yield this.get(requestUrl, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      return val2;
-    }
-    function decodeLEs(bytes) {
-      var val2 = decodeLEu(bytes);
-      if ((bytes[bytes.length - 1] & 128) == 128) {
-        val2 -= Math.pow(256, bytes.length);
+      postJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.post(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      return val2;
-    }
-    function words(decode) {
-      var self2 = {};
-      [1, 2, 4, 8].forEach(function(bytes) {
-        var bits = bytes * 8;
-        self2["word" + bits + "le"] = self2["word" + bits + "lu"] = decode(bytes, decodeLEu);
-        self2["word" + bits + "ls"] = decode(bytes, decodeLEs);
-        self2["word" + bits + "be"] = self2["word" + bits + "bu"] = decode(bytes, decodeBEu);
-        self2["word" + bits + "bs"] = decode(bytes, decodeBEs);
-      });
-      self2.word8 = self2.word8u = self2.word8be;
-      self2.word8s = self2.word8bs;
-      return self2;
-    }
-  }
-});
-
-// node_modules/unzip-stream/lib/matcher-stream.js
-var require_matcher_stream = __commonJS({
-  "node_modules/unzip-stream/lib/matcher-stream.js"(exports2, module2) {
-    var Transform = require("stream").Transform;
-    var util = require("util");
-    function MatcherStream(patternDesc, matchFn) {
-      if (!(this instanceof MatcherStream)) {
-        return new MatcherStream();
+      putJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.put(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      Transform.call(this);
-      var p = typeof patternDesc === "object" ? patternDesc.pattern : patternDesc;
-      this.pattern = Buffer.isBuffer(p) ? p : Buffer.from(p);
-      this.requiredLength = this.pattern.length;
-      if (patternDesc.requiredExtraSize) this.requiredLength += patternDesc.requiredExtraSize;
-      this.data = new Buffer("");
-      this.bytesSoFar = 0;
-      this.matchFn = matchFn;
-    }
-    util.inherits(MatcherStream, Transform);
-    MatcherStream.prototype.checkDataChunk = function(ignoreMatchZero) {
-      var enoughData = this.data.length >= this.requiredLength;
-      if (!enoughData) {
-        return;
+      patchJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.patch(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      var matchIndex = this.data.indexOf(this.pattern, ignoreMatchZero ? 1 : 0);
-      if (matchIndex >= 0 && matchIndex + this.requiredLength > this.data.length) {
-        if (matchIndex > 0) {
-          var packet = this.data.slice(0, matchIndex);
-          this.push(packet);
-          this.bytesSoFar += matchIndex;
-          this.data = this.data.slice(matchIndex);
+      /**
+       * Makes a raw http request.
+       * All other methods such as get, post, patch, and request ultimately call this.
+       * Prefer get, del, post and patch
+       */
+      request(verb, requestUrl, data, headers) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          if (this._disposed) {
+            throw new Error("Client has already been disposed.");
+          }
+          const parsedUrl = new URL(requestUrl);
+          let info7 = this._prepareRequest(verb, parsedUrl, headers);
+          const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1;
+          let numTries = 0;
+          let response;
+          do {
+            response = yield this.requestRaw(info7, data);
+            if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
+              let authenticationHandler;
+              for (const handler of this.handlers) {
+                if (handler.canHandleAuthentication(response)) {
+                  authenticationHandler = handler;
+                  break;
+                }
+              }
+              if (authenticationHandler) {
+                return authenticationHandler.handleAuthentication(this, info7, data);
+              } else {
+                return response;
+              }
+            }
+            let redirectsRemaining = this._maxRedirects;
+            while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) {
+              const redirectUrl = response.message.headers["location"];
+              if (!redirectUrl) {
+                break;
+              }
+              const parsedRedirectUrl = new URL(redirectUrl);
+              if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
+                throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
+              }
+              yield response.readBody();
+              if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+                for (const header in headers) {
+                  if (header.toLowerCase() === "authorization") {
+                    delete headers[header];
+                  }
+                }
+              }
+              info7 = this._prepareRequest(verb, parsedRedirectUrl, headers);
+              response = yield this.requestRaw(info7, data);
+              redirectsRemaining--;
+            }
+            if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+              return response;
+            }
+            numTries += 1;
+            if (numTries < maxTries) {
+              yield response.readBody();
+              yield this._performExponentialBackoff(numTries);
+            }
+          } while (numTries < maxTries);
+          return response;
+        });
+      }
+      /**
+       * Needs to be called if keepAlive is set to true in request options.
+       */
+      dispose() {
+        if (this._agent) {
+          this._agent.destroy();
         }
-        return;
+        this._disposed = true;
       }
-      if (matchIndex === -1) {
-        var packetLen = this.data.length - this.requiredLength + 1;
-        var packet = this.data.slice(0, packetLen);
-        this.push(packet);
-        this.bytesSoFar += packetLen;
-        this.data = this.data.slice(packetLen);
-        return;
+      /**
+       * Raw request.
+       * @param info
+       * @param data
+       */
+      requestRaw(info7, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2, reject) => {
+            function callbackForResult(err, res) {
+              if (err) {
+                reject(err);
+              } else if (!res) {
+                reject(new Error("Unknown error"));
+              } else {
+                resolve2(res);
+              }
+            }
+            this.requestRawWithCallback(info7, data, callbackForResult);
+          });
+        });
       }
-      if (matchIndex > 0) {
-        var packet = this.data.slice(0, matchIndex);
-        this.data = this.data.slice(matchIndex);
-        this.push(packet);
-        this.bytesSoFar += matchIndex;
+      /**
+       * Raw request with callback.
+       * @param info
+       * @param data
+       * @param onResult
+       */
+      requestRawWithCallback(info7, data, onResult) {
+        if (typeof data === "string") {
+          if (!info7.options.headers) {
+            info7.options.headers = {};
+          }
+          info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8");
+        }
+        let callbackCalled = false;
+        function handleResult(err, res) {
+          if (!callbackCalled) {
+            callbackCalled = true;
+            onResult(err, res);
+          }
+        }
+        const req = info7.httpModule.request(info7.options, (msg) => {
+          const res = new HttpClientResponse(msg);
+          handleResult(void 0, res);
+        });
+        let socket;
+        req.on("socket", (sock) => {
+          socket = sock;
+        });
+        req.setTimeout(this._socketTimeout || 3 * 6e4, () => {
+          if (socket) {
+            socket.end();
+          }
+          handleResult(new Error(`Request timeout: ${info7.options.path}`));
+        });
+        req.on("error", function(err) {
+          handleResult(err);
+        });
+        if (data && typeof data === "string") {
+          req.write(data, "utf8");
+        }
+        if (data && typeof data !== "string") {
+          data.on("close", function() {
+            req.end();
+          });
+          data.pipe(req);
+        } else {
+          req.end();
+        }
       }
-      var finished = this.matchFn ? this.matchFn(this.data, this.bytesSoFar) : true;
-      if (finished) {
-        this.data = new Buffer("");
-        return;
+      /**
+       * Gets an http agent. This function is useful when you need an http agent that handles
+       * routing through a proxy server - depending upon the url and proxy environment variables.
+       * @param serverUrl  The server URL where the request will be sent. For example, https://api.github.com
+       */
+      getAgent(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        return this._getAgent(parsedUrl);
       }
-      return true;
-    };
-    MatcherStream.prototype._transform = function(chunk, encoding, cb) {
-      this.data = Buffer.concat([this.data, chunk]);
-      var firstIteration = true;
-      while (this.checkDataChunk(!firstIteration)) {
-        firstIteration = false;
+      getAgentDispatcher(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (!useProxy) {
+          return;
+        }
+        return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
       }
-      cb();
-    };
-    MatcherStream.prototype._flush = function(cb) {
-      if (this.data.length > 0) {
-        var firstIteration = true;
-        while (this.checkDataChunk(!firstIteration)) {
-          firstIteration = false;
+      _prepareRequest(method, requestUrl, headers) {
+        const info7 = {};
+        info7.parsedUrl = requestUrl;
+        const usingSsl = info7.parsedUrl.protocol === "https:";
+        info7.httpModule = usingSsl ? https2 : http;
+        const defaultPort = usingSsl ? 443 : 80;
+        info7.options = {};
+        info7.options.host = info7.parsedUrl.hostname;
+        info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort;
+        info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || "");
+        info7.options.method = method;
+        info7.options.headers = this._mergeHeaders(headers);
+        if (this.userAgent != null) {
+          info7.options.headers["user-agent"] = this.userAgent;
+        }
+        info7.options.agent = this._getAgent(info7.parsedUrl);
+        if (this.handlers) {
+          for (const handler of this.handlers) {
+            handler.prepareRequest(info7.options);
+          }
         }
+        return info7;
       }
-      if (this.data.length > 0) {
-        this.push(this.data);
-        this.data = null;
+      _mergeHeaders(headers) {
+        if (this.requestOptions && this.requestOptions.headers) {
+          return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
+        }
+        return lowercaseKeys(headers || {});
       }
-      cb();
-    };
-    module2.exports = MatcherStream;
-  }
-});
-
-// node_modules/unzip-stream/lib/entry.js
-var require_entry = __commonJS({
-  "node_modules/unzip-stream/lib/entry.js"(exports2, module2) {
-    "use strict";
-    var stream = require("stream");
-    var inherits = require("util").inherits;
-    function Entry() {
-      if (!(this instanceof Entry)) {
-        return new Entry();
+      _getExistingOrDefaultHeader(additionalHeaders, header, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
+        }
+        return additionalHeaders[header] || clientHeader || _default2;
       }
-      stream.PassThrough.call(this);
-      this.path = null;
-      this.type = null;
-      this.isDirectory = false;
-    }
-    inherits(Entry, stream.PassThrough);
-    Entry.prototype.autodrain = function() {
-      return this.pipe(new stream.Transform({ transform: function(d, e, cb) {
-        cb();
-      } }));
-    };
-    module2.exports = Entry;
-  }
-});
-
-// node_modules/unzip-stream/lib/unzip-stream.js
-var require_unzip_stream = __commonJS({
-  "node_modules/unzip-stream/lib/unzip-stream.js"(exports2, module2) {
-    "use strict";
-    var binary2 = require_binary();
-    var stream = require("stream");
-    var util = require("util");
-    var zlib = require("zlib");
-    var MatcherStream = require_matcher_stream();
-    var Entry = require_entry();
-    var states = {
-      STREAM_START: 0,
-      START: 1,
-      LOCAL_FILE_HEADER: 2,
-      LOCAL_FILE_HEADER_SUFFIX: 3,
-      FILE_DATA: 4,
-      FILE_DATA_END: 5,
-      DATA_DESCRIPTOR: 6,
-      CENTRAL_DIRECTORY_FILE_HEADER: 7,
-      CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX: 8,
-      CDIR64_END: 9,
-      CDIR64_END_DATA_SECTOR: 10,
-      CDIR64_LOCATOR: 11,
-      CENTRAL_DIRECTORY_END: 12,
-      CENTRAL_DIRECTORY_END_COMMENT: 13,
-      TRAILING_JUNK: 14,
-      ERROR: 99
-    };
-    var FOUR_GIGS = 4294967296;
-    var SIG_LOCAL_FILE_HEADER = 67324752;
-    var SIG_DATA_DESCRIPTOR = 134695760;
-    var SIG_CDIR_RECORD = 33639248;
-    var SIG_CDIR64_RECORD_END = 101075792;
-    var SIG_CDIR64_LOCATOR_END = 117853008;
-    var SIG_CDIR_RECORD_END = 101010256;
-    function UnzipStream(options) {
-      if (!(this instanceof UnzipStream)) {
-        return new UnzipStream(options);
+      _getAgent(parsedUrl) {
+        let agent;
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (this._keepAlive && useProxy) {
+          agent = this._proxyAgent;
+        }
+        if (!useProxy) {
+          agent = this._agent;
+        }
+        if (agent) {
+          return agent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        let maxSockets = 100;
+        if (this.requestOptions) {
+          maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
+        }
+        if (proxyUrl && proxyUrl.hostname) {
+          const agentOptions = {
+            maxSockets,
+            keepAlive: this._keepAlive,
+            proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && {
+              proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+            }), { host: proxyUrl.hostname, port: proxyUrl.port })
+          };
+          let tunnelAgent;
+          const overHttps = proxyUrl.protocol === "https:";
+          if (usingSsl) {
+            tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+          } else {
+            tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
+          }
+          agent = tunnelAgent(agentOptions);
+          this._proxyAgent = agent;
+        }
+        if (!agent) {
+          const options = { keepAlive: this._keepAlive, maxSockets };
+          agent = usingSsl ? new https2.Agent(options) : new http.Agent(options);
+          this._agent = agent;
+        }
+        if (usingSsl && this._ignoreSslError) {
+          agent.options = Object.assign(agent.options || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return agent;
       }
-      stream.Transform.call(this);
-      this.options = options || {};
-      this.data = new Buffer("");
-      this.state = states.STREAM_START;
-      this.skippedBytes = 0;
-      this.parsedEntity = null;
-      this.outStreamInfo = {};
-    }
-    util.inherits(UnzipStream, stream.Transform);
-    UnzipStream.prototype.processDataChunk = function(chunk) {
-      var requiredLength;
-      switch (this.state) {
-        case states.STREAM_START:
-        case states.START:
-          requiredLength = 4;
-          break;
-        case states.LOCAL_FILE_HEADER:
-          requiredLength = 26;
-          break;
-        case states.LOCAL_FILE_HEADER_SUFFIX:
-          requiredLength = this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength;
-          break;
-        case states.DATA_DESCRIPTOR:
-          requiredLength = 12;
-          break;
-        case states.CENTRAL_DIRECTORY_FILE_HEADER:
-          requiredLength = 42;
-          break;
-        case states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:
-          requiredLength = this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength + this.parsedEntity.fileCommentLength;
-          break;
-        case states.CDIR64_END:
-          requiredLength = 52;
-          break;
-        case states.CDIR64_END_DATA_SECTOR:
-          requiredLength = this.parsedEntity.centralDirectoryRecordSize - 44;
-          break;
-        case states.CDIR64_LOCATOR:
-          requiredLength = 16;
-          break;
-        case states.CENTRAL_DIRECTORY_END:
-          requiredLength = 18;
-          break;
-        case states.CENTRAL_DIRECTORY_END_COMMENT:
-          requiredLength = this.parsedEntity.commentLength;
-          break;
-        case states.FILE_DATA:
-          return 0;
-        case states.FILE_DATA_END:
-          return 0;
-        case states.TRAILING_JUNK:
-          if (this.options.debug) console.log("found", chunk.length, "bytes of TRAILING_JUNK");
-          return chunk.length;
-        default:
-          return chunk.length;
+      _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+        let proxyAgent;
+        if (this._keepAlive) {
+          proxyAgent = this._proxyAgentDispatcher;
+        }
+        if (proxyAgent) {
+          return proxyAgent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && {
+          token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}`
+        }));
+        this._proxyAgentDispatcher = proxyAgent;
+        if (usingSsl && this._ignoreSslError) {
+          proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return proxyAgent;
       }
-      var chunkLength = chunk.length;
-      if (chunkLength < requiredLength) {
-        return 0;
+      _performExponentialBackoff(retryNumber) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+          const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+          return new Promise((resolve2) => setTimeout(() => resolve2(), ms));
+        });
       }
-      switch (this.state) {
-        case states.STREAM_START:
-        case states.START:
-          var signature = chunk.readUInt32LE(0);
-          switch (signature) {
-            case SIG_LOCAL_FILE_HEADER:
-              this.state = states.LOCAL_FILE_HEADER;
-              break;
-            case SIG_CDIR_RECORD:
-              this.state = states.CENTRAL_DIRECTORY_FILE_HEADER;
-              break;
-            case SIG_CDIR64_RECORD_END:
-              this.state = states.CDIR64_END;
-              break;
-            case SIG_CDIR64_LOCATOR_END:
-              this.state = states.CDIR64_LOCATOR;
-              break;
-            case SIG_CDIR_RECORD_END:
-              this.state = states.CENTRAL_DIRECTORY_END;
-              break;
-            default:
-              var isStreamStart = this.state === states.STREAM_START;
-              if (!isStreamStart && (signature & 65535) !== 19280 && this.skippedBytes < 26) {
-                var remaining = signature;
-                var toSkip = 4;
-                for (var i = 1; i < 4 && remaining !== 0; i++) {
-                  remaining = remaining >>> 8;
-                  if ((remaining & 255) === 80) {
-                    toSkip = i;
-                    break;
-                  }
+      _processResponse(res, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () {
+            const statusCode = res.message.statusCode || 0;
+            const response = {
+              statusCode,
+              result: null,
+              headers: {}
+            };
+            if (statusCode === HttpCodes.NotFound) {
+              resolve2(response);
+            }
+            function dateTimeDeserializer(key, value) {
+              if (typeof value === "string") {
+                const a = new Date(value);
+                if (!isNaN(a.valueOf())) {
+                  return a;
                 }
-                this.skippedBytes += toSkip;
-                if (this.options.debug) console.log("Skipped", this.skippedBytes, "bytes");
-                return toSkip;
               }
-              this.state = states.ERROR;
-              var errMsg = isStreamStart ? "Not a valid zip file" : "Invalid signature in zip file";
-              if (this.options.debug) {
-                var sig = chunk.readUInt32LE(0);
-                var asString;
-                try {
-                  asString = chunk.slice(0, 4).toString();
-                } catch (e) {
+              return value;
+            }
+            let obj;
+            let contents;
+            try {
+              contents = yield res.readBody();
+              if (contents && contents.length > 0) {
+                if (options && options.deserializeDates) {
+                  obj = JSON.parse(contents, dateTimeDeserializer);
+                } else {
+                  obj = JSON.parse(contents);
                 }
-                console.log("Unexpected signature in zip file: 0x" + sig.toString(16), '"' + asString + '", skipped', this.skippedBytes, "bytes");
+                response.result = obj;
               }
-              this.emit("error", new Error(errMsg));
-              return chunk.length;
-          }
-          this.skippedBytes = 0;
-          return requiredLength;
-        case states.LOCAL_FILE_HEADER:
-          this.parsedEntity = this._readFile(chunk);
-          this.state = states.LOCAL_FILE_HEADER_SUFFIX;
-          return requiredLength;
-        case states.LOCAL_FILE_HEADER_SUFFIX:
-          var entry = new Entry();
-          var isUtf8 = (this.parsedEntity.flags & 2048) !== 0;
-          entry.path = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8);
-          var extraDataBuffer = chunk.slice(this.parsedEntity.fileNameLength, this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength);
-          var extra = this._readExtraFields(extraDataBuffer);
-          if (extra && extra.parsed) {
-            if (extra.parsed.path && !isUtf8) {
-              entry.path = extra.parsed.path;
-            }
-            if (Number.isFinite(extra.parsed.uncompressedSize) && this.parsedEntity.uncompressedSize === FOUR_GIGS - 1) {
-              this.parsedEntity.uncompressedSize = extra.parsed.uncompressedSize;
-            }
-            if (Number.isFinite(extra.parsed.compressedSize) && this.parsedEntity.compressedSize === FOUR_GIGS - 1) {
-              this.parsedEntity.compressedSize = extra.parsed.compressedSize;
+              response.headers = res.message.headers;
+            } catch (err) {
             }
-          }
-          this.parsedEntity.extra = extra.parsed || {};
-          if (this.options.debug) {
-            const debugObj = Object.assign({}, this.parsedEntity, {
-              path: entry.path,
-              flags: "0x" + this.parsedEntity.flags.toString(16),
-              extraFields: extra && extra.debug
-            });
-            console.log("decoded LOCAL_FILE_HEADER:", JSON.stringify(debugObj, null, 2));
-          }
-          this._prepareOutStream(this.parsedEntity, entry);
-          this.emit("entry", entry);
-          this.state = states.FILE_DATA;
-          return requiredLength;
-        case states.CENTRAL_DIRECTORY_FILE_HEADER:
-          this.parsedEntity = this._readCentralDirectoryEntry(chunk);
-          this.state = states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX;
-          return requiredLength;
-        case states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:
-          var isUtf8 = (this.parsedEntity.flags & 2048) !== 0;
-          var path2 = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8);
-          var extraDataBuffer = chunk.slice(this.parsedEntity.fileNameLength, this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength);
-          var extra = this._readExtraFields(extraDataBuffer);
-          if (extra && extra.parsed && extra.parsed.path && !isUtf8) {
-            path2 = extra.parsed.path;
-          }
-          this.parsedEntity.extra = extra.parsed;
-          var isUnix = (this.parsedEntity.versionMadeBy & 65280) >> 8 === 3;
-          var unixAttrs, isSymlink;
-          if (isUnix) {
-            unixAttrs = this.parsedEntity.externalFileAttributes >>> 16;
-            var fileType = unixAttrs >>> 12;
-            isSymlink = (fileType & 10) === 10;
-          }
-          if (this.options.debug) {
-            const debugObj = Object.assign({}, this.parsedEntity, {
-              path: path2,
-              flags: "0x" + this.parsedEntity.flags.toString(16),
-              unixAttrs: unixAttrs && "0" + unixAttrs.toString(8),
-              isSymlink,
-              extraFields: extra.debug
-            });
-            console.log("decoded CENTRAL_DIRECTORY_FILE_HEADER:", JSON.stringify(debugObj, null, 2));
-          }
-          this.state = states.START;
-          return requiredLength;
-        case states.CDIR64_END:
-          this.parsedEntity = this._readEndOfCentralDirectory64(chunk);
-          if (this.options.debug) {
-            console.log("decoded CDIR64_END_RECORD:", this.parsedEntity);
-          }
-          this.state = states.CDIR64_END_DATA_SECTOR;
-          return requiredLength;
-        case states.CDIR64_END_DATA_SECTOR:
-          this.state = states.START;
-          return requiredLength;
-        case states.CDIR64_LOCATOR:
-          this.state = states.START;
-          return requiredLength;
-        case states.CENTRAL_DIRECTORY_END:
-          this.parsedEntity = this._readEndOfCentralDirectory(chunk);
-          if (this.options.debug) {
-            console.log("decoded CENTRAL_DIRECTORY_END:", this.parsedEntity);
-          }
-          this.state = states.CENTRAL_DIRECTORY_END_COMMENT;
-          return requiredLength;
-        case states.CENTRAL_DIRECTORY_END_COMMENT:
-          if (this.options.debug) {
-            console.log("decoded CENTRAL_DIRECTORY_END_COMMENT:", chunk.slice(0, requiredLength).toString());
-          }
-          this.state = states.TRAILING_JUNK;
-          return requiredLength;
-        case states.ERROR:
-          return chunk.length;
-        // discard
-        default:
-          console.log("didn't handle state #", this.state, "discarding");
-          return chunk.length;
+            if (statusCode > 299) {
+              let msg;
+              if (obj && obj.message) {
+                msg = obj.message;
+              } else if (contents && contents.length > 0) {
+                msg = contents;
+              } else {
+                msg = `Failed request: (${statusCode})`;
+              }
+              const err = new HttpClientError(msg, statusCode);
+              err.result = response.result;
+              reject(err);
+            } else {
+              resolve2(response);
+            }
+          }));
+        });
       }
     };
-    UnzipStream.prototype._prepareOutStream = function(vars, entry) {
-      var self2 = this;
-      var isDirectory = vars.uncompressedSize === 0 && /[\/\\]$/.test(entry.path);
-      entry.path = entry.path.replace(/(?<=^|[/\\]+)[.][.]+(?=[/\\]+|$)/g, ".");
-      entry.type = isDirectory ? "Directory" : "File";
-      entry.isDirectory = isDirectory;
-      var fileSizeKnown = !(vars.flags & 8);
-      if (fileSizeKnown) {
-        entry.size = vars.uncompressedSize;
+    exports2.HttpClient = HttpClient2;
+    var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
+  }
+});
+
+// node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/auth.js
+var require_auth3 = __commonJS({
+  "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client/lib/auth.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      var isVersionSupported = vars.versionsNeededToExtract <= 45;
-      this.outStreamInfo = {
-        stream: null,
-        limit: fileSizeKnown ? vars.compressedSize : -1,
-        written: 0
-      };
-      if (!fileSizeKnown) {
-        var pattern = new Buffer(4);
-        pattern.writeUInt32LE(SIG_DATA_DESCRIPTOR, 0);
-        var zip64Mode = vars.extra.zip64Mode;
-        var extraSize = zip64Mode ? 20 : 12;
-        var searchPattern = {
-          pattern,
-          requiredExtraSize: extraSize
-        };
-        var matcherStream = new MatcherStream(searchPattern, function(matchedChunk, sizeSoFar) {
-          var vars2 = self2._readDataDescriptor(matchedChunk, zip64Mode);
-          var compressedSizeMatches = vars2.compressedSize === sizeSoFar;
-          if (!zip64Mode && !compressedSizeMatches && sizeSoFar >= FOUR_GIGS) {
-            var overflown = sizeSoFar - FOUR_GIGS;
-            while (overflown >= 0) {
-              compressedSizeMatches = vars2.compressedSize === overflown;
-              if (compressedSizeMatches) break;
-              overflown -= FOUR_GIGS;
-            }
-          }
-          if (!compressedSizeMatches) {
-            return;
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
           }
-          self2.state = states.FILE_DATA_END;
-          var sliceOffset = zip64Mode ? 24 : 16;
-          if (self2.data.length > 0) {
-            self2.data = Buffer.concat([matchedChunk.slice(sliceOffset), self2.data]);
-          } else {
-            self2.data = matchedChunk.slice(sliceOffset);
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
           }
-          return true;
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0;
+    var BasicCredentialHandler = class {
+      constructor(username, password) {
+        this.username = username;
+        this.password = password;
+      }
+      prepareRequest(options) {
+        if (!options.headers) {
+          throw Error("The request has no headers");
+        }
+        options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`;
+      }
+      // This handler cannot handle 401
+      canHandleAuthentication() {
+        return false;
+      }
+      handleAuthentication() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          throw new Error("not implemented");
         });
-        this.outStreamInfo.stream = matcherStream;
-      } else {
-        this.outStreamInfo.stream = new stream.PassThrough();
       }
-      var isEncrypted = vars.flags & 1 || vars.flags & 64;
-      if (isEncrypted || !isVersionSupported) {
-        var message = isEncrypted ? "Encrypted files are not supported!" : "Zip version " + Math.floor(vars.versionsNeededToExtract / 10) + "." + vars.versionsNeededToExtract % 10 + " is not supported";
-        entry.skip = true;
-        setImmediate(() => {
-          self2.emit("error", new Error(message));
+    };
+    exports2.BasicCredentialHandler = BasicCredentialHandler;
+    var BearerCredentialHandler = class {
+      constructor(token) {
+        this.token = token;
+      }
+      // currently implements pre-authorization
+      // TODO: support preAuth = false where it hooks on 401
+      prepareRequest(options) {
+        if (!options.headers) {
+          throw Error("The request has no headers");
+        }
+        options.headers["Authorization"] = `Bearer ${this.token}`;
+      }
+      // This handler cannot handle 401
+      canHandleAuthentication() {
+        return false;
+      }
+      handleAuthentication() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          throw new Error("not implemented");
         });
-        this.outStreamInfo.stream.pipe(new Entry().autodrain());
-        return;
       }
-      var isCompressed = vars.compressionMethod > 0;
-      if (isCompressed) {
-        var inflater = zlib.createInflateRaw();
-        inflater.on("error", function(err) {
-          self2.state = states.ERROR;
-          self2.emit("error", err);
-        });
-        this.outStreamInfo.stream.pipe(inflater).pipe(entry);
-      } else {
-        this.outStreamInfo.stream.pipe(entry);
+    };
+    exports2.BearerCredentialHandler = BearerCredentialHandler;
+    var PersonalAccessTokenCredentialHandler = class {
+      constructor(token) {
+        this.token = token;
+      }
+      // currently implements pre-authorization
+      // TODO: support preAuth = false where it hooks on 401
+      prepareRequest(options) {
+        if (!options.headers) {
+          throw Error("The request has no headers");
+        }
+        options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`;
+      }
+      // This handler cannot handle 401
+      canHandleAuthentication() {
+        return false;
+      }
+      handleAuthentication() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          throw new Error("not implemented");
+        });
+      }
+    };
+    exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
+  }
+});
+
+// node_modules/@actions/artifact-legacy/lib/internal/config-variables.js
+var require_config_variables = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/config-variables.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.isGhes = exports2.getRetentionDays = exports2.getWorkSpaceDirectory = exports2.getWorkFlowRunId = exports2.getRuntimeUrl = exports2.getRuntimeToken = exports2.getDownloadFileConcurrency = exports2.getInitialRetryIntervalInMilliseconds = exports2.getRetryMultiplier = exports2.getRetryLimit = exports2.getUploadChunkSize = exports2.getUploadFileConcurrency = void 0;
+    function getUploadFileConcurrency() {
+      return 2;
+    }
+    exports2.getUploadFileConcurrency = getUploadFileConcurrency;
+    function getUploadChunkSize() {
+      return 8 * 1024 * 1024;
+    }
+    exports2.getUploadChunkSize = getUploadChunkSize;
+    function getRetryLimit() {
+      return 5;
+    }
+    exports2.getRetryLimit = getRetryLimit;
+    function getRetryMultiplier() {
+      return 1.5;
+    }
+    exports2.getRetryMultiplier = getRetryMultiplier;
+    function getInitialRetryIntervalInMilliseconds() {
+      return 3e3;
+    }
+    exports2.getInitialRetryIntervalInMilliseconds = getInitialRetryIntervalInMilliseconds;
+    function getDownloadFileConcurrency() {
+      return 2;
+    }
+    exports2.getDownloadFileConcurrency = getDownloadFileConcurrency;
+    function getRuntimeToken() {
+      const token = process.env["ACTIONS_RUNTIME_TOKEN"];
+      if (!token) {
+        throw new Error("Unable to get ACTIONS_RUNTIME_TOKEN env variable");
+      }
+      return token;
+    }
+    exports2.getRuntimeToken = getRuntimeToken;
+    function getRuntimeUrl() {
+      const runtimeUrl = process.env["ACTIONS_RUNTIME_URL"];
+      if (!runtimeUrl) {
+        throw new Error("Unable to get ACTIONS_RUNTIME_URL env variable");
+      }
+      return runtimeUrl;
+    }
+    exports2.getRuntimeUrl = getRuntimeUrl;
+    function getWorkFlowRunId() {
+      const workFlowRunId = process.env["GITHUB_RUN_ID"];
+      if (!workFlowRunId) {
+        throw new Error("Unable to get GITHUB_RUN_ID env variable");
+      }
+      return workFlowRunId;
+    }
+    exports2.getWorkFlowRunId = getWorkFlowRunId;
+    function getWorkSpaceDirectory() {
+      const workspaceDirectory = process.env["GITHUB_WORKSPACE"];
+      if (!workspaceDirectory) {
+        throw new Error("Unable to get GITHUB_WORKSPACE env variable");
+      }
+      return workspaceDirectory;
+    }
+    exports2.getWorkSpaceDirectory = getWorkSpaceDirectory;
+    function getRetentionDays() {
+      return process.env["GITHUB_RETENTION_DAYS"];
+    }
+    exports2.getRetentionDays = getRetentionDays;
+    function isGhes() {
+      const ghUrl = new URL(process.env["GITHUB_SERVER_URL"] || "https://github.com");
+      return ghUrl.hostname.toUpperCase() !== "GITHUB.COM";
+    }
+    exports2.isGhes = isGhes;
+  }
+});
+
+// node_modules/@actions/artifact-legacy/lib/internal/crc64.js
+var require_crc64 = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/crc64.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    var PREGEN_POLY_TABLE = [
+      BigInt("0x0000000000000000"),
+      BigInt("0x7F6EF0C830358979"),
+      BigInt("0xFEDDE190606B12F2"),
+      BigInt("0x81B31158505E9B8B"),
+      BigInt("0xC962E5739841B68F"),
+      BigInt("0xB60C15BBA8743FF6"),
+      BigInt("0x37BF04E3F82AA47D"),
+      BigInt("0x48D1F42BC81F2D04"),
+      BigInt("0xA61CECB46814FE75"),
+      BigInt("0xD9721C7C5821770C"),
+      BigInt("0x58C10D24087FEC87"),
+      BigInt("0x27AFFDEC384A65FE"),
+      BigInt("0x6F7E09C7F05548FA"),
+      BigInt("0x1010F90FC060C183"),
+      BigInt("0x91A3E857903E5A08"),
+      BigInt("0xEECD189FA00BD371"),
+      BigInt("0x78E0FF3B88BE6F81"),
+      BigInt("0x078E0FF3B88BE6F8"),
+      BigInt("0x863D1EABE8D57D73"),
+      BigInt("0xF953EE63D8E0F40A"),
+      BigInt("0xB1821A4810FFD90E"),
+      BigInt("0xCEECEA8020CA5077"),
+      BigInt("0x4F5FFBD87094CBFC"),
+      BigInt("0x30310B1040A14285"),
+      BigInt("0xDEFC138FE0AA91F4"),
+      BigInt("0xA192E347D09F188D"),
+      BigInt("0x2021F21F80C18306"),
+      BigInt("0x5F4F02D7B0F40A7F"),
+      BigInt("0x179EF6FC78EB277B"),
+      BigInt("0x68F0063448DEAE02"),
+      BigInt("0xE943176C18803589"),
+      BigInt("0x962DE7A428B5BCF0"),
+      BigInt("0xF1C1FE77117CDF02"),
+      BigInt("0x8EAF0EBF2149567B"),
+      BigInt("0x0F1C1FE77117CDF0"),
+      BigInt("0x7072EF2F41224489"),
+      BigInt("0x38A31B04893D698D"),
+      BigInt("0x47CDEBCCB908E0F4"),
+      BigInt("0xC67EFA94E9567B7F"),
+      BigInt("0xB9100A5CD963F206"),
+      BigInt("0x57DD12C379682177"),
+      BigInt("0x28B3E20B495DA80E"),
+      BigInt("0xA900F35319033385"),
+      BigInt("0xD66E039B2936BAFC"),
+      BigInt("0x9EBFF7B0E12997F8"),
+      BigInt("0xE1D10778D11C1E81"),
+      BigInt("0x606216208142850A"),
+      BigInt("0x1F0CE6E8B1770C73"),
+      BigInt("0x8921014C99C2B083"),
+      BigInt("0xF64FF184A9F739FA"),
+      BigInt("0x77FCE0DCF9A9A271"),
+      BigInt("0x08921014C99C2B08"),
+      BigInt("0x4043E43F0183060C"),
+      BigInt("0x3F2D14F731B68F75"),
+      BigInt("0xBE9E05AF61E814FE"),
+      BigInt("0xC1F0F56751DD9D87"),
+      BigInt("0x2F3DEDF8F1D64EF6"),
+      BigInt("0x50531D30C1E3C78F"),
+      BigInt("0xD1E00C6891BD5C04"),
+      BigInt("0xAE8EFCA0A188D57D"),
+      BigInt("0xE65F088B6997F879"),
+      BigInt("0x9931F84359A27100"),
+      BigInt("0x1882E91B09FCEA8B"),
+      BigInt("0x67EC19D339C963F2"),
+      BigInt("0xD75ADABD7A6E2D6F"),
+      BigInt("0xA8342A754A5BA416"),
+      BigInt("0x29873B2D1A053F9D"),
+      BigInt("0x56E9CBE52A30B6E4"),
+      BigInt("0x1E383FCEE22F9BE0"),
+      BigInt("0x6156CF06D21A1299"),
+      BigInt("0xE0E5DE5E82448912"),
+      BigInt("0x9F8B2E96B271006B"),
+      BigInt("0x71463609127AD31A"),
+      BigInt("0x0E28C6C1224F5A63"),
+      BigInt("0x8F9BD7997211C1E8"),
+      BigInt("0xF0F5275142244891"),
+      BigInt("0xB824D37A8A3B6595"),
+      BigInt("0xC74A23B2BA0EECEC"),
+      BigInt("0x46F932EAEA507767"),
+      BigInt("0x3997C222DA65FE1E"),
+      BigInt("0xAFBA2586F2D042EE"),
+      BigInt("0xD0D4D54EC2E5CB97"),
+      BigInt("0x5167C41692BB501C"),
+      BigInt("0x2E0934DEA28ED965"),
+      BigInt("0x66D8C0F56A91F461"),
+      BigInt("0x19B6303D5AA47D18"),
+      BigInt("0x980521650AFAE693"),
+      BigInt("0xE76BD1AD3ACF6FEA"),
+      BigInt("0x09A6C9329AC4BC9B"),
+      BigInt("0x76C839FAAAF135E2"),
+      BigInt("0xF77B28A2FAAFAE69"),
+      BigInt("0x8815D86ACA9A2710"),
+      BigInt("0xC0C42C4102850A14"),
+      BigInt("0xBFAADC8932B0836D"),
+      BigInt("0x3E19CDD162EE18E6"),
+      BigInt("0x41773D1952DB919F"),
+      BigInt("0x269B24CA6B12F26D"),
+      BigInt("0x59F5D4025B277B14"),
+      BigInt("0xD846C55A0B79E09F"),
+      BigInt("0xA72835923B4C69E6"),
+      BigInt("0xEFF9C1B9F35344E2"),
+      BigInt("0x90973171C366CD9B"),
+      BigInt("0x1124202993385610"),
+      BigInt("0x6E4AD0E1A30DDF69"),
+      BigInt("0x8087C87E03060C18"),
+      BigInt("0xFFE938B633338561"),
+      BigInt("0x7E5A29EE636D1EEA"),
+      BigInt("0x0134D92653589793"),
+      BigInt("0x49E52D0D9B47BA97"),
+      BigInt("0x368BDDC5AB7233EE"),
+      BigInt("0xB738CC9DFB2CA865"),
+      BigInt("0xC8563C55CB19211C"),
+      BigInt("0x5E7BDBF1E3AC9DEC"),
+      BigInt("0x21152B39D3991495"),
+      BigInt("0xA0A63A6183C78F1E"),
+      BigInt("0xDFC8CAA9B3F20667"),
+      BigInt("0x97193E827BED2B63"),
+      BigInt("0xE877CE4A4BD8A21A"),
+      BigInt("0x69C4DF121B863991"),
+      BigInt("0x16AA2FDA2BB3B0E8"),
+      BigInt("0xF86737458BB86399"),
+      BigInt("0x8709C78DBB8DEAE0"),
+      BigInt("0x06BAD6D5EBD3716B"),
+      BigInt("0x79D4261DDBE6F812"),
+      BigInt("0x3105D23613F9D516"),
+      BigInt("0x4E6B22FE23CC5C6F"),
+      BigInt("0xCFD833A67392C7E4"),
+      BigInt("0xB0B6C36E43A74E9D"),
+      BigInt("0x9A6C9329AC4BC9B5"),
+      BigInt("0xE50263E19C7E40CC"),
+      BigInt("0x64B172B9CC20DB47"),
+      BigInt("0x1BDF8271FC15523E"),
+      BigInt("0x530E765A340A7F3A"),
+      BigInt("0x2C608692043FF643"),
+      BigInt("0xADD397CA54616DC8"),
+      BigInt("0xD2BD67026454E4B1"),
+      BigInt("0x3C707F9DC45F37C0"),
+      BigInt("0x431E8F55F46ABEB9"),
+      BigInt("0xC2AD9E0DA4342532"),
+      BigInt("0xBDC36EC59401AC4B"),
+      BigInt("0xF5129AEE5C1E814F"),
+      BigInt("0x8A7C6A266C2B0836"),
+      BigInt("0x0BCF7B7E3C7593BD"),
+      BigInt("0x74A18BB60C401AC4"),
+      BigInt("0xE28C6C1224F5A634"),
+      BigInt("0x9DE29CDA14C02F4D"),
+      BigInt("0x1C518D82449EB4C6"),
+      BigInt("0x633F7D4A74AB3DBF"),
+      BigInt("0x2BEE8961BCB410BB"),
+      BigInt("0x548079A98C8199C2"),
+      BigInt("0xD53368F1DCDF0249"),
+      BigInt("0xAA5D9839ECEA8B30"),
+      BigInt("0x449080A64CE15841"),
+      BigInt("0x3BFE706E7CD4D138"),
+      BigInt("0xBA4D61362C8A4AB3"),
+      BigInt("0xC52391FE1CBFC3CA"),
+      BigInt("0x8DF265D5D4A0EECE"),
+      BigInt("0xF29C951DE49567B7"),
+      BigInt("0x732F8445B4CBFC3C"),
+      BigInt("0x0C41748D84FE7545"),
+      BigInt("0x6BAD6D5EBD3716B7"),
+      BigInt("0x14C39D968D029FCE"),
+      BigInt("0x95708CCEDD5C0445"),
+      BigInt("0xEA1E7C06ED698D3C"),
+      BigInt("0xA2CF882D2576A038"),
+      BigInt("0xDDA178E515432941"),
+      BigInt("0x5C1269BD451DB2CA"),
+      BigInt("0x237C997575283BB3"),
+      BigInt("0xCDB181EAD523E8C2"),
+      BigInt("0xB2DF7122E51661BB"),
+      BigInt("0x336C607AB548FA30"),
+      BigInt("0x4C0290B2857D7349"),
+      BigInt("0x04D364994D625E4D"),
+      BigInt("0x7BBD94517D57D734"),
+      BigInt("0xFA0E85092D094CBF"),
+      BigInt("0x856075C11D3CC5C6"),
+      BigInt("0x134D926535897936"),
+      BigInt("0x6C2362AD05BCF04F"),
+      BigInt("0xED9073F555E26BC4"),
+      BigInt("0x92FE833D65D7E2BD"),
+      BigInt("0xDA2F7716ADC8CFB9"),
+      BigInt("0xA54187DE9DFD46C0"),
+      BigInt("0x24F29686CDA3DD4B"),
+      BigInt("0x5B9C664EFD965432"),
+      BigInt("0xB5517ED15D9D8743"),
+      BigInt("0xCA3F8E196DA80E3A"),
+      BigInt("0x4B8C9F413DF695B1"),
+      BigInt("0x34E26F890DC31CC8"),
+      BigInt("0x7C339BA2C5DC31CC"),
+      BigInt("0x035D6B6AF5E9B8B5"),
+      BigInt("0x82EE7A32A5B7233E"),
+      BigInt("0xFD808AFA9582AA47"),
+      BigInt("0x4D364994D625E4DA"),
+      BigInt("0x3258B95CE6106DA3"),
+      BigInt("0xB3EBA804B64EF628"),
+      BigInt("0xCC8558CC867B7F51"),
+      BigInt("0x8454ACE74E645255"),
+      BigInt("0xFB3A5C2F7E51DB2C"),
+      BigInt("0x7A894D772E0F40A7"),
+      BigInt("0x05E7BDBF1E3AC9DE"),
+      BigInt("0xEB2AA520BE311AAF"),
+      BigInt("0x944455E88E0493D6"),
+      BigInt("0x15F744B0DE5A085D"),
+      BigInt("0x6A99B478EE6F8124"),
+      BigInt("0x224840532670AC20"),
+      BigInt("0x5D26B09B16452559"),
+      BigInt("0xDC95A1C3461BBED2"),
+      BigInt("0xA3FB510B762E37AB"),
+      BigInt("0x35D6B6AF5E9B8B5B"),
+      BigInt("0x4AB846676EAE0222"),
+      BigInt("0xCB0B573F3EF099A9"),
+      BigInt("0xB465A7F70EC510D0"),
+      BigInt("0xFCB453DCC6DA3DD4"),
+      BigInt("0x83DAA314F6EFB4AD"),
+      BigInt("0x0269B24CA6B12F26"),
+      BigInt("0x7D0742849684A65F"),
+      BigInt("0x93CA5A1B368F752E"),
+      BigInt("0xECA4AAD306BAFC57"),
+      BigInt("0x6D17BB8B56E467DC"),
+      BigInt("0x12794B4366D1EEA5"),
+      BigInt("0x5AA8BF68AECEC3A1"),
+      BigInt("0x25C64FA09EFB4AD8"),
+      BigInt("0xA4755EF8CEA5D153"),
+      BigInt("0xDB1BAE30FE90582A"),
+      BigInt("0xBCF7B7E3C7593BD8"),
+      BigInt("0xC399472BF76CB2A1"),
+      BigInt("0x422A5673A732292A"),
+      BigInt("0x3D44A6BB9707A053"),
+      BigInt("0x759552905F188D57"),
+      BigInt("0x0AFBA2586F2D042E"),
+      BigInt("0x8B48B3003F739FA5"),
+      BigInt("0xF42643C80F4616DC"),
+      BigInt("0x1AEB5B57AF4DC5AD"),
+      BigInt("0x6585AB9F9F784CD4"),
+      BigInt("0xE436BAC7CF26D75F"),
+      BigInt("0x9B584A0FFF135E26"),
+      BigInt("0xD389BE24370C7322"),
+      BigInt("0xACE74EEC0739FA5B"),
+      BigInt("0x2D545FB4576761D0"),
+      BigInt("0x523AAF7C6752E8A9"),
+      BigInt("0xC41748D84FE75459"),
+      BigInt("0xBB79B8107FD2DD20"),
+      BigInt("0x3ACAA9482F8C46AB"),
+      BigInt("0x45A459801FB9CFD2"),
+      BigInt("0x0D75ADABD7A6E2D6"),
+      BigInt("0x721B5D63E7936BAF"),
+      BigInt("0xF3A84C3BB7CDF024"),
+      BigInt("0x8CC6BCF387F8795D"),
+      BigInt("0x620BA46C27F3AA2C"),
+      BigInt("0x1D6554A417C62355"),
+      BigInt("0x9CD645FC4798B8DE"),
+      BigInt("0xE3B8B53477AD31A7"),
+      BigInt("0xAB69411FBFB21CA3"),
+      BigInt("0xD407B1D78F8795DA"),
+      BigInt("0x55B4A08FDFD90E51"),
+      BigInt("0x2ADA5047EFEC8728")
+    ];
+    var CRC64 = class _CRC64 {
+      constructor() {
+        this._crc = BigInt(0);
+      }
+      update(data) {
+        const buffer = typeof data === "string" ? Buffer.from(data) : data;
+        let crc = _CRC64.flip64Bits(this._crc);
+        for (const dataByte of buffer) {
+          const crcByte = Number(crc & BigInt(255));
+          crc = PREGEN_POLY_TABLE[crcByte ^ dataByte] ^ crc >> BigInt(8);
+        }
+        this._crc = _CRC64.flip64Bits(crc);
+      }
+      digest(encoding) {
+        switch (encoding) {
+          case "hex":
+            return this._crc.toString(16).toUpperCase();
+          case "base64":
+            return this.toBuffer().toString("base64");
+          default:
+            return this.toBuffer();
+        }
       }
-      if (this._drainAllEntries) {
-        entry.autodrain();
+      toBuffer() {
+        return Buffer.from([0, 8, 16, 24, 32, 40, 48, 56].map((s) => Number(this._crc >> BigInt(s) & BigInt(255))));
+      }
+      static flip64Bits(n) {
+        return (BigInt(1) << BigInt(64)) - BigInt(1) - n;
       }
     };
-    UnzipStream.prototype._readFile = function(data) {
-      var vars = binary2.parse(data).word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars;
-      return vars;
-    };
-    UnzipStream.prototype._readExtraFields = function(data) {
-      var extra = {};
-      var result = { parsed: extra };
-      if (this.options.debug) {
-        result.debug = [];
+    exports2.default = CRC64;
+  }
+});
+
+// node_modules/@actions/artifact-legacy/lib/internal/utils.js
+var require_utils7 = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/utils.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      var index = 0;
-      while (index < data.length) {
-        var vars = binary2.parse(data).skip(index).word16lu("extraId").word16lu("extraSize").vars;
-        index += 4;
-        var fieldType = void 0;
-        switch (vars.extraId) {
-          case 1:
-            fieldType = "Zip64 extended information extra field";
-            var z64vars = binary2.parse(data.slice(index, index + vars.extraSize)).word64lu("uncompressedSize").word64lu("compressedSize").word64lu("offsetToLocalHeader").word32lu("diskStartNumber").vars;
-            if (z64vars.uncompressedSize !== null) {
-              extra.uncompressedSize = z64vars.uncompressedSize;
-            }
-            if (z64vars.compressedSize !== null) {
-              extra.compressedSize = z64vars.compressedSize;
-            }
-            extra.zip64Mode = true;
-            break;
-          case 10:
-            fieldType = "NTFS extra field";
-            break;
-          case 21589:
-            fieldType = "extended timestamp";
-            var timestampFields = data.readUInt8(index);
-            var offset = 1;
-            if (vars.extraSize >= offset + 4 && timestampFields & 1) {
-              extra.mtime = new Date(data.readUInt32LE(index + offset) * 1e3);
-              offset += 4;
-            }
-            if (vars.extraSize >= offset + 4 && timestampFields & 2) {
-              extra.atime = new Date(data.readUInt32LE(index + offset) * 1e3);
-              offset += 4;
-            }
-            if (vars.extraSize >= offset + 4 && timestampFields & 4) {
-              extra.ctime = new Date(data.readUInt32LE(index + offset) * 1e3);
-            }
-            break;
-          case 28789:
-            fieldType = "Info-ZIP Unicode Path Extra Field";
-            var fieldVer = data.readUInt8(index);
-            if (fieldVer === 1) {
-              var offset = 1;
-              var nameCrc32 = data.readUInt32LE(index + offset);
-              offset += 4;
-              var pathBuffer = data.slice(index + offset);
-              extra.path = pathBuffer.toString();
-            }
-            break;
-          case 13:
-          case 22613:
-            fieldType = vars.extraId === 13 ? "PKWARE Unix" : "Info-ZIP UNIX (type 1)";
-            var offset = 0;
-            if (vars.extraSize >= 8) {
-              var atime = new Date(data.readUInt32LE(index + offset) * 1e3);
-              offset += 4;
-              var mtime = new Date(data.readUInt32LE(index + offset) * 1e3);
-              offset += 4;
-              extra.atime = atime;
-              extra.mtime = mtime;
-              if (vars.extraSize >= 12) {
-                var uid = data.readUInt16LE(index + offset);
-                offset += 2;
-                var gid = data.readUInt16LE(index + offset);
-                offset += 2;
-                extra.uid = uid;
-                extra.gid = gid;
-              }
-            }
-            break;
-          case 30805:
-            fieldType = "Info-ZIP UNIX (type 2)";
-            var offset = 0;
-            if (vars.extraSize >= 4) {
-              var uid = data.readUInt16LE(index + offset);
-              offset += 2;
-              var gid = data.readUInt16LE(index + offset);
-              offset += 2;
-              extra.uid = uid;
-              extra.gid = gid;
-            }
-            break;
-          case 30837:
-            fieldType = "Info-ZIP New Unix";
-            var offset = 0;
-            var extraVer = data.readUInt8(index);
-            offset += 1;
-            if (extraVer === 1) {
-              var uidSize = data.readUInt8(index + offset);
-              offset += 1;
-              if (uidSize <= 6) {
-                extra.uid = data.readUIntLE(index + offset, uidSize);
-              }
-              offset += uidSize;
-              var gidSize = data.readUInt8(index + offset);
-              offset += 1;
-              if (gidSize <= 6) {
-                extra.gid = data.readUIntLE(index + offset, gidSize);
-              }
-            }
-            break;
-          case 30062:
-            fieldType = "ASi Unix";
-            var offset = 0;
-            if (vars.extraSize >= 14) {
-              var crc = data.readUInt32LE(index + offset);
-              offset += 4;
-              var mode = data.readUInt16LE(index + offset);
-              offset += 2;
-              var sizdev = data.readUInt32LE(index + offset);
-              offset += 4;
-              var uid = data.readUInt16LE(index + offset);
-              offset += 2;
-              var gid = data.readUInt16LE(index + offset);
-              offset += 2;
-              extra.mode = mode;
-              extra.uid = uid;
-              extra.gid = gid;
-              if (vars.extraSize > 14) {
-                var start = index + offset;
-                var end = index + vars.extraSize - 14;
-                var symlinkName = this._decodeString(data.slice(start, end));
-                extra.symlink = symlinkName;
-              }
-            }
-            break;
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        if (this.options.debug) {
-          result.debug.push({
-            extraId: "0x" + vars.extraId.toString(16),
-            description: fieldType,
-            data: data.slice(index, index + vars.extraSize).inspect()
-          });
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        index += vars.extraSize;
-      }
-      return result;
-    };
-    UnzipStream.prototype._readDataDescriptor = function(data, zip64Mode) {
-      if (zip64Mode) {
-        var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word64lu("compressedSize").word64lu("uncompressedSize").vars;
-        return vars;
-      }
-      var vars = binary2.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").vars;
-      return vars;
-    };
-    UnzipStream.prototype._readCentralDirectoryEntry = function(data) {
-      var vars = binary2.parse(data).word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars;
-      return vars;
-    };
-    UnzipStream.prototype._readEndOfCentralDirectory64 = function(data) {
-      var vars = binary2.parse(data).word64lu("centralDirectoryRecordSize").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskNumberWithCentralDirectoryStart").word64lu("centralDirectoryEntries").word64lu("totalCentralDirectoryEntries").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars;
-      return vars;
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    UnzipStream.prototype._readEndOfCentralDirectory = function(data) {
-      var vars = binary2.parse(data).word16lu("diskNumber").word16lu("diskStart").word16lu("centralDirectoryEntries").word16lu("totalCentralDirectoryEntries").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars;
-      return vars;
+    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
+      return mod && mod.__esModule ? mod : { "default": mod };
     };
-    var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 ";
-    UnzipStream.prototype._decodeString = function(buffer, isUtf8) {
-      if (isUtf8) {
-        return buffer.toString("utf8");
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.digestForStream = exports2.sleep = exports2.getProperRetention = exports2.rmFile = exports2.getFileSize = exports2.createEmptyFilesForArtifact = exports2.createDirectoriesForArtifact = exports2.displayHttpDiagnostics = exports2.getArtifactUrl = exports2.createHttpClient = exports2.getUploadHeaders = exports2.getDownloadHeaders = exports2.getContentRange = exports2.tryGetRetryAfterValueTimeInMilliseconds = exports2.isThrottledStatusCode = exports2.isRetryableStatusCode = exports2.isForbiddenStatusCode = exports2.isSuccessStatusCode = exports2.getApiVersion = exports2.parseEnvNumber = exports2.getExponentialRetryTimeInMilliseconds = void 0;
+    var crypto_1 = __importDefault4(require("crypto"));
+    var fs_1 = require("fs");
+    var core_1 = require_core();
+    var http_client_1 = require_lib5();
+    var auth_1 = require_auth3();
+    var config_variables_1 = require_config_variables();
+    var crc64_1 = __importDefault4(require_crc64());
+    function getExponentialRetryTimeInMilliseconds(retryCount) {
+      if (retryCount < 0) {
+        throw new Error("RetryCount should not be negative");
+      } else if (retryCount === 0) {
+        return (0, config_variables_1.getInitialRetryIntervalInMilliseconds)();
       }
-      if (this.options.decodeString) {
-        return this.options.decodeString(buffer);
+      const minTime = (0, config_variables_1.getInitialRetryIntervalInMilliseconds)() * (0, config_variables_1.getRetryMultiplier)() * retryCount;
+      const maxTime = minTime * (0, config_variables_1.getRetryMultiplier)();
+      return Math.trunc(Math.random() * (maxTime - minTime) + minTime);
+    }
+    exports2.getExponentialRetryTimeInMilliseconds = getExponentialRetryTimeInMilliseconds;
+    function parseEnvNumber(key) {
+      const value = Number(process.env[key]);
+      if (Number.isNaN(value) || value < 0) {
+        return void 0;
       }
-      let result = "";
-      for (var i = 0; i < buffer.length; i++) {
-        result += cp437[buffer[i]];
+      return value;
+    }
+    exports2.parseEnvNumber = parseEnvNumber;
+    function getApiVersion() {
+      return "6.0-preview";
+    }
+    exports2.getApiVersion = getApiVersion;
+    function isSuccessStatusCode(statusCode) {
+      if (!statusCode) {
+        return false;
       }
-      return result;
-    };
-    UnzipStream.prototype._parseOrOutput = function(encoding, cb) {
-      var consume;
-      while ((consume = this.processDataChunk(this.data)) > 0) {
-        this.data = this.data.slice(consume);
-        if (this.data.length === 0) break;
+      return statusCode >= 200 && statusCode < 300;
+    }
+    exports2.isSuccessStatusCode = isSuccessStatusCode;
+    function isForbiddenStatusCode(statusCode) {
+      if (!statusCode) {
+        return false;
       }
-      if (this.state === states.FILE_DATA) {
-        if (this.outStreamInfo.limit >= 0) {
-          var remaining = this.outStreamInfo.limit - this.outStreamInfo.written;
-          var packet;
-          if (remaining < this.data.length) {
-            packet = this.data.slice(0, remaining);
-            this.data = this.data.slice(remaining);
-          } else {
-            packet = this.data;
-            this.data = new Buffer("");
-          }
-          this.outStreamInfo.written += packet.length;
-          if (this.outStreamInfo.limit === this.outStreamInfo.written) {
-            this.state = states.START;
-            this.outStreamInfo.stream.end(packet, encoding, cb);
-          } else {
-            this.outStreamInfo.stream.write(packet, encoding, cb);
-          }
-        } else {
-          var packet = this.data;
-          this.data = new Buffer("");
-          this.outStreamInfo.written += packet.length;
-          var outputStream = this.outStreamInfo.stream;
-          outputStream.write(packet, encoding, () => {
-            if (this.state === states.FILE_DATA_END) {
-              this.state = states.START;
-              return outputStream.end(cb);
-            }
-            cb();
-          });
+      return statusCode === http_client_1.HttpCodes.Forbidden;
+    }
+    exports2.isForbiddenStatusCode = isForbiddenStatusCode;
+    function isRetryableStatusCode(statusCode) {
+      if (!statusCode) {
+        return false;
+      }
+      const retryableStatusCodes = [
+        http_client_1.HttpCodes.BadGateway,
+        http_client_1.HttpCodes.GatewayTimeout,
+        http_client_1.HttpCodes.InternalServerError,
+        http_client_1.HttpCodes.ServiceUnavailable,
+        http_client_1.HttpCodes.TooManyRequests,
+        413
+        // Payload Too Large
+      ];
+      return retryableStatusCodes.includes(statusCode);
+    }
+    exports2.isRetryableStatusCode = isRetryableStatusCode;
+    function isThrottledStatusCode(statusCode) {
+      if (!statusCode) {
+        return false;
+      }
+      return statusCode === http_client_1.HttpCodes.TooManyRequests;
+    }
+    exports2.isThrottledStatusCode = isThrottledStatusCode;
+    function tryGetRetryAfterValueTimeInMilliseconds(headers) {
+      if (headers["retry-after"]) {
+        const retryTime = Number(headers["retry-after"]);
+        if (!isNaN(retryTime)) {
+          (0, core_1.info)(`Retry-After header is present with a value of ${retryTime}`);
+          return retryTime * 1e3;
         }
-        return;
+        (0, core_1.info)(`Returned retry-after header value: ${retryTime} is non-numeric and cannot be used`);
+        return void 0;
       }
-      cb();
-    };
-    UnzipStream.prototype.drainAll = function() {
-      this._drainAllEntries = true;
-    };
-    UnzipStream.prototype._transform = function(chunk, encoding, cb) {
-      var self2 = this;
-      if (self2.data.length > 0) {
-        self2.data = Buffer.concat([self2.data, chunk]);
+      (0, core_1.info)(`No retry-after header was found. Dumping all headers for diagnostic purposes`);
+      console.log(headers);
+      return void 0;
+    }
+    exports2.tryGetRetryAfterValueTimeInMilliseconds = tryGetRetryAfterValueTimeInMilliseconds;
+    function getContentRange(start, end, total) {
+      return `bytes ${start}-${end}/${total}`;
+    }
+    exports2.getContentRange = getContentRange;
+    function getDownloadHeaders(contentType, isKeepAlive, acceptGzip) {
+      const requestOptions = {};
+      if (contentType) {
+        requestOptions["Content-Type"] = contentType;
+      }
+      if (isKeepAlive) {
+        requestOptions["Connection"] = "Keep-Alive";
+        requestOptions["Keep-Alive"] = "10";
+      }
+      if (acceptGzip) {
+        requestOptions["Accept-Encoding"] = "gzip";
+        requestOptions["Accept"] = `application/octet-stream;api-version=${getApiVersion()}`;
       } else {
-        self2.data = chunk;
+        requestOptions["Accept"] = `application/json;api-version=${getApiVersion()}`;
       }
-      var startDataLength = self2.data.length;
-      var done = function() {
-        if (self2.data.length > 0 && self2.data.length < startDataLength) {
-          startDataLength = self2.data.length;
-          self2._parseOrOutput(encoding, done);
-          return;
-        }
-        cb();
-      };
-      self2._parseOrOutput(encoding, done);
-    };
-    UnzipStream.prototype._flush = function(cb) {
-      var self2 = this;
-      if (self2.data.length > 0) {
-        self2._parseOrOutput("buffer", function() {
-          if (self2.data.length > 0) return setImmediate(function() {
-            self2._flush(cb);
-          });
-          cb();
-        });
-        return;
+      return requestOptions;
+    }
+    exports2.getDownloadHeaders = getDownloadHeaders;
+    function getUploadHeaders(contentType, isKeepAlive, isGzip, uncompressedLength, contentLength, contentRange, digest) {
+      const requestOptions = {};
+      requestOptions["Accept"] = `application/json;api-version=${getApiVersion()}`;
+      if (contentType) {
+        requestOptions["Content-Type"] = contentType;
       }
-      if (self2.state === states.FILE_DATA) {
-        return cb(new Error("Stream finished in an invalid state, uncompression failed"));
+      if (isKeepAlive) {
+        requestOptions["Connection"] = "Keep-Alive";
+        requestOptions["Keep-Alive"] = "10";
       }
-      setImmediate(cb);
-    };
-    module2.exports = UnzipStream;
-  }
-});
-
-// node_modules/unzip-stream/lib/parser-stream.js
-var require_parser_stream = __commonJS({
-  "node_modules/unzip-stream/lib/parser-stream.js"(exports2, module2) {
-    var Transform = require("stream").Transform;
-    var util = require("util");
-    var UnzipStream = require_unzip_stream();
-    function ParserStream(opts) {
-      if (!(this instanceof ParserStream)) {
-        return new ParserStream(opts);
+      if (isGzip) {
+        requestOptions["Content-Encoding"] = "gzip";
+        requestOptions["x-tfs-filelength"] = uncompressedLength;
       }
-      var transformOpts = opts || {};
-      Transform.call(this, { readableObjectMode: true });
-      this.opts = opts || {};
-      this.unzipStream = new UnzipStream(this.opts);
-      var self2 = this;
-      this.unzipStream.on("entry", function(entry) {
-        self2.push(entry);
+      if (contentLength) {
+        requestOptions["Content-Length"] = contentLength;
+      }
+      if (contentRange) {
+        requestOptions["Content-Range"] = contentRange;
+      }
+      if (digest) {
+        requestOptions["x-actions-results-crc64"] = digest.crc64;
+        requestOptions["x-actions-results-md5"] = digest.md5;
+      }
+      return requestOptions;
+    }
+    exports2.getUploadHeaders = getUploadHeaders;
+    function createHttpClient(userAgent) {
+      return new http_client_1.HttpClient(userAgent, [
+        new auth_1.BearerCredentialHandler((0, config_variables_1.getRuntimeToken)())
+      ]);
+    }
+    exports2.createHttpClient = createHttpClient;
+    function getArtifactUrl() {
+      const artifactUrl = `${(0, config_variables_1.getRuntimeUrl)()}_apis/pipelines/workflows/${(0, config_variables_1.getWorkFlowRunId)()}/artifacts?api-version=${getApiVersion()}`;
+      (0, core_1.debug)(`Artifact Url: ${artifactUrl}`);
+      return artifactUrl;
+    }
+    exports2.getArtifactUrl = getArtifactUrl;
+    function displayHttpDiagnostics(response) {
+      (0, core_1.info)(`##### Begin Diagnostic HTTP information #####
+Status Code: ${response.message.statusCode}
+Status Message: ${response.message.statusMessage}
+Header Information: ${JSON.stringify(response.message.headers, void 0, 2)}
+###### End Diagnostic HTTP information ######`);
+    }
+    exports2.displayHttpDiagnostics = displayHttpDiagnostics;
+    function createDirectoriesForArtifact(directories) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        for (const directory of directories) {
+          yield fs_1.promises.mkdir(directory, {
+            recursive: true
+          });
+        }
       });
-      this.unzipStream.on("error", function(error4) {
-        self2.emit("error", error4);
+    }
+    exports2.createDirectoriesForArtifact = createDirectoriesForArtifact;
+    function createEmptyFilesForArtifact(emptyFilesToCreate) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        for (const filePath of emptyFilesToCreate) {
+          yield (yield fs_1.promises.open(filePath, "w")).close();
+        }
+      });
+    }
+    exports2.createEmptyFilesForArtifact = createEmptyFilesForArtifact;
+    function getFileSize(filePath) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const stats = yield fs_1.promises.stat(filePath);
+        (0, core_1.debug)(`${filePath} size:(${stats.size}) blksize:(${stats.blksize}) blocks:(${stats.blocks})`);
+        return stats.size;
+      });
+    }
+    exports2.getFileSize = getFileSize;
+    function rmFile(filePath) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        yield fs_1.promises.unlink(filePath);
+      });
+    }
+    exports2.rmFile = rmFile;
+    function getProperRetention(retentionInput, retentionSetting) {
+      if (retentionInput < 0) {
+        throw new Error("Invalid retention, minimum value is 1.");
+      }
+      let retention = retentionInput;
+      if (retentionSetting) {
+        const maxRetention = parseInt(retentionSetting);
+        if (!isNaN(maxRetention) && maxRetention < retention) {
+          (0, core_1.warning)(`Retention days is greater than the max value allowed by the repository setting, reduce retention to ${maxRetention} days`);
+          retention = maxRetention;
+        }
+      }
+      return retention;
+    }
+    exports2.getProperRetention = getProperRetention;
+    function sleep(milliseconds) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
       });
     }
-    util.inherits(ParserStream, Transform);
-    ParserStream.prototype._transform = function(chunk, encoding, cb) {
-      this.unzipStream.write(chunk, encoding, cb);
-    };
-    ParserStream.prototype._flush = function(cb) {
-      var self2 = this;
-      this.unzipStream.end(function() {
-        process.nextTick(function() {
-          self2.emit("close");
+    exports2.sleep = sleep;
+    function digestForStream(stream) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        return new Promise((resolve2, reject) => {
+          const crc64 = new crc64_1.default();
+          const md5 = crypto_1.default.createHash("md5");
+          stream.on("data", (data) => {
+            crc64.update(data);
+            md5.update(data);
+          }).on("end", () => resolve2({
+            crc64: crc64.digest("base64"),
+            md5: md5.digest("base64")
+          })).on("error", reject);
         });
-        cb();
       });
-    };
-    ParserStream.prototype.on = function(eventName, fn) {
-      if (eventName === "entry") {
-        return Transform.prototype.on.call(this, "data", fn);
-      }
-      return Transform.prototype.on.call(this, eventName, fn);
-    };
-    ParserStream.prototype.drainAll = function() {
-      this.unzipStream.drainAll();
-      return this.pipe(new Transform({ objectMode: true, transform: function(d, e, cb) {
-        cb();
-      } }));
-    };
-    module2.exports = ParserStream;
+    }
+    exports2.digestForStream = digestForStream;
   }
 });
 
-// node_modules/mkdirp/index.js
-var require_mkdirp = __commonJS({
-  "node_modules/mkdirp/index.js"(exports2, module2) {
-    var path2 = require("path");
-    var fs2 = require("fs");
-    var _0777 = parseInt("0777", 8);
-    module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
-    function mkdirP(p, opts, f, made) {
-      if (typeof opts === "function") {
-        f = opts;
-        opts = {};
-      } else if (!opts || typeof opts !== "object") {
-        opts = { mode: opts };
+// node_modules/@actions/artifact-legacy/lib/internal/status-reporter.js
+var require_status_reporter = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/status-reporter.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.StatusReporter = void 0;
+    var core_1 = require_core();
+    var StatusReporter = class {
+      constructor(displayFrequencyInMilliseconds) {
+        this.totalNumberOfFilesToProcess = 0;
+        this.processedCount = 0;
+        this.largeFiles = /* @__PURE__ */ new Map();
+        this.totalFileStatus = void 0;
+        this.displayFrequencyInMilliseconds = displayFrequencyInMilliseconds;
       }
-      var mode = opts.mode;
-      var xfs = opts.fs || fs2;
-      if (mode === void 0) {
-        mode = _0777;
+      setTotalNumberOfFilesToProcess(fileTotal) {
+        this.totalNumberOfFilesToProcess = fileTotal;
+        this.processedCount = 0;
       }
-      if (!made) made = null;
-      var cb = f || /* istanbul ignore next */
-      function() {
-      };
-      p = path2.resolve(p);
-      xfs.mkdir(p, mode, function(er) {
-        if (!er) {
-          made = made || p;
-          return cb(null, made);
-        }
-        switch (er.code) {
-          case "ENOENT":
-            if (path2.dirname(p) === p) return cb(er);
-            mkdirP(path2.dirname(p), opts, function(er2, made2) {
-              if (er2) cb(er2, made2);
-              else mkdirP(p, opts, cb, made2);
-            });
-            break;
-          // In the case of any other error, just see if there's a dir
-          // there already.  If so, then hooray!  If not, then something
-          // is borked.
-          default:
-            xfs.stat(p, function(er2, stat) {
-              if (er2 || !stat.isDirectory()) cb(er, made);
-              else cb(null, made);
-            });
-            break;
-        }
-      });
-    }
-    mkdirP.sync = function sync(p, opts, made) {
-      if (!opts || typeof opts !== "object") {
-        opts = { mode: opts };
+      start() {
+        this.totalFileStatus = setInterval(() => {
+          const percentage = this.formatPercentage(this.processedCount, this.totalNumberOfFilesToProcess);
+          (0, core_1.info)(`Total file count: ${this.totalNumberOfFilesToProcess} ---- Processed file #${this.processedCount} (${percentage.slice(0, percentage.indexOf(".") + 2)}%)`);
+        }, this.displayFrequencyInMilliseconds);
       }
-      var mode = opts.mode;
-      var xfs = opts.fs || fs2;
-      if (mode === void 0) {
-        mode = _0777;
+      // if there is a large file that is being uploaded in chunks, this is used to display extra information about the status of the upload
+      updateLargeFileStatus(fileName, chunkStartIndex, chunkEndIndex, totalUploadFileSize) {
+        const percentage = this.formatPercentage(chunkEndIndex, totalUploadFileSize);
+        (0, core_1.info)(`Uploaded ${fileName} (${percentage.slice(0, percentage.indexOf(".") + 2)}%) bytes ${chunkStartIndex}:${chunkEndIndex}`);
       }
-      if (!made) made = null;
-      p = path2.resolve(p);
-      try {
-        xfs.mkdirSync(p, mode);
-        made = made || p;
-      } catch (err0) {
-        switch (err0.code) {
-          case "ENOENT":
-            made = sync(path2.dirname(p), opts, made);
-            sync(p, opts, made);
-            break;
-          // In the case of any other error, just see if there's a dir
-          // there already.  If so, then hooray!  If not, then something
-          // is borked.
-          default:
-            var stat;
-            try {
-              stat = xfs.statSync(p);
-            } catch (err1) {
-              throw err0;
-            }
-            if (!stat.isDirectory()) throw err0;
-            break;
+      stop() {
+        if (this.totalFileStatus) {
+          clearInterval(this.totalFileStatus);
         }
       }
-      return made;
+      incrementProcessedCount() {
+        this.processedCount++;
+      }
+      formatPercentage(numerator, denominator) {
+        return (numerator / denominator * 100).toFixed(4).toString();
+      }
     };
+    exports2.StatusReporter = StatusReporter;
   }
 });
 
-// node_modules/unzip-stream/lib/extract.js
-var require_extract2 = __commonJS({
-  "node_modules/unzip-stream/lib/extract.js"(exports2, module2) {
-    var fs2 = require("fs");
-    var path2 = require("path");
-    var util = require("util");
-    var mkdirp = require_mkdirp();
-    var Transform = require("stream").Transform;
-    var UnzipStream = require_unzip_stream();
-    function Extract(opts) {
-      if (!(this instanceof Extract))
-        return new Extract(opts);
-      Transform.call(this);
-      this.opts = opts || {};
-      this.unzipStream = new UnzipStream(this.opts);
-      this.unfinishedEntries = 0;
-      this.afterFlushWait = false;
-      this.createdDirectories = {};
-      var self2 = this;
-      this.unzipStream.on("entry", this._processEntry.bind(this));
-      this.unzipStream.on("error", function(error4) {
-        self2.emit("error", error4);
-      });
-    }
-    util.inherits(Extract, Transform);
-    Extract.prototype._transform = function(chunk, encoding, cb) {
-      this.unzipStream.write(chunk, encoding, cb);
-    };
-    Extract.prototype._flush = function(cb) {
-      var self2 = this;
-      var allDone = function() {
-        process.nextTick(function() {
-          self2.emit("close");
-        });
-        cb();
-      };
-      this.unzipStream.end(function() {
-        if (self2.unfinishedEntries > 0) {
-          self2.afterFlushWait = true;
-          return self2.on("await-finished", allDone);
+// node_modules/@actions/artifact-legacy/lib/internal/http-manager.js
+var require_http_manager = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/http-manager.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.HttpManager = void 0;
+    var utils_1 = require_utils7();
+    var HttpManager = class {
+      constructor(clientCount, userAgent) {
+        if (clientCount < 1) {
+          throw new Error("There must be at least one client");
         }
-        allDone();
-      });
-    };
-    Extract.prototype._processEntry = function(entry) {
-      var self2 = this;
-      var destPath = path2.join(this.opts.path, entry.path);
-      var directory = entry.isDirectory ? destPath : path2.dirname(destPath);
-      this.unfinishedEntries++;
-      var writeFileFn = function() {
-        var pipedStream = fs2.createWriteStream(destPath);
-        pipedStream.on("close", function() {
-          self2.unfinishedEntries--;
-          self2._notifyAwaiter();
-        });
-        pipedStream.on("error", function(error4) {
-          self2.emit("error", error4);
-        });
-        entry.pipe(pipedStream);
-      };
-      if (this.createdDirectories[directory] || directory === ".") {
-        return writeFileFn();
+        this.userAgent = userAgent;
+        this.clients = new Array(clientCount).fill((0, utils_1.createHttpClient)(userAgent));
       }
-      mkdirp(directory, function(err) {
-        if (err) return self2.emit("error", err);
-        self2.createdDirectories[directory] = true;
-        if (entry.isDirectory) {
-          self2.unfinishedEntries--;
-          self2._notifyAwaiter();
-          return;
+      getClient(index) {
+        return this.clients[index];
+      }
+      // client disposal is necessary if a keep-alive connection is used to properly close the connection
+      // for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292
+      disposeAndReplaceClient(index) {
+        this.clients[index].dispose();
+        this.clients[index] = (0, utils_1.createHttpClient)(this.userAgent);
+      }
+      disposeAndReplaceAllClients() {
+        for (const [index] of this.clients.entries()) {
+          this.disposeAndReplaceClient(index);
         }
-        writeFileFn();
-      });
-    };
-    Extract.prototype._notifyAwaiter = function() {
-      if (this.afterFlushWait && this.unfinishedEntries === 0) {
-        this.emit("await-finished");
-        this.afterFlushWait = false;
       }
     };
-    module2.exports = Extract;
-  }
-});
-
-// node_modules/unzip-stream/unzip.js
-var require_unzip = __commonJS({
-  "node_modules/unzip-stream/unzip.js"(exports2) {
-    "use strict";
-    exports2.Parse = require_parser_stream();
-    exports2.Extract = require_extract2();
+    exports2.HttpManager = HttpManager;
   }
 });
 
-// node_modules/@actions/artifact/lib/internal/download/download-artifact.js
-var require_download_artifact = __commonJS({
-  "node_modules/@actions/artifact/lib/internal/download/download-artifact.js"(exports2) {
+// node_modules/@actions/artifact-legacy/lib/internal/upload-gzip.js
+var require_upload_gzip = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/upload-gzip.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -97420,25 +102003,15 @@ var require_download_artifact = __commonJS({
     }) : function(o, v) {
       o["default"] = v;
     });
-    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
-      var ownKeys = function(o) {
-        ownKeys = Object.getOwnPropertyNames || function(o2) {
-          var ar = [];
-          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
-          return ar;
-        };
-        return ownKeys(o);
-      };
-      return function(mod) {
-        if (mod && mod.__esModule) return mod;
-        var result = {};
-        if (mod != null) {
-          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
-        }
-        __setModuleDefault4(result, mod);
-        return result;
-      };
-    })();
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
     var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
       function adopt(value) {
         return value instanceof P ? value : new P(function(resolve2) {
@@ -97466,200 +102039,235 @@ var require_download_artifact = __commonJS({
         step((generator = generator.apply(thisArg, _arguments || [])).next());
       });
     };
-    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
-      return mod && mod.__esModule ? mod : { "default": mod };
+    var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) {
+      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+      var m = o[Symbol.asyncIterator], i;
+      return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
+        return this;
+      }, i);
+      function verb(n) {
+        i[n] = o[n] && function(v) {
+          return new Promise(function(resolve2, reject) {
+            v = o[n](v), settle(resolve2, reject, v.done, v.value);
+          });
+        };
+      }
+      function settle(resolve2, reject, d, v) {
+        Promise.resolve(v).then(function(v2) {
+          resolve2({ value: v2, done: d });
+        }, reject);
+      }
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.streamExtractExternal = streamExtractExternal;
-    exports2.downloadArtifactPublic = downloadArtifactPublic;
-    exports2.downloadArtifactInternal = downloadArtifactInternal;
-    var promises_1 = __importDefault4(require("fs/promises"));
-    var crypto = __importStar4(require("crypto"));
-    var stream = __importStar4(require("stream"));
-    var github2 = __importStar4(require_github());
-    var core14 = __importStar4(require_core());
-    var httpClient = __importStar4(require_lib());
-    var unzip_stream_1 = __importDefault4(require_unzip());
-    var user_agent_1 = require_user_agent();
-    var config_1 = require_config();
-    var artifact_twirp_client_1 = require_artifact_twirp_client2();
-    var generated_1 = require_generated();
-    var util_1 = require_util8();
-    var errors_1 = require_errors2();
-    var scrubQueryParameters = (url) => {
-      const parsed = new URL(url);
-      parsed.search = "";
-      return parsed.toString();
-    };
-    function exists(path2) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        try {
-          yield promises_1.default.access(path2);
-          return true;
-        } catch (error4) {
-          if (error4.code === "ENOENT") {
-            return false;
-          } else {
-            throw error4;
-          }
-        }
-      });
-    }
-    function streamExtract(url, directory) {
+    exports2.createGZipFileInBuffer = exports2.createGZipFileOnDisk = void 0;
+    var fs2 = __importStar4(require("fs"));
+    var zlib = __importStar4(require("zlib"));
+    var util_1 = require("util");
+    var stat = (0, util_1.promisify)(fs2.stat);
+    var gzipExemptFileExtensions = [
+      ".gz",
+      ".gzip",
+      ".tgz",
+      ".taz",
+      ".Z",
+      ".taZ",
+      ".bz2",
+      ".tbz",
+      ".tbz2",
+      ".tz2",
+      ".lz",
+      ".lzma",
+      ".tlz",
+      ".lzo",
+      ".xz",
+      ".txz",
+      ".zst",
+      ".zstd",
+      ".tzst",
+      ".zip",
+      ".7z"
+      // 7ZIP
+    ];
+    function createGZipFileOnDisk(originalFilePath, tempFilePath) {
       return __awaiter4(this, void 0, void 0, function* () {
-        let retryCount = 0;
-        while (retryCount < 5) {
-          try {
-            return yield streamExtractExternal(url, directory);
-          } catch (error4) {
-            retryCount++;
-            core14.debug(`Failed to download artifact after ${retryCount} retries due to ${error4.message}. Retrying in 5 seconds...`);
-            yield new Promise((resolve2) => setTimeout(resolve2, 5e3));
+        for (const gzipExemptExtension of gzipExemptFileExtensions) {
+          if (originalFilePath.endsWith(gzipExemptExtension)) {
+            return Number.MAX_SAFE_INTEGER;
           }
         }
-        throw new Error(`Artifact download failed after ${retryCount} retries.`);
-      });
-    }
-    function streamExtractExternal(url_1, directory_1) {
-      return __awaiter4(this, arguments, void 0, function* (url, directory, opts = { timeout: 30 * 1e3 }) {
-        const client = new httpClient.HttpClient((0, user_agent_1.getUserAgentString)());
-        const response = yield client.get(url);
-        if (response.message.statusCode !== 200) {
-          throw new Error(`Unexpected HTTP response from blob storage: ${response.message.statusCode} ${response.message.statusMessage}`);
-        }
-        let sha256Digest = void 0;
         return new Promise((resolve2, reject) => {
-          const timerFn = () => {
-            const timeoutError = new Error(`Blob storage chunk did not respond in ${opts.timeout}ms`);
-            response.message.destroy(timeoutError);
-            reject(timeoutError);
-          };
-          const timer = setTimeout(timerFn, opts.timeout);
-          const hashStream = crypto.createHash("sha256").setEncoding("hex");
-          const passThrough = new stream.PassThrough();
-          response.message.pipe(passThrough);
-          passThrough.pipe(hashStream);
-          const extractStream = passThrough;
-          extractStream.on("data", () => {
-            timer.refresh();
-          }).on("error", (error4) => {
-            core14.debug(`response.message: Artifact download failed: ${error4.message}`);
-            clearTimeout(timer);
-            reject(error4);
-          }).pipe(unzip_stream_1.default.Extract({ path: directory })).on("close", () => {
-            clearTimeout(timer);
-            if (hashStream) {
-              hashStream.end();
-              sha256Digest = hashStream.read();
-              core14.info(`SHA256 digest of downloaded artifact is ${sha256Digest}`);
-            }
-            resolve2({ sha256Digest: `sha256:${sha256Digest}` });
-          }).on("error", (error4) => {
+          const inputStream = fs2.createReadStream(originalFilePath);
+          const gzip = zlib.createGzip();
+          const outputStream = fs2.createWriteStream(tempFilePath);
+          inputStream.pipe(gzip).pipe(outputStream);
+          outputStream.on("finish", () => __awaiter4(this, void 0, void 0, function* () {
+            const size = (yield stat(tempFilePath)).size;
+            resolve2(size);
+          }));
+          outputStream.on("error", (error4) => {
+            console.log(error4);
             reject(error4);
           });
         });
       });
     }
-    function downloadArtifactPublic(artifactId, repositoryOwner, repositoryName, token, options) {
+    exports2.createGZipFileOnDisk = createGZipFileOnDisk;
+    function createGZipFileInBuffer(originalFilePath) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path);
-        const api = github2.getOctokit(token);
-        let digestMismatch = false;
-        core14.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`);
-        const { headers, status } = yield api.rest.actions.downloadArtifact({
-          owner: repositoryOwner,
-          repo: repositoryName,
-          artifact_id: artifactId,
-          archive_format: "zip",
-          request: {
-            redirect: "manual"
+        return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
+          var _a, e_1, _b, _c;
+          const inputStream = fs2.createReadStream(originalFilePath);
+          const gzip = zlib.createGzip();
+          inputStream.pipe(gzip);
+          const chunks = [];
+          try {
+            for (var _d = true, gzip_1 = __asyncValues4(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), _a = gzip_1_1.done, !_a; ) {
+              _c = gzip_1_1.value;
+              _d = false;
+              try {
+                const chunk = _c;
+                chunks.push(chunk);
+              } finally {
+                _d = true;
+              }
+            }
+          } catch (e_1_1) {
+            e_1 = { error: e_1_1 };
+          } finally {
+            try {
+              if (!_d && !_a && (_b = gzip_1.return)) yield _b.call(gzip_1);
+            } finally {
+              if (e_1) throw e_1.error;
+            }
           }
+          resolve2(Buffer.concat(chunks));
+        }));
+      });
+    }
+    exports2.createGZipFileInBuffer = createGZipFileInBuffer;
+  }
+});
+
+// node_modules/@actions/artifact-legacy/lib/internal/requestUtils.js
+var require_requestUtils = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/requestUtils.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
         });
-        if (status !== 302) {
-          throw new Error(`Unable to download artifact. Unexpected status: ${status}`);
-        }
-        const { location } = headers;
-        if (!location) {
-          throw new Error(`Unable to redirect to artifact download url`);
+      }
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        core14.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`);
-        try {
-          core14.info(`Starting download of artifact to: ${downloadPath}`);
-          const extractResponse = yield streamExtract(location, downloadPath);
-          core14.info(`Artifact download completed successfully.`);
-          if (options === null || options === void 0 ? void 0 : options.expectedHash) {
-            if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) {
-              digestMismatch = true;
-              core14.debug(`Computed digest: ${extractResponse.sha256Digest}`);
-              core14.debug(`Expected digest: ${options.expectedHash}`);
-            }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
           }
-        } catch (error4) {
-          throw new Error(`Unable to download and extract artifact: ${error4.message}`);
         }
-        return { downloadPath, digestMismatch };
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
       });
-    }
-    function downloadArtifactInternal(artifactId, options) {
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.retryHttpClientRequest = exports2.retry = void 0;
+    var utils_1 = require_utils7();
+    var core14 = __importStar4(require_core());
+    var config_variables_1 = require_config_variables();
+    function retry3(name, operation, customErrorMessages, maxAttempts) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path);
-        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
-        let digestMismatch = false;
-        const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)();
-        const listReq = {
-          workflowRunBackendId,
-          workflowJobRunBackendId,
-          idFilter: generated_1.Int64Value.create({ value: artifactId.toString() })
-        };
-        const { artifacts } = yield artifactClient.ListArtifacts(listReq);
-        if (artifacts.length === 0) {
-          throw new errors_1.ArtifactNotFoundError(`No artifacts found for ID: ${artifactId}
-Are you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`);
-        }
-        if (artifacts.length > 1) {
-          core14.warning("Multiple artifacts found, defaulting to first.");
-        }
-        const signedReq = {
-          workflowRunBackendId: artifacts[0].workflowRunBackendId,
-          workflowJobRunBackendId: artifacts[0].workflowJobRunBackendId,
-          name: artifacts[0].name
-        };
-        const { signedUrl } = yield artifactClient.GetSignedArtifactURL(signedReq);
-        core14.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`);
-        try {
-          core14.info(`Starting download of artifact to: ${downloadPath}`);
-          const extractResponse = yield streamExtract(signedUrl, downloadPath);
-          core14.info(`Artifact download completed successfully.`);
-          if (options === null || options === void 0 ? void 0 : options.expectedHash) {
-            if ((options === null || options === void 0 ? void 0 : options.expectedHash) !== extractResponse.sha256Digest) {
-              digestMismatch = true;
-              core14.debug(`Computed digest: ${extractResponse.sha256Digest}`);
-              core14.debug(`Expected digest: ${options.expectedHash}`);
+        let response = void 0;
+        let statusCode = void 0;
+        let isRetryable = false;
+        let errorMessage = "";
+        let customErrorInformation = void 0;
+        let attempt = 1;
+        while (attempt <= maxAttempts) {
+          try {
+            response = yield operation();
+            statusCode = response.message.statusCode;
+            if ((0, utils_1.isSuccessStatusCode)(statusCode)) {
+              return response;
+            }
+            if (statusCode) {
+              customErrorInformation = customErrorMessages.get(statusCode);
+            }
+            isRetryable = (0, utils_1.isRetryableStatusCode)(statusCode);
+            errorMessage = `Artifact service responded with ${statusCode}`;
+          } catch (error4) {
+            isRetryable = true;
+            errorMessage = error4.message;
+          }
+          if (!isRetryable) {
+            core14.info(`${name} - Error is not retryable`);
+            if (response) {
+              (0, utils_1.displayHttpDiagnostics)(response);
             }
+            break;
           }
-        } catch (error4) {
-          throw new Error(`Unable to download and extract artifact: ${error4.message}`);
+          core14.info(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`);
+          yield (0, utils_1.sleep)((0, utils_1.getExponentialRetryTimeInMilliseconds)(attempt));
+          attempt++;
         }
-        return { downloadPath, digestMismatch };
+        if (response) {
+          (0, utils_1.displayHttpDiagnostics)(response);
+        }
+        if (customErrorInformation) {
+          throw Error(`${name} failed: ${customErrorInformation}`);
+        }
+        throw Error(`${name} failed: ${errorMessage}`);
       });
     }
-    function resolveOrCreateDirectory() {
-      return __awaiter4(this, arguments, void 0, function* (downloadPath = (0, config_1.getGitHubWorkspaceDir)()) {
-        if (!(yield exists(downloadPath))) {
-          core14.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`);
-          yield promises_1.default.mkdir(downloadPath, { recursive: true });
-        } else {
-          core14.debug(`Artifact destination folder already exists: ${downloadPath}`);
-        }
-        return downloadPath;
+    exports2.retry = retry3;
+    function retryHttpClientRequest(name, method, customErrorMessages = /* @__PURE__ */ new Map(), maxAttempts = (0, config_variables_1.getRetryLimit)()) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        return yield retry3(name, method, customErrorMessages, maxAttempts);
       });
     }
+    exports2.retryHttpClientRequest = retryHttpClientRequest;
   }
 });
 
-// node_modules/@actions/artifact/lib/internal/find/retry-options.js
-var require_retry_options = __commonJS({
-  "node_modules/@actions/artifact/lib/internal/find/retry-options.js"(exports2) {
+// node_modules/@actions/artifact-legacy/lib/internal/upload-http-client.js
+var require_upload_http_client = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/upload-http-client.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -97679,139 +102287,379 @@ var require_retry_options = __commonJS({
     }) : function(o, v) {
       o["default"] = v;
     });
-    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
-      var ownKeys = function(o) {
-        ownKeys = Object.getOwnPropertyNames || function(o2) {
-          var ar = [];
-          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
-          return ar;
-        };
-        return ownKeys(o);
-      };
-      return function(mod) {
-        if (mod && mod.__esModule) return mod;
-        var result = {};
-        if (mod != null) {
-          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        __setModuleDefault4(result, mod);
-        return result;
-      };
-    })();
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getRetryOptions = getRetryOptions;
+    exports2.UploadHttpClient = void 0;
+    var fs2 = __importStar4(require("fs"));
     var core14 = __importStar4(require_core());
-    var defaultMaxRetryNumber = 5;
-    var defaultExemptStatusCodes = [400, 401, 403, 404, 422];
-    function getRetryOptions(defaultOptions, retries = defaultMaxRetryNumber, exemptStatusCodes = defaultExemptStatusCodes) {
-      var _a;
-      if (retries <= 0) {
-        return [{ enabled: false }, defaultOptions.request];
+    var tmp = __importStar4(require_tmp_promise());
+    var stream = __importStar4(require("stream"));
+    var utils_1 = require_utils7();
+    var config_variables_1 = require_config_variables();
+    var util_1 = require("util");
+    var url_1 = require("url");
+    var perf_hooks_1 = require("perf_hooks");
+    var status_reporter_1 = require_status_reporter();
+    var http_client_1 = require_lib5();
+    var http_manager_1 = require_http_manager();
+    var upload_gzip_1 = require_upload_gzip();
+    var requestUtils_1 = require_requestUtils();
+    var stat = (0, util_1.promisify)(fs2.stat);
+    var UploadHttpClient = class {
+      constructor() {
+        this.uploadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getUploadFileConcurrency)(), "@actions/artifact-upload");
+        this.statusReporter = new status_reporter_1.StatusReporter(1e4);
       }
-      const retryOptions = {
-        enabled: true
-      };
-      if (exemptStatusCodes.length > 0) {
-        retryOptions.doNotRetry = exemptStatusCodes;
+      /**
+       * Creates a file container for the new artifact in the remote blob storage/file service
+       * @param {string} artifactName Name of the artifact being created
+       * @returns The response from the Artifact Service if the file container was successfully created
+       */
+      createArtifactInFileContainer(artifactName, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const parameters = {
+            Type: "actions_storage",
+            Name: artifactName
+          };
+          if (options && options.retentionDays) {
+            const maxRetentionStr = (0, config_variables_1.getRetentionDays)();
+            parameters.RetentionDays = (0, utils_1.getProperRetention)(options.retentionDays, maxRetentionStr);
+          }
+          const data = JSON.stringify(parameters, null, 2);
+          const artifactUrl = (0, utils_1.getArtifactUrl)();
+          const client = this.uploadHttpManager.getClient(0);
+          const headers = (0, utils_1.getUploadHeaders)("application/json", false);
+          const customErrorMessages = /* @__PURE__ */ new Map([
+            [
+              http_client_1.HttpCodes.Forbidden,
+              (0, config_variables_1.isGhes)() ? "Please reference [Enabling GitHub Actions for GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@3.8/admin/github-actions/enabling-github-actions-for-github-enterprise-server) to ensure Actions storage is configured correctly." : "Artifact storage quota has been hit. Unable to upload any new artifacts"
+            ],
+            [
+              http_client_1.HttpCodes.BadRequest,
+              `The artifact name ${artifactName} is not valid. Request URL ${artifactUrl}`
+            ]
+          ]);
+          const response = yield (0, requestUtils_1.retryHttpClientRequest)("Create Artifact Container", () => __awaiter4(this, void 0, void 0, function* () {
+            return client.post(artifactUrl, data, headers);
+          }), customErrorMessages);
+          const body = yield response.readBody();
+          return JSON.parse(body);
+        });
       }
-      const requestOptions = Object.assign(Object.assign({}, defaultOptions.request), { retries });
-      core14.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a = retryOptions.doNotRetry) !== null && _a !== void 0 ? _a : "octokit default: [400, 401, 403, 404, 422]"})`);
-      return [retryOptions, requestOptions];
-    }
-  }
-});
-
-// node_modules/@octokit/plugin-request-log/dist-node/index.js
-var require_dist_node16 = __commonJS({
-  "node_modules/@octokit/plugin-request-log/dist-node/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    var VERSION = "1.0.4";
-    function requestLog(octokit) {
-      octokit.hook.wrap("request", (request, 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 request(options).then((response) => {
-          octokit.log.info(`${requestOptions.method} ${path2} - ${response.status} in ${Date.now() - start}ms`);
-          return response;
-        }).catch((error4) => {
-          octokit.log.info(`${requestOptions.method} ${path2} - ${error4.status} in ${Date.now() - start}ms`);
-          throw error4;
+      /**
+       * Concurrently upload all of the files in chunks
+       * @param {string} uploadUrl Base Url for the artifact that was created
+       * @param {SearchResult[]} filesToUpload A list of information about the files being uploaded
+       * @returns The size of all the files uploaded in bytes
+       */
+      uploadArtifactToFileContainer(uploadUrl, filesToUpload, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const FILE_CONCURRENCY = (0, config_variables_1.getUploadFileConcurrency)();
+          const MAX_CHUNK_SIZE = (0, config_variables_1.getUploadChunkSize)();
+          core14.debug(`File Concurrency: ${FILE_CONCURRENCY}, and Chunk Size: ${MAX_CHUNK_SIZE}`);
+          const parameters = [];
+          let continueOnError = true;
+          if (options) {
+            if (options.continueOnError === false) {
+              continueOnError = false;
+            }
+          }
+          for (const file of filesToUpload) {
+            const resourceUrl = new url_1.URL(uploadUrl);
+            resourceUrl.searchParams.append("itemPath", file.uploadFilePath);
+            parameters.push({
+              file: file.absoluteFilePath,
+              resourceUrl: resourceUrl.toString(),
+              maxChunkSize: MAX_CHUNK_SIZE,
+              continueOnError
+            });
+          }
+          const parallelUploads = [...new Array(FILE_CONCURRENCY).keys()];
+          const failedItemsToReport = [];
+          let currentFile = 0;
+          let completedFiles = 0;
+          let uploadFileSize = 0;
+          let totalFileSize = 0;
+          let abortPendingFileUploads = false;
+          this.statusReporter.setTotalNumberOfFilesToProcess(filesToUpload.length);
+          this.statusReporter.start();
+          yield Promise.all(parallelUploads.map((index) => __awaiter4(this, void 0, void 0, function* () {
+            while (currentFile < filesToUpload.length) {
+              const currentFileParameters = parameters[currentFile];
+              currentFile += 1;
+              if (abortPendingFileUploads) {
+                failedItemsToReport.push(currentFileParameters.file);
+                continue;
+              }
+              const startTime = perf_hooks_1.performance.now();
+              const uploadFileResult = yield this.uploadFileAsync(index, currentFileParameters);
+              if (core14.isDebug()) {
+                core14.debug(`File: ${++completedFiles}/${filesToUpload.length}. ${currentFileParameters.file} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish upload`);
+              }
+              uploadFileSize += uploadFileResult.successfulUploadSize;
+              totalFileSize += uploadFileResult.totalSize;
+              if (uploadFileResult.isSuccess === false) {
+                failedItemsToReport.push(currentFileParameters.file);
+                if (!continueOnError) {
+                  core14.error(`aborting artifact upload`);
+                  abortPendingFileUploads = true;
+                }
+              }
+              this.statusReporter.incrementProcessedCount();
+            }
+          })));
+          this.statusReporter.stop();
+          this.uploadHttpManager.disposeAndReplaceAllClients();
+          core14.info(`Total size of all the files uploaded is ${uploadFileSize} bytes`);
+          return {
+            uploadSize: uploadFileSize,
+            totalSize: totalFileSize,
+            failedItems: failedItemsToReport
+          };
+        });
+      }
+      /**
+       * Asynchronously uploads a file. The file is compressed and uploaded using GZip if it is determined to save space.
+       * If the upload file is bigger than the max chunk size it will be uploaded via multiple calls
+       * @param {number} httpClientIndex The index of the httpClient that is being used to make all of the calls
+       * @param {UploadFileParameters} parameters Information about the file that needs to be uploaded
+       * @returns The size of the file that was uploaded in bytes along with any failed uploads
+       */
+      uploadFileAsync(httpClientIndex, parameters) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const fileStat = yield stat(parameters.file);
+          const totalFileSize = fileStat.size;
+          const isFIFO = fileStat.isFIFO();
+          let offset = 0;
+          let isUploadSuccessful = true;
+          let failedChunkSizes = 0;
+          let uploadFileSize = 0;
+          let isGzip = true;
+          if (!isFIFO && totalFileSize < 65536) {
+            core14.debug(`${parameters.file} is less than 64k in size. Creating a gzip file in-memory to potentially reduce the upload size`);
+            const buffer = yield (0, upload_gzip_1.createGZipFileInBuffer)(parameters.file);
+            let openUploadStream;
+            if (totalFileSize < buffer.byteLength) {
+              core14.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`);
+              openUploadStream = () => fs2.createReadStream(parameters.file);
+              isGzip = false;
+              uploadFileSize = totalFileSize;
+            } else {
+              core14.debug(`A gzip file created for ${parameters.file} helped with reducing the size of the original file. The file will be uploaded using gzip.`);
+              openUploadStream = () => {
+                const passThrough = new stream.PassThrough();
+                passThrough.end(buffer);
+                return passThrough;
+              };
+              uploadFileSize = buffer.byteLength;
+            }
+            const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, openUploadStream, 0, uploadFileSize - 1, uploadFileSize, isGzip, totalFileSize);
+            if (!result) {
+              isUploadSuccessful = false;
+              failedChunkSizes += uploadFileSize;
+              core14.warning(`Aborting upload for ${parameters.file} due to failure`);
+            }
+            return {
+              isSuccess: isUploadSuccessful,
+              successfulUploadSize: uploadFileSize - failedChunkSizes,
+              totalSize: totalFileSize
+            };
+          } else {
+            const tempFile = yield tmp.file();
+            core14.debug(`${parameters.file} is greater than 64k in size. Creating a gzip file on-disk ${tempFile.path} to potentially reduce the upload size`);
+            uploadFileSize = yield (0, upload_gzip_1.createGZipFileOnDisk)(parameters.file, tempFile.path);
+            let uploadFilePath = tempFile.path;
+            if (!isFIFO && totalFileSize < uploadFileSize) {
+              core14.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`);
+              uploadFileSize = totalFileSize;
+              uploadFilePath = parameters.file;
+              isGzip = false;
+            } else {
+              core14.debug(`The gzip file created for ${parameters.file} is smaller than the original file. The file will be uploaded using gzip.`);
+            }
+            let abortFileUpload = false;
+            while (offset < uploadFileSize) {
+              const chunkSize = Math.min(uploadFileSize - offset, parameters.maxChunkSize);
+              const startChunkIndex = offset;
+              const endChunkIndex = offset + chunkSize - 1;
+              offset += parameters.maxChunkSize;
+              if (abortFileUpload) {
+                failedChunkSizes += chunkSize;
+                continue;
+              }
+              const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs2.createReadStream(uploadFilePath, {
+                start: startChunkIndex,
+                end: endChunkIndex,
+                autoClose: false
+              }), startChunkIndex, endChunkIndex, uploadFileSize, isGzip, totalFileSize);
+              if (!result) {
+                isUploadSuccessful = false;
+                failedChunkSizes += chunkSize;
+                core14.warning(`Aborting upload for ${parameters.file} due to failure`);
+                abortFileUpload = true;
+              } else {
+                if (uploadFileSize > 8388608) {
+                  this.statusReporter.updateLargeFileStatus(parameters.file, startChunkIndex, endChunkIndex, uploadFileSize);
+                }
+              }
+            }
+            core14.debug(`deleting temporary gzip file ${tempFile.path}`);
+            yield tempFile.cleanup();
+            return {
+              isSuccess: isUploadSuccessful,
+              successfulUploadSize: uploadFileSize - failedChunkSizes,
+              totalSize: totalFileSize
+            };
+          }
+        });
+      }
+      /**
+       * Uploads a chunk of an individual file to the specified resourceUrl. If the upload fails and the status code
+       * indicates a retryable status, we try to upload the chunk as well
+       * @param {number} httpClientIndex The index of the httpClient being used to make all the necessary calls
+       * @param {string} resourceUrl Url of the resource that the chunk will be uploaded to
+       * @param {NodeJS.ReadableStream} openStream Stream of the file that will be uploaded
+       * @param {number} start Starting byte index of file that the chunk belongs to
+       * @param {number} end Ending byte index of file that the chunk belongs to
+       * @param {number} uploadFileSize Total size of the file in bytes that is being uploaded
+       * @param {boolean} isGzip Denotes if we are uploading a Gzip compressed stream
+       * @param {number} totalFileSize Original total size of the file that is being uploaded
+       * @returns if the chunk was successfully uploaded
+       */
+      uploadChunk(httpClientIndex, resourceUrl, openStream, start, end, uploadFileSize, isGzip, totalFileSize) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const digest = yield (0, utils_1.digestForStream)(openStream());
+          const headers = (0, utils_1.getUploadHeaders)("application/octet-stream", true, isGzip, totalFileSize, end - start + 1, (0, utils_1.getContentRange)(start, end, uploadFileSize), digest);
+          const uploadChunkRequest = () => __awaiter4(this, void 0, void 0, function* () {
+            const client = this.uploadHttpManager.getClient(httpClientIndex);
+            return yield client.sendStream("PUT", resourceUrl, openStream(), headers);
+          });
+          let retryCount = 0;
+          const retryLimit = (0, config_variables_1.getRetryLimit)();
+          const incrementAndCheckRetryLimit = (response) => {
+            retryCount++;
+            if (retryCount > retryLimit) {
+              if (response) {
+                (0, utils_1.displayHttpDiagnostics)(response);
+              }
+              core14.info(`Retry limit has been reached for chunk at offset ${start} to ${resourceUrl}`);
+              return true;
+            }
+            return false;
+          };
+          const backOff = (retryAfterValue) => __awaiter4(this, void 0, void 0, function* () {
+            this.uploadHttpManager.disposeAndReplaceClient(httpClientIndex);
+            if (retryAfterValue) {
+              core14.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the upload`);
+              yield (0, utils_1.sleep)(retryAfterValue);
+            } else {
+              const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount);
+              core14.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the upload at offset ${start}`);
+              yield (0, utils_1.sleep)(backoffTime);
+            }
+            core14.info(`Finished backoff for retry #${retryCount}, continuing with upload`);
+            return;
+          });
+          while (retryCount <= retryLimit) {
+            let response;
+            try {
+              response = yield uploadChunkRequest();
+            } catch (error4) {
+              core14.info(`An error has been caught http-client index ${httpClientIndex}, retrying the upload`);
+              console.log(error4);
+              if (incrementAndCheckRetryLimit()) {
+                return false;
+              }
+              yield backOff();
+              continue;
+            }
+            yield response.readBody();
+            if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) {
+              return true;
+            } else if ((0, utils_1.isRetryableStatusCode)(response.message.statusCode)) {
+              core14.info(`A ${response.message.statusCode} status code has been received, will attempt to retry the upload`);
+              if (incrementAndCheckRetryLimit(response)) {
+                return false;
+              }
+              (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff();
+            } else {
+              core14.error(`Unexpected response. Unable to upload chunk to ${resourceUrl}`);
+              (0, utils_1.displayHttpDiagnostics)(response);
+              return false;
+            }
+          }
+          return false;
         });
-      });
-    }
-    requestLog.VERSION = VERSION;
-    exports2.requestLog = requestLog;
-  }
-});
-
-// node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js
-var require_dist_node17 = __commonJS({
-  "node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-node/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    function _interopDefault(ex) {
-      return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
-    }
-    var Bottleneck = _interopDefault(require_light());
-    async function errorRequest(octokit, state, error4, options) {
-      if (!error4.request || !error4.request.request) {
-        throw error4;
-      }
-      if (error4.status >= 400 && !state.doNotRetry.includes(error4.status)) {
-        const retries = options.request.retries != null ? options.request.retries : state.retries;
-        const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2);
-        throw octokit.retry.retryRequest(error4, retries, retryAfter);
       }
-      throw error4;
-    }
-    async function wrapRequest(state, request, options) {
-      const limiter = new Bottleneck();
-      limiter.on("failed", function(error4, info7) {
-        const maxRetries = ~~error4.request.request.retries;
-        const after = ~~error4.request.request.retryAfter;
-        options.request.retryCount = info7.retryCount + 1;
-        if (maxRetries > info7.retryCount) {
-          return after * state.retryAfterBaseValue;
-        }
-      });
-      return limiter.schedule(request, options);
-    }
-    var VERSION = "3.0.9";
-    function retry3(octokit, octokitOptions) {
-      const state = Object.assign({
-        enabled: true,
-        retryAfterBaseValue: 1e3,
-        doNotRetry: [400, 401, 403, 404, 422],
-        retries: 3
-      }, octokitOptions.retry);
-      if (state.enabled) {
-        octokit.hook.error("request", errorRequest.bind(null, octokit, state));
-        octokit.hook.wrap("request", wrapRequest.bind(null, state));
+      /**
+       * Updates the size of the artifact from -1 which was initially set when the container was first created for the artifact.
+       * Updating the size indicates that we are done uploading all the contents of the artifact
+       */
+      patchArtifactSize(size, artifactName) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const resourceUrl = new url_1.URL((0, utils_1.getArtifactUrl)());
+          resourceUrl.searchParams.append("artifactName", artifactName);
+          const parameters = { Size: size };
+          const data = JSON.stringify(parameters, null, 2);
+          core14.debug(`URL is ${resourceUrl.toString()}`);
+          const client = this.uploadHttpManager.getClient(0);
+          const headers = (0, utils_1.getUploadHeaders)("application/json", false);
+          const customErrorMessages = /* @__PURE__ */ new Map([
+            [
+              http_client_1.HttpCodes.NotFound,
+              `An Artifact with the name ${artifactName} was not found`
+            ]
+          ]);
+          const response = yield (0, requestUtils_1.retryHttpClientRequest)("Finalize artifact upload", () => __awaiter4(this, void 0, void 0, function* () {
+            return client.patch(resourceUrl.toString(), data, headers);
+          }), customErrorMessages);
+          yield response.readBody();
+          core14.debug(`Artifact ${artifactName} has been successfully uploaded, total size in bytes: ${size}`);
+        });
       }
-      return {
-        retry: {
-          retryRequest: (error4, retries, retryAfter) => {
-            error4.request.request = Object.assign({}, error4.request.request, {
-              retries,
-              retryAfter
-            });
-            return error4;
-          }
-        }
-      };
-    }
-    retry3.VERSION = VERSION;
-    exports2.VERSION = VERSION;
-    exports2.retry = retry3;
+    };
+    exports2.UploadHttpClient = UploadHttpClient;
   }
 });
 
-// node_modules/@actions/artifact/lib/internal/find/get-artifact.js
-var require_get_artifact = __commonJS({
-  "node_modules/@actions/artifact/lib/internal/find/get-artifact.js"(exports2) {
+// node_modules/@actions/artifact-legacy/lib/internal/download-http-client.js
+var require_download_http_client = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/download-http-client.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -97831,25 +102679,15 @@ var require_get_artifact = __commonJS({
     }) : function(o, v) {
       o["default"] = v;
     });
-    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
-      var ownKeys = function(o) {
-        ownKeys = Object.getOwnPropertyNames || function(o2) {
-          var ar = [];
-          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
-          return ar;
-        };
-        return ownKeys(o);
-      };
-      return function(mod) {
-        if (mod && mod.__esModule) return mod;
-        var result = {};
-        if (mod != null) {
-          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
-        }
-        __setModuleDefault4(result, mod);
-        return result;
-      };
-    })();
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
     var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
       function adopt(value) {
         return value instanceof P ? value : new P(function(resolve2) {
@@ -97878,100 +102716,321 @@ var require_get_artifact = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getArtifactPublic = getArtifactPublic;
-    exports2.getArtifactInternal = getArtifactInternal;
-    var github_1 = require_github();
-    var plugin_retry_1 = require_dist_node17();
+    exports2.DownloadHttpClient = void 0;
+    var fs2 = __importStar4(require("fs"));
     var core14 = __importStar4(require_core());
-    var utils_1 = require_utils4();
-    var retry_options_1 = require_retry_options();
-    var plugin_request_log_1 = require_dist_node16();
-    var util_1 = require_util8();
-    var user_agent_1 = require_user_agent();
-    var artifact_twirp_client_1 = require_artifact_twirp_client2();
-    var generated_1 = require_generated();
-    var errors_1 = require_errors2();
-    function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        var _a;
-        const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults);
-        const opts = {
-          log: void 0,
-          userAgent: (0, user_agent_1.getUserAgentString)(),
-          previews: void 0,
-          retry: retryOpts,
-          request: requestOpts
-        };
-        const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog);
-        const getArtifactResp = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}", {
-          owner: repositoryOwner,
-          repo: repositoryName,
-          run_id: workflowRunId,
-          name: artifactName
+    var zlib = __importStar4(require("zlib"));
+    var utils_1 = require_utils7();
+    var url_1 = require("url");
+    var status_reporter_1 = require_status_reporter();
+    var perf_hooks_1 = require("perf_hooks");
+    var http_manager_1 = require_http_manager();
+    var config_variables_1 = require_config_variables();
+    var requestUtils_1 = require_requestUtils();
+    var DownloadHttpClient = class {
+      constructor() {
+        this.downloadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getDownloadFileConcurrency)(), "@actions/artifact-download");
+        this.statusReporter = new status_reporter_1.StatusReporter(1e3);
+      }
+      /**
+       * Gets a list of all artifacts that are in a specific container
+       */
+      listArtifacts() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const artifactUrl = (0, utils_1.getArtifactUrl)();
+          const client = this.downloadHttpManager.getClient(0);
+          const headers = (0, utils_1.getDownloadHeaders)("application/json");
+          const response = yield (0, requestUtils_1.retryHttpClientRequest)("List Artifacts", () => __awaiter4(this, void 0, void 0, function* () {
+            return client.get(artifactUrl, headers);
+          }));
+          const body = yield response.readBody();
+          return JSON.parse(body);
         });
-        if (getArtifactResp.status !== 200) {
-          throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`);
-        }
-        if (getArtifactResp.data.artifacts.length === 0) {
-          throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}
-        Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.
-        For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`);
-        }
-        let artifact2 = getArtifactResp.data.artifacts[0];
-        if (getArtifactResp.data.artifacts.length > 1) {
-          artifact2 = getArtifactResp.data.artifacts.sort((a, b) => b.id - a.id)[0];
-          core14.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.id})`);
-        }
-        return {
-          artifact: {
-            name: artifact2.name,
-            id: artifact2.id,
-            size: artifact2.size_in_bytes,
-            createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0,
-            digest: artifact2.digest
+      }
+      /**
+       * Fetches a set of container items that describe the contents of an artifact
+       * @param artifactName the name of the artifact
+       * @param containerUrl the artifact container URL for the run
+       */
+      getContainerItems(artifactName, containerUrl) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const resourceUrl = new url_1.URL(containerUrl);
+          resourceUrl.searchParams.append("itemPath", artifactName);
+          const client = this.downloadHttpManager.getClient(0);
+          const headers = (0, utils_1.getDownloadHeaders)("application/json");
+          const response = yield (0, requestUtils_1.retryHttpClientRequest)("Get Container Items", () => __awaiter4(this, void 0, void 0, function* () {
+            return client.get(resourceUrl.toString(), headers);
+          }));
+          const body = yield response.readBody();
+          return JSON.parse(body);
+        });
+      }
+      /**
+       * Concurrently downloads all the files that are part of an artifact
+       * @param downloadItems information about what items to download and where to save them
+       */
+      downloadSingleArtifact(downloadItems) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const DOWNLOAD_CONCURRENCY = (0, config_variables_1.getDownloadFileConcurrency)();
+          core14.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`);
+          const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()];
+          let currentFile = 0;
+          let downloadedFiles = 0;
+          core14.info(`Total number of files that will be downloaded: ${downloadItems.length}`);
+          this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length);
+          this.statusReporter.start();
+          yield Promise.all(parallelDownloads.map((index) => __awaiter4(this, void 0, void 0, function* () {
+            while (currentFile < downloadItems.length) {
+              const currentFileToDownload = downloadItems[currentFile];
+              currentFile += 1;
+              const startTime = perf_hooks_1.performance.now();
+              yield this.downloadIndividualFile(index, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath);
+              if (core14.isDebug()) {
+                core14.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`);
+              }
+              this.statusReporter.incrementProcessedCount();
+            }
+          }))).catch((error4) => {
+            throw new Error(`Unable to download the artifact: ${error4}`);
+          }).finally(() => {
+            this.statusReporter.stop();
+            this.downloadHttpManager.disposeAndReplaceAllClients();
+          });
+        });
+      }
+      /**
+       * Downloads an individual file
+       * @param httpClientIndex the index of the http client that is used to make all of the calls
+       * @param artifactLocation origin location where a file will be downloaded from
+       * @param downloadPath destination location for the file being downloaded
+       */
+      downloadIndividualFile(httpClientIndex, artifactLocation, downloadPath) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          let retryCount = 0;
+          const retryLimit = (0, config_variables_1.getRetryLimit)();
+          let destinationStream = fs2.createWriteStream(downloadPath);
+          const headers = (0, utils_1.getDownloadHeaders)("application/json", true, true);
+          const makeDownloadRequest = () => __awaiter4(this, void 0, void 0, function* () {
+            const client = this.downloadHttpManager.getClient(httpClientIndex);
+            return yield client.get(artifactLocation, headers);
+          });
+          const isGzip = (incomingHeaders) => {
+            return "content-encoding" in incomingHeaders && incomingHeaders["content-encoding"] === "gzip";
+          };
+          const backOff = (retryAfterValue) => __awaiter4(this, void 0, void 0, function* () {
+            retryCount++;
+            if (retryCount > retryLimit) {
+              return Promise.reject(new Error(`Retry limit has been reached. Unable to download ${artifactLocation}`));
+            } else {
+              this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex);
+              if (retryAfterValue) {
+                core14.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`);
+                yield (0, utils_1.sleep)(retryAfterValue);
+              } else {
+                const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount);
+                core14.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`);
+                yield (0, utils_1.sleep)(backoffTime);
+              }
+              core14.info(`Finished backoff for retry #${retryCount}, continuing with download`);
+            }
+          });
+          const isAllBytesReceived = (expected, received) => {
+            if (!expected || !received || process.env["ACTIONS_ARTIFACT_SKIP_DOWNLOAD_VALIDATION"]) {
+              core14.info("Skipping download validation.");
+              return true;
+            }
+            return parseInt(expected) === received;
+          };
+          const resetDestinationStream = (fileDownloadPath) => __awaiter4(this, void 0, void 0, function* () {
+            destinationStream.close();
+            yield new Promise((resolve2) => {
+              destinationStream.on("close", resolve2);
+              if (destinationStream.writableFinished) {
+                resolve2();
+              }
+            });
+            yield (0, utils_1.rmFile)(fileDownloadPath);
+            destinationStream = fs2.createWriteStream(fileDownloadPath);
+          });
+          while (retryCount <= retryLimit) {
+            let response;
+            try {
+              response = yield makeDownloadRequest();
+            } catch (error4) {
+              core14.info("An error occurred while attempting to download a file");
+              console.log(error4);
+              yield backOff();
+              continue;
+            }
+            let forceRetry = false;
+            if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) {
+              try {
+                const isGzipped = isGzip(response.message.headers);
+                yield this.pipeResponseToFile(response, destinationStream, isGzipped);
+                if (isGzipped || isAllBytesReceived(response.message.headers["content-length"], yield (0, utils_1.getFileSize)(downloadPath))) {
+                  return;
+                } else {
+                  forceRetry = true;
+                }
+              } catch (error4) {
+                forceRetry = true;
+              }
+            }
+            if (forceRetry || (0, utils_1.isRetryableStatusCode)(response.message.statusCode)) {
+              core14.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`);
+              resetDestinationStream(downloadPath);
+              (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff();
+            } else {
+              (0, utils_1.displayHttpDiagnostics)(response);
+              return Promise.reject(new Error(`Unexpected http ${response.message.statusCode} during download for ${artifactLocation}`));
+            }
           }
-        };
-      });
-    }
-    function getArtifactInternal(artifactName) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        var _a;
-        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
-        const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)();
-        const req = {
-          workflowRunBackendId,
-          workflowJobRunBackendId,
-          nameFilter: generated_1.StringValue.create({ value: artifactName })
-        };
-        const res = yield artifactClient.ListArtifacts(req);
-        if (res.artifacts.length === 0) {
-          throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}
-        Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.
-        For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`);
-        }
-        let artifact2 = res.artifacts[0];
-        if (res.artifacts.length > 1) {
-          artifact2 = res.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0];
-          core14.debug(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`);
-        }
-        return {
-          artifact: {
-            name: artifact2.name,
-            id: Number(artifact2.databaseId),
-            size: Number(artifact2.size),
-            createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0,
-            digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value
+        });
+      }
+      /**
+       * Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary
+       * @param response the http response received when downloading a file
+       * @param destinationStream the stream where the file should be written to
+       * @param isGzip a boolean denoting if the content is compressed using gzip and if we need to decode it
+       */
+      pipeResponseToFile(response, destinationStream, isGzip) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          yield new Promise((resolve2, reject) => {
+            if (isGzip) {
+              const gunzip = zlib.createGunzip();
+              response.message.on("error", (error4) => {
+                core14.info(`An error occurred while attempting to read the response stream`);
+                gunzip.close();
+                destinationStream.close();
+                reject(error4);
+              }).pipe(gunzip).on("error", (error4) => {
+                core14.info(`An error occurred while attempting to decompress the response stream`);
+                destinationStream.close();
+                reject(error4);
+              }).pipe(destinationStream).on("close", () => {
+                resolve2();
+              }).on("error", (error4) => {
+                core14.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`);
+                reject(error4);
+              });
+            } else {
+              response.message.on("error", (error4) => {
+                core14.info(`An error occurred while attempting to read the response stream`);
+                destinationStream.close();
+                reject(error4);
+              }).pipe(destinationStream).on("close", () => {
+                resolve2();
+              }).on("error", (error4) => {
+                core14.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`);
+                reject(error4);
+              });
+            }
+          });
+          return;
+        });
+      }
+    };
+    exports2.DownloadHttpClient = DownloadHttpClient;
+  }
+});
+
+// node_modules/@actions/artifact-legacy/lib/internal/download-specification.js
+var require_download_specification = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/download-specification.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getDownloadSpecification = void 0;
+    var path2 = __importStar4(require("path"));
+    function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) {
+      const directories = /* @__PURE__ */ new Set();
+      const specifications = {
+        rootDownloadLocation: includeRootDirectory ? path2.join(downloadPath, artifactName) : downloadPath,
+        directoryStructure: [],
+        emptyFilesToCreate: [],
+        filesToDownload: []
+      };
+      for (const entry of artifactEntries) {
+        if (entry.path.startsWith(`${artifactName}/`) || entry.path.startsWith(`${artifactName}\\`)) {
+          const normalizedPathEntry = path2.normalize(entry.path);
+          const filePath = path2.join(downloadPath, includeRootDirectory ? normalizedPathEntry : normalizedPathEntry.replace(artifactName, ""));
+          if (entry.itemType === "file") {
+            directories.add(path2.dirname(filePath));
+            if (entry.fileLength === 0) {
+              specifications.emptyFilesToCreate.push(filePath);
+            } else {
+              specifications.filesToDownload.push({
+                sourceLocation: entry.contentLocation,
+                targetPath: filePath
+              });
+            }
           }
-        };
-      });
+        }
+      }
+      specifications.directoryStructure = Array.from(directories);
+      return specifications;
     }
+    exports2.getDownloadSpecification = getDownloadSpecification;
   }
 });
 
-// node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js
-var require_delete_artifact = __commonJS({
-  "node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js"(exports2) {
+// node_modules/@actions/artifact-legacy/lib/internal/artifact-client.js
+var require_artifact_client = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/internal/artifact-client.js"(exports2) {
     "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
     var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
       function adopt(value) {
         return value instanceof P ? value : new P(function(resolve2) {
@@ -98000,1689 +103059,1668 @@ var require_delete_artifact = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.deleteArtifactPublic = deleteArtifactPublic;
-    exports2.deleteArtifactInternal = deleteArtifactInternal;
-    var core_1 = require_core();
-    var github_1 = require_github();
-    var user_agent_1 = require_user_agent();
-    var retry_options_1 = require_retry_options();
-    var utils_1 = require_utils4();
-    var plugin_request_log_1 = require_dist_node16();
-    var plugin_retry_1 = require_dist_node17();
-    var artifact_twirp_client_1 = require_artifact_twirp_client2();
-    var util_1 = require_util8();
-    var generated_1 = require_generated();
-    var get_artifact_1 = require_get_artifact();
-    var errors_1 = require_errors2();
-    function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        var _a;
-        const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults);
-        const opts = {
-          log: void 0,
-          userAgent: (0, user_agent_1.getUserAgentString)(),
-          previews: void 0,
-          retry: retryOpts,
-          request: requestOpts
-        };
-        const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog);
-        const getArtifactResp = yield (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token);
-        const deleteArtifactResp = yield github2.rest.actions.deleteArtifact({
-          owner: repositoryOwner,
-          repo: repositoryName,
-          artifact_id: getArtifactResp.artifact.id
+    exports2.DefaultArtifactClient = void 0;
+    var core14 = __importStar4(require_core());
+    var upload_specification_1 = require_upload_specification();
+    var upload_http_client_1 = require_upload_http_client();
+    var utils_1 = require_utils7();
+    var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2();
+    var download_http_client_1 = require_download_http_client();
+    var download_specification_1 = require_download_specification();
+    var config_variables_1 = require_config_variables();
+    var path_1 = require("path");
+    var DefaultArtifactClient2 = class _DefaultArtifactClient {
+      /**
+       * Constructs a DefaultArtifactClient
+       */
+      static create() {
+        return new _DefaultArtifactClient();
+      }
+      /**
+       * Uploads an artifact
+       */
+      uploadArtifact(name, files, rootDirectory, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          core14.info(`Starting artifact upload
+For more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging`);
+          (0, path_and_artifact_name_validation_1.checkArtifactName)(name);
+          const uploadSpecification = (0, upload_specification_1.getUploadSpecification)(name, rootDirectory, files);
+          const uploadResponse = {
+            artifactName: name,
+            artifactItems: [],
+            size: 0,
+            failedItems: []
+          };
+          const uploadHttpClient = new upload_http_client_1.UploadHttpClient();
+          if (uploadSpecification.length === 0) {
+            core14.warning(`No files found that can be uploaded`);
+          } else {
+            const response = yield uploadHttpClient.createArtifactInFileContainer(name, options);
+            if (!response.fileContainerResourceUrl) {
+              core14.debug(response.toString());
+              throw new Error("No URL provided by the Artifact Service to upload an artifact to");
+            }
+            core14.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`);
+            core14.info(`Container for artifact "${name}" successfully created. Starting upload of file(s)`);
+            const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options);
+            core14.info(`File upload process has finished. Finalizing the artifact upload`);
+            yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name);
+            if (uploadResult.failedItems.length > 0) {
+              core14.info(`Upload finished. There were ${uploadResult.failedItems.length} items that failed to upload`);
+            } else {
+              core14.info(`Artifact has been finalized. All files have been successfully uploaded!`);
+            }
+            core14.info(`
+The raw size of all the files that were specified for upload is ${uploadResult.totalSize} bytes
+The size of all the files that were uploaded is ${uploadResult.uploadSize} bytes. This takes into account any gzip compression used to reduce the upload size, time and storage
+
+Note: The size of downloaded zips can differ significantly from the reported size. For more information see: https://github.com/actions/upload-artifact#zipped-artifact-downloads \r
+`);
+            uploadResponse.artifactItems = uploadSpecification.map((item) => item.absoluteFilePath);
+            uploadResponse.size = uploadResult.uploadSize;
+            uploadResponse.failedItems = uploadResult.failedItems;
+          }
+          return uploadResponse;
         });
-        if (deleteArtifactResp.status !== 204) {
-          throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a === void 0 ? void 0 : _a["x-github-request-id"]})`);
-        }
-        return {
-          id: getArtifactResp.artifact.id
-        };
-      });
-    }
-    function deleteArtifactInternal(artifactName) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
-        const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)();
-        const listReq = {
-          workflowRunBackendId,
-          workflowJobRunBackendId,
-          nameFilter: generated_1.StringValue.create({ value: artifactName })
-        };
-        const listRes = yield artifactClient.ListArtifacts(listReq);
-        if (listRes.artifacts.length === 0) {
-          throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`);
-        }
-        let artifact2 = listRes.artifacts[0];
-        if (listRes.artifacts.length > 1) {
-          artifact2 = listRes.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0];
-          (0, core_1.debug)(`More than one artifact found for a single name, returning newest (id: ${artifact2.databaseId})`);
-        }
-        const req = {
-          workflowRunBackendId: artifact2.workflowRunBackendId,
-          workflowJobRunBackendId: artifact2.workflowJobRunBackendId,
-          name: artifact2.name
-        };
-        const res = yield artifactClient.DeleteArtifact(req);
-        (0, core_1.info)(`Artifact '${artifactName}' (ID: ${res.artifactId}) deleted`);
-        return {
-          id: Number(res.artifactId)
-        };
-      });
+      }
+      downloadArtifact(name, path2, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const downloadHttpClient = new download_http_client_1.DownloadHttpClient();
+          const artifacts = yield downloadHttpClient.listArtifacts();
+          if (artifacts.count === 0) {
+            throw new Error(`Unable to find any artifacts for the associated workflow`);
+          }
+          const artifactToDownload = artifacts.value.find((artifact2) => {
+            return artifact2.name === name;
+          });
+          if (!artifactToDownload) {
+            throw new Error(`Unable to find an artifact with the name: ${name}`);
+          }
+          const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl);
+          if (!path2) {
+            path2 = (0, config_variables_1.getWorkSpaceDirectory)();
+          }
+          path2 = (0, path_1.normalize)(path2);
+          path2 = (0, path_1.resolve)(path2);
+          const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(name, items.value, path2, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false);
+          if (downloadSpecification.filesToDownload.length === 0) {
+            core14.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`);
+          } else {
+            yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure);
+            core14.info("Directory structure has been set up for the artifact");
+            yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate);
+            yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload);
+          }
+          return {
+            artifactName: name,
+            downloadPath: downloadSpecification.rootDownloadLocation
+          };
+        });
+      }
+      downloadAllArtifacts(path2) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const downloadHttpClient = new download_http_client_1.DownloadHttpClient();
+          const response = [];
+          const artifacts = yield downloadHttpClient.listArtifacts();
+          if (artifacts.count === 0) {
+            core14.info("Unable to find any artifacts for the associated workflow");
+            return response;
+          }
+          if (!path2) {
+            path2 = (0, config_variables_1.getWorkSpaceDirectory)();
+          }
+          path2 = (0, path_1.normalize)(path2);
+          path2 = (0, path_1.resolve)(path2);
+          let downloadedArtifacts = 0;
+          while (downloadedArtifacts < artifacts.count) {
+            const currentArtifactToDownload = artifacts.value[downloadedArtifacts];
+            downloadedArtifacts += 1;
+            core14.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`);
+            const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl);
+            const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(currentArtifactToDownload.name, items.value, path2, true);
+            if (downloadSpecification.filesToDownload.length === 0) {
+              core14.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`);
+            } else {
+              yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure);
+              yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate);
+              yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload);
+            }
+            response.push({
+              artifactName: currentArtifactToDownload.name,
+              downloadPath: downloadSpecification.rootDownloadLocation
+            });
+          }
+          return response;
+        });
+      }
+    };
+    exports2.DefaultArtifactClient = DefaultArtifactClient2;
+  }
+});
+
+// node_modules/@actions/artifact-legacy/lib/artifact-client.js
+var require_artifact_client2 = __commonJS({
+  "node_modules/@actions/artifact-legacy/lib/artifact-client.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.create = void 0;
+    var artifact_client_1 = require_artifact_client();
+    function create3() {
+      return artifact_client_1.DefaultArtifactClient.create();
     }
+    exports2.create = create3;
   }
 });
 
-// node_modules/@actions/artifact/lib/internal/find/list-artifacts.js
-var require_list_artifacts = __commonJS({
-  "node_modules/@actions/artifact/lib/internal/find/list-artifacts.js"(exports2) {
+// node_modules/jsonschema/lib/helpers.js
+var require_helpers3 = __commonJS({
+  "node_modules/jsonschema/lib/helpers.js"(exports2, module2) {
     "use strict";
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
+    var uri = require("url");
+    var ValidationError = exports2.ValidationError = function ValidationError2(message, instance, schema2, path2, name, argument) {
+      if (Array.isArray(path2)) {
+        this.path = path2;
+        this.property = path2.reduce(function(sum, item) {
+          return sum + makeSuffix(item);
+        }, "instance");
+      } else if (path2 !== void 0) {
+        this.property = path2;
       }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
+      if (message) {
+        this.message = message;
+      }
+      if (schema2) {
+        var id = schema2.$id || schema2.id;
+        this.schema = id || schema2;
+      }
+      if (instance !== void 0) {
+        this.instance = instance;
+      }
+      this.name = name;
+      this.argument = argument;
+      this.stack = this.toString();
+    };
+    ValidationError.prototype.toString = function toString2() {
+      return this.property + " " + this.message;
+    };
+    var ValidatorResult = exports2.ValidatorResult = function ValidatorResult2(instance, schema2, options, ctx) {
+      this.instance = instance;
+      this.schema = schema2;
+      this.options = options;
+      this.path = ctx.path;
+      this.propertyPath = ctx.propertyPath;
+      this.errors = [];
+      this.throwError = options && options.throwError;
+      this.throwFirst = options && options.throwFirst;
+      this.throwAll = options && options.throwAll;
+      this.disableFormat = options && options.disableFormat === true;
+    };
+    ValidatorResult.prototype.addError = function addError(detail) {
+      var err;
+      if (typeof detail == "string") {
+        err = new ValidationError(detail, this.instance, this.schema, this.path);
+      } else {
+        if (!detail) throw new Error("Missing error detail");
+        if (!detail.message) throw new Error("Missing error message");
+        if (!detail.name) throw new Error("Missing validator type");
+        err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument);
+      }
+      this.errors.push(err);
+      if (this.throwFirst) {
+        throw new ValidatorResultError(this);
+      } else if (this.throwError) {
+        throw err;
+      }
+      return err;
+    };
+    ValidatorResult.prototype.importErrors = function importErrors(res) {
+      if (typeof res == "string" || res && res.validatorType) {
+        this.addError(res);
+      } else if (res && res.errors) {
+        this.errors = this.errors.concat(res.errors);
+      }
+    };
+    function stringizer(v, i) {
+      return i + ": " + v.toString() + "\n";
+    }
+    ValidatorResult.prototype.toString = function toString2(res) {
+      return this.errors.map(stringizer).join("");
+    };
+    Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() {
+      return !this.errors.length;
+    } });
+    module2.exports.ValidatorResultError = ValidatorResultError;
+    function ValidatorResultError(result) {
+      if (Error.captureStackTrace) {
+        Error.captureStackTrace(this, ValidatorResultError);
+      }
+      this.instance = result.instance;
+      this.schema = result.schema;
+      this.options = result.options;
+      this.errors = result.errors;
+    }
+    ValidatorResultError.prototype = new Error();
+    ValidatorResultError.prototype.constructor = ValidatorResultError;
+    ValidatorResultError.prototype.name = "Validation Error";
+    var SchemaError = exports2.SchemaError = function SchemaError2(msg, schema2) {
+      this.message = msg;
+      this.schema = schema2;
+      Error.call(this, msg);
+      Error.captureStackTrace(this, SchemaError2);
+    };
+    SchemaError.prototype = Object.create(
+      Error.prototype,
+      {
+        constructor: { value: SchemaError, enumerable: false },
+        name: { value: "SchemaError", enumerable: false }
+      }
+    );
+    var SchemaContext = exports2.SchemaContext = function SchemaContext2(schema2, options, path2, base, schemas) {
+      this.schema = schema2;
+      this.options = options;
+      if (Array.isArray(path2)) {
+        this.path = path2;
+        this.propertyPath = path2.reduce(function(sum, item) {
+          return sum + makeSuffix(item);
+        }, "instance");
+      } else {
+        this.propertyPath = path2;
+      }
+      this.base = base;
+      this.schemas = schemas;
+    };
+    SchemaContext.prototype.resolve = function resolve2(target) {
+      return uri.resolve(this.base, target);
+    };
+    SchemaContext.prototype.makeChild = function makeChild(schema2, propertyName) {
+      var path2 = propertyName === void 0 ? this.path : this.path.concat([propertyName]);
+      var id = schema2.$id || schema2.id;
+      var base = uri.resolve(this.base, id || "");
+      var ctx = new SchemaContext(schema2, this.options, path2, base, Object.create(this.schemas));
+      if (id && !ctx.schemas[base]) {
+        ctx.schemas[base] = schema2;
+      }
+      return ctx;
+    };
+    var FORMAT_REGEXPS = exports2.FORMAT_REGEXPS = {
+      // 7.3.1. Dates, Times, and Duration
+      "date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,
+      "date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,
+      "time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,
+      "duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,
+      // 7.3.2. Email Addresses
+      // TODO: fix the email production
+      "email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,
+      "idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,
+      // 7.3.3. Hostnames
+      // 7.3.4. IP Addresses
+      "ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
+      // FIXME whitespace is invalid
+      "ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,
+      // 7.3.5. Resource Identifiers
+      // TODO: A more accurate regular expression for "uri" goes:
+      // [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)?
+      "uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
+      "uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,
+      "iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
+      "iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,
+      "uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
+      // 7.3.6. uri-template
+      "uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,
+      // 7.3.7. JSON Pointers
+      "json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,
+      "relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,
+      // hostname regex from: http://stackoverflow.com/a/1420225/5628
+      "hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
+      "host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
+      "utc-millisec": function(input) {
+        return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input);
+      },
+      // 7.3.8. regex
+      "regex": function(input) {
+        var result = true;
+        try {
+          new RegExp(input);
+        } catch (e) {
+          result = false;
         }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
+        return result;
+      },
+      // Other definitions
+      // "style" was removed from JSON Schema in draft-4 and is deprecated
+      "style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,
+      // "color" was removed from JSON Schema in draft-4 and is deprecated
+      "color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,
+      "phone": /^\+(?:[0-9] ?){6,14}[0-9]$/,
+      "alpha": /^[a-zA-Z]+$/,
+      "alphanumeric": /^[a-zA-Z0-9]+$/
+    };
+    FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex;
+    FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex;
+    FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"];
+    exports2.isFormat = function isFormat(input, format, validator) {
+      if (typeof input === "string" && FORMAT_REGEXPS[format] !== void 0) {
+        if (FORMAT_REGEXPS[format] instanceof RegExp) {
+          return FORMAT_REGEXPS[format].test(input);
         }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        if (typeof FORMAT_REGEXPS[format] === "function") {
+          return FORMAT_REGEXPS[format](input);
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
+      } else if (validator && validator.customFormats && typeof validator.customFormats[format] === "function") {
+        return validator.customFormats[format](input);
+      }
+      return true;
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.listArtifactsPublic = listArtifactsPublic;
-    exports2.listArtifactsInternal = listArtifactsInternal;
-    var core_1 = require_core();
-    var github_1 = require_github();
-    var user_agent_1 = require_user_agent();
-    var retry_options_1 = require_retry_options();
-    var utils_1 = require_utils4();
-    var plugin_request_log_1 = require_dist_node16();
-    var plugin_retry_1 = require_dist_node17();
-    var artifact_twirp_client_1 = require_artifact_twirp_client2();
-    var util_1 = require_util8();
-    var config_1 = require_config();
-    var generated_1 = require_generated();
-    var maximumArtifactCount = (0, config_1.getMaxArtifactListCount)();
-    var paginationCount = 100;
-    var maxNumberOfPages = Math.ceil(maximumArtifactCount / paginationCount);
-    function listArtifactsPublic(workflowRunId_1, repositoryOwner_1, repositoryName_1, token_1) {
-      return __awaiter4(this, arguments, void 0, function* (workflowRunId, repositoryOwner, repositoryName, token, latest = false) {
-        (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`);
-        let artifacts = [];
-        const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults);
-        const opts = {
-          log: void 0,
-          userAgent: (0, user_agent_1.getUserAgentString)(),
-          previews: void 0,
-          retry: retryOpts,
-          request: requestOpts
-        };
-        const github2 = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog);
-        let currentPageNumber = 1;
-        const { data: listArtifactResponse } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", {
-          owner: repositoryOwner,
-          repo: repositoryName,
-          run_id: workflowRunId,
-          per_page: paginationCount,
-          page: currentPageNumber
-        });
-        let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount);
-        const totalArtifactCount = listArtifactResponse.total_count;
-        if (totalArtifactCount > maximumArtifactCount) {
-          (0, core_1.warning)(`Workflow run ${workflowRunId} has ${totalArtifactCount} artifacts, exceeding the limit of ${maximumArtifactCount}. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`);
-          numberOfPages = maxNumberOfPages;
+    var makeSuffix = exports2.makeSuffix = function makeSuffix2(key) {
+      key = key.toString();
+      if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) {
+        return "." + key;
+      }
+      if (key.match(/^\d+$/)) {
+        return "[" + key + "]";
+      }
+      return "[" + JSON.stringify(key) + "]";
+    };
+    exports2.deepCompareStrict = function deepCompareStrict(a, b) {
+      if (typeof a !== typeof b) {
+        return false;
+      }
+      if (Array.isArray(a)) {
+        if (!Array.isArray(b)) {
+          return false;
         }
-        for (const artifact2 of listArtifactResponse.artifacts) {
-          artifacts.push({
-            name: artifact2.name,
-            id: artifact2.id,
-            size: artifact2.size_in_bytes,
-            createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0,
-            digest: artifact2.digest
-          });
+        if (a.length !== b.length) {
+          return false;
         }
-        currentPageNumber++;
-        for (currentPageNumber; currentPageNumber <= numberOfPages; currentPageNumber++) {
-          (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`);
-          const { data: listArtifactResponse2 } = yield github2.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", {
-            owner: repositoryOwner,
-            repo: repositoryName,
-            run_id: workflowRunId,
-            per_page: paginationCount,
-            page: currentPageNumber
-          });
-          for (const artifact2 of listArtifactResponse2.artifacts) {
-            artifacts.push({
-              name: artifact2.name,
-              id: artifact2.id,
-              size: artifact2.size_in_bytes,
-              createdAt: artifact2.created_at ? new Date(artifact2.created_at) : void 0,
-              digest: artifact2.digest
-            });
-          }
+        return a.every(function(v, i) {
+          return deepCompareStrict(a[i], b[i]);
+        });
+      }
+      if (typeof a === "object") {
+        if (!a || !b) {
+          return a === b;
         }
-        if (latest) {
-          artifacts = filterLatest(artifacts);
+        var aKeys = Object.keys(a);
+        var bKeys = Object.keys(b);
+        if (aKeys.length !== bKeys.length) {
+          return false;
         }
-        (0, core_1.info)(`Found ${artifacts.length} artifact(s)`);
-        return {
-          artifacts
-        };
-      });
-    }
-    function listArtifactsInternal() {
-      return __awaiter4(this, arguments, void 0, function* (latest = false) {
-        const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)();
-        const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)();
-        const req = {
-          workflowRunBackendId,
-          workflowJobRunBackendId
-        };
-        const res = yield artifactClient.ListArtifacts(req);
-        let artifacts = res.artifacts.map((artifact2) => {
-          var _a;
-          return {
-            name: artifact2.name,
-            id: Number(artifact2.databaseId),
-            size: Number(artifact2.size),
-            createdAt: artifact2.createdAt ? generated_1.Timestamp.toDate(artifact2.createdAt) : void 0,
-            digest: (_a = artifact2.digest) === null || _a === void 0 ? void 0 : _a.value
-          };
+        return aKeys.every(function(v) {
+          return deepCompareStrict(a[v], b[v]);
         });
-        if (latest) {
-          artifacts = filterLatest(artifacts);
+      }
+      return a === b;
+    };
+    function deepMerger(target, dst, e, i) {
+      if (typeof e === "object") {
+        dst[i] = deepMerge(target[i], e);
+      } else {
+        if (target.indexOf(e) === -1) {
+          dst.push(e);
         }
-        (0, core_1.info)(`Found ${artifacts.length} artifact(s)`);
-        return {
-          artifacts
-        };
-      });
+      }
     }
-    function filterLatest(artifacts) {
-      artifacts.sort((a, b) => b.id - a.id);
-      const latestArtifacts = [];
-      const seenArtifactNames = /* @__PURE__ */ new Set();
-      for (const artifact2 of artifacts) {
-        if (!seenArtifactNames.has(artifact2.name)) {
-          latestArtifacts.push(artifact2);
-          seenArtifactNames.add(artifact2.name);
+    function copyist(src, dst, key) {
+      dst[key] = src[key];
+    }
+    function copyistWithDeepMerge(target, src, dst, key) {
+      if (typeof src[key] !== "object" || !src[key]) {
+        dst[key] = src[key];
+      } else {
+        if (!target[key]) {
+          dst[key] = src[key];
+        } else {
+          dst[key] = deepMerge(target[key], src[key]);
         }
       }
-      return latestArtifacts;
     }
+    function deepMerge(target, src) {
+      var array = Array.isArray(src);
+      var dst = array && [] || {};
+      if (array) {
+        target = target || [];
+        dst = dst.concat(target);
+        src.forEach(deepMerger.bind(null, target, dst));
+      } else {
+        if (target && typeof target === "object") {
+          Object.keys(target).forEach(copyist.bind(null, target, dst));
+        }
+        Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst));
+      }
+      return dst;
+    }
+    module2.exports.deepMerge = deepMerge;
+    exports2.objectGetPath = function objectGetPath(o, s) {
+      var parts = s.split("/").slice(1);
+      var k;
+      while (typeof (k = parts.shift()) == "string") {
+        var n = decodeURIComponent(k.replace(/~0/, "~").replace(/~1/g, "/"));
+        if (!(n in o)) return;
+        o = o[n];
+      }
+      return o;
+    };
+    function pathEncoder(v) {
+      return "/" + encodeURIComponent(v).replace(/~/g, "%7E");
+    }
+    exports2.encodePath = function encodePointer(a) {
+      return a.map(pathEncoder).join("");
+    };
+    exports2.getDecimalPlaces = function getDecimalPlaces(number) {
+      var decimalPlaces = 0;
+      if (isNaN(number)) return decimalPlaces;
+      if (typeof number !== "number") {
+        number = Number(number);
+      }
+      var parts = number.toString().split("e");
+      if (parts.length === 2) {
+        if (parts[1][0] !== "-") {
+          return decimalPlaces;
+        } else {
+          decimalPlaces = Number(parts[1].slice(1));
+        }
+      }
+      var decimalParts = parts[0].split(".");
+      if (decimalParts.length === 2) {
+        decimalPlaces += decimalParts[1].length;
+      }
+      return decimalPlaces;
+    };
+    exports2.isSchema = function isSchema(val2) {
+      return typeof val2 === "object" && val2 || typeof val2 === "boolean";
+    };
   }
 });
 
-// node_modules/@actions/artifact/lib/internal/client.js
-var require_client2 = __commonJS({
-  "node_modules/@actions/artifact/lib/internal/client.js"(exports2) {
+// node_modules/jsonschema/lib/attribute.js
+var require_attribute = __commonJS({
+  "node_modules/jsonschema/lib/attribute.js"(exports2, module2) {
     "use strict";
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
+    var helpers = require_helpers3();
+    var ValidatorResult = helpers.ValidatorResult;
+    var SchemaError = helpers.SchemaError;
+    var attribute = {};
+    attribute.ignoreProperties = {
+      // informative properties
+      "id": true,
+      "default": true,
+      "description": true,
+      "title": true,
+      // arguments to other properties
+      "additionalItems": true,
+      "then": true,
+      "else": true,
+      // special-handled properties
+      "$schema": true,
+      "$ref": true,
+      "extends": true
+    };
+    var validators = attribute.validators = {};
+    validators.type = function validateType(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var types = Array.isArray(schema2.type) ? schema2.type : [schema2.type];
+      if (!types.some(this.testType.bind(this, instance, schema2, options, ctx))) {
+        var list = types.map(function(v) {
+          if (!v) return;
+          var id = v.$id || v.id;
+          return id ? "<" + id + ">" : v + "";
+        });
+        result.addError({
+          name: "type",
+          argument: list,
+          message: "is not of a type(s) " + list
         });
       }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
-    };
-    var __rest4 = exports2 && exports2.__rest || function(s, e) {
-      var t = {};
-      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
-        t[p] = s[p];
-      if (s != null && typeof Object.getOwnPropertySymbols === "function")
-        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
-          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
-            t[p[i]] = s[p[i]];
-        }
-      return t;
+      return result;
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.DefaultArtifactClient = void 0;
-    var core_1 = require_core();
-    var config_1 = require_config();
-    var upload_artifact_1 = require_upload_artifact();
-    var download_artifact_1 = require_download_artifact();
-    var delete_artifact_1 = require_delete_artifact();
-    var get_artifact_1 = require_get_artifact();
-    var list_artifacts_1 = require_list_artifacts();
-    var errors_1 = require_errors2();
-    var DefaultArtifactClient2 = class {
-      uploadArtifact(name, files, rootDirectory, options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          try {
-            if ((0, config_1.isGhes)()) {
-              throw new errors_1.GHESNotSupportedError();
-            }
-            return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options);
-          } catch (error4) {
-            (0, core_1.warning)(`Artifact upload failed with error: ${error4}.
-
-Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
-
-If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
-            throw error4;
-          }
-        });
+    function testSchemaNoThrow(instance, options, ctx, callback, schema2) {
+      var throwError2 = options.throwError;
+      var throwAll = options.throwAll;
+      options.throwError = false;
+      options.throwAll = false;
+      var res = this.validateSchema(instance, schema2, options, ctx);
+      options.throwError = throwError2;
+      options.throwAll = throwAll;
+      if (!res.valid && callback instanceof Function) {
+        callback(res);
       }
-      downloadArtifact(artifactId, options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          try {
-            if ((0, config_1.isGhes)()) {
-              throw new errors_1.GHESNotSupportedError();
-            }
-            if (options === null || options === void 0 ? void 0 : options.findBy) {
-              const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest4(options, ["findBy"]);
-              return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions);
-            }
-            return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options);
-          } catch (error4) {
-            (0, core_1.warning)(`Download Artifact failed with error: ${error4}.
-
-Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
-
-If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
-            throw error4;
-          }
-        });
+      return res.valid;
+    }
+    validators.anyOf = function validateAnyOf(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
       }
-      listArtifacts(options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          try {
-            if ((0, config_1.isGhes)()) {
-              throw new errors_1.GHESNotSupportedError();
-            }
-            if (options === null || options === void 0 ? void 0 : options.findBy) {
-              const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options;
-              return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest);
-            }
-            return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest);
-          } catch (error4) {
-            (0, core_1.warning)(`Listing Artifacts failed with error: ${error4}.
-
-Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
-
-If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
-            throw error4;
-          }
-        });
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var inner = new ValidatorResult(instance, schema2, options, ctx);
+      if (!Array.isArray(schema2.anyOf)) {
+        throw new SchemaError("anyOf must be an array");
       }
-      getArtifact(artifactName, options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          try {
-            if ((0, config_1.isGhes)()) {
-              throw new errors_1.GHESNotSupportedError();
-            }
-            if (options === null || options === void 0 ? void 0 : options.findBy) {
-              const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options;
-              return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token);
-            }
-            return (0, get_artifact_1.getArtifactInternal)(artifactName);
-          } catch (error4) {
-            (0, core_1.warning)(`Get Artifact failed with error: ${error4}.
-
-Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
-
-If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
-            throw error4;
+      if (!schema2.anyOf.some(
+        testSchemaNoThrow.bind(
+          this,
+          instance,
+          options,
+          ctx,
+          function(res) {
+            inner.importErrors(res);
           }
+        )
+      )) {
+        var list = schema2.anyOf.map(function(v, i) {
+          var id = v.$id || v.id;
+          if (id) return "<" + id + ">";
+          return v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
         });
-      }
-      deleteArtifact(artifactName, options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          try {
-            if ((0, config_1.isGhes)()) {
-              throw new errors_1.GHESNotSupportedError();
-            }
-            if (options === null || options === void 0 ? void 0 : options.findBy) {
-              const { findBy: { repositoryOwner, repositoryName, workflowRunId, token } } = options;
-              return (0, delete_artifact_1.deleteArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token);
-            }
-            return (0, delete_artifact_1.deleteArtifactInternal)(artifactName);
-          } catch (error4) {
-            (0, core_1.warning)(`Delete Artifact failed with error: ${error4}.
-
-Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information.
-
-If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`);
-            throw error4;
-          }
+        if (options.nestedErrors) {
+          result.importErrors(inner);
+        }
+        result.addError({
+          name: "anyOf",
+          argument: list,
+          message: "is not any of " + list.join(",")
         });
       }
+      return result;
     };
-    exports2.DefaultArtifactClient = DefaultArtifactClient2;
-  }
-});
-
-// node_modules/@actions/artifact/lib/internal/shared/interfaces.js
-var require_interfaces2 = __commonJS({
-  "node_modules/@actions/artifact/lib/internal/shared/interfaces.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-  }
-});
-
-// node_modules/@actions/artifact/lib/artifact.js
-var require_artifact2 = __commonJS({
-  "node_modules/@actions/artifact/lib/artifact.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+    validators.allOf = function validateAllOf(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) {
-      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p);
+      if (!Array.isArray(schema2.allOf)) {
+        throw new SchemaError("allOf must be an array");
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var self2 = this;
+      schema2.allOf.forEach(function(v, i) {
+        var valid3 = self2.validateSchema(instance, v, options, ctx);
+        if (!valid3.valid) {
+          var id = v.$id || v.id;
+          var msg = id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
+          result.addError({
+            name: "allOf",
+            argument: { id: msg, length: valid3.errors.length, valid: valid3 },
+            message: "does not match allOf schema " + msg + " with " + valid3.errors.length + " error[s]:"
+          });
+          result.importErrors(valid3);
+        }
+      });
+      return result;
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    var client_1 = require_client2();
-    __exportStar4(require_interfaces2(), exports2);
-    __exportStar4(require_errors2(), exports2);
-    __exportStar4(require_client2(), exports2);
-    var client = new client_1.DefaultArtifactClient();
-    exports2.default = client;
-  }
-});
-
-// node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js
-var require_path_and_artifact_name_validation2 = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/path-and-artifact-name-validation.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.checkArtifactFilePath = exports2.checkArtifactName = void 0;
-    var core_1 = require_core();
-    var invalidArtifactFilePathCharacters = /* @__PURE__ */ new Map([
-      ['"', ' Double quote "'],
-      [":", " Colon :"],
-      ["<", " Less than <"],
-      [">", " Greater than >"],
-      ["|", " Vertical bar |"],
-      ["*", " Asterisk *"],
-      ["?", " Question mark ?"],
-      ["\r", " Carriage return \\r"],
-      ["\n", " Line feed \\n"]
-    ]);
-    var invalidArtifactNameCharacters = new Map([
-      ...invalidArtifactFilePathCharacters,
-      ["\\", " Backslash \\"],
-      ["/", " Forward slash /"]
-    ]);
-    function checkArtifactName(name) {
-      if (!name) {
-        throw new Error(`Artifact name: ${name}, is incorrectly provided`);
+    validators.oneOf = function validateOneOf(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
       }
-      for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) {
-        if (name.includes(invalidCharacterKey)) {
-          throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter}
-          
-Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()}
-          
-These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`);
+      if (!Array.isArray(schema2.oneOf)) {
+        throw new SchemaError("oneOf must be an array");
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var inner = new ValidatorResult(instance, schema2, options, ctx);
+      var count = schema2.oneOf.filter(
+        testSchemaNoThrow.bind(
+          this,
+          instance,
+          options,
+          ctx,
+          function(res) {
+            inner.importErrors(res);
+          }
+        )
+      ).length;
+      var list = schema2.oneOf.map(function(v, i) {
+        var id = v.$id || v.id;
+        return id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
+      });
+      if (count !== 1) {
+        if (options.nestedErrors) {
+          result.importErrors(inner);
         }
+        result.addError({
+          name: "oneOf",
+          argument: list,
+          message: "is not exactly one from " + list.join(",")
+        });
       }
-      (0, core_1.info)(`Artifact name is valid!`);
-    }
-    exports2.checkArtifactName = checkArtifactName;
-    function checkArtifactFilePath(path2) {
-      if (!path2) {
-        throw new Error(`Artifact path: ${path2}, is incorrectly provided`);
+      return result;
+    };
+    validators.if = function validateIf(instance, schema2, options, ctx) {
+      if (instance === void 0) return null;
+      if (!helpers.isSchema(schema2.if)) throw new Error('Expected "if" keyword to be a schema');
+      var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema2.if);
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var res;
+      if (ifValid) {
+        if (schema2.then === void 0) return;
+        if (!helpers.isSchema(schema2.then)) throw new Error('Expected "then" keyword to be a schema');
+        res = this.validateSchema(instance, schema2.then, options, ctx.makeChild(schema2.then));
+        result.importErrors(res);
+      } else {
+        if (schema2.else === void 0) return;
+        if (!helpers.isSchema(schema2.else)) throw new Error('Expected "else" keyword to be a schema');
+        res = this.validateSchema(instance, schema2.else, options, ctx.makeChild(schema2.else));
+        result.importErrors(res);
       }
-      for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) {
-        if (path2.includes(invalidCharacterKey)) {
-          throw new Error(`Artifact path is not valid: ${path2}. Contains the following character: ${errorMessageForCharacter}
-          
-Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()}
-          
-The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.
-          `);
-        }
+      return result;
+    };
+    function getEnumerableProperty(object, key) {
+      if (Object.hasOwnProperty.call(object, key)) return object[key];
+      if (!(key in object)) return;
+      while (object = Object.getPrototypeOf(object)) {
+        if (Object.propertyIsEnumerable.call(object, key)) return object[key];
       }
     }
-    exports2.checkArtifactFilePath = checkArtifactFilePath;
-  }
-});
-
-// node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js
-var require_upload_specification = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/upload-specification.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+    validators.propertyNames = function validatePropertyNames(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var subschema = schema2.propertyNames !== void 0 ? schema2.propertyNames : {};
+      if (!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)');
+      for (var property in instance) {
+        if (getEnumerableProperty(instance, property) !== void 0) {
+          var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema));
+          result.importErrors(res);
+        }
       }
-      __setModuleDefault4(result, mod);
       return result;
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getUploadSpecification = void 0;
-    var fs2 = __importStar4(require("fs"));
-    var core_1 = require_core();
-    var path_1 = require("path");
-    var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2();
-    function getUploadSpecification(artifactName, rootDirectory, artifactFiles) {
-      const specifications = [];
-      if (!fs2.existsSync(rootDirectory)) {
-        throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`);
+    validators.properties = function validateProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var properties = schema2.properties || {};
+      for (var property in properties) {
+        var subschema = properties[property];
+        if (subschema === void 0) {
+          continue;
+        } else if (subschema === null) {
+          throw new SchemaError('Unexpected null, expected schema in "properties"');
+        }
+        if (typeof options.preValidateProperty == "function") {
+          options.preValidateProperty(instance, property, subschema, options, ctx);
+        }
+        var prop = getEnumerableProperty(instance, property);
+        var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property));
+        if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
+        result.importErrors(res);
       }
-      if (!fs2.statSync(rootDirectory).isDirectory()) {
-        throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`);
+      return result;
+    };
+    function testAdditionalProperty(instance, schema2, options, ctx, property, result) {
+      if (!this.types.object(instance)) return;
+      if (schema2.properties && schema2.properties[property] !== void 0) {
+        return;
       }
-      rootDirectory = (0, path_1.normalize)(rootDirectory);
-      rootDirectory = (0, path_1.resolve)(rootDirectory);
-      for (let file of artifactFiles) {
-        if (!fs2.existsSync(file)) {
-          throw new Error(`File ${file} does not exist`);
-        }
-        if (!fs2.statSync(file).isDirectory()) {
-          file = (0, path_1.normalize)(file);
-          file = (0, path_1.resolve)(file);
-          if (!file.startsWith(rootDirectory)) {
-            throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`);
-          }
-          const uploadPath = file.replace(rootDirectory, "");
-          (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath);
-          specifications.push({
-            absoluteFilePath: file,
-            uploadFilePath: (0, path_1.join)(artifactName, uploadPath)
-          });
-        } else {
-          (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`);
+      if (schema2.additionalProperties === false) {
+        result.addError({
+          name: "additionalProperties",
+          argument: property,
+          message: "is not allowed to have the additional property " + JSON.stringify(property)
+        });
+      } else {
+        var additionalProperties = schema2.additionalProperties || {};
+        if (typeof options.preValidateProperty == "function") {
+          options.preValidateProperty(instance, property, additionalProperties, options, ctx);
         }
+        var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property));
+        if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
+        result.importErrors(res);
       }
-      return specifications;
-    }
-    exports2.getUploadSpecification = getUploadSpecification;
-  }
-});
-
-// node_modules/tmp/lib/tmp.js
-var require_tmp = __commonJS({
-  "node_modules/tmp/lib/tmp.js"(exports2, module2) {
-    var fs2 = require("fs");
-    var os = require("os");
-    var path2 = require("path");
-    var crypto = require("crypto");
-    var _c = { fs: fs2.constants, os: os.constants };
-    var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
-    var TEMPLATE_PATTERN = /XXXXXX/;
-    var DEFAULT_TRIES = 3;
-    var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR);
-    var IS_WIN32 = os.platform() === "win32";
-    var EBADF = _c.EBADF || _c.os.errno.EBADF;
-    var ENOENT = _c.ENOENT || _c.os.errno.ENOENT;
-    var DIR_MODE = 448;
-    var FILE_MODE = 384;
-    var EXIT = "exit";
-    var _removeObjects = [];
-    var FN_RMDIR_SYNC = fs2.rmdirSync.bind(fs2);
-    var _gracefulCleanup = false;
-    function rimraf(dirPath, callback) {
-      return fs2.rm(dirPath, { recursive: true }, callback);
-    }
-    function FN_RIMRAF_SYNC(dirPath) {
-      return fs2.rmSync(dirPath, { recursive: true });
     }
-    function tmpName(options, callback) {
-      const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
-      _assertAndSanitizeOptions(opts, function(err, sanitizedOptions) {
-        if (err) return cb(err);
-        let tries = sanitizedOptions.tries;
-        (function _getUniqueName() {
+    validators.patternProperties = function validatePatternProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var patternProperties = schema2.patternProperties || {};
+      for (var property in instance) {
+        var test = true;
+        for (var pattern in patternProperties) {
+          var subschema = patternProperties[pattern];
+          if (subschema === void 0) {
+            continue;
+          } else if (subschema === null) {
+            throw new SchemaError('Unexpected null, expected schema in "patternProperties"');
+          }
           try {
-            const name = _generateTmpName(sanitizedOptions);
-            fs2.stat(name, function(err2) {
-              if (!err2) {
-                if (tries-- > 0) return _getUniqueName();
-                return cb(new Error("Could not get a unique tmp filename, max tries reached " + name));
-              }
-              cb(null, name);
-            });
-          } catch (err2) {
-            cb(err2);
+            var regexp = new RegExp(pattern, "u");
+          } catch (_e) {
+            regexp = new RegExp(pattern);
           }
-        })();
-      });
-    }
-    function tmpNameSync(options) {
-      const args = _parseArguments(options), opts = args[0];
-      const sanitizedOptions = _assertAndSanitizeOptionsSync(opts);
-      let tries = sanitizedOptions.tries;
-      do {
-        const name = _generateTmpName(sanitizedOptions);
-        try {
-          fs2.statSync(name);
-        } catch (e) {
-          return name;
-        }
-      } while (tries-- > 0);
-      throw new Error("Could not get a unique tmp filename, max tries reached");
-    }
-    function file(options, callback) {
-      const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
-      tmpName(opts, function _tmpNameCreated(err, name) {
-        if (err) return cb(err);
-        fs2.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) {
-          if (err2) return cb(err2);
-          if (opts.discardDescriptor) {
-            return fs2.close(fd, function _discardCallback(possibleErr) {
-              return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false));
-            });
-          } else {
-            const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
-            cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false));
+          if (!regexp.test(property)) {
+            continue;
+          }
+          test = false;
+          if (typeof options.preValidateProperty == "function") {
+            options.preValidateProperty(instance, property, subschema, options, ctx);
           }
+          var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property));
+          if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
+          result.importErrors(res);
+        }
+        if (test) {
+          testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result);
+        }
+      }
+      return result;
+    };
+    validators.additionalProperties = function validateAdditionalProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      if (schema2.patternProperties) {
+        return null;
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      for (var property in instance) {
+        testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result);
+      }
+      return result;
+    };
+    validators.minProperties = function validateMinProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var keys = Object.keys(instance);
+      if (!(keys.length >= schema2.minProperties)) {
+        result.addError({
+          name: "minProperties",
+          argument: schema2.minProperties,
+          message: "does not meet minimum property length of " + schema2.minProperties
         });
-      });
-    }
-    function fileSync(options) {
-      const args = _parseArguments(options), opts = args[0];
-      const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
-      const name = tmpNameSync(opts);
-      let fd = fs2.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
-      if (opts.discardDescriptor) {
-        fs2.closeSync(fd);
-        fd = void 0;
       }
-      return {
-        name,
-        fd,
-        removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true)
-      };
-    }
-    function dir(options, callback) {
-      const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
-      tmpName(opts, function _tmpNameCreated(err, name) {
-        if (err) return cb(err);
-        fs2.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) {
-          if (err2) return cb(err2);
-          cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false));
+      return result;
+    };
+    validators.maxProperties = function validateMaxProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var keys = Object.keys(instance);
+      if (!(keys.length <= schema2.maxProperties)) {
+        result.addError({
+          name: "maxProperties",
+          argument: schema2.maxProperties,
+          message: "does not meet maximum property length of " + schema2.maxProperties
         });
-      });
-    }
-    function dirSync(options) {
-      const args = _parseArguments(options), opts = args[0];
-      const name = tmpNameSync(opts);
-      fs2.mkdirSync(name, opts.mode || DIR_MODE);
-      return {
-        name,
-        removeCallback: _prepareTmpDirRemoveCallback(name, opts, true)
-      };
-    }
-    function _removeFileAsync(fdPath, next) {
-      const _handler = function(err) {
-        if (err && !_isENOENT(err)) {
-          return next(err);
+      }
+      return result;
+    };
+    validators.items = function validateItems(instance, schema2, options, ctx) {
+      var self2 = this;
+      if (!this.types.array(instance)) return;
+      if (schema2.items === void 0) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      instance.every(function(value, i) {
+        if (Array.isArray(schema2.items)) {
+          var items = schema2.items[i] === void 0 ? schema2.additionalItems : schema2.items[i];
+        } else {
+          var items = schema2.items;
         }
-        next();
-      };
-      if (0 <= fdPath[0])
-        fs2.close(fdPath[0], function() {
-          fs2.unlink(fdPath[1], _handler);
+        if (items === void 0) {
+          return true;
+        }
+        if (items === false) {
+          result.addError({
+            name: "items",
+            message: "additionalItems not permitted"
+          });
+          return false;
+        }
+        var res = self2.validateSchema(value, items, options, ctx.makeChild(items, i));
+        if (res.instance !== result.instance[i]) result.instance[i] = res.instance;
+        result.importErrors(res);
+        return true;
+      });
+      return result;
+    };
+    validators.contains = function validateContains(instance, schema2, options, ctx) {
+      var self2 = this;
+      if (!this.types.array(instance)) return;
+      if (schema2.contains === void 0) return;
+      if (!helpers.isSchema(schema2.contains)) throw new Error('Expected "contains" keyword to be a schema');
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var count = instance.some(function(value, i) {
+        var res = self2.validateSchema(value, schema2.contains, options, ctx.makeChild(schema2.contains, i));
+        return res.errors.length === 0;
+      });
+      if (count === false) {
+        result.addError({
+          name: "contains",
+          argument: schema2.contains,
+          message: "must contain an item matching given schema"
         });
-      else fs2.unlink(fdPath[1], _handler);
-    }
-    function _removeFileSync(fdPath) {
-      let rethrownException = null;
-      try {
-        if (0 <= fdPath[0]) fs2.closeSync(fdPath[0]);
-      } catch (e) {
-        if (!_isEBADF(e) && !_isENOENT(e)) throw e;
-      } finally {
-        try {
-          fs2.unlinkSync(fdPath[1]);
-        } catch (e) {
-          if (!_isENOENT(e)) rethrownException = e;
+      }
+      return result;
+    };
+    validators.minimum = function validateMinimum(instance, schema2, options, ctx) {
+      if (!this.types.number(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (schema2.exclusiveMinimum && schema2.exclusiveMinimum === true) {
+        if (!(instance > schema2.minimum)) {
+          result.addError({
+            name: "minimum",
+            argument: schema2.minimum,
+            message: "must be greater than " + schema2.minimum
+          });
+        }
+      } else {
+        if (!(instance >= schema2.minimum)) {
+          result.addError({
+            name: "minimum",
+            argument: schema2.minimum,
+            message: "must be greater than or equal to " + schema2.minimum
+          });
         }
       }
-      if (rethrownException !== null) {
-        throw rethrownException;
+      return result;
+    };
+    validators.maximum = function validateMaximum(instance, schema2, options, ctx) {
+      if (!this.types.number(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (schema2.exclusiveMaximum && schema2.exclusiveMaximum === true) {
+        if (!(instance < schema2.maximum)) {
+          result.addError({
+            name: "maximum",
+            argument: schema2.maximum,
+            message: "must be less than " + schema2.maximum
+          });
+        }
+      } else {
+        if (!(instance <= schema2.maximum)) {
+          result.addError({
+            name: "maximum",
+            argument: schema2.maximum,
+            message: "must be less than or equal to " + schema2.maximum
+          });
+        }
       }
-    }
-    function _prepareTmpFileRemoveCallback(name, fd, opts, sync) {
-      const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync);
-      const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync);
-      if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
-      return sync ? removeCallbackSync : removeCallback;
-    }
-    function _prepareTmpDirRemoveCallback(name, opts, sync) {
-      const removeFunction = opts.unsafeCleanup ? rimraf : fs2.rmdir.bind(fs2);
-      const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC;
-      const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync);
-      const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync);
-      if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
-      return sync ? removeCallbackSync : removeCallback;
-    }
-    function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) {
-      let called = false;
-      return function _cleanupCallback(next) {
-        if (!called) {
-          const toRemove = cleanupCallbackSync || _cleanupCallback;
-          const index = _removeObjects.indexOf(toRemove);
-          if (index >= 0) _removeObjects.splice(index, 1);
-          called = true;
-          if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) {
-            return removeFunction(fileOrDirName);
-          } else {
-            return removeFunction(fileOrDirName, next || function() {
+      return result;
+    };
+    validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema2, options, ctx) {
+      if (typeof schema2.exclusiveMinimum === "boolean") return;
+      if (!this.types.number(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var valid3 = instance > schema2.exclusiveMinimum;
+      if (!valid3) {
+        result.addError({
+          name: "exclusiveMinimum",
+          argument: schema2.exclusiveMinimum,
+          message: "must be strictly greater than " + schema2.exclusiveMinimum
+        });
+      }
+      return result;
+    };
+    validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema2, options, ctx) {
+      if (typeof schema2.exclusiveMaximum === "boolean") return;
+      if (!this.types.number(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var valid3 = instance < schema2.exclusiveMaximum;
+      if (!valid3) {
+        result.addError({
+          name: "exclusiveMaximum",
+          argument: schema2.exclusiveMaximum,
+          message: "must be strictly less than " + schema2.exclusiveMaximum
+        });
+      }
+      return result;
+    };
+    var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema2, options, ctx, validationType, errorMessage) {
+      if (!this.types.number(instance)) return;
+      var validationArgument = schema2[validationType];
+      if (validationArgument == 0) {
+        throw new SchemaError(validationType + " cannot be zero");
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var instanceDecimals = helpers.getDecimalPlaces(instance);
+      var divisorDecimals = helpers.getDecimalPlaces(validationArgument);
+      var maxDecimals = Math.max(instanceDecimals, divisorDecimals);
+      var multiplier = Math.pow(10, maxDecimals);
+      if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) {
+        result.addError({
+          name: validationType,
+          argument: validationArgument,
+          message: errorMessage + JSON.stringify(validationArgument)
+        });
+      }
+      return result;
+    };
+    validators.multipleOf = function validateMultipleOf(instance, schema2, options, ctx) {
+      return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "multipleOf", "is not a multiple of (divisible by) ");
+    };
+    validators.divisibleBy = function validateDivisibleBy(instance, schema2, options, ctx) {
+      return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "divisibleBy", "is not divisible by (multiple of) ");
+    };
+    validators.required = function validateRequired(instance, schema2, options, ctx) {
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (instance === void 0 && schema2.required === true) {
+        result.addError({
+          name: "required",
+          message: "is required"
+        });
+      } else if (this.types.object(instance) && Array.isArray(schema2.required)) {
+        schema2.required.forEach(function(n) {
+          if (getEnumerableProperty(instance, n) === void 0) {
+            result.addError({
+              name: "required",
+              argument: n,
+              message: "requires property " + JSON.stringify(n)
             });
           }
-        }
-      };
-    }
-    function _garbageCollector() {
-      if (!_gracefulCleanup) return;
-      while (_removeObjects.length) {
-        try {
-          _removeObjects[0]();
-        } catch (e) {
-        }
+        });
       }
-    }
-    function _randomChars(howMany) {
-      let value = [], rnd = null;
+      return result;
+    };
+    validators.pattern = function validatePattern(instance, schema2, options, ctx) {
+      if (!this.types.string(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var pattern = schema2.pattern;
       try {
-        rnd = crypto.randomBytes(howMany);
-      } catch (e) {
-        rnd = crypto.pseudoRandomBytes(howMany);
+        var regexp = new RegExp(pattern, "u");
+      } catch (_e) {
+        regexp = new RegExp(pattern);
       }
-      for (let i = 0; i < howMany; i++) {
-        value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);
+      if (!instance.match(regexp)) {
+        result.addError({
+          name: "pattern",
+          argument: schema2.pattern,
+          message: "does not match pattern " + JSON.stringify(schema2.pattern.toString())
+        });
       }
-      return value.join("");
-    }
-    function _isUndefined(obj) {
-      return typeof obj === "undefined";
-    }
-    function _parseArguments(options, callback) {
-      if (typeof options === "function") {
-        return [{}, options];
+      return result;
+    };
+    validators.format = function validateFormat(instance, schema2, options, ctx) {
+      if (instance === void 0) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!result.disableFormat && !helpers.isFormat(instance, schema2.format, this)) {
+        result.addError({
+          name: "format",
+          argument: schema2.format,
+          message: "does not conform to the " + JSON.stringify(schema2.format) + " format"
+        });
       }
-      if (_isUndefined(options)) {
-        return [{}, callback];
+      return result;
+    };
+    validators.minLength = function validateMinLength(instance, schema2, options, ctx) {
+      if (!this.types.string(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var hsp = instance.match(/[\uDC00-\uDFFF]/g);
+      var length = instance.length - (hsp ? hsp.length : 0);
+      if (!(length >= schema2.minLength)) {
+        result.addError({
+          name: "minLength",
+          argument: schema2.minLength,
+          message: "does not meet minimum length of " + schema2.minLength
+        });
       }
-      const actualOptions = {};
-      for (const key of Object.getOwnPropertyNames(options)) {
-        actualOptions[key] = options[key];
+      return result;
+    };
+    validators.maxLength = function validateMaxLength(instance, schema2, options, ctx) {
+      if (!this.types.string(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var hsp = instance.match(/[\uDC00-\uDFFF]/g);
+      var length = instance.length - (hsp ? hsp.length : 0);
+      if (!(length <= schema2.maxLength)) {
+        result.addError({
+          name: "maxLength",
+          argument: schema2.maxLength,
+          message: "does not meet maximum length of " + schema2.maxLength
+        });
       }
-      return [actualOptions, callback];
+      return result;
+    };
+    validators.minItems = function validateMinItems(instance, schema2, options, ctx) {
+      if (!this.types.array(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!(instance.length >= schema2.minItems)) {
+        result.addError({
+          name: "minItems",
+          argument: schema2.minItems,
+          message: "does not meet minimum length of " + schema2.minItems
+        });
+      }
+      return result;
+    };
+    validators.maxItems = function validateMaxItems(instance, schema2, options, ctx) {
+      if (!this.types.array(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!(instance.length <= schema2.maxItems)) {
+        result.addError({
+          name: "maxItems",
+          argument: schema2.maxItems,
+          message: "does not meet maximum length of " + schema2.maxItems
+        });
+      }
+      return result;
+    };
+    function testArrays(v, i, a) {
+      var j, len = a.length;
+      for (j = i + 1, len; j < len; j++) {
+        if (helpers.deepCompareStrict(v, a[j])) {
+          return false;
+        }
+      }
+      return true;
     }
-    function _resolvePath(name, tmpDir, cb) {
-      const pathToResolve = path2.isAbsolute(name) ? name : path2.join(tmpDir, name);
-      fs2.stat(pathToResolve, function(err) {
-        if (err) {
-          fs2.realpath(path2.dirname(pathToResolve), function(err2, parentDir) {
-            if (err2) return cb(err2);
-            cb(null, path2.join(parentDir, path2.basename(pathToResolve)));
+    validators.uniqueItems = function validateUniqueItems(instance, schema2, options, ctx) {
+      if (schema2.uniqueItems !== true) return;
+      if (!this.types.array(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!instance.every(testArrays)) {
+        result.addError({
+          name: "uniqueItems",
+          message: "contains duplicate item"
+        });
+      }
+      return result;
+    };
+    validators.dependencies = function validateDependencies(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      for (var property in schema2.dependencies) {
+        if (instance[property] === void 0) {
+          continue;
+        }
+        var dep = schema2.dependencies[property];
+        var childContext = ctx.makeChild(dep, property);
+        if (typeof dep == "string") {
+          dep = [dep];
+        }
+        if (Array.isArray(dep)) {
+          dep.forEach(function(prop) {
+            if (instance[prop] === void 0) {
+              result.addError({
+                // FIXME there's two different "dependencies" errors here with slightly different outputs
+                // Can we make these the same? Or should we create different error types?
+                name: "dependencies",
+                argument: childContext.propertyPath,
+                message: "property " + prop + " not found, required by " + childContext.propertyPath
+              });
+            }
           });
         } else {
-          fs2.realpath(path2, cb);
+          var res = this.validateSchema(instance, dep, options, childContext);
+          if (result.instance !== res.instance) result.instance = res.instance;
+          if (res && res.errors.length) {
+            result.addError({
+              name: "dependencies",
+              argument: childContext.propertyPath,
+              message: "does not meet dependency required by " + childContext.propertyPath
+            });
+            result.importErrors(res);
+          }
         }
-      });
-    }
-    function _resolvePathSync(name, tmpDir) {
-      const pathToResolve = path2.isAbsolute(name) ? name : path2.join(tmpDir, name);
-      try {
-        fs2.statSync(pathToResolve);
-        return fs2.realpathSync(pathToResolve);
-      } catch (_err) {
-        const parentDir = fs2.realpathSync(path2.dirname(pathToResolve));
-        return path2.join(parentDir, path2.basename(pathToResolve));
       }
-    }
-    function _generateTmpName(opts) {
-      const tmpDir = opts.tmpdir;
-      if (!_isUndefined(opts.name)) {
-        return path2.join(tmpDir, opts.dir, opts.name);
+      return result;
+    };
+    validators["enum"] = function validateEnum(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
       }
-      if (!_isUndefined(opts.template)) {
-        return path2.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6));
+      if (!Array.isArray(schema2["enum"])) {
+        throw new SchemaError("enum expects an array", schema2);
       }
-      const name = [
-        opts.prefix ? opts.prefix : "tmp",
-        "-",
-        process.pid,
-        "-",
-        _randomChars(12),
-        opts.postfix ? "-" + opts.postfix : ""
-      ].join("");
-      return path2.join(tmpDir, opts.dir, name);
-    }
-    function _assertOptionsBase(options) {
-      if (!_isUndefined(options.name)) {
-        const name = options.name;
-        if (path2.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`);
-        const basename = path2.basename(name);
-        if (basename === ".." || basename === "." || basename !== name)
-          throw new Error(`name option must not contain a path, found "${name}".`);
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!schema2["enum"].some(helpers.deepCompareStrict.bind(null, instance))) {
+        result.addError({
+          name: "enum",
+          argument: schema2["enum"],
+          message: "is not one of enum values: " + schema2["enum"].map(String).join(",")
+        });
       }
-      if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) {
-        throw new Error(`Invalid template, found "${options.template}".`);
+      return result;
+    };
+    validators["const"] = function validateEnum(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
       }
-      if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) {
-        throw new Error(`Invalid tries, found "${options.tries}".`);
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!helpers.deepCompareStrict(schema2["const"], instance)) {
+        result.addError({
+          name: "const",
+          argument: schema2["const"],
+          message: "does not exactly match expected constant: " + schema2["const"]
+        });
       }
-      options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1;
-      options.keep = !!options.keep;
-      options.detachDescriptor = !!options.detachDescriptor;
-      options.discardDescriptor = !!options.discardDescriptor;
-      options.unsafeCleanup = !!options.unsafeCleanup;
-      options.prefix = _isUndefined(options.prefix) ? "" : options.prefix;
-      options.postfix = _isUndefined(options.postfix) ? "" : options.postfix;
-    }
-    function _getRelativePath(option, name, tmpDir, cb) {
-      if (_isUndefined(name)) return cb(null);
-      _resolvePath(name, tmpDir, function(err, resolvedPath) {
-        if (err) return cb(err);
-        const relativePath = path2.relative(tmpDir, resolvedPath);
-        if (!resolvedPath.startsWith(tmpDir)) {
-          return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`));
+      return result;
+    };
+    validators.not = validators.disallow = function validateNot(instance, schema2, options, ctx) {
+      var self2 = this;
+      if (instance === void 0) return null;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var notTypes = schema2.not || schema2.disallow;
+      if (!notTypes) return null;
+      if (!Array.isArray(notTypes)) notTypes = [notTypes];
+      notTypes.forEach(function(type2) {
+        if (self2.testType(instance, schema2, options, ctx, type2)) {
+          var id = type2 && (type2.$id || type2.id);
+          var schemaId = id || type2;
+          result.addError({
+            name: "not",
+            argument: schemaId,
+            message: "is of prohibited type " + schemaId
+          });
         }
-        cb(null, relativePath);
       });
+      return result;
+    };
+    module2.exports = attribute;
+  }
+});
+
+// node_modules/jsonschema/lib/scan.js
+var require_scan = __commonJS({
+  "node_modules/jsonschema/lib/scan.js"(exports2, module2) {
+    "use strict";
+    var urilib = require("url");
+    var helpers = require_helpers3();
+    module2.exports.SchemaScanResult = SchemaScanResult;
+    function SchemaScanResult(found, ref) {
+      this.id = found;
+      this.ref = ref;
     }
-    function _getRelativePathSync(option, name, tmpDir) {
-      if (_isUndefined(name)) return;
-      const resolvedPath = _resolvePathSync(name, tmpDir);
-      const relativePath = path2.relative(tmpDir, resolvedPath);
-      if (!resolvedPath.startsWith(tmpDir)) {
-        throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`);
+    module2.exports.scan = function scan(base, schema2) {
+      function scanSchema(baseuri, schema3) {
+        if (!schema3 || typeof schema3 != "object") return;
+        if (schema3.$ref) {
+          var resolvedUri = urilib.resolve(baseuri, schema3.$ref);
+          ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0;
+          return;
+        }
+        var id = schema3.$id || schema3.id;
+        var ourBase = id ? urilib.resolve(baseuri, id) : baseuri;
+        if (ourBase) {
+          if (ourBase.indexOf("#") < 0) ourBase += "#";
+          if (found[ourBase]) {
+            if (!helpers.deepCompareStrict(found[ourBase], schema3)) {
+              throw new Error("Schema <" + ourBase + "> already exists with different definition");
+            }
+            return found[ourBase];
+          }
+          found[ourBase] = schema3;
+          if (ourBase[ourBase.length - 1] == "#") {
+            found[ourBase.substring(0, ourBase.length - 1)] = schema3;
+          }
+        }
+        scanArray(ourBase + "/items", Array.isArray(schema3.items) ? schema3.items : [schema3.items]);
+        scanArray(ourBase + "/extends", Array.isArray(schema3.extends) ? schema3.extends : [schema3.extends]);
+        scanSchema(ourBase + "/additionalItems", schema3.additionalItems);
+        scanObject(ourBase + "/properties", schema3.properties);
+        scanSchema(ourBase + "/additionalProperties", schema3.additionalProperties);
+        scanObject(ourBase + "/definitions", schema3.definitions);
+        scanObject(ourBase + "/patternProperties", schema3.patternProperties);
+        scanObject(ourBase + "/dependencies", schema3.dependencies);
+        scanArray(ourBase + "/disallow", schema3.disallow);
+        scanArray(ourBase + "/allOf", schema3.allOf);
+        scanArray(ourBase + "/anyOf", schema3.anyOf);
+        scanArray(ourBase + "/oneOf", schema3.oneOf);
+        scanSchema(ourBase + "/not", schema3.not);
       }
-      return relativePath;
-    }
-    function _assertAndSanitizeOptions(options, cb) {
-      _getTmpDir(options, function(err, tmpDir) {
-        if (err) return cb(err);
-        options.tmpdir = tmpDir;
-        try {
-          _assertOptionsBase(options, tmpDir);
-        } catch (err2) {
-          return cb(err2);
+      function scanArray(baseuri, schemas) {
+        if (!Array.isArray(schemas)) return;
+        for (var i = 0; i < schemas.length; i++) {
+          scanSchema(baseuri + "/" + i, schemas[i]);
         }
-        _getRelativePath("dir", options.dir, tmpDir, function(err2, dir2) {
-          if (err2) return cb(err2);
-          options.dir = _isUndefined(dir2) ? "" : dir2;
-          _getRelativePath("template", options.template, tmpDir, function(err3, template) {
-            if (err3) return cb(err3);
-            options.template = template;
-            cb(null, options);
-          });
-        });
-      });
-    }
-    function _assertAndSanitizeOptionsSync(options) {
-      const tmpDir = options.tmpdir = _getTmpDirSync(options);
-      _assertOptionsBase(options, tmpDir);
-      const dir2 = _getRelativePathSync("dir", options.dir, tmpDir);
-      options.dir = _isUndefined(dir2) ? "" : dir2;
-      options.template = _getRelativePathSync("template", options.template, tmpDir);
-      return options;
-    }
-    function _isEBADF(error4) {
-      return _isExpectedError(error4, -EBADF, "EBADF");
-    }
-    function _isENOENT(error4) {
-      return _isExpectedError(error4, -ENOENT, "ENOENT");
-    }
-    function _isExpectedError(error4, errno, code) {
-      return IS_WIN32 ? error4.code === code : error4.code === code && error4.errno === errno;
-    }
-    function setGracefulCleanup() {
-      _gracefulCleanup = true;
-    }
-    function _getTmpDir(options, cb) {
-      return fs2.realpath(options && options.tmpdir || os.tmpdir(), cb);
-    }
-    function _getTmpDirSync(options) {
-      return fs2.realpathSync(options && options.tmpdir || os.tmpdir());
-    }
-    process.addListener(EXIT, _garbageCollector);
-    Object.defineProperty(module2.exports, "tmpdir", {
-      enumerable: true,
-      configurable: false,
-      get: function() {
-        return _getTmpDirSync();
       }
-    });
-    module2.exports.dir = dir;
-    module2.exports.dirSync = dirSync;
-    module2.exports.file = file;
-    module2.exports.fileSync = fileSync;
-    module2.exports.tmpName = tmpName;
-    module2.exports.tmpNameSync = tmpNameSync;
-    module2.exports.setGracefulCleanup = setGracefulCleanup;
+      function scanObject(baseuri, schemas) {
+        if (!schemas || typeof schemas != "object") return;
+        for (var p in schemas) {
+          scanSchema(baseuri + "/" + p, schemas[p]);
+        }
+      }
+      var found = {};
+      var ref = {};
+      scanSchema(base, schema2);
+      return new SchemaScanResult(found, ref);
+    };
   }
 });
 
-// node_modules/tmp-promise/index.js
-var require_tmp_promise = __commonJS({
-  "node_modules/tmp-promise/index.js"(exports2, module2) {
+// node_modules/jsonschema/lib/validator.js
+var require_validator2 = __commonJS({
+  "node_modules/jsonschema/lib/validator.js"(exports2, module2) {
     "use strict";
-    var { promisify } = require("util");
-    var tmp = require_tmp();
-    module2.exports.fileSync = tmp.fileSync;
-    var fileWithOptions = promisify(
-      (options, cb) => tmp.file(
-        options,
-        (err, path2, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path2, fd, cleanup: promisify(cleanup) })
-      )
-    );
-    module2.exports.file = async (options) => fileWithOptions(options);
-    module2.exports.withFile = async function withFile(fn, options) {
-      const { path: path2, fd, cleanup } = await module2.exports.file(options);
-      try {
-        return await fn({ path: path2, fd });
-      } finally {
-        await cleanup();
+    var urilib = require("url");
+    var attribute = require_attribute();
+    var helpers = require_helpers3();
+    var scanSchema = require_scan().scan;
+    var ValidatorResult = helpers.ValidatorResult;
+    var ValidatorResultError = helpers.ValidatorResultError;
+    var SchemaError = helpers.SchemaError;
+    var SchemaContext = helpers.SchemaContext;
+    var anonymousBase = "/";
+    var Validator2 = function Validator3() {
+      this.customFormats = Object.create(Validator3.prototype.customFormats);
+      this.schemas = {};
+      this.unresolvedRefs = [];
+      this.types = Object.create(types);
+      this.attributes = Object.create(attribute.validators);
+    };
+    Validator2.prototype.customFormats = {};
+    Validator2.prototype.schemas = null;
+    Validator2.prototype.types = null;
+    Validator2.prototype.attributes = null;
+    Validator2.prototype.unresolvedRefs = null;
+    Validator2.prototype.addSchema = function addSchema(schema2, base) {
+      var self2 = this;
+      if (!schema2) {
+        return null;
+      }
+      var scan = scanSchema(base || anonymousBase, schema2);
+      var ourUri = base || schema2.$id || schema2.id;
+      for (var uri in scan.id) {
+        this.schemas[uri] = scan.id[uri];
       }
+      for (var uri in scan.ref) {
+        this.unresolvedRefs.push(uri);
+      }
+      this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) {
+        return typeof self2.schemas[uri2] === "undefined";
+      });
+      return this.schemas[ourUri];
     };
-    module2.exports.dirSync = tmp.dirSync;
-    var dirWithOptions = promisify(
-      (options, cb) => tmp.dir(
-        options,
-        (err, path2, cleanup) => err ? cb(err) : cb(void 0, { path: path2, cleanup: promisify(cleanup) })
-      )
-    );
-    module2.exports.dir = async (options) => dirWithOptions(options);
-    module2.exports.withDir = async function withDir(fn, options) {
-      const { path: path2, cleanup } = await module2.exports.dir(options);
-      try {
-        return await fn({ path: path2 });
-      } finally {
-        await cleanup();
+    Validator2.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) {
+      if (!Array.isArray(schemas)) return;
+      for (var i = 0; i < schemas.length; i++) {
+        this.addSubSchema(baseuri, schemas[i]);
       }
     };
-    module2.exports.tmpNameSync = tmp.tmpNameSync;
-    module2.exports.tmpName = promisify(tmp.tmpName);
-    module2.exports.tmpdir = tmp.tmpdir;
-    module2.exports.setGracefulCleanup = tmp.setGracefulCleanup;
-  }
-});
-
-// node_modules/@actions/artifact-legacy/lib/internal/config-variables.js
-var require_config_variables = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/config-variables.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.isGhes = exports2.getRetentionDays = exports2.getWorkSpaceDirectory = exports2.getWorkFlowRunId = exports2.getRuntimeUrl = exports2.getRuntimeToken = exports2.getDownloadFileConcurrency = exports2.getInitialRetryIntervalInMilliseconds = exports2.getRetryMultiplier = exports2.getRetryLimit = exports2.getUploadChunkSize = exports2.getUploadFileConcurrency = void 0;
-    function getUploadFileConcurrency() {
-      return 2;
-    }
-    exports2.getUploadFileConcurrency = getUploadFileConcurrency;
-    function getUploadChunkSize() {
-      return 8 * 1024 * 1024;
-    }
-    exports2.getUploadChunkSize = getUploadChunkSize;
-    function getRetryLimit() {
-      return 5;
-    }
-    exports2.getRetryLimit = getRetryLimit;
-    function getRetryMultiplier() {
-      return 1.5;
-    }
-    exports2.getRetryMultiplier = getRetryMultiplier;
-    function getInitialRetryIntervalInMilliseconds() {
-      return 3e3;
-    }
-    exports2.getInitialRetryIntervalInMilliseconds = getInitialRetryIntervalInMilliseconds;
-    function getDownloadFileConcurrency() {
-      return 2;
-    }
-    exports2.getDownloadFileConcurrency = getDownloadFileConcurrency;
-    function getRuntimeToken() {
-      const token = process.env["ACTIONS_RUNTIME_TOKEN"];
-      if (!token) {
-        throw new Error("Unable to get ACTIONS_RUNTIME_TOKEN env variable");
+    Validator2.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) {
+      if (!schemas || typeof schemas != "object") return;
+      for (var p in schemas) {
+        this.addSubSchema(baseuri, schemas[p]);
       }
-      return token;
-    }
-    exports2.getRuntimeToken = getRuntimeToken;
-    function getRuntimeUrl() {
-      const runtimeUrl = process.env["ACTIONS_RUNTIME_URL"];
-      if (!runtimeUrl) {
-        throw new Error("Unable to get ACTIONS_RUNTIME_URL env variable");
+    };
+    Validator2.prototype.setSchemas = function setSchemas(schemas) {
+      this.schemas = schemas;
+    };
+    Validator2.prototype.getSchema = function getSchema(urn) {
+      return this.schemas[urn];
+    };
+    Validator2.prototype.validate = function validate(instance, schema2, options, ctx) {
+      if (typeof schema2 !== "boolean" && typeof schema2 !== "object" || schema2 === null) {
+        throw new SchemaError("Expected `schema` to be an object or boolean");
       }
-      return runtimeUrl;
-    }
-    exports2.getRuntimeUrl = getRuntimeUrl;
-    function getWorkFlowRunId() {
-      const workFlowRunId = process.env["GITHUB_RUN_ID"];
-      if (!workFlowRunId) {
-        throw new Error("Unable to get GITHUB_RUN_ID env variable");
+      if (!options) {
+        options = {};
       }
-      return workFlowRunId;
-    }
-    exports2.getWorkFlowRunId = getWorkFlowRunId;
-    function getWorkSpaceDirectory() {
-      const workspaceDirectory = process.env["GITHUB_WORKSPACE"];
-      if (!workspaceDirectory) {
-        throw new Error("Unable to get GITHUB_WORKSPACE env variable");
+      var id = schema2.$id || schema2.id;
+      var base = urilib.resolve(options.base || anonymousBase, id || "");
+      if (!ctx) {
+        ctx = new SchemaContext(schema2, options, [], base, Object.create(this.schemas));
+        if (!ctx.schemas[base]) {
+          ctx.schemas[base] = schema2;
+        }
+        var found = scanSchema(base, schema2);
+        for (var n in found.id) {
+          var sch = found.id[n];
+          ctx.schemas[n] = sch;
+        }
       }
-      return workspaceDirectory;
-    }
-    exports2.getWorkSpaceDirectory = getWorkSpaceDirectory;
-    function getRetentionDays() {
-      return process.env["GITHUB_RETENTION_DAYS"];
-    }
-    exports2.getRetentionDays = getRetentionDays;
-    function isGhes() {
-      const ghUrl = new URL(process.env["GITHUB_SERVER_URL"] || "https://github.com");
-      return ghUrl.hostname.toUpperCase() !== "GITHUB.COM";
+      if (options.required && instance === void 0) {
+        var result = new ValidatorResult(instance, schema2, options, ctx);
+        result.addError("is required, but is undefined");
+        return result;
+      }
+      var result = this.validateSchema(instance, schema2, options, ctx);
+      if (!result) {
+        throw new Error("Result undefined");
+      } else if (options.throwAll && result.errors.length) {
+        throw new ValidatorResultError(result);
+      }
+      return result;
+    };
+    function shouldResolve(schema2) {
+      var ref = typeof schema2 === "string" ? schema2 : schema2.$ref;
+      if (typeof ref == "string") return ref;
+      return false;
     }
-    exports2.isGhes = isGhes;
-  }
-});
-
-// node_modules/@actions/artifact-legacy/lib/internal/crc64.js
-var require_crc64 = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/crc64.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    var PREGEN_POLY_TABLE = [
-      BigInt("0x0000000000000000"),
-      BigInt("0x7F6EF0C830358979"),
-      BigInt("0xFEDDE190606B12F2"),
-      BigInt("0x81B31158505E9B8B"),
-      BigInt("0xC962E5739841B68F"),
-      BigInt("0xB60C15BBA8743FF6"),
-      BigInt("0x37BF04E3F82AA47D"),
-      BigInt("0x48D1F42BC81F2D04"),
-      BigInt("0xA61CECB46814FE75"),
-      BigInt("0xD9721C7C5821770C"),
-      BigInt("0x58C10D24087FEC87"),
-      BigInt("0x27AFFDEC384A65FE"),
-      BigInt("0x6F7E09C7F05548FA"),
-      BigInt("0x1010F90FC060C183"),
-      BigInt("0x91A3E857903E5A08"),
-      BigInt("0xEECD189FA00BD371"),
-      BigInt("0x78E0FF3B88BE6F81"),
-      BigInt("0x078E0FF3B88BE6F8"),
-      BigInt("0x863D1EABE8D57D73"),
-      BigInt("0xF953EE63D8E0F40A"),
-      BigInt("0xB1821A4810FFD90E"),
-      BigInt("0xCEECEA8020CA5077"),
-      BigInt("0x4F5FFBD87094CBFC"),
-      BigInt("0x30310B1040A14285"),
-      BigInt("0xDEFC138FE0AA91F4"),
-      BigInt("0xA192E347D09F188D"),
-      BigInt("0x2021F21F80C18306"),
-      BigInt("0x5F4F02D7B0F40A7F"),
-      BigInt("0x179EF6FC78EB277B"),
-      BigInt("0x68F0063448DEAE02"),
-      BigInt("0xE943176C18803589"),
-      BigInt("0x962DE7A428B5BCF0"),
-      BigInt("0xF1C1FE77117CDF02"),
-      BigInt("0x8EAF0EBF2149567B"),
-      BigInt("0x0F1C1FE77117CDF0"),
-      BigInt("0x7072EF2F41224489"),
-      BigInt("0x38A31B04893D698D"),
-      BigInt("0x47CDEBCCB908E0F4"),
-      BigInt("0xC67EFA94E9567B7F"),
-      BigInt("0xB9100A5CD963F206"),
-      BigInt("0x57DD12C379682177"),
-      BigInt("0x28B3E20B495DA80E"),
-      BigInt("0xA900F35319033385"),
-      BigInt("0xD66E039B2936BAFC"),
-      BigInt("0x9EBFF7B0E12997F8"),
-      BigInt("0xE1D10778D11C1E81"),
-      BigInt("0x606216208142850A"),
-      BigInt("0x1F0CE6E8B1770C73"),
-      BigInt("0x8921014C99C2B083"),
-      BigInt("0xF64FF184A9F739FA"),
-      BigInt("0x77FCE0DCF9A9A271"),
-      BigInt("0x08921014C99C2B08"),
-      BigInt("0x4043E43F0183060C"),
-      BigInt("0x3F2D14F731B68F75"),
-      BigInt("0xBE9E05AF61E814FE"),
-      BigInt("0xC1F0F56751DD9D87"),
-      BigInt("0x2F3DEDF8F1D64EF6"),
-      BigInt("0x50531D30C1E3C78F"),
-      BigInt("0xD1E00C6891BD5C04"),
-      BigInt("0xAE8EFCA0A188D57D"),
-      BigInt("0xE65F088B6997F879"),
-      BigInt("0x9931F84359A27100"),
-      BigInt("0x1882E91B09FCEA8B"),
-      BigInt("0x67EC19D339C963F2"),
-      BigInt("0xD75ADABD7A6E2D6F"),
-      BigInt("0xA8342A754A5BA416"),
-      BigInt("0x29873B2D1A053F9D"),
-      BigInt("0x56E9CBE52A30B6E4"),
-      BigInt("0x1E383FCEE22F9BE0"),
-      BigInt("0x6156CF06D21A1299"),
-      BigInt("0xE0E5DE5E82448912"),
-      BigInt("0x9F8B2E96B271006B"),
-      BigInt("0x71463609127AD31A"),
-      BigInt("0x0E28C6C1224F5A63"),
-      BigInt("0x8F9BD7997211C1E8"),
-      BigInt("0xF0F5275142244891"),
-      BigInt("0xB824D37A8A3B6595"),
-      BigInt("0xC74A23B2BA0EECEC"),
-      BigInt("0x46F932EAEA507767"),
-      BigInt("0x3997C222DA65FE1E"),
-      BigInt("0xAFBA2586F2D042EE"),
-      BigInt("0xD0D4D54EC2E5CB97"),
-      BigInt("0x5167C41692BB501C"),
-      BigInt("0x2E0934DEA28ED965"),
-      BigInt("0x66D8C0F56A91F461"),
-      BigInt("0x19B6303D5AA47D18"),
-      BigInt("0x980521650AFAE693"),
-      BigInt("0xE76BD1AD3ACF6FEA"),
-      BigInt("0x09A6C9329AC4BC9B"),
-      BigInt("0x76C839FAAAF135E2"),
-      BigInt("0xF77B28A2FAAFAE69"),
-      BigInt("0x8815D86ACA9A2710"),
-      BigInt("0xC0C42C4102850A14"),
-      BigInt("0xBFAADC8932B0836D"),
-      BigInt("0x3E19CDD162EE18E6"),
-      BigInt("0x41773D1952DB919F"),
-      BigInt("0x269B24CA6B12F26D"),
-      BigInt("0x59F5D4025B277B14"),
-      BigInt("0xD846C55A0B79E09F"),
-      BigInt("0xA72835923B4C69E6"),
-      BigInt("0xEFF9C1B9F35344E2"),
-      BigInt("0x90973171C366CD9B"),
-      BigInt("0x1124202993385610"),
-      BigInt("0x6E4AD0E1A30DDF69"),
-      BigInt("0x8087C87E03060C18"),
-      BigInt("0xFFE938B633338561"),
-      BigInt("0x7E5A29EE636D1EEA"),
-      BigInt("0x0134D92653589793"),
-      BigInt("0x49E52D0D9B47BA97"),
-      BigInt("0x368BDDC5AB7233EE"),
-      BigInt("0xB738CC9DFB2CA865"),
-      BigInt("0xC8563C55CB19211C"),
-      BigInt("0x5E7BDBF1E3AC9DEC"),
-      BigInt("0x21152B39D3991495"),
-      BigInt("0xA0A63A6183C78F1E"),
-      BigInt("0xDFC8CAA9B3F20667"),
-      BigInt("0x97193E827BED2B63"),
-      BigInt("0xE877CE4A4BD8A21A"),
-      BigInt("0x69C4DF121B863991"),
-      BigInt("0x16AA2FDA2BB3B0E8"),
-      BigInt("0xF86737458BB86399"),
-      BigInt("0x8709C78DBB8DEAE0"),
-      BigInt("0x06BAD6D5EBD3716B"),
-      BigInt("0x79D4261DDBE6F812"),
-      BigInt("0x3105D23613F9D516"),
-      BigInt("0x4E6B22FE23CC5C6F"),
-      BigInt("0xCFD833A67392C7E4"),
-      BigInt("0xB0B6C36E43A74E9D"),
-      BigInt("0x9A6C9329AC4BC9B5"),
-      BigInt("0xE50263E19C7E40CC"),
-      BigInt("0x64B172B9CC20DB47"),
-      BigInt("0x1BDF8271FC15523E"),
-      BigInt("0x530E765A340A7F3A"),
-      BigInt("0x2C608692043FF643"),
-      BigInt("0xADD397CA54616DC8"),
-      BigInt("0xD2BD67026454E4B1"),
-      BigInt("0x3C707F9DC45F37C0"),
-      BigInt("0x431E8F55F46ABEB9"),
-      BigInt("0xC2AD9E0DA4342532"),
-      BigInt("0xBDC36EC59401AC4B"),
-      BigInt("0xF5129AEE5C1E814F"),
-      BigInt("0x8A7C6A266C2B0836"),
-      BigInt("0x0BCF7B7E3C7593BD"),
-      BigInt("0x74A18BB60C401AC4"),
-      BigInt("0xE28C6C1224F5A634"),
-      BigInt("0x9DE29CDA14C02F4D"),
-      BigInt("0x1C518D82449EB4C6"),
-      BigInt("0x633F7D4A74AB3DBF"),
-      BigInt("0x2BEE8961BCB410BB"),
-      BigInt("0x548079A98C8199C2"),
-      BigInt("0xD53368F1DCDF0249"),
-      BigInt("0xAA5D9839ECEA8B30"),
-      BigInt("0x449080A64CE15841"),
-      BigInt("0x3BFE706E7CD4D138"),
-      BigInt("0xBA4D61362C8A4AB3"),
-      BigInt("0xC52391FE1CBFC3CA"),
-      BigInt("0x8DF265D5D4A0EECE"),
-      BigInt("0xF29C951DE49567B7"),
-      BigInt("0x732F8445B4CBFC3C"),
-      BigInt("0x0C41748D84FE7545"),
-      BigInt("0x6BAD6D5EBD3716B7"),
-      BigInt("0x14C39D968D029FCE"),
-      BigInt("0x95708CCEDD5C0445"),
-      BigInt("0xEA1E7C06ED698D3C"),
-      BigInt("0xA2CF882D2576A038"),
-      BigInt("0xDDA178E515432941"),
-      BigInt("0x5C1269BD451DB2CA"),
-      BigInt("0x237C997575283BB3"),
-      BigInt("0xCDB181EAD523E8C2"),
-      BigInt("0xB2DF7122E51661BB"),
-      BigInt("0x336C607AB548FA30"),
-      BigInt("0x4C0290B2857D7349"),
-      BigInt("0x04D364994D625E4D"),
-      BigInt("0x7BBD94517D57D734"),
-      BigInt("0xFA0E85092D094CBF"),
-      BigInt("0x856075C11D3CC5C6"),
-      BigInt("0x134D926535897936"),
-      BigInt("0x6C2362AD05BCF04F"),
-      BigInt("0xED9073F555E26BC4"),
-      BigInt("0x92FE833D65D7E2BD"),
-      BigInt("0xDA2F7716ADC8CFB9"),
-      BigInt("0xA54187DE9DFD46C0"),
-      BigInt("0x24F29686CDA3DD4B"),
-      BigInt("0x5B9C664EFD965432"),
-      BigInt("0xB5517ED15D9D8743"),
-      BigInt("0xCA3F8E196DA80E3A"),
-      BigInt("0x4B8C9F413DF695B1"),
-      BigInt("0x34E26F890DC31CC8"),
-      BigInt("0x7C339BA2C5DC31CC"),
-      BigInt("0x035D6B6AF5E9B8B5"),
-      BigInt("0x82EE7A32A5B7233E"),
-      BigInt("0xFD808AFA9582AA47"),
-      BigInt("0x4D364994D625E4DA"),
-      BigInt("0x3258B95CE6106DA3"),
-      BigInt("0xB3EBA804B64EF628"),
-      BigInt("0xCC8558CC867B7F51"),
-      BigInt("0x8454ACE74E645255"),
-      BigInt("0xFB3A5C2F7E51DB2C"),
-      BigInt("0x7A894D772E0F40A7"),
-      BigInt("0x05E7BDBF1E3AC9DE"),
-      BigInt("0xEB2AA520BE311AAF"),
-      BigInt("0x944455E88E0493D6"),
-      BigInt("0x15F744B0DE5A085D"),
-      BigInt("0x6A99B478EE6F8124"),
-      BigInt("0x224840532670AC20"),
-      BigInt("0x5D26B09B16452559"),
-      BigInt("0xDC95A1C3461BBED2"),
-      BigInt("0xA3FB510B762E37AB"),
-      BigInt("0x35D6B6AF5E9B8B5B"),
-      BigInt("0x4AB846676EAE0222"),
-      BigInt("0xCB0B573F3EF099A9"),
-      BigInt("0xB465A7F70EC510D0"),
-      BigInt("0xFCB453DCC6DA3DD4"),
-      BigInt("0x83DAA314F6EFB4AD"),
-      BigInt("0x0269B24CA6B12F26"),
-      BigInt("0x7D0742849684A65F"),
-      BigInt("0x93CA5A1B368F752E"),
-      BigInt("0xECA4AAD306BAFC57"),
-      BigInt("0x6D17BB8B56E467DC"),
-      BigInt("0x12794B4366D1EEA5"),
-      BigInt("0x5AA8BF68AECEC3A1"),
-      BigInt("0x25C64FA09EFB4AD8"),
-      BigInt("0xA4755EF8CEA5D153"),
-      BigInt("0xDB1BAE30FE90582A"),
-      BigInt("0xBCF7B7E3C7593BD8"),
-      BigInt("0xC399472BF76CB2A1"),
-      BigInt("0x422A5673A732292A"),
-      BigInt("0x3D44A6BB9707A053"),
-      BigInt("0x759552905F188D57"),
-      BigInt("0x0AFBA2586F2D042E"),
-      BigInt("0x8B48B3003F739FA5"),
-      BigInt("0xF42643C80F4616DC"),
-      BigInt("0x1AEB5B57AF4DC5AD"),
-      BigInt("0x6585AB9F9F784CD4"),
-      BigInt("0xE436BAC7CF26D75F"),
-      BigInt("0x9B584A0FFF135E26"),
-      BigInt("0xD389BE24370C7322"),
-      BigInt("0xACE74EEC0739FA5B"),
-      BigInt("0x2D545FB4576761D0"),
-      BigInt("0x523AAF7C6752E8A9"),
-      BigInt("0xC41748D84FE75459"),
-      BigInt("0xBB79B8107FD2DD20"),
-      BigInt("0x3ACAA9482F8C46AB"),
-      BigInt("0x45A459801FB9CFD2"),
-      BigInt("0x0D75ADABD7A6E2D6"),
-      BigInt("0x721B5D63E7936BAF"),
-      BigInt("0xF3A84C3BB7CDF024"),
-      BigInt("0x8CC6BCF387F8795D"),
-      BigInt("0x620BA46C27F3AA2C"),
-      BigInt("0x1D6554A417C62355"),
-      BigInt("0x9CD645FC4798B8DE"),
-      BigInt("0xE3B8B53477AD31A7"),
-      BigInt("0xAB69411FBFB21CA3"),
-      BigInt("0xD407B1D78F8795DA"),
-      BigInt("0x55B4A08FDFD90E51"),
-      BigInt("0x2ADA5047EFEC8728")
-    ];
-    var CRC64 = class _CRC64 {
-      constructor() {
-        this._crc = BigInt(0);
+    Validator2.prototype.validateSchema = function validateSchema(instance, schema2, options, ctx) {
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (typeof schema2 === "boolean") {
+        if (schema2 === true) {
+          schema2 = {};
+        } else if (schema2 === false) {
+          schema2 = { type: [] };
+        }
+      } else if (!schema2) {
+        throw new Error("schema is undefined");
       }
-      update(data) {
-        const buffer = typeof data === "string" ? Buffer.from(data) : data;
-        let crc = _CRC64.flip64Bits(this._crc);
-        for (const dataByte of buffer) {
-          const crcByte = Number(crc & BigInt(255));
-          crc = PREGEN_POLY_TABLE[crcByte ^ dataByte] ^ crc >> BigInt(8);
+      if (schema2["extends"]) {
+        if (Array.isArray(schema2["extends"])) {
+          var schemaobj = { schema: schema2, ctx };
+          schema2["extends"].forEach(this.schemaTraverser.bind(this, schemaobj));
+          schema2 = schemaobj.schema;
+          schemaobj.schema = null;
+          schemaobj.ctx = null;
+          schemaobj = null;
+        } else {
+          schema2 = helpers.deepMerge(schema2, this.superResolve(schema2["extends"], ctx));
         }
-        this._crc = _CRC64.flip64Bits(crc);
       }
-      digest(encoding) {
-        switch (encoding) {
-          case "hex":
-            return this._crc.toString(16).toUpperCase();
-          case "base64":
-            return this.toBuffer().toString("base64");
-          default:
-            return this.toBuffer();
+      var switchSchema = shouldResolve(schema2);
+      if (switchSchema) {
+        var resolved = this.resolve(schema2, switchSchema, ctx);
+        var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas);
+        return this.validateSchema(instance, resolved.subschema, options, subctx);
+      }
+      var skipAttributes = options && options.skipAttributes || [];
+      for (var key in schema2) {
+        if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) {
+          var validatorErr = null;
+          var validator = this.attributes[key];
+          if (validator) {
+            validatorErr = validator.call(this, instance, schema2, options, ctx);
+          } else if (options.allowUnknownAttributes === false) {
+            throw new SchemaError("Unsupported attribute: " + key, schema2);
+          }
+          if (validatorErr) {
+            result.importErrors(validatorErr);
+          }
         }
       }
-      toBuffer() {
-        return Buffer.from([0, 8, 16, 24, 32, 40, 48, 56].map((s) => Number(this._crc >> BigInt(s) & BigInt(255))));
+      if (typeof options.rewrite == "function") {
+        var value = options.rewrite.call(this, instance, schema2, options, ctx);
+        result.instance = value;
       }
-      static flip64Bits(n) {
-        return (BigInt(1) << BigInt(64)) - BigInt(1) - n;
+      return result;
+    };
+    Validator2.prototype.schemaTraverser = function schemaTraverser(schemaobj, s) {
+      schemaobj.schema = helpers.deepMerge(schemaobj.schema, this.superResolve(s, schemaobj.ctx));
+    };
+    Validator2.prototype.superResolve = function superResolve(schema2, ctx) {
+      var ref = shouldResolve(schema2);
+      if (ref) {
+        return this.resolve(schema2, ref, ctx).subschema;
+      }
+      return schema2;
+    };
+    Validator2.prototype.resolve = function resolve2(schema2, switchSchema, ctx) {
+      switchSchema = ctx.resolve(switchSchema);
+      if (ctx.schemas[switchSchema]) {
+        return { subschema: ctx.schemas[switchSchema], switchSchema };
+      }
+      var parsed = urilib.parse(switchSchema);
+      var fragment = parsed && parsed.hash;
+      var document2 = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length);
+      if (!document2 || !ctx.schemas[document2]) {
+        throw new SchemaError("no such schema <" + switchSchema + ">", schema2);
+      }
+      var subschema = helpers.objectGetPath(ctx.schemas[document2], fragment.substr(1));
+      if (subschema === void 0) {
+        throw new SchemaError("no such schema " + fragment + " located in <" + document2 + ">", schema2);
+      }
+      return { subschema, switchSchema };
+    };
+    Validator2.prototype.testType = function validateType(instance, schema2, options, ctx, type2) {
+      if (type2 === void 0) {
+        return;
+      } else if (type2 === null) {
+        throw new SchemaError('Unexpected null in "type" keyword');
+      }
+      if (typeof this.types[type2] == "function") {
+        return this.types[type2].call(this, instance);
+      }
+      if (type2 && typeof type2 == "object") {
+        var res = this.validateSchema(instance, type2, options, ctx);
+        return res === void 0 || !(res && res.errors.length);
       }
+      return true;
+    };
+    var types = Validator2.prototype.types = {};
+    types.string = function testString(instance) {
+      return typeof instance == "string";
+    };
+    types.number = function testNumber(instance) {
+      return typeof instance == "number" && isFinite(instance);
+    };
+    types.integer = function testInteger(instance) {
+      return typeof instance == "number" && instance % 1 === 0;
+    };
+    types.boolean = function testBoolean(instance) {
+      return typeof instance == "boolean";
+    };
+    types.array = function testArray(instance) {
+      return Array.isArray(instance);
+    };
+    types["null"] = function testNull(instance) {
+      return instance === null;
+    };
+    types.date = function testDate(instance) {
+      return instance instanceof Date;
     };
-    exports2.default = CRC64;
+    types.any = function testAny(instance) {
+      return true;
+    };
+    types.object = function testObject(instance) {
+      return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date);
+    };
+    module2.exports = Validator2;
   }
 });
 
-// node_modules/@actions/artifact-legacy/lib/internal/utils.js
-var require_utils7 = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/utils.js"(exports2) {
+// node_modules/jsonschema/lib/index.js
+var require_lib6 = __commonJS({
+  "node_modules/jsonschema/lib/index.js"(exports2, module2) {
     "use strict";
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
+    var Validator2 = module2.exports.Validator = require_validator2();
+    module2.exports.ValidatorResult = require_helpers3().ValidatorResult;
+    module2.exports.ValidatorResultError = require_helpers3().ValidatorResultError;
+    module2.exports.ValidationError = require_helpers3().ValidationError;
+    module2.exports.SchemaError = require_helpers3().SchemaError;
+    module2.exports.SchemaScanResult = require_scan().SchemaScanResult;
+    module2.exports.scan = require_scan().scan;
+    module2.exports.validate = function(instance, schema2, options) {
+      var v = new Validator2();
+      return v.validate(instance, schema2, options);
+    };
+  }
+});
+
+// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-glob-options-helper.js
+var require_internal_glob_options_helper = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-glob-options-helper.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      Object.defineProperty(o, k2, { enumerable: true, get: function() {
+        return m[k];
+      } });
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getOptions = void 0;
+    var core14 = __importStar4(require_core());
+    function getOptions(copy) {
+      const result = {
+        followSymbolicLinks: true,
+        implicitDescendants: true,
+        omitBrokenSymbolicLinks: true
+      };
+      if (copy) {
+        if (typeof copy.followSymbolicLinks === "boolean") {
+          result.followSymbolicLinks = copy.followSymbolicLinks;
+          core14.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`);
         }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
+        if (typeof copy.implicitDescendants === "boolean") {
+          result.implicitDescendants = copy.implicitDescendants;
+          core14.debug(`implicitDescendants '${result.implicitDescendants}'`);
         }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        if (typeof copy.omitBrokenSymbolicLinks === "boolean") {
+          result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks;
+          core14.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`);
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
+      }
+      return result;
+    }
+    exports2.getOptions = getOptions;
+  }
+});
+
+// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path-helper.js
+var require_internal_path_helper = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path-helper.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      Object.defineProperty(o, k2, { enumerable: true, get: function() {
+        return m[k];
+      } });
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
     };
     var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
       return mod && mod.__esModule ? mod : { "default": mod };
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.digestForStream = exports2.sleep = exports2.getProperRetention = exports2.rmFile = exports2.getFileSize = exports2.createEmptyFilesForArtifact = exports2.createDirectoriesForArtifact = exports2.displayHttpDiagnostics = exports2.getArtifactUrl = exports2.createHttpClient = exports2.getUploadHeaders = exports2.getDownloadHeaders = exports2.getContentRange = exports2.tryGetRetryAfterValueTimeInMilliseconds = exports2.isThrottledStatusCode = exports2.isRetryableStatusCode = exports2.isForbiddenStatusCode = exports2.isSuccessStatusCode = exports2.getApiVersion = exports2.parseEnvNumber = exports2.getExponentialRetryTimeInMilliseconds = void 0;
-    var crypto_1 = __importDefault4(require("crypto"));
-    var fs_1 = require("fs");
-    var core_1 = require_core();
-    var http_client_1 = require_lib();
-    var auth_1 = require_auth();
-    var config_variables_1 = require_config_variables();
-    var crc64_1 = __importDefault4(require_crc64());
-    function getExponentialRetryTimeInMilliseconds(retryCount) {
-      if (retryCount < 0) {
-        throw new Error("RetryCount should not be negative");
-      } else if (retryCount === 0) {
-        return (0, config_variables_1.getInitialRetryIntervalInMilliseconds)();
-      }
-      const minTime = (0, config_variables_1.getInitialRetryIntervalInMilliseconds)() * (0, config_variables_1.getRetryMultiplier)() * retryCount;
-      const maxTime = minTime * (0, config_variables_1.getRetryMultiplier)();
-      return Math.trunc(Math.random() * (maxTime - minTime) + minTime);
-    }
-    exports2.getExponentialRetryTimeInMilliseconds = getExponentialRetryTimeInMilliseconds;
-    function parseEnvNumber(key) {
-      const value = Number(process.env[key]);
-      if (Number.isNaN(value) || value < 0) {
-        return void 0;
-      }
-      return value;
-    }
-    exports2.parseEnvNumber = parseEnvNumber;
-    function getApiVersion() {
-      return "6.0-preview";
-    }
-    exports2.getApiVersion = getApiVersion;
-    function isSuccessStatusCode(statusCode) {
-      if (!statusCode) {
-        return false;
-      }
-      return statusCode >= 200 && statusCode < 300;
-    }
-    exports2.isSuccessStatusCode = isSuccessStatusCode;
-    function isForbiddenStatusCode(statusCode) {
-      if (!statusCode) {
-        return false;
+    exports2.safeTrimTrailingSeparator = exports2.normalizeSeparators = exports2.hasRoot = exports2.hasAbsoluteRoot = exports2.ensureAbsoluteRoot = exports2.dirname = void 0;
+    var path2 = __importStar4(require("path"));
+    var assert_1 = __importDefault4(require("assert"));
+    var IS_WINDOWS = process.platform === "win32";
+    function dirname(p) {
+      p = safeTrimTrailingSeparator(p);
+      if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) {
+        return p;
       }
-      return statusCode === http_client_1.HttpCodes.Forbidden;
-    }
-    exports2.isForbiddenStatusCode = isForbiddenStatusCode;
-    function isRetryableStatusCode(statusCode) {
-      if (!statusCode) {
-        return false;
+      let result = path2.dirname(p);
+      if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) {
+        result = safeTrimTrailingSeparator(result);
       }
-      const retryableStatusCodes = [
-        http_client_1.HttpCodes.BadGateway,
-        http_client_1.HttpCodes.GatewayTimeout,
-        http_client_1.HttpCodes.InternalServerError,
-        http_client_1.HttpCodes.ServiceUnavailable,
-        http_client_1.HttpCodes.TooManyRequests,
-        413
-        // Payload Too Large
-      ];
-      return retryableStatusCodes.includes(statusCode);
+      return result;
     }
-    exports2.isRetryableStatusCode = isRetryableStatusCode;
-    function isThrottledStatusCode(statusCode) {
-      if (!statusCode) {
-        return false;
+    exports2.dirname = dirname;
+    function ensureAbsoluteRoot(root, itemPath) {
+      assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`);
+      assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`);
+      if (hasAbsoluteRoot(itemPath)) {
+        return itemPath;
       }
-      return statusCode === http_client_1.HttpCodes.TooManyRequests;
-    }
-    exports2.isThrottledStatusCode = isThrottledStatusCode;
-    function tryGetRetryAfterValueTimeInMilliseconds(headers) {
-      if (headers["retry-after"]) {
-        const retryTime = Number(headers["retry-after"]);
-        if (!isNaN(retryTime)) {
-          (0, core_1.info)(`Retry-After header is present with a value of ${retryTime}`);
-          return retryTime * 1e3;
+      if (IS_WINDOWS) {
+        if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) {
+          let cwd = process.cwd();
+          assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
+          if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) {
+            if (itemPath.length === 2) {
+              return `${itemPath[0]}:\\${cwd.substr(3)}`;
+            } else {
+              if (!cwd.endsWith("\\")) {
+                cwd += "\\";
+              }
+              return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`;
+            }
+          } else {
+            return `${itemPath[0]}:\\${itemPath.substr(2)}`;
+          }
+        } else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) {
+          const cwd = process.cwd();
+          assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
+          return `${cwd[0]}:\\${itemPath.substr(1)}`;
         }
-        (0, core_1.info)(`Returned retry-after header value: ${retryTime} is non-numeric and cannot be used`);
-        return void 0;
-      }
-      (0, core_1.info)(`No retry-after header was found. Dumping all headers for diagnostic purposes`);
-      console.log(headers);
-      return void 0;
-    }
-    exports2.tryGetRetryAfterValueTimeInMilliseconds = tryGetRetryAfterValueTimeInMilliseconds;
-    function getContentRange(start, end, total) {
-      return `bytes ${start}-${end}/${total}`;
-    }
-    exports2.getContentRange = getContentRange;
-    function getDownloadHeaders(contentType, isKeepAlive, acceptGzip) {
-      const requestOptions = {};
-      if (contentType) {
-        requestOptions["Content-Type"] = contentType;
-      }
-      if (isKeepAlive) {
-        requestOptions["Connection"] = "Keep-Alive";
-        requestOptions["Keep-Alive"] = "10";
       }
-      if (acceptGzip) {
-        requestOptions["Accept-Encoding"] = "gzip";
-        requestOptions["Accept"] = `application/octet-stream;api-version=${getApiVersion()}`;
+      assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`);
+      if (root.endsWith("/") || IS_WINDOWS && root.endsWith("\\")) {
       } else {
-        requestOptions["Accept"] = `application/json;api-version=${getApiVersion()}`;
+        root += path2.sep;
       }
-      return requestOptions;
+      return root + itemPath;
     }
-    exports2.getDownloadHeaders = getDownloadHeaders;
-    function getUploadHeaders(contentType, isKeepAlive, isGzip, uncompressedLength, contentLength, contentRange, digest) {
-      const requestOptions = {};
-      requestOptions["Accept"] = `application/json;api-version=${getApiVersion()}`;
-      if (contentType) {
-        requestOptions["Content-Type"] = contentType;
-      }
-      if (isKeepAlive) {
-        requestOptions["Connection"] = "Keep-Alive";
-        requestOptions["Keep-Alive"] = "10";
-      }
-      if (isGzip) {
-        requestOptions["Content-Encoding"] = "gzip";
-        requestOptions["x-tfs-filelength"] = uncompressedLength;
-      }
-      if (contentLength) {
-        requestOptions["Content-Length"] = contentLength;
-      }
-      if (contentRange) {
-        requestOptions["Content-Range"] = contentRange;
-      }
-      if (digest) {
-        requestOptions["x-actions-results-crc64"] = digest.crc64;
-        requestOptions["x-actions-results-md5"] = digest.md5;
+    exports2.ensureAbsoluteRoot = ensureAbsoluteRoot;
+    function hasAbsoluteRoot(itemPath) {
+      assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`);
+      itemPath = normalizeSeparators(itemPath);
+      if (IS_WINDOWS) {
+        return itemPath.startsWith("\\\\") || /^[A-Z]:\\/i.test(itemPath);
       }
-      return requestOptions;
-    }
-    exports2.getUploadHeaders = getUploadHeaders;
-    function createHttpClient(userAgent) {
-      return new http_client_1.HttpClient(userAgent, [
-        new auth_1.BearerCredentialHandler((0, config_variables_1.getRuntimeToken)())
-      ]);
-    }
-    exports2.createHttpClient = createHttpClient;
-    function getArtifactUrl() {
-      const artifactUrl = `${(0, config_variables_1.getRuntimeUrl)()}_apis/pipelines/workflows/${(0, config_variables_1.getWorkFlowRunId)()}/artifacts?api-version=${getApiVersion()}`;
-      (0, core_1.debug)(`Artifact Url: ${artifactUrl}`);
-      return artifactUrl;
-    }
-    exports2.getArtifactUrl = getArtifactUrl;
-    function displayHttpDiagnostics(response) {
-      (0, core_1.info)(`##### Begin Diagnostic HTTP information #####
-Status Code: ${response.message.statusCode}
-Status Message: ${response.message.statusMessage}
-Header Information: ${JSON.stringify(response.message.headers, void 0, 2)}
-###### End Diagnostic HTTP information ######`);
-    }
-    exports2.displayHttpDiagnostics = displayHttpDiagnostics;
-    function createDirectoriesForArtifact(directories) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        for (const directory of directories) {
-          yield fs_1.promises.mkdir(directory, {
-            recursive: true
-          });
-        }
-      });
-    }
-    exports2.createDirectoriesForArtifact = createDirectoriesForArtifact;
-    function createEmptyFilesForArtifact(emptyFilesToCreate) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        for (const filePath of emptyFilesToCreate) {
-          yield (yield fs_1.promises.open(filePath, "w")).close();
-        }
-      });
-    }
-    exports2.createEmptyFilesForArtifact = createEmptyFilesForArtifact;
-    function getFileSize(filePath) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const stats = yield fs_1.promises.stat(filePath);
-        (0, core_1.debug)(`${filePath} size:(${stats.size}) blksize:(${stats.blksize}) blocks:(${stats.blocks})`);
-        return stats.size;
-      });
-    }
-    exports2.getFileSize = getFileSize;
-    function rmFile(filePath) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        yield fs_1.promises.unlink(filePath);
-      });
+      return itemPath.startsWith("/");
     }
-    exports2.rmFile = rmFile;
-    function getProperRetention(retentionInput, retentionSetting) {
-      if (retentionInput < 0) {
-        throw new Error("Invalid retention, minimum value is 1.");
-      }
-      let retention = retentionInput;
-      if (retentionSetting) {
-        const maxRetention = parseInt(retentionSetting);
-        if (!isNaN(maxRetention) && maxRetention < retention) {
-          (0, core_1.warning)(`Retention days is greater than the max value allowed by the repository setting, reduce retention to ${maxRetention} days`);
-          retention = maxRetention;
-        }
+    exports2.hasAbsoluteRoot = hasAbsoluteRoot;
+    function hasRoot(itemPath) {
+      assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`);
+      itemPath = normalizeSeparators(itemPath);
+      if (IS_WINDOWS) {
+        return itemPath.startsWith("\\") || /^[A-Z]:/i.test(itemPath);
       }
-      return retention;
-    }
-    exports2.getProperRetention = getProperRetention;
-    function sleep(milliseconds) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
-      });
-    }
-    exports2.sleep = sleep;
-    function digestForStream(stream) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        return new Promise((resolve2, reject) => {
-          const crc64 = new crc64_1.default();
-          const md5 = crypto_1.default.createHash("md5");
-          stream.on("data", (data) => {
-            crc64.update(data);
-            md5.update(data);
-          }).on("end", () => resolve2({
-            crc64: crc64.digest("base64"),
-            md5: md5.digest("base64")
-          })).on("error", reject);
-        });
-      });
+      return itemPath.startsWith("/");
     }
-    exports2.digestForStream = digestForStream;
-  }
-});
-
-// node_modules/@actions/artifact-legacy/lib/internal/status-reporter.js
-var require_status_reporter = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/status-reporter.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.StatusReporter = void 0;
-    var core_1 = require_core();
-    var StatusReporter = class {
-      constructor(displayFrequencyInMilliseconds) {
-        this.totalNumberOfFilesToProcess = 0;
-        this.processedCount = 0;
-        this.largeFiles = /* @__PURE__ */ new Map();
-        this.totalFileStatus = void 0;
-        this.displayFrequencyInMilliseconds = displayFrequencyInMilliseconds;
-      }
-      setTotalNumberOfFilesToProcess(fileTotal) {
-        this.totalNumberOfFilesToProcess = fileTotal;
-        this.processedCount = 0;
-      }
-      start() {
-        this.totalFileStatus = setInterval(() => {
-          const percentage = this.formatPercentage(this.processedCount, this.totalNumberOfFilesToProcess);
-          (0, core_1.info)(`Total file count: ${this.totalNumberOfFilesToProcess} ---- Processed file #${this.processedCount} (${percentage.slice(0, percentage.indexOf(".") + 2)}%)`);
-        }, this.displayFrequencyInMilliseconds);
+    exports2.hasRoot = hasRoot;
+    function normalizeSeparators(p) {
+      p = p || "";
+      if (IS_WINDOWS) {
+        p = p.replace(/\//g, "\\");
+        const isUnc = /^\\\\+[^\\]/.test(p);
+        return (isUnc ? "\\" : "") + p.replace(/\\\\+/g, "\\");
       }
-      // if there is a large file that is being uploaded in chunks, this is used to display extra information about the status of the upload
-      updateLargeFileStatus(fileName, chunkStartIndex, chunkEndIndex, totalUploadFileSize) {
-        const percentage = this.formatPercentage(chunkEndIndex, totalUploadFileSize);
-        (0, core_1.info)(`Uploaded ${fileName} (${percentage.slice(0, percentage.indexOf(".") + 2)}%) bytes ${chunkStartIndex}:${chunkEndIndex}`);
+      return p.replace(/\/\/+/g, "/");
+    }
+    exports2.normalizeSeparators = normalizeSeparators;
+    function safeTrimTrailingSeparator(p) {
+      if (!p) {
+        return "";
       }
-      stop() {
-        if (this.totalFileStatus) {
-          clearInterval(this.totalFileStatus);
-        }
+      p = normalizeSeparators(p);
+      if (!p.endsWith(path2.sep)) {
+        return p;
       }
-      incrementProcessedCount() {
-        this.processedCount++;
+      if (p === path2.sep) {
+        return p;
       }
-      formatPercentage(numerator, denominator) {
-        return (numerator / denominator * 100).toFixed(4).toString();
+      if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) {
+        return p;
       }
-    };
-    exports2.StatusReporter = StatusReporter;
+      return p.substr(0, p.length - 1);
+    }
+    exports2.safeTrimTrailingSeparator = safeTrimTrailingSeparator;
   }
 });
 
-// node_modules/@actions/artifact-legacy/lib/internal/http-manager.js
-var require_http_manager = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/http-manager.js"(exports2) {
+// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-match-kind.js
+var require_internal_match_kind = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-match-kind.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.HttpManager = void 0;
-    var utils_1 = require_utils7();
-    var HttpManager = class {
-      constructor(clientCount, userAgent) {
-        if (clientCount < 1) {
-          throw new Error("There must be at least one client");
-        }
-        this.userAgent = userAgent;
-        this.clients = new Array(clientCount).fill((0, utils_1.createHttpClient)(userAgent));
-      }
-      getClient(index) {
-        return this.clients[index];
-      }
-      // client disposal is necessary if a keep-alive connection is used to properly close the connection
-      // for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292
-      disposeAndReplaceClient(index) {
-        this.clients[index].dispose();
-        this.clients[index] = (0, utils_1.createHttpClient)(this.userAgent);
-      }
-      disposeAndReplaceAllClients() {
-        for (const [index] of this.clients.entries()) {
-          this.disposeAndReplaceClient(index);
-        }
-      }
-    };
-    exports2.HttpManager = HttpManager;
+    exports2.MatchKind = void 0;
+    var MatchKind;
+    (function(MatchKind2) {
+      MatchKind2[MatchKind2["None"] = 0] = "None";
+      MatchKind2[MatchKind2["Directory"] = 1] = "Directory";
+      MatchKind2[MatchKind2["File"] = 2] = "File";
+      MatchKind2[MatchKind2["All"] = 3] = "All";
+    })(MatchKind = exports2.MatchKind || (exports2.MatchKind = {}));
   }
 });
 
-// node_modules/@actions/artifact-legacy/lib/internal/upload-gzip.js
-var require_upload_gzip = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/upload-gzip.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
+// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern-helper.js
+var require_internal_pattern_helper = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern-helper.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      Object.defineProperty(o, k2, { enumerable: true, get: function() {
+        return m[k];
+      } });
     }) : (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
       o[k2] = m[k];
@@ -99696,946 +104734,811 @@ var require_upload_gzip = __commonJS({
       if (mod && mod.__esModule) return mod;
       var result = {};
       if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
       __setModuleDefault4(result, mod);
       return result;
     };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.partialMatch = exports2.match = exports2.getSearchPaths = void 0;
+    var pathHelper = __importStar4(require_internal_path_helper());
+    var internal_match_kind_1 = require_internal_match_kind();
+    var IS_WINDOWS = process.platform === "win32";
+    function getSearchPaths(patterns) {
+      patterns = patterns.filter((x) => !x.negate);
+      const searchPathMap = {};
+      for (const pattern of patterns) {
+        const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath;
+        searchPathMap[key] = "candidate";
       }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
+      const result = [];
+      for (const pattern of patterns) {
+        const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath;
+        if (searchPathMap[key] === "included") {
+          continue;
         }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+        let foundAncestor = false;
+        let tempKey = key;
+        let parent = pathHelper.dirname(tempKey);
+        while (parent !== tempKey) {
+          if (searchPathMap[parent]) {
+            foundAncestor = true;
+            break;
           }
+          tempKey = parent;
+          parent = pathHelper.dirname(tempKey);
         }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        if (!foundAncestor) {
+          result.push(pattern.searchPath);
+          searchPathMap[key] = "included";
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
-    };
-    var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) {
-      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
-      var m = o[Symbol.asyncIterator], i;
-      return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
-        return this;
-      }, i);
-      function verb(n) {
-        i[n] = o[n] && function(v) {
-          return new Promise(function(resolve2, reject) {
-            v = o[n](v), settle(resolve2, reject, v.done, v.value);
-          });
-        };
       }
-      function settle(resolve2, reject, d, v) {
-        Promise.resolve(v).then(function(v2) {
-          resolve2({ value: v2, done: d });
-        }, reject);
+      return result;
+    }
+    exports2.getSearchPaths = getSearchPaths;
+    function match(patterns, itemPath) {
+      let result = internal_match_kind_1.MatchKind.None;
+      for (const pattern of patterns) {
+        if (pattern.negate) {
+          result &= ~pattern.match(itemPath);
+        } else {
+          result |= pattern.match(itemPath);
+        }
+      }
+      return result;
+    }
+    exports2.match = match;
+    function partialMatch(patterns, itemPath) {
+      return patterns.some((x) => !x.negate && x.partialMatch(itemPath));
+    }
+    exports2.partialMatch = partialMatch;
+  }
+});
+
+// node_modules/concat-map/index.js
+var require_concat_map = __commonJS({
+  "node_modules/concat-map/index.js"(exports2, module2) {
+    module2.exports = function(xs, fn) {
+      var res = [];
+      for (var i = 0; i < xs.length; i++) {
+        var x = fn(xs[i], i);
+        if (isArray(x)) res.push.apply(res, x);
+        else res.push(x);
       }
+      return res;
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createGZipFileInBuffer = exports2.createGZipFileOnDisk = void 0;
-    var fs2 = __importStar4(require("fs"));
-    var zlib = __importStar4(require("zlib"));
-    var util_1 = require("util");
-    var stat = (0, util_1.promisify)(fs2.stat);
-    var gzipExemptFileExtensions = [
-      ".gz",
-      ".gzip",
-      ".tgz",
-      ".taz",
-      ".Z",
-      ".taZ",
-      ".bz2",
-      ".tbz",
-      ".tbz2",
-      ".tz2",
-      ".lz",
-      ".lzma",
-      ".tlz",
-      ".lzo",
-      ".xz",
-      ".txz",
-      ".zst",
-      ".zstd",
-      ".tzst",
-      ".zip",
-      ".7z"
-      // 7ZIP
-    ];
-    function createGZipFileOnDisk(originalFilePath, tempFilePath) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        for (const gzipExemptExtension of gzipExemptFileExtensions) {
-          if (originalFilePath.endsWith(gzipExemptExtension)) {
-            return Number.MAX_SAFE_INTEGER;
+    var isArray = Array.isArray || function(xs) {
+      return Object.prototype.toString.call(xs) === "[object Array]";
+    };
+  }
+});
+
+// node_modules/brace-expansion/index.js
+var require_brace_expansion3 = __commonJS({
+  "node_modules/brace-expansion/index.js"(exports2, module2) {
+    var concatMap = require_concat_map();
+    var balanced = require_balanced_match();
+    module2.exports = expandTop;
+    var escSlash = "\0SLASH" + Math.random() + "\0";
+    var escOpen = "\0OPEN" + Math.random() + "\0";
+    var escClose = "\0CLOSE" + Math.random() + "\0";
+    var escComma = "\0COMMA" + Math.random() + "\0";
+    var escPeriod = "\0PERIOD" + Math.random() + "\0";
+    function numeric(str2) {
+      return parseInt(str2, 10) == str2 ? parseInt(str2, 10) : str2.charCodeAt(0);
+    }
+    function escapeBraces(str2) {
+      return str2.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
+    }
+    function unescapeBraces(str2) {
+      return str2.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
+    }
+    function parseCommaParts(str2) {
+      if (!str2)
+        return [""];
+      var parts = [];
+      var m = balanced("{", "}", str2);
+      if (!m)
+        return str2.split(",");
+      var pre = m.pre;
+      var body = m.body;
+      var post = m.post;
+      var p = pre.split(",");
+      p[p.length - 1] += "{" + body + "}";
+      var postParts = parseCommaParts(post);
+      if (post.length) {
+        p[p.length - 1] += postParts.shift();
+        p.push.apply(p, postParts);
+      }
+      parts.push.apply(parts, p);
+      return parts;
+    }
+    function expandTop(str2) {
+      if (!str2)
+        return [];
+      if (str2.substr(0, 2) === "{}") {
+        str2 = "\\{\\}" + str2.substr(2);
+      }
+      return expand(escapeBraces(str2), true).map(unescapeBraces);
+    }
+    function embrace(str2) {
+      return "{" + str2 + "}";
+    }
+    function isPadded(el) {
+      return /^-?0\d/.test(el);
+    }
+    function lte(i, y) {
+      return i <= y;
+    }
+    function gte5(i, y) {
+      return i >= y;
+    }
+    function expand(str2, isTop) {
+      var expansions = [];
+      var m = balanced("{", "}", str2);
+      if (!m || /\$$/.test(m.pre)) return [str2];
+      var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+      var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+      var isSequence = isNumericSequence || isAlphaSequence;
+      var isOptions = m.body.indexOf(",") >= 0;
+      if (!isSequence && !isOptions) {
+        if (m.post.match(/,(?!,).*\}/)) {
+          str2 = m.pre + "{" + m.body + escClose + m.post;
+          return expand(str2);
+        }
+        return [str2];
+      }
+      var n;
+      if (isSequence) {
+        n = m.body.split(/\.\./);
+      } else {
+        n = parseCommaParts(m.body);
+        if (n.length === 1) {
+          n = expand(n[0], false).map(embrace);
+          if (n.length === 1) {
+            var post = m.post.length ? expand(m.post, false) : [""];
+            return post.map(function(p) {
+              return m.pre + n[0] + p;
+            });
           }
         }
-        return new Promise((resolve2, reject) => {
-          const inputStream = fs2.createReadStream(originalFilePath);
-          const gzip = zlib.createGzip();
-          const outputStream = fs2.createWriteStream(tempFilePath);
-          inputStream.pipe(gzip).pipe(outputStream);
-          outputStream.on("finish", () => __awaiter4(this, void 0, void 0, function* () {
-            const size = (yield stat(tempFilePath)).size;
-            resolve2(size);
-          }));
-          outputStream.on("error", (error4) => {
-            console.log(error4);
-            reject(error4);
-          });
-        });
-      });
-    }
-    exports2.createGZipFileOnDisk = createGZipFileOnDisk;
-    function createGZipFileInBuffer(originalFilePath) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
-          var _a, e_1, _b, _c;
-          const inputStream = fs2.createReadStream(originalFilePath);
-          const gzip = zlib.createGzip();
-          inputStream.pipe(gzip);
-          const chunks = [];
-          try {
-            for (var _d = true, gzip_1 = __asyncValues4(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), _a = gzip_1_1.done, !_a; ) {
-              _c = gzip_1_1.value;
-              _d = false;
-              try {
-                const chunk = _c;
-                chunks.push(chunk);
-              } finally {
-                _d = true;
+      }
+      var pre = m.pre;
+      var post = m.post.length ? expand(m.post, false) : [""];
+      var N;
+      if (isSequence) {
+        var x = numeric(n[0]);
+        var y = numeric(n[1]);
+        var width = Math.max(n[0].length, n[1].length);
+        var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
+        var test = lte;
+        var reverse = y < x;
+        if (reverse) {
+          incr *= -1;
+          test = gte5;
+        }
+        var pad = n.some(isPadded);
+        N = [];
+        for (var i = x; test(i, y); i += incr) {
+          var c;
+          if (isAlphaSequence) {
+            c = String.fromCharCode(i);
+            if (c === "\\")
+              c = "";
+          } else {
+            c = String(i);
+            if (pad) {
+              var need = width - c.length;
+              if (need > 0) {
+                var z = new Array(need + 1).join("0");
+                if (i < 0)
+                  c = "-" + z + c.slice(1);
+                else
+                  c = z + c;
               }
             }
-          } catch (e_1_1) {
-            e_1 = { error: e_1_1 };
-          } finally {
-            try {
-              if (!_d && !_a && (_b = gzip_1.return)) yield _b.call(gzip_1);
-            } finally {
-              if (e_1) throw e_1.error;
-            }
           }
-          resolve2(Buffer.concat(chunks));
-        }));
-      });
+          N.push(c);
+        }
+      } else {
+        N = concatMap(n, function(el) {
+          return expand(el, false);
+        });
+      }
+      for (var j = 0; j < N.length; j++) {
+        for (var k = 0; k < post.length; k++) {
+          var expansion = pre + N[j] + post[k];
+          if (!isTop || isSequence || expansion)
+            expansions.push(expansion);
+        }
+      }
+      return expansions;
     }
-    exports2.createGZipFileInBuffer = createGZipFileInBuffer;
   }
 });
 
-// node_modules/@actions/artifact-legacy/lib/internal/requestUtils.js
-var require_requestUtils = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/requestUtils.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+// node_modules/minimatch/minimatch.js
+var require_minimatch2 = __commonJS({
+  "node_modules/minimatch/minimatch.js"(exports2, module2) {
+    module2.exports = minimatch;
+    minimatch.Minimatch = Minimatch;
+    var path2 = (function() {
+      try {
+        return require("path");
+      } catch (e) {
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+    })() || {
+      sep: "/"
+    };
+    minimatch.sep = path2.sep;
+    var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
+    var expand = require_brace_expansion3();
+    var plTypes = {
+      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
+      "?": { open: "(?:", close: ")?" },
+      "+": { open: "(?:", close: ")+" },
+      "*": { open: "(?:", close: ")*" },
+      "@": { open: "(?:", close: ")" }
+    };
+    var qmark = "[^/]";
+    var star = qmark + "*?";
+    var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
+    var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
+    var reSpecials = charSet("().*{}+?[]^$\\!");
+    function charSet(s) {
+      return s.split("").reduce(function(set2, c) {
+        set2[c] = true;
+        return set2;
+      }, {});
+    }
+    var slashSplit = /\/+/;
+    minimatch.filter = filter;
+    function filter(pattern, options) {
+      options = options || {};
+      return function(p, i, list) {
+        return minimatch(p, pattern, options);
+      };
+    }
+    function ext(a, b) {
+      b = b || {};
+      var t = {};
+      Object.keys(a).forEach(function(k) {
+        t[k] = a[k];
+      });
+      Object.keys(b).forEach(function(k) {
+        t[k] = b[k];
+      });
+      return t;
+    }
+    minimatch.defaults = function(def) {
+      if (!def || typeof def !== "object" || !Object.keys(def).length) {
+        return minimatch;
       }
-      __setModuleDefault4(result, mod);
-      return result;
+      var orig = minimatch;
+      var m = function minimatch2(p, pattern, options) {
+        return orig(p, pattern, ext(def, options));
+      };
+      m.Minimatch = function Minimatch2(pattern, options) {
+        return new orig.Minimatch(pattern, ext(def, options));
+      };
+      m.Minimatch.defaults = function defaults(options) {
+        return orig.defaults(ext(def, options)).Minimatch;
+      };
+      m.filter = function filter2(pattern, options) {
+        return orig.filter(pattern, ext(def, options));
+      };
+      m.defaults = function defaults(options) {
+        return orig.defaults(ext(def, options));
+      };
+      m.makeRe = function makeRe2(pattern, options) {
+        return orig.makeRe(pattern, ext(def, options));
+      };
+      m.braceExpand = function braceExpand2(pattern, options) {
+        return orig.braceExpand(pattern, ext(def, options));
+      };
+      m.match = function(list, pattern, options) {
+        return orig.match(list, pattern, ext(def, options));
+      };
+      return m;
     };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
+    Minimatch.defaults = function(def) {
+      return minimatch.defaults(def).Minimatch;
+    };
+    function minimatch(p, pattern, options) {
+      assertValidPattern(pattern);
+      if (!options) options = {};
+      if (!options.nocomment && pattern.charAt(0) === "#") {
+        return false;
       }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      return new Minimatch(pattern, options).match(p);
+    }
+    function Minimatch(pattern, options) {
+      if (!(this instanceof Minimatch)) {
+        return new Minimatch(pattern, options);
+      }
+      assertValidPattern(pattern);
+      if (!options) options = {};
+      pattern = pattern.trim();
+      if (!options.allowWindowsEscape && path2.sep !== "/") {
+        pattern = pattern.split(path2.sep).join("/");
+      }
+      this.options = options;
+      this.set = [];
+      this.pattern = pattern;
+      this.regexp = null;
+      this.negate = false;
+      this.comment = false;
+      this.empty = false;
+      this.partial = !!options.partial;
+      this.make();
+    }
+    Minimatch.prototype.debug = function() {
+    };
+    Minimatch.prototype.make = make;
+    function make() {
+      var pattern = this.pattern;
+      var options = this.options;
+      if (!options.nocomment && pattern.charAt(0) === "#") {
+        this.comment = true;
+        return;
+      }
+      if (!pattern) {
+        this.empty = true;
+        return;
+      }
+      this.parseNegate();
+      var set2 = this.globSet = this.braceExpand();
+      if (options.debug) this.debug = function debug4() {
+        console.error.apply(console, arguments);
+      };
+      this.debug(this.pattern, set2);
+      set2 = this.globParts = set2.map(function(s) {
+        return s.split(slashSplit);
       });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.retryHttpClientRequest = exports2.retry = void 0;
-    var utils_1 = require_utils7();
-    var core14 = __importStar4(require_core());
-    var config_variables_1 = require_config_variables();
-    function retry3(name, operation, customErrorMessages, maxAttempts) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        let response = void 0;
-        let statusCode = void 0;
-        let isRetryable = false;
-        let errorMessage = "";
-        let customErrorInformation = void 0;
-        let attempt = 1;
-        while (attempt <= maxAttempts) {
-          try {
-            response = yield operation();
-            statusCode = response.message.statusCode;
-            if ((0, utils_1.isSuccessStatusCode)(statusCode)) {
-              return response;
-            }
-            if (statusCode) {
-              customErrorInformation = customErrorMessages.get(statusCode);
-            }
-            isRetryable = (0, utils_1.isRetryableStatusCode)(statusCode);
-            errorMessage = `Artifact service responded with ${statusCode}`;
-          } catch (error4) {
-            isRetryable = true;
-            errorMessage = error4.message;
-          }
-          if (!isRetryable) {
-            core14.info(`${name} - Error is not retryable`);
-            if (response) {
-              (0, utils_1.displayHttpDiagnostics)(response);
-            }
-            break;
-          }
-          core14.info(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`);
-          yield (0, utils_1.sleep)((0, utils_1.getExponentialRetryTimeInMilliseconds)(attempt));
-          attempt++;
-        }
-        if (response) {
-          (0, utils_1.displayHttpDiagnostics)(response);
-        }
-        if (customErrorInformation) {
-          throw Error(`${name} failed: ${customErrorInformation}`);
-        }
-        throw Error(`${name} failed: ${errorMessage}`);
+      this.debug(this.pattern, set2);
+      set2 = set2.map(function(s, si, set3) {
+        return s.map(this.parse, this);
+      }, this);
+      this.debug(this.pattern, set2);
+      set2 = set2.filter(function(s) {
+        return s.indexOf(false) === -1;
       });
+      this.debug(this.pattern, set2);
+      this.set = set2;
     }
-    exports2.retry = retry3;
-    function retryHttpClientRequest(name, method, customErrorMessages = /* @__PURE__ */ new Map(), maxAttempts = (0, config_variables_1.getRetryLimit)()) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        return yield retry3(name, method, customErrorMessages, maxAttempts);
-      });
+    Minimatch.prototype.parseNegate = parseNegate;
+    function parseNegate() {
+      var pattern = this.pattern;
+      var negate = false;
+      var options = this.options;
+      var negateOffset = 0;
+      if (options.nonegate) return;
+      for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
+        negate = !negate;
+        negateOffset++;
+      }
+      if (negateOffset) this.pattern = pattern.substr(negateOffset);
+      this.negate = negate;
     }
-    exports2.retryHttpClientRequest = retryHttpClientRequest;
-  }
-});
-
-// node_modules/@actions/artifact-legacy/lib/internal/upload-http-client.js
-var require_upload_http_client = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/upload-http-client.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+    minimatch.braceExpand = function(pattern, options) {
+      return braceExpand(pattern, options);
+    };
+    Minimatch.prototype.braceExpand = braceExpand;
+    function braceExpand(pattern, options) {
+      if (!options) {
+        if (this instanceof Minimatch) {
+          options = this.options;
+        } else {
+          options = {};
+        }
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      pattern = typeof pattern === "undefined" ? this.pattern : pattern;
+      assertValidPattern(pattern);
+      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+        return [pattern];
       }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
+      return expand(pattern);
+    }
+    var MAX_PATTERN_LENGTH = 1024 * 64;
+    var assertValidPattern = function(pattern) {
+      if (typeof pattern !== "string") {
+        throw new TypeError("invalid pattern");
+      }
+      if (pattern.length > MAX_PATTERN_LENGTH) {
+        throw new TypeError("pattern is too long");
       }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.UploadHttpClient = void 0;
-    var fs2 = __importStar4(require("fs"));
-    var core14 = __importStar4(require_core());
-    var tmp = __importStar4(require_tmp_promise());
-    var stream = __importStar4(require("stream"));
-    var utils_1 = require_utils7();
-    var config_variables_1 = require_config_variables();
-    var util_1 = require("util");
-    var url_1 = require("url");
-    var perf_hooks_1 = require("perf_hooks");
-    var status_reporter_1 = require_status_reporter();
-    var http_client_1 = require_lib();
-    var http_manager_1 = require_http_manager();
-    var upload_gzip_1 = require_upload_gzip();
-    var requestUtils_1 = require_requestUtils();
-    var stat = (0, util_1.promisify)(fs2.stat);
-    var UploadHttpClient = class {
-      constructor() {
-        this.uploadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getUploadFileConcurrency)(), "@actions/artifact-upload");
-        this.statusReporter = new status_reporter_1.StatusReporter(1e4);
+    Minimatch.prototype.parse = parse;
+    var SUBPARSE = {};
+    function parse(pattern, isSub) {
+      assertValidPattern(pattern);
+      var options = this.options;
+      if (pattern === "**") {
+        if (!options.noglobstar)
+          return GLOBSTAR;
+        else
+          pattern = "*";
       }
-      /**
-       * Creates a file container for the new artifact in the remote blob storage/file service
-       * @param {string} artifactName Name of the artifact being created
-       * @returns The response from the Artifact Service if the file container was successfully created
-       */
-      createArtifactInFileContainer(artifactName, options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const parameters = {
-            Type: "actions_storage",
-            Name: artifactName
-          };
-          if (options && options.retentionDays) {
-            const maxRetentionStr = (0, config_variables_1.getRetentionDays)();
-            parameters.RetentionDays = (0, utils_1.getProperRetention)(options.retentionDays, maxRetentionStr);
+      if (pattern === "") return "";
+      var re = "";
+      var hasMagic = !!options.nocase;
+      var escaping = false;
+      var patternListStack = [];
+      var negativeLists = [];
+      var stateChar;
+      var inClass = false;
+      var reClassStart = -1;
+      var classStart = -1;
+      var patternStart = pattern.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
+      var self2 = this;
+      function clearStateChar() {
+        if (stateChar) {
+          switch (stateChar) {
+            case "*":
+              re += star;
+              hasMagic = true;
+              break;
+            case "?":
+              re += qmark;
+              hasMagic = true;
+              break;
+            default:
+              re += "\\" + stateChar;
+              break;
           }
-          const data = JSON.stringify(parameters, null, 2);
-          const artifactUrl = (0, utils_1.getArtifactUrl)();
-          const client = this.uploadHttpManager.getClient(0);
-          const headers = (0, utils_1.getUploadHeaders)("application/json", false);
-          const customErrorMessages = /* @__PURE__ */ new Map([
-            [
-              http_client_1.HttpCodes.Forbidden,
-              (0, config_variables_1.isGhes)() ? "Please reference [Enabling GitHub Actions for GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@3.8/admin/github-actions/enabling-github-actions-for-github-enterprise-server) to ensure Actions storage is configured correctly." : "Artifact storage quota has been hit. Unable to upload any new artifacts"
-            ],
-            [
-              http_client_1.HttpCodes.BadRequest,
-              `The artifact name ${artifactName} is not valid. Request URL ${artifactUrl}`
-            ]
-          ]);
-          const response = yield (0, requestUtils_1.retryHttpClientRequest)("Create Artifact Container", () => __awaiter4(this, void 0, void 0, function* () {
-            return client.post(artifactUrl, data, headers);
-          }), customErrorMessages);
-          const body = yield response.readBody();
-          return JSON.parse(body);
-        });
+          self2.debug("clearStateChar %j %j", stateChar, re);
+          stateChar = false;
+        }
       }
-      /**
-       * Concurrently upload all of the files in chunks
-       * @param {string} uploadUrl Base Url for the artifact that was created
-       * @param {SearchResult[]} filesToUpload A list of information about the files being uploaded
-       * @returns The size of all the files uploaded in bytes
-       */
-      uploadArtifactToFileContainer(uploadUrl, filesToUpload, options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const FILE_CONCURRENCY = (0, config_variables_1.getUploadFileConcurrency)();
-          const MAX_CHUNK_SIZE = (0, config_variables_1.getUploadChunkSize)();
-          core14.debug(`File Concurrency: ${FILE_CONCURRENCY}, and Chunk Size: ${MAX_CHUNK_SIZE}`);
-          const parameters = [];
-          let continueOnError = true;
-          if (options) {
-            if (options.continueOnError === false) {
-              continueOnError = false;
-            }
-          }
-          for (const file of filesToUpload) {
-            const resourceUrl = new url_1.URL(uploadUrl);
-            resourceUrl.searchParams.append("itemPath", file.uploadFilePath);
-            parameters.push({
-              file: file.absoluteFilePath,
-              resourceUrl: resourceUrl.toString(),
-              maxChunkSize: MAX_CHUNK_SIZE,
-              continueOnError
-            });
+      for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
+        this.debug("%s	%s %s %j", pattern, i, re, c);
+        if (escaping && reSpecials[c]) {
+          re += "\\" + c;
+          escaping = false;
+          continue;
+        }
+        switch (c) {
+          /* istanbul ignore next */
+          case "/": {
+            return false;
           }
-          const parallelUploads = [...new Array(FILE_CONCURRENCY).keys()];
-          const failedItemsToReport = [];
-          let currentFile = 0;
-          let completedFiles = 0;
-          let uploadFileSize = 0;
-          let totalFileSize = 0;
-          let abortPendingFileUploads = false;
-          this.statusReporter.setTotalNumberOfFilesToProcess(filesToUpload.length);
-          this.statusReporter.start();
-          yield Promise.all(parallelUploads.map((index) => __awaiter4(this, void 0, void 0, function* () {
-            while (currentFile < filesToUpload.length) {
-              const currentFileParameters = parameters[currentFile];
-              currentFile += 1;
-              if (abortPendingFileUploads) {
-                failedItemsToReport.push(currentFileParameters.file);
-                continue;
-              }
-              const startTime = perf_hooks_1.performance.now();
-              const uploadFileResult = yield this.uploadFileAsync(index, currentFileParameters);
-              if (core14.isDebug()) {
-                core14.debug(`File: ${++completedFiles}/${filesToUpload.length}. ${currentFileParameters.file} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish upload`);
-              }
-              uploadFileSize += uploadFileResult.successfulUploadSize;
-              totalFileSize += uploadFileResult.totalSize;
-              if (uploadFileResult.isSuccess === false) {
-                failedItemsToReport.push(currentFileParameters.file);
-                if (!continueOnError) {
-                  core14.error(`aborting artifact upload`);
-                  abortPendingFileUploads = true;
-                }
-              }
-              this.statusReporter.incrementProcessedCount();
+          case "\\":
+            clearStateChar();
+            escaping = true;
+            continue;
+          // the various stateChar values
+          // for the "extglob" stuff.
+          case "?":
+          case "*":
+          case "+":
+          case "@":
+          case "!":
+            this.debug("%s	%s %s %j <-- stateChar", pattern, i, re, c);
+            if (inClass) {
+              this.debug("  in class");
+              if (c === "!" && i === classStart + 1) c = "^";
+              re += c;
+              continue;
             }
-          })));
-          this.statusReporter.stop();
-          this.uploadHttpManager.disposeAndReplaceAllClients();
-          core14.info(`Total size of all the files uploaded is ${uploadFileSize} bytes`);
-          return {
-            uploadSize: uploadFileSize,
-            totalSize: totalFileSize,
-            failedItems: failedItemsToReport
-          };
-        });
-      }
-      /**
-       * Asynchronously uploads a file. The file is compressed and uploaded using GZip if it is determined to save space.
-       * If the upload file is bigger than the max chunk size it will be uploaded via multiple calls
-       * @param {number} httpClientIndex The index of the httpClient that is being used to make all of the calls
-       * @param {UploadFileParameters} parameters Information about the file that needs to be uploaded
-       * @returns The size of the file that was uploaded in bytes along with any failed uploads
-       */
-      uploadFileAsync(httpClientIndex, parameters) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const fileStat = yield stat(parameters.file);
-          const totalFileSize = fileStat.size;
-          const isFIFO = fileStat.isFIFO();
-          let offset = 0;
-          let isUploadSuccessful = true;
-          let failedChunkSizes = 0;
-          let uploadFileSize = 0;
-          let isGzip = true;
-          if (!isFIFO && totalFileSize < 65536) {
-            core14.debug(`${parameters.file} is less than 64k in size. Creating a gzip file in-memory to potentially reduce the upload size`);
-            const buffer = yield (0, upload_gzip_1.createGZipFileInBuffer)(parameters.file);
-            let openUploadStream;
-            if (totalFileSize < buffer.byteLength) {
-              core14.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`);
-              openUploadStream = () => fs2.createReadStream(parameters.file);
-              isGzip = false;
-              uploadFileSize = totalFileSize;
-            } else {
-              core14.debug(`A gzip file created for ${parameters.file} helped with reducing the size of the original file. The file will be uploaded using gzip.`);
-              openUploadStream = () => {
-                const passThrough = new stream.PassThrough();
-                passThrough.end(buffer);
-                return passThrough;
-              };
-              uploadFileSize = buffer.byteLength;
+            self2.debug("call clearStateChar %j", stateChar);
+            clearStateChar();
+            stateChar = c;
+            if (options.noext) clearStateChar();
+            continue;
+          case "(":
+            if (inClass) {
+              re += "(";
+              continue;
             }
-            const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, openUploadStream, 0, uploadFileSize - 1, uploadFileSize, isGzip, totalFileSize);
-            if (!result) {
-              isUploadSuccessful = false;
-              failedChunkSizes += uploadFileSize;
-              core14.warning(`Aborting upload for ${parameters.file} due to failure`);
+            if (!stateChar) {
+              re += "\\(";
+              continue;
             }
-            return {
-              isSuccess: isUploadSuccessful,
-              successfulUploadSize: uploadFileSize - failedChunkSizes,
-              totalSize: totalFileSize
-            };
-          } else {
-            const tempFile = yield tmp.file();
-            core14.debug(`${parameters.file} is greater than 64k in size. Creating a gzip file on-disk ${tempFile.path} to potentially reduce the upload size`);
-            uploadFileSize = yield (0, upload_gzip_1.createGZipFileOnDisk)(parameters.file, tempFile.path);
-            let uploadFilePath = tempFile.path;
-            if (!isFIFO && totalFileSize < uploadFileSize) {
-              core14.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`);
-              uploadFileSize = totalFileSize;
-              uploadFilePath = parameters.file;
-              isGzip = false;
-            } else {
-              core14.debug(`The gzip file created for ${parameters.file} is smaller than the original file. The file will be uploaded using gzip.`);
+            patternListStack.push({
+              type: stateChar,
+              start: i - 1,
+              reStart: re.length,
+              open: plTypes[stateChar].open,
+              close: plTypes[stateChar].close
+            });
+            re += stateChar === "!" ? "(?:(?!(?:" : "(?:";
+            this.debug("plType %j %j", stateChar, re);
+            stateChar = false;
+            continue;
+          case ")":
+            if (inClass || !patternListStack.length) {
+              re += "\\)";
+              continue;
             }
-            let abortFileUpload = false;
-            while (offset < uploadFileSize) {
-              const chunkSize = Math.min(uploadFileSize - offset, parameters.maxChunkSize);
-              const startChunkIndex = offset;
-              const endChunkIndex = offset + chunkSize - 1;
-              offset += parameters.maxChunkSize;
-              if (abortFileUpload) {
-                failedChunkSizes += chunkSize;
-                continue;
-              }
-              const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs2.createReadStream(uploadFilePath, {
-                start: startChunkIndex,
-                end: endChunkIndex,
-                autoClose: false
-              }), startChunkIndex, endChunkIndex, uploadFileSize, isGzip, totalFileSize);
-              if (!result) {
-                isUploadSuccessful = false;
-                failedChunkSizes += chunkSize;
-                core14.warning(`Aborting upload for ${parameters.file} due to failure`);
-                abortFileUpload = true;
-              } else {
-                if (uploadFileSize > 8388608) {
-                  this.statusReporter.updateLargeFileStatus(parameters.file, startChunkIndex, endChunkIndex, uploadFileSize);
-                }
-              }
+            clearStateChar();
+            hasMagic = true;
+            var pl = patternListStack.pop();
+            re += pl.close;
+            if (pl.type === "!") {
+              negativeLists.push(pl);
             }
-            core14.debug(`deleting temporary gzip file ${tempFile.path}`);
-            yield tempFile.cleanup();
-            return {
-              isSuccess: isUploadSuccessful,
-              successfulUploadSize: uploadFileSize - failedChunkSizes,
-              totalSize: totalFileSize
-            };
-          }
-        });
-      }
-      /**
-       * Uploads a chunk of an individual file to the specified resourceUrl. If the upload fails and the status code
-       * indicates a retryable status, we try to upload the chunk as well
-       * @param {number} httpClientIndex The index of the httpClient being used to make all the necessary calls
-       * @param {string} resourceUrl Url of the resource that the chunk will be uploaded to
-       * @param {NodeJS.ReadableStream} openStream Stream of the file that will be uploaded
-       * @param {number} start Starting byte index of file that the chunk belongs to
-       * @param {number} end Ending byte index of file that the chunk belongs to
-       * @param {number} uploadFileSize Total size of the file in bytes that is being uploaded
-       * @param {boolean} isGzip Denotes if we are uploading a Gzip compressed stream
-       * @param {number} totalFileSize Original total size of the file that is being uploaded
-       * @returns if the chunk was successfully uploaded
-       */
-      uploadChunk(httpClientIndex, resourceUrl, openStream, start, end, uploadFileSize, isGzip, totalFileSize) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const digest = yield (0, utils_1.digestForStream)(openStream());
-          const headers = (0, utils_1.getUploadHeaders)("application/octet-stream", true, isGzip, totalFileSize, end - start + 1, (0, utils_1.getContentRange)(start, end, uploadFileSize), digest);
-          const uploadChunkRequest = () => __awaiter4(this, void 0, void 0, function* () {
-            const client = this.uploadHttpManager.getClient(httpClientIndex);
-            return yield client.sendStream("PUT", resourceUrl, openStream(), headers);
-          });
-          let retryCount = 0;
-          const retryLimit = (0, config_variables_1.getRetryLimit)();
-          const incrementAndCheckRetryLimit = (response) => {
-            retryCount++;
-            if (retryCount > retryLimit) {
-              if (response) {
-                (0, utils_1.displayHttpDiagnostics)(response);
-              }
-              core14.info(`Retry limit has been reached for chunk at offset ${start} to ${resourceUrl}`);
-              return true;
+            pl.reEnd = re.length;
+            continue;
+          case "|":
+            if (inClass || !patternListStack.length || escaping) {
+              re += "\\|";
+              escaping = false;
+              continue;
             }
-            return false;
-          };
-          const backOff = (retryAfterValue) => __awaiter4(this, void 0, void 0, function* () {
-            this.uploadHttpManager.disposeAndReplaceClient(httpClientIndex);
-            if (retryAfterValue) {
-              core14.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the upload`);
-              yield (0, utils_1.sleep)(retryAfterValue);
-            } else {
-              const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount);
-              core14.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the upload at offset ${start}`);
-              yield (0, utils_1.sleep)(backoffTime);
+            clearStateChar();
+            re += "|";
+            continue;
+          // these are mostly the same in regexp and glob
+          case "[":
+            clearStateChar();
+            if (inClass) {
+              re += "\\" + c;
+              continue;
             }
-            core14.info(`Finished backoff for retry #${retryCount}, continuing with upload`);
-            return;
-          });
-          while (retryCount <= retryLimit) {
-            let response;
+            inClass = true;
+            classStart = i;
+            reClassStart = re.length;
+            re += c;
+            continue;
+          case "]":
+            if (i === classStart + 1 || !inClass) {
+              re += "\\" + c;
+              escaping = false;
+              continue;
+            }
+            var cs = pattern.substring(classStart + 1, i);
             try {
-              response = yield uploadChunkRequest();
-            } catch (error4) {
-              core14.info(`An error has been caught http-client index ${httpClientIndex}, retrying the upload`);
-              console.log(error4);
-              if (incrementAndCheckRetryLimit()) {
-                return false;
-              }
-              yield backOff();
+              RegExp("[" + cs + "]");
+            } catch (er) {
+              var sp = this.parse(cs, SUBPARSE);
+              re = re.substr(0, reClassStart) + "\\[" + sp[0] + "\\]";
+              hasMagic = hasMagic || sp[1];
+              inClass = false;
               continue;
             }
-            yield response.readBody();
-            if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) {
-              return true;
-            } else if ((0, utils_1.isRetryableStatusCode)(response.message.statusCode)) {
-              core14.info(`A ${response.message.statusCode} status code has been received, will attempt to retry the upload`);
-              if (incrementAndCheckRetryLimit(response)) {
-                return false;
-              }
-              (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff();
-            } else {
-              core14.error(`Unexpected response. Unable to upload chunk to ${resourceUrl}`);
-              (0, utils_1.displayHttpDiagnostics)(response);
-              return false;
+            hasMagic = true;
+            inClass = false;
+            re += c;
+            continue;
+          default:
+            clearStateChar();
+            if (escaping) {
+              escaping = false;
+            } else if (reSpecials[c] && !(c === "^" && inClass)) {
+              re += "\\";
             }
+            re += c;
+        }
+      }
+      if (inClass) {
+        cs = pattern.substr(classStart + 1);
+        sp = this.parse(cs, SUBPARSE);
+        re = re.substr(0, reClassStart) + "\\[" + sp[0];
+        hasMagic = hasMagic || sp[1];
+      }
+      for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
+        var tail = re.slice(pl.reStart + pl.open.length);
+        this.debug("setting tail", re, pl);
+        tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function(_2, $1, $2) {
+          if (!$2) {
+            $2 = "\\";
           }
-          return false;
+          return $1 + $1 + $2 + "|";
         });
+        this.debug("tail=%j\n   %s", tail, tail, pl, re);
+        var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
+        hasMagic = true;
+        re = re.slice(0, pl.reStart) + t + "\\(" + tail;
       }
-      /**
-       * Updates the size of the artifact from -1 which was initially set when the container was first created for the artifact.
-       * Updating the size indicates that we are done uploading all the contents of the artifact
-       */
-      patchArtifactSize(size, artifactName) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const resourceUrl = new url_1.URL((0, utils_1.getArtifactUrl)());
-          resourceUrl.searchParams.append("artifactName", artifactName);
-          const parameters = { Size: size };
-          const data = JSON.stringify(parameters, null, 2);
-          core14.debug(`URL is ${resourceUrl.toString()}`);
-          const client = this.uploadHttpManager.getClient(0);
-          const headers = (0, utils_1.getUploadHeaders)("application/json", false);
-          const customErrorMessages = /* @__PURE__ */ new Map([
-            [
-              http_client_1.HttpCodes.NotFound,
-              `An Artifact with the name ${artifactName} was not found`
-            ]
-          ]);
-          const response = yield (0, requestUtils_1.retryHttpClientRequest)("Finalize artifact upload", () => __awaiter4(this, void 0, void 0, function* () {
-            return client.patch(resourceUrl.toString(), data, headers);
-          }), customErrorMessages);
-          yield response.readBody();
-          core14.debug(`Artifact ${artifactName} has been successfully uploaded, total size in bytes: ${size}`);
-        });
+      clearStateChar();
+      if (escaping) {
+        re += "\\\\";
       }
-    };
-    exports2.UploadHttpClient = UploadHttpClient;
-  }
-});
-
-// node_modules/@actions/artifact-legacy/lib/internal/download-http-client.js
-var require_download_http_client = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/download-http-client.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+      var addPatternStart = false;
+      switch (re.charAt(0)) {
+        case "[":
+        case ".":
+        case "(":
+          addPatternStart = true;
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      for (var n = negativeLists.length - 1; n > -1; n--) {
+        var nl = negativeLists[n];
+        var nlBefore = re.slice(0, nl.reStart);
+        var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
+        var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
+        var nlAfter = re.slice(nl.reEnd);
+        nlLast += nlAfter;
+        var openParensBefore = nlBefore.split("(").length - 1;
+        var cleanAfter = nlAfter;
+        for (i = 0; i < openParensBefore; i++) {
+          cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
+        }
+        nlAfter = cleanAfter;
+        var dollar = "";
+        if (nlAfter === "" && isSub !== SUBPARSE) {
+          dollar = "$";
+        }
+        var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
+        re = newRe;
       }
-      __setModuleDefault4(result, mod);
-      return result;
+      if (re !== "" && hasMagic) {
+        re = "(?=.)" + re;
+      }
+      if (addPatternStart) {
+        re = patternStart + re;
+      }
+      if (isSub === SUBPARSE) {
+        return [re, hasMagic];
+      }
+      if (!hasMagic) {
+        return globUnescape(pattern);
+      }
+      var flags = options.nocase ? "i" : "";
+      try {
+        var regExp = new RegExp("^" + re + "$", flags);
+      } catch (er) {
+        return new RegExp("$.");
+      }
+      regExp._glob = pattern;
+      regExp._src = re;
+      return regExp;
+    }
+    minimatch.makeRe = function(pattern, options) {
+      return new Minimatch(pattern, options || {}).makeRe();
     };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
+    Minimatch.prototype.makeRe = makeRe;
+    function makeRe() {
+      if (this.regexp || this.regexp === false) return this.regexp;
+      var set2 = this.set;
+      if (!set2.length) {
+        this.regexp = false;
+        return this.regexp;
       }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      var options = this.options;
+      var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
+      var flags = options.nocase ? "i" : "";
+      var re = set2.map(function(pattern) {
+        return pattern.map(function(p) {
+          return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
+        }).join("\\/");
+      }).join("|");
+      re = "^(?:" + re + ")$";
+      if (this.negate) re = "^(?!" + re + ").*$";
+      try {
+        this.regexp = new RegExp(re, flags);
+      } catch (ex) {
+        this.regexp = false;
+      }
+      return this.regexp;
+    }
+    minimatch.match = function(list, pattern, options) {
+      options = options || {};
+      var mm = new Minimatch(pattern, options);
+      list = list.filter(function(f) {
+        return mm.match(f);
       });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.DownloadHttpClient = void 0;
-    var fs2 = __importStar4(require("fs"));
-    var core14 = __importStar4(require_core());
-    var zlib = __importStar4(require("zlib"));
-    var utils_1 = require_utils7();
-    var url_1 = require("url");
-    var status_reporter_1 = require_status_reporter();
-    var perf_hooks_1 = require("perf_hooks");
-    var http_manager_1 = require_http_manager();
-    var config_variables_1 = require_config_variables();
-    var requestUtils_1 = require_requestUtils();
-    var DownloadHttpClient = class {
-      constructor() {
-        this.downloadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getDownloadFileConcurrency)(), "@actions/artifact-download");
-        this.statusReporter = new status_reporter_1.StatusReporter(1e3);
+      if (mm.options.nonull && !list.length) {
+        list.push(pattern);
       }
-      /**
-       * Gets a list of all artifacts that are in a specific container
-       */
-      listArtifacts() {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const artifactUrl = (0, utils_1.getArtifactUrl)();
-          const client = this.downloadHttpManager.getClient(0);
-          const headers = (0, utils_1.getDownloadHeaders)("application/json");
-          const response = yield (0, requestUtils_1.retryHttpClientRequest)("List Artifacts", () => __awaiter4(this, void 0, void 0, function* () {
-            return client.get(artifactUrl, headers);
-          }));
-          const body = yield response.readBody();
-          return JSON.parse(body);
-        });
+      return list;
+    };
+    Minimatch.prototype.match = function match(f, partial) {
+      if (typeof partial === "undefined") partial = this.partial;
+      this.debug("match", f, this.pattern);
+      if (this.comment) return false;
+      if (this.empty) return f === "";
+      if (f === "/" && partial) return true;
+      var options = this.options;
+      if (path2.sep !== "/") {
+        f = f.split(path2.sep).join("/");
       }
-      /**
-       * Fetches a set of container items that describe the contents of an artifact
-       * @param artifactName the name of the artifact
-       * @param containerUrl the artifact container URL for the run
-       */
-      getContainerItems(artifactName, containerUrl) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const resourceUrl = new url_1.URL(containerUrl);
-          resourceUrl.searchParams.append("itemPath", artifactName);
-          const client = this.downloadHttpManager.getClient(0);
-          const headers = (0, utils_1.getDownloadHeaders)("application/json");
-          const response = yield (0, requestUtils_1.retryHttpClientRequest)("Get Container Items", () => __awaiter4(this, void 0, void 0, function* () {
-            return client.get(resourceUrl.toString(), headers);
-          }));
-          const body = yield response.readBody();
-          return JSON.parse(body);
-        });
+      f = f.split(slashSplit);
+      this.debug(this.pattern, "split", f);
+      var set2 = this.set;
+      this.debug(this.pattern, "set", set2);
+      var filename;
+      var i;
+      for (i = f.length - 1; i >= 0; i--) {
+        filename = f[i];
+        if (filename) break;
       }
-      /**
-       * Concurrently downloads all the files that are part of an artifact
-       * @param downloadItems information about what items to download and where to save them
-       */
-      downloadSingleArtifact(downloadItems) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const DOWNLOAD_CONCURRENCY = (0, config_variables_1.getDownloadFileConcurrency)();
-          core14.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`);
-          const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()];
-          let currentFile = 0;
-          let downloadedFiles = 0;
-          core14.info(`Total number of files that will be downloaded: ${downloadItems.length}`);
-          this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length);
-          this.statusReporter.start();
-          yield Promise.all(parallelDownloads.map((index) => __awaiter4(this, void 0, void 0, function* () {
-            while (currentFile < downloadItems.length) {
-              const currentFileToDownload = downloadItems[currentFile];
-              currentFile += 1;
-              const startTime = perf_hooks_1.performance.now();
-              yield this.downloadIndividualFile(index, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath);
-              if (core14.isDebug()) {
-                core14.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`);
-              }
-              this.statusReporter.incrementProcessedCount();
-            }
-          }))).catch((error4) => {
-            throw new Error(`Unable to download the artifact: ${error4}`);
-          }).finally(() => {
-            this.statusReporter.stop();
-            this.downloadHttpManager.disposeAndReplaceAllClients();
-          });
-        });
+      for (i = 0; i < set2.length; i++) {
+        var pattern = set2[i];
+        var file = f;
+        if (options.matchBase && pattern.length === 1) {
+          file = [filename];
+        }
+        var hit = this.matchOne(file, pattern, partial);
+        if (hit) {
+          if (options.flipNegate) return true;
+          return !this.negate;
+        }
       }
-      /**
-       * Downloads an individual file
-       * @param httpClientIndex the index of the http client that is used to make all of the calls
-       * @param artifactLocation origin location where a file will be downloaded from
-       * @param downloadPath destination location for the file being downloaded
-       */
-      downloadIndividualFile(httpClientIndex, artifactLocation, downloadPath) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          let retryCount = 0;
-          const retryLimit = (0, config_variables_1.getRetryLimit)();
-          let destinationStream = fs2.createWriteStream(downloadPath);
-          const headers = (0, utils_1.getDownloadHeaders)("application/json", true, true);
-          const makeDownloadRequest = () => __awaiter4(this, void 0, void 0, function* () {
-            const client = this.downloadHttpManager.getClient(httpClientIndex);
-            return yield client.get(artifactLocation, headers);
-          });
-          const isGzip = (incomingHeaders) => {
-            return "content-encoding" in incomingHeaders && incomingHeaders["content-encoding"] === "gzip";
-          };
-          const backOff = (retryAfterValue) => __awaiter4(this, void 0, void 0, function* () {
-            retryCount++;
-            if (retryCount > retryLimit) {
-              return Promise.reject(new Error(`Retry limit has been reached. Unable to download ${artifactLocation}`));
-            } else {
-              this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex);
-              if (retryAfterValue) {
-                core14.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`);
-                yield (0, utils_1.sleep)(retryAfterValue);
-              } else {
-                const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount);
-                core14.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`);
-                yield (0, utils_1.sleep)(backoffTime);
-              }
-              core14.info(`Finished backoff for retry #${retryCount}, continuing with download`);
-            }
-          });
-          const isAllBytesReceived = (expected, received) => {
-            if (!expected || !received || process.env["ACTIONS_ARTIFACT_SKIP_DOWNLOAD_VALIDATION"]) {
-              core14.info("Skipping download validation.");
-              return true;
-            }
-            return parseInt(expected) === received;
-          };
-          const resetDestinationStream = (fileDownloadPath) => __awaiter4(this, void 0, void 0, function* () {
-            destinationStream.close();
-            yield new Promise((resolve2) => {
-              destinationStream.on("close", resolve2);
-              if (destinationStream.writableFinished) {
-                resolve2();
-              }
-            });
-            yield (0, utils_1.rmFile)(fileDownloadPath);
-            destinationStream = fs2.createWriteStream(fileDownloadPath);
-          });
-          while (retryCount <= retryLimit) {
-            let response;
-            try {
-              response = yield makeDownloadRequest();
-            } catch (error4) {
-              core14.info("An error occurred while attempting to download a file");
-              console.log(error4);
-              yield backOff();
-              continue;
-            }
-            let forceRetry = false;
-            if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) {
-              try {
-                const isGzipped = isGzip(response.message.headers);
-                yield this.pipeResponseToFile(response, destinationStream, isGzipped);
-                if (isGzipped || isAllBytesReceived(response.message.headers["content-length"], yield (0, utils_1.getFileSize)(downloadPath))) {
-                  return;
-                } else {
-                  forceRetry = true;
-                }
-              } catch (error4) {
-                forceRetry = true;
-              }
-            }
-            if (forceRetry || (0, utils_1.isRetryableStatusCode)(response.message.statusCode)) {
-              core14.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`);
-              resetDestinationStream(downloadPath);
-              (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff();
-            } else {
-              (0, utils_1.displayHttpDiagnostics)(response);
-              return Promise.reject(new Error(`Unexpected http ${response.message.statusCode} during download for ${artifactLocation}`));
+      if (options.flipNegate) return false;
+      return this.negate;
+    };
+    Minimatch.prototype.matchOne = function(file, pattern, partial) {
+      var options = this.options;
+      this.debug(
+        "matchOne",
+        { "this": this, file, pattern }
+      );
+      this.debug("matchOne", file.length, pattern.length);
+      for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
+        this.debug("matchOne loop");
+        var p = pattern[pi];
+        var f = file[fi];
+        this.debug(pattern, p, f);
+        if (p === false) return false;
+        if (p === GLOBSTAR) {
+          this.debug("GLOBSTAR", [pattern, p, f]);
+          var fr = fi;
+          var pr = pi + 1;
+          if (pr === pl) {
+            this.debug("** at the end");
+            for (; fi < fl; fi++) {
+              if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
             }
+            return true;
           }
-        });
-      }
-      /**
-       * Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary
-       * @param response the http response received when downloading a file
-       * @param destinationStream the stream where the file should be written to
-       * @param isGzip a boolean denoting if the content is compressed using gzip and if we need to decode it
-       */
-      pipeResponseToFile(response, destinationStream, isGzip) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          yield new Promise((resolve2, reject) => {
-            if (isGzip) {
-              const gunzip = zlib.createGunzip();
-              response.message.on("error", (error4) => {
-                core14.info(`An error occurred while attempting to read the response stream`);
-                gunzip.close();
-                destinationStream.close();
-                reject(error4);
-              }).pipe(gunzip).on("error", (error4) => {
-                core14.info(`An error occurred while attempting to decompress the response stream`);
-                destinationStream.close();
-                reject(error4);
-              }).pipe(destinationStream).on("close", () => {
-                resolve2();
-              }).on("error", (error4) => {
-                core14.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`);
-                reject(error4);
-              });
+          while (fr < fl) {
+            var swallowee = file[fr];
+            this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
+            if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+              this.debug("globstar found match!", fr, fl, swallowee);
+              return true;
             } else {
-              response.message.on("error", (error4) => {
-                core14.info(`An error occurred while attempting to read the response stream`);
-                destinationStream.close();
-                reject(error4);
-              }).pipe(destinationStream).on("close", () => {
-                resolve2();
-              }).on("error", (error4) => {
-                core14.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`);
-                reject(error4);
-              });
+              if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
+                this.debug("dot detected!", file, fr, pattern, pr);
+                break;
+              }
+              this.debug("globstar swallow a segment, and continue");
+              fr++;
             }
-          });
-          return;
-        });
+          }
+          if (partial) {
+            this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
+            if (fr === fl) return true;
+          }
+          return false;
+        }
+        var hit;
+        if (typeof p === "string") {
+          hit = f === p;
+          this.debug("string match", p, f, hit);
+        } else {
+          hit = f.match(p);
+          this.debug("pattern match", p, f, hit);
+        }
+        if (!hit) return false;
+      }
+      if (fi === fl && pi === pl) {
+        return true;
+      } else if (fi === fl) {
+        return partial;
+      } else if (pi === pl) {
+        return fi === fl - 1 && file[fi] === "";
       }
+      throw new Error("wtf?");
     };
-    exports2.DownloadHttpClient = DownloadHttpClient;
+    function globUnescape(s) {
+      return s.replace(/\\(.)/g, "$1");
+    }
+    function regExpEscape(s) {
+      return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
+    }
   }
 });
 
-// node_modules/@actions/artifact-legacy/lib/internal/download-specification.js
-var require_download_specification = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/download-specification.js"(exports2) {
+// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path.js
+var require_internal_path = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
+      Object.defineProperty(o, k2, { enumerable: true, get: function() {
+        return m[k];
+      } });
     }) : (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
       o[k2] = m[k];
@@ -100649,59 +105552,90 @@ var require_download_specification = __commonJS({
       if (mod && mod.__esModule) return mod;
       var result = {};
       if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
       __setModuleDefault4(result, mod);
       return result;
     };
+    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
+      return mod && mod.__esModule ? mod : { "default": mod };
+    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getDownloadSpecification = void 0;
+    exports2.Path = void 0;
     var path2 = __importStar4(require("path"));
-    function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) {
-      const directories = /* @__PURE__ */ new Set();
-      const specifications = {
-        rootDownloadLocation: includeRootDirectory ? path2.join(downloadPath, artifactName) : downloadPath,
-        directoryStructure: [],
-        emptyFilesToCreate: [],
-        filesToDownload: []
-      };
-      for (const entry of artifactEntries) {
-        if (entry.path.startsWith(`${artifactName}/`) || entry.path.startsWith(`${artifactName}\\`)) {
-          const normalizedPathEntry = path2.normalize(entry.path);
-          const filePath = path2.join(downloadPath, includeRootDirectory ? normalizedPathEntry : normalizedPathEntry.replace(artifactName, ""));
-          if (entry.itemType === "file") {
-            directories.add(path2.dirname(filePath));
-            if (entry.fileLength === 0) {
-              specifications.emptyFilesToCreate.push(filePath);
+    var pathHelper = __importStar4(require_internal_path_helper());
+    var assert_1 = __importDefault4(require("assert"));
+    var IS_WINDOWS = process.platform === "win32";
+    var Path = class {
+      /**
+       * Constructs a Path
+       * @param itemPath Path or array of segments
+       */
+      constructor(itemPath) {
+        this.segments = [];
+        if (typeof itemPath === "string") {
+          assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`);
+          itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);
+          if (!pathHelper.hasRoot(itemPath)) {
+            this.segments = itemPath.split(path2.sep);
+          } else {
+            let remaining = itemPath;
+            let dir = pathHelper.dirname(remaining);
+            while (dir !== remaining) {
+              const basename = path2.basename(remaining);
+              this.segments.unshift(basename);
+              remaining = dir;
+              dir = pathHelper.dirname(remaining);
+            }
+            this.segments.unshift(remaining);
+          }
+        } else {
+          assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`);
+          for (let i = 0; i < itemPath.length; i++) {
+            let segment = itemPath[i];
+            assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`);
+            segment = pathHelper.normalizeSeparators(itemPath[i]);
+            if (i === 0 && pathHelper.hasRoot(segment)) {
+              segment = pathHelper.safeTrimTrailingSeparator(segment);
+              assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`);
+              this.segments.push(segment);
             } else {
-              specifications.filesToDownload.push({
-                sourceLocation: entry.contentLocation,
-                targetPath: filePath
-              });
+              assert_1.default(!segment.includes(path2.sep), `Parameter 'itemPath' contains unexpected path separators`);
+              this.segments.push(segment);
             }
           }
         }
       }
-      specifications.directoryStructure = Array.from(directories);
-      return specifications;
-    }
-    exports2.getDownloadSpecification = getDownloadSpecification;
+      /**
+       * Converts the path to it's string representation
+       */
+      toString() {
+        let result = this.segments[0];
+        let skipSlash = result.endsWith(path2.sep) || IS_WINDOWS && /^[A-Z]:$/i.test(result);
+        for (let i = 1; i < this.segments.length; i++) {
+          if (skipSlash) {
+            skipSlash = false;
+          } else {
+            result += path2.sep;
+          }
+          result += this.segments[i];
+        }
+        return result;
+      }
+    };
+    exports2.Path = Path;
   }
 });
 
-// node_modules/@actions/artifact-legacy/lib/internal/artifact-client.js
-var require_artifact_client = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/internal/artifact-client.js"(exports2) {
+// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern.js
+var require_internal_pattern = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
+      Object.defineProperty(o, k2, { enumerable: true, get: function() {
+        return m[k];
+      } });
     }) : (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
       o[k2] = m[k];
@@ -100715,1701 +105649,1709 @@ var require_artifact_client = __commonJS({
       if (mod && mod.__esModule) return mod;
       var result = {};
       if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
       __setModuleDefault4(result, mod);
       return result;
     };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
+    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
+      return mod && mod.__esModule ? mod : { "default": mod };
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.Pattern = void 0;
+    var os = __importStar4(require("os"));
+    var path2 = __importStar4(require("path"));
+    var pathHelper = __importStar4(require_internal_path_helper());
+    var assert_1 = __importDefault4(require("assert"));
+    var minimatch_1 = require_minimatch2();
+    var internal_match_kind_1 = require_internal_match_kind();
+    var internal_path_1 = require_internal_path();
+    var IS_WINDOWS = process.platform === "win32";
+    var Pattern = class _Pattern {
+      constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) {
+        this.negate = false;
+        let pattern;
+        if (typeof patternOrNegate === "string") {
+          pattern = patternOrNegate.trim();
+        } else {
+          segments = segments || [];
+          assert_1.default(segments.length, `Parameter 'segments' must not empty`);
+          const root = _Pattern.getLiteral(segments[0]);
+          assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`);
+          pattern = new internal_path_1.Path(segments).toString().trim();
+          if (patternOrNegate) {
+            pattern = `!${pattern}`;
           }
         }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+        while (pattern.startsWith("!")) {
+          this.negate = !this.negate;
+          pattern = pattern.substr(1).trim();
+        }
+        pattern = _Pattern.fixupPattern(pattern, homedir);
+        this.segments = new internal_path_1.Path(pattern).segments;
+        this.trailingSeparator = pathHelper.normalizeSeparators(pattern).endsWith(path2.sep);
+        pattern = pathHelper.safeTrimTrailingSeparator(pattern);
+        let foundGlob = false;
+        const searchSegments = this.segments.map((x) => _Pattern.getLiteral(x)).filter((x) => !foundGlob && !(foundGlob = x === ""));
+        this.searchPath = new internal_path_1.Path(searchSegments).toString();
+        this.rootRegExp = new RegExp(_Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? "i" : "");
+        this.isImplicitPattern = isImplicitPattern;
+        const minimatchOptions = {
+          dot: true,
+          nobrace: true,
+          nocase: IS_WINDOWS,
+          nocomment: true,
+          noext: true,
+          nonegate: true
+        };
+        pattern = IS_WINDOWS ? pattern.replace(/\\/g, "/") : pattern;
+        this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions);
+      }
+      /**
+       * Matches the pattern against the specified path
+       */
+      match(itemPath) {
+        if (this.segments[this.segments.length - 1] === "**") {
+          itemPath = pathHelper.normalizeSeparators(itemPath);
+          if (!itemPath.endsWith(path2.sep) && this.isImplicitPattern === false) {
+            itemPath = `${itemPath}${path2.sep}`;
           }
+        } else {
+          itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);
         }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        if (this.minimatch.match(itemPath)) {
+          return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All;
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.DefaultArtifactClient = void 0;
-    var core14 = __importStar4(require_core());
-    var upload_specification_1 = require_upload_specification();
-    var upload_http_client_1 = require_upload_http_client();
-    var utils_1 = require_utils7();
-    var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2();
-    var download_http_client_1 = require_download_http_client();
-    var download_specification_1 = require_download_specification();
-    var config_variables_1 = require_config_variables();
-    var path_1 = require("path");
-    var DefaultArtifactClient2 = class _DefaultArtifactClient {
+        return internal_match_kind_1.MatchKind.None;
+      }
       /**
-       * Constructs a DefaultArtifactClient
+       * Indicates whether the pattern may match descendants of the specified path
        */
-      static create() {
-        return new _DefaultArtifactClient();
+      partialMatch(itemPath) {
+        itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);
+        if (pathHelper.dirname(itemPath) === itemPath) {
+          return this.rootRegExp.test(itemPath);
+        }
+        return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true);
       }
       /**
-       * Uploads an artifact
+       * Escapes glob patterns within a path
        */
-      uploadArtifact(name, files, rootDirectory, options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          core14.info(`Starting artifact upload
-For more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging`);
-          (0, path_and_artifact_name_validation_1.checkArtifactName)(name);
-          const uploadSpecification = (0, upload_specification_1.getUploadSpecification)(name, rootDirectory, files);
-          const uploadResponse = {
-            artifactName: name,
-            artifactItems: [],
-            size: 0,
-            failedItems: []
-          };
-          const uploadHttpClient = new upload_http_client_1.UploadHttpClient();
-          if (uploadSpecification.length === 0) {
-            core14.warning(`No files found that can be uploaded`);
-          } else {
-            const response = yield uploadHttpClient.createArtifactInFileContainer(name, options);
-            if (!response.fileContainerResourceUrl) {
-              core14.debug(response.toString());
-              throw new Error("No URL provided by the Artifact Service to upload an artifact to");
-            }
-            core14.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`);
-            core14.info(`Container for artifact "${name}" successfully created. Starting upload of file(s)`);
-            const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options);
-            core14.info(`File upload process has finished. Finalizing the artifact upload`);
-            yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name);
-            if (uploadResult.failedItems.length > 0) {
-              core14.info(`Upload finished. There were ${uploadResult.failedItems.length} items that failed to upload`);
-            } else {
-              core14.info(`Artifact has been finalized. All files have been successfully uploaded!`);
-            }
-            core14.info(`
-The raw size of all the files that were specified for upload is ${uploadResult.totalSize} bytes
-The size of all the files that were uploaded is ${uploadResult.uploadSize} bytes. This takes into account any gzip compression used to reduce the upload size, time and storage
-
-Note: The size of downloaded zips can differ significantly from the reported size. For more information see: https://github.com/actions/upload-artifact#zipped-artifact-downloads \r
-`);
-            uploadResponse.artifactItems = uploadSpecification.map((item) => item.absoluteFilePath);
-            uploadResponse.size = uploadResult.uploadSize;
-            uploadResponse.failedItems = uploadResult.failedItems;
-          }
-          return uploadResponse;
-        });
-      }
-      downloadArtifact(name, path2, options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const downloadHttpClient = new download_http_client_1.DownloadHttpClient();
-          const artifacts = yield downloadHttpClient.listArtifacts();
-          if (artifacts.count === 0) {
-            throw new Error(`Unable to find any artifacts for the associated workflow`);
-          }
-          const artifactToDownload = artifacts.value.find((artifact2) => {
-            return artifact2.name === name;
-          });
-          if (!artifactToDownload) {
-            throw new Error(`Unable to find an artifact with the name: ${name}`);
-          }
-          const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl);
-          if (!path2) {
-            path2 = (0, config_variables_1.getWorkSpaceDirectory)();
-          }
-          path2 = (0, path_1.normalize)(path2);
-          path2 = (0, path_1.resolve)(path2);
-          const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(name, items.value, path2, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false);
-          if (downloadSpecification.filesToDownload.length === 0) {
-            core14.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`);
-          } else {
-            yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure);
-            core14.info("Directory structure has been set up for the artifact");
-            yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate);
-            yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload);
-          }
-          return {
-            artifactName: name,
-            downloadPath: downloadSpecification.rootDownloadLocation
-          };
-        });
+      static globEscape(s) {
+        return (IS_WINDOWS ? s : s.replace(/\\/g, "\\\\")).replace(/(\[)(?=[^/]+\])/g, "[[]").replace(/\?/g, "[?]").replace(/\*/g, "[*]");
       }
-      downloadAllArtifacts(path2) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const downloadHttpClient = new download_http_client_1.DownloadHttpClient();
-          const response = [];
-          const artifacts = yield downloadHttpClient.listArtifacts();
-          if (artifacts.count === 0) {
-            core14.info("Unable to find any artifacts for the associated workflow");
-            return response;
-          }
-          if (!path2) {
-            path2 = (0, config_variables_1.getWorkSpaceDirectory)();
+      /**
+       * Normalizes slashes and ensures absolute root
+       */
+      static fixupPattern(pattern, homedir) {
+        assert_1.default(pattern, "pattern cannot be empty");
+        const literalSegments = new internal_path_1.Path(pattern).segments.map((x) => _Pattern.getLiteral(x));
+        assert_1.default(literalSegments.every((x, i) => (x !== "." || i === 0) && x !== ".."), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`);
+        assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`);
+        pattern = pathHelper.normalizeSeparators(pattern);
+        if (pattern === "." || pattern.startsWith(`.${path2.sep}`)) {
+          pattern = _Pattern.globEscape(process.cwd()) + pattern.substr(1);
+        } else if (pattern === "~" || pattern.startsWith(`~${path2.sep}`)) {
+          homedir = homedir || os.homedir();
+          assert_1.default(homedir, "Unable to determine HOME directory");
+          assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`);
+          pattern = _Pattern.globEscape(homedir) + pattern.substr(1);
+        } else if (IS_WINDOWS && (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) {
+          let root = pathHelper.ensureAbsoluteRoot("C:\\dummy-root", pattern.substr(0, 2));
+          if (pattern.length > 2 && !root.endsWith("\\")) {
+            root += "\\";
           }
-          path2 = (0, path_1.normalize)(path2);
-          path2 = (0, path_1.resolve)(path2);
-          let downloadedArtifacts = 0;
-          while (downloadedArtifacts < artifacts.count) {
-            const currentArtifactToDownload = artifacts.value[downloadedArtifacts];
-            downloadedArtifacts += 1;
-            core14.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`);
-            const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl);
-            const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(currentArtifactToDownload.name, items.value, path2, true);
-            if (downloadSpecification.filesToDownload.length === 0) {
-              core14.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`);
-            } else {
-              yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure);
-              yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate);
-              yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload);
-            }
-            response.push({
-              artifactName: currentArtifactToDownload.name,
-              downloadPath: downloadSpecification.rootDownloadLocation
-            });
+          pattern = _Pattern.globEscape(root) + pattern.substr(2);
+        } else if (IS_WINDOWS && (pattern === "\\" || pattern.match(/^\\[^\\]/))) {
+          let root = pathHelper.ensureAbsoluteRoot("C:\\dummy-root", "\\");
+          if (!root.endsWith("\\")) {
+            root += "\\";
           }
-          return response;
-        });
-      }
-    };
-    exports2.DefaultArtifactClient = DefaultArtifactClient2;
-  }
-});
-
-// node_modules/@actions/artifact-legacy/lib/artifact-client.js
-var require_artifact_client2 = __commonJS({
-  "node_modules/@actions/artifact-legacy/lib/artifact-client.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.create = void 0;
-    var artifact_client_1 = require_artifact_client();
-    function create3() {
-      return artifact_client_1.DefaultArtifactClient.create();
-    }
-    exports2.create = create3;
-  }
-});
-
-// node_modules/jsonschema/lib/helpers.js
-var require_helpers3 = __commonJS({
-  "node_modules/jsonschema/lib/helpers.js"(exports2, module2) {
-    "use strict";
-    var uri = require("url");
-    var ValidationError = exports2.ValidationError = function ValidationError2(message, instance, schema2, path2, name, argument) {
-      if (Array.isArray(path2)) {
-        this.path = path2;
-        this.property = path2.reduce(function(sum, item) {
-          return sum + makeSuffix(item);
-        }, "instance");
-      } else if (path2 !== void 0) {
-        this.property = path2;
-      }
-      if (message) {
-        this.message = message;
-      }
-      if (schema2) {
-        var id = schema2.$id || schema2.id;
-        this.schema = id || schema2;
-      }
-      if (instance !== void 0) {
-        this.instance = instance;
+          pattern = _Pattern.globEscape(root) + pattern.substr(1);
+        } else {
+          pattern = pathHelper.ensureAbsoluteRoot(_Pattern.globEscape(process.cwd()), pattern);
+        }
+        return pathHelper.normalizeSeparators(pattern);
       }
-      this.name = name;
-      this.argument = argument;
-      this.stack = this.toString();
-    };
-    ValidationError.prototype.toString = function toString2() {
-      return this.property + " " + this.message;
-    };
-    var ValidatorResult = exports2.ValidatorResult = function ValidatorResult2(instance, schema2, options, ctx) {
-      this.instance = instance;
-      this.schema = schema2;
-      this.options = options;
-      this.path = ctx.path;
-      this.propertyPath = ctx.propertyPath;
-      this.errors = [];
-      this.throwError = options && options.throwError;
-      this.throwFirst = options && options.throwFirst;
-      this.throwAll = options && options.throwAll;
-      this.disableFormat = options && options.disableFormat === true;
-    };
-    ValidatorResult.prototype.addError = function addError(detail) {
-      var err;
-      if (typeof detail == "string") {
-        err = new ValidationError(detail, this.instance, this.schema, this.path);
-      } else {
-        if (!detail) throw new Error("Missing error detail");
-        if (!detail.message) throw new Error("Missing error message");
-        if (!detail.name) throw new Error("Missing validator type");
-        err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument);
+      /**
+       * Attempts to unescape a pattern segment to create a literal path segment.
+       * Otherwise returns empty string.
+       */
+      static getLiteral(segment) {
+        let literal = "";
+        for (let i = 0; i < segment.length; i++) {
+          const c = segment[i];
+          if (c === "\\" && !IS_WINDOWS && i + 1 < segment.length) {
+            literal += segment[++i];
+            continue;
+          } else if (c === "*" || c === "?") {
+            return "";
+          } else if (c === "[" && i + 1 < segment.length) {
+            let set2 = "";
+            let closed = -1;
+            for (let i2 = i + 1; i2 < segment.length; i2++) {
+              const c2 = segment[i2];
+              if (c2 === "\\" && !IS_WINDOWS && i2 + 1 < segment.length) {
+                set2 += segment[++i2];
+                continue;
+              } else if (c2 === "]") {
+                closed = i2;
+                break;
+              } else {
+                set2 += c2;
+              }
+            }
+            if (closed >= 0) {
+              if (set2.length > 1) {
+                return "";
+              }
+              if (set2) {
+                literal += set2;
+                i = closed;
+                continue;
+              }
+            }
+          }
+          literal += c;
+        }
+        return literal;
       }
-      this.errors.push(err);
-      if (this.throwFirst) {
-        throw new ValidatorResultError(this);
-      } else if (this.throwError) {
-        throw err;
+      /**
+       * Escapes regexp special characters
+       * https://javascript.info/regexp-escaping
+       */
+      static regExpEscape(s) {
+        return s.replace(/[[\\^$.|?*+()]/g, "\\$&");
       }
-      return err;
     };
-    ValidatorResult.prototype.importErrors = function importErrors(res) {
-      if (typeof res == "string" || res && res.validatorType) {
-        this.addError(res);
-      } else if (res && res.errors) {
-        this.errors = this.errors.concat(res.errors);
+    exports2.Pattern = Pattern;
+  }
+});
+
+// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-search-state.js
+var require_internal_search_state = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-search-state.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.SearchState = void 0;
+    var SearchState = class {
+      constructor(path2, level) {
+        this.path = path2;
+        this.level = level;
       }
     };
-    function stringizer(v, i) {
-      return i + ": " + v.toString() + "\n";
-    }
-    ValidatorResult.prototype.toString = function toString2(res) {
-      return this.errors.map(stringizer).join("");
+    exports2.SearchState = SearchState;
+  }
+});
+
+// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-globber.js
+var require_internal_globber = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-globber.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      Object.defineProperty(o, k2, { enumerable: true, get: function() {
+        return m[k];
+      } });
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
     };
-    Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() {
-      return !this.errors.length;
-    } });
-    module2.exports.ValidatorResultError = ValidatorResultError;
-    function ValidatorResultError(result) {
-      if (Error.captureStackTrace) {
-        Error.captureStackTrace(this, ValidatorResultError);
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      this.instance = result.instance;
-      this.schema = result.schema;
-      this.options = result.options;
-      this.errors = result.errors;
-    }
-    ValidatorResultError.prototype = new Error();
-    ValidatorResultError.prototype.constructor = ValidatorResultError;
-    ValidatorResultError.prototype.name = "Validation Error";
-    var SchemaError = exports2.SchemaError = function SchemaError2(msg, schema2) {
-      this.message = msg;
-      this.schema = schema2;
-      Error.call(this, msg);
-      Error.captureStackTrace(this, SchemaError2);
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    SchemaError.prototype = Object.create(
-      Error.prototype,
-      {
-        constructor: { value: SchemaError, enumerable: false },
-        name: { value: "SchemaError", enumerable: false }
+    var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) {
+      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+      var m = o[Symbol.asyncIterator], i;
+      return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
+        return this;
+      }, i);
+      function verb(n) {
+        i[n] = o[n] && function(v) {
+          return new Promise(function(resolve2, reject) {
+            v = o[n](v), settle(resolve2, reject, v.done, v.value);
+          });
+        };
       }
-    );
-    var SchemaContext = exports2.SchemaContext = function SchemaContext2(schema2, options, path2, base, schemas) {
-      this.schema = schema2;
-      this.options = options;
-      if (Array.isArray(path2)) {
-        this.path = path2;
-        this.propertyPath = path2.reduce(function(sum, item) {
-          return sum + makeSuffix(item);
-        }, "instance");
-      } else {
-        this.propertyPath = path2;
+      function settle(resolve2, reject, d, v) {
+        Promise.resolve(v).then(function(v2) {
+          resolve2({ value: v2, done: d });
+        }, reject);
       }
-      this.base = base;
-      this.schemas = schemas;
     };
-    SchemaContext.prototype.resolve = function resolve2(target) {
-      return uri.resolve(this.base, target);
+    var __await4 = exports2 && exports2.__await || function(v) {
+      return this instanceof __await4 ? (this.v = v, this) : new __await4(v);
     };
-    SchemaContext.prototype.makeChild = function makeChild(schema2, propertyName) {
-      var path2 = propertyName === void 0 ? this.path : this.path.concat([propertyName]);
-      var id = schema2.$id || schema2.id;
-      var base = uri.resolve(this.base, id || "");
-      var ctx = new SchemaContext(schema2, this.options, path2, base, Object.create(this.schemas));
-      if (id && !ctx.schemas[base]) {
-        ctx.schemas[base] = schema2;
+    var __asyncGenerator4 = exports2 && exports2.__asyncGenerator || function(thisArg, _arguments, generator) {
+      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+      var g = generator.apply(thisArg, _arguments || []), i, q = [];
+      return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
+        return this;
+      }, i;
+      function verb(n) {
+        if (g[n]) i[n] = function(v) {
+          return new Promise(function(a, b) {
+            q.push([n, v, a, b]) > 1 || resume(n, v);
+          });
+        };
       }
-      return ctx;
-    };
-    var FORMAT_REGEXPS = exports2.FORMAT_REGEXPS = {
-      // 7.3.1. Dates, Times, and Duration
-      "date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,
-      "date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,
-      "time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,
-      "duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,
-      // 7.3.2. Email Addresses
-      // TODO: fix the email production
-      "email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,
-      "idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,
-      // 7.3.3. Hostnames
-      // 7.3.4. IP Addresses
-      "ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
-      // FIXME whitespace is invalid
-      "ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,
-      // 7.3.5. Resource Identifiers
-      // TODO: A more accurate regular expression for "uri" goes:
-      // [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)?
-      "uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
-      "uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,
-      "iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
-      "iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,
-      "uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
-      // 7.3.6. uri-template
-      "uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,
-      // 7.3.7. JSON Pointers
-      "json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,
-      "relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,
-      // hostname regex from: http://stackoverflow.com/a/1420225/5628
-      "hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
-      "host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
-      "utc-millisec": function(input) {
-        return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input);
-      },
-      // 7.3.8. regex
-      "regex": function(input) {
-        var result = true;
+      function resume(n, v) {
         try {
-          new RegExp(input);
+          step(g[n](v));
         } catch (e) {
-          result = false;
-        }
-        return result;
-      },
-      // Other definitions
-      // "style" was removed from JSON Schema in draft-4 and is deprecated
-      "style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,
-      // "color" was removed from JSON Schema in draft-4 and is deprecated
-      "color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,
-      "phone": /^\+(?:[0-9] ?){6,14}[0-9]$/,
-      "alpha": /^[a-zA-Z]+$/,
-      "alphanumeric": /^[a-zA-Z0-9]+$/
-    };
-    FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex;
-    FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex;
-    FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"];
-    exports2.isFormat = function isFormat(input, format, validator) {
-      if (typeof input === "string" && FORMAT_REGEXPS[format] !== void 0) {
-        if (FORMAT_REGEXPS[format] instanceof RegExp) {
-          return FORMAT_REGEXPS[format].test(input);
-        }
-        if (typeof FORMAT_REGEXPS[format] === "function") {
-          return FORMAT_REGEXPS[format](input);
+          settle(q[0][3], e);
         }
-      } else if (validator && validator.customFormats && typeof validator.customFormats[format] === "function") {
-        return validator.customFormats[format](input);
       }
-      return true;
-    };
-    var makeSuffix = exports2.makeSuffix = function makeSuffix2(key) {
-      key = key.toString();
-      if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) {
-        return "." + key;
-      }
-      if (key.match(/^\d+$/)) {
-        return "[" + key + "]";
+      function step(r) {
+        r.value instanceof __await4 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
       }
-      return "[" + JSON.stringify(key) + "]";
-    };
-    exports2.deepCompareStrict = function deepCompareStrict(a, b) {
-      if (typeof a !== typeof b) {
-        return false;
+      function fulfill(value) {
+        resume("next", value);
       }
-      if (Array.isArray(a)) {
-        if (!Array.isArray(b)) {
-          return false;
-        }
-        if (a.length !== b.length) {
-          return false;
-        }
-        return a.every(function(v, i) {
-          return deepCompareStrict(a[i], b[i]);
-        });
+      function reject(value) {
+        resume("throw", value);
       }
-      if (typeof a === "object") {
-        if (!a || !b) {
-          return a === b;
-        }
-        var aKeys = Object.keys(a);
-        var bKeys = Object.keys(b);
-        if (aKeys.length !== bKeys.length) {
-          return false;
-        }
-        return aKeys.every(function(v) {
-          return deepCompareStrict(a[v], b[v]);
-        });
+      function settle(f, v) {
+        if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
       }
-      return a === b;
     };
-    function deepMerger(target, dst, e, i) {
-      if (typeof e === "object") {
-        dst[i] = deepMerge(target[i], e);
-      } else {
-        if (target.indexOf(e) === -1) {
-          dst.push(e);
-        }
-      }
-    }
-    function copyist(src, dst, key) {
-      dst[key] = src[key];
-    }
-    function copyistWithDeepMerge(target, src, dst, key) {
-      if (typeof src[key] !== "object" || !src[key]) {
-        dst[key] = src[key];
-      } else {
-        if (!target[key]) {
-          dst[key] = src[key];
-        } else {
-          dst[key] = deepMerge(target[key], src[key]);
-        }
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.DefaultGlobber = void 0;
+    var core14 = __importStar4(require_core());
+    var fs2 = __importStar4(require("fs"));
+    var globOptionsHelper = __importStar4(require_internal_glob_options_helper());
+    var path2 = __importStar4(require("path"));
+    var patternHelper = __importStar4(require_internal_pattern_helper());
+    var internal_match_kind_1 = require_internal_match_kind();
+    var internal_pattern_1 = require_internal_pattern();
+    var internal_search_state_1 = require_internal_search_state();
+    var IS_WINDOWS = process.platform === "win32";
+    var DefaultGlobber = class _DefaultGlobber {
+      constructor(options) {
+        this.patterns = [];
+        this.searchPaths = [];
+        this.options = globOptionsHelper.getOptions(options);
       }
-    }
-    function deepMerge(target, src) {
-      var array = Array.isArray(src);
-      var dst = array && [] || {};
-      if (array) {
-        target = target || [];
-        dst = dst.concat(target);
-        src.forEach(deepMerger.bind(null, target, dst));
-      } else {
-        if (target && typeof target === "object") {
-          Object.keys(target).forEach(copyist.bind(null, target, dst));
-        }
-        Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst));
+      getSearchPaths() {
+        return this.searchPaths.slice();
       }
-      return dst;
-    }
-    module2.exports.deepMerge = deepMerge;
-    exports2.objectGetPath = function objectGetPath(o, s) {
-      var parts = s.split("/").slice(1);
-      var k;
-      while (typeof (k = parts.shift()) == "string") {
-        var n = decodeURIComponent(k.replace(/~0/, "~").replace(/~1/g, "/"));
-        if (!(n in o)) return;
-        o = o[n];
+      glob() {
+        var e_1, _a;
+        return __awaiter4(this, void 0, void 0, function* () {
+          const result = [];
+          try {
+            for (var _b = __asyncValues4(this.globGenerator()), _c; _c = yield _b.next(), !_c.done; ) {
+              const itemPath = _c.value;
+              result.push(itemPath);
+            }
+          } catch (e_1_1) {
+            e_1 = { error: e_1_1 };
+          } finally {
+            try {
+              if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
+            } finally {
+              if (e_1) throw e_1.error;
+            }
+          }
+          return result;
+        });
       }
-      return o;
-    };
-    function pathEncoder(v) {
-      return "/" + encodeURIComponent(v).replace(/~/g, "%7E");
-    }
-    exports2.encodePath = function encodePointer(a) {
-      return a.map(pathEncoder).join("");
-    };
-    exports2.getDecimalPlaces = function getDecimalPlaces(number) {
-      var decimalPlaces = 0;
-      if (isNaN(number)) return decimalPlaces;
-      if (typeof number !== "number") {
-        number = Number(number);
+      globGenerator() {
+        return __asyncGenerator4(this, arguments, function* globGenerator_1() {
+          const options = globOptionsHelper.getOptions(this.options);
+          const patterns = [];
+          for (const pattern of this.patterns) {
+            patterns.push(pattern);
+            if (options.implicitDescendants && (pattern.trailingSeparator || pattern.segments[pattern.segments.length - 1] !== "**")) {
+              patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat("**")));
+            }
+          }
+          const stack = [];
+          for (const searchPath of patternHelper.getSearchPaths(patterns)) {
+            core14.debug(`Search path '${searchPath}'`);
+            try {
+              yield __await4(fs2.promises.lstat(searchPath));
+            } catch (err) {
+              if (err.code === "ENOENT") {
+                continue;
+              }
+              throw err;
+            }
+            stack.unshift(new internal_search_state_1.SearchState(searchPath, 1));
+          }
+          const traversalChain = [];
+          while (stack.length) {
+            const item = stack.pop();
+            const match = patternHelper.match(patterns, item.path);
+            const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path);
+            if (!match && !partialMatch) {
+              continue;
+            }
+            const stats = yield __await4(
+              _DefaultGlobber.stat(item, options, traversalChain)
+              // Broken symlink, or symlink cycle detected, or no longer exists
+            );
+            if (!stats) {
+              continue;
+            }
+            if (stats.isDirectory()) {
+              if (match & internal_match_kind_1.MatchKind.Directory) {
+                yield yield __await4(item.path);
+              } else if (!partialMatch) {
+                continue;
+              }
+              const childLevel = item.level + 1;
+              const childItems = (yield __await4(fs2.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path2.join(item.path, x), childLevel));
+              stack.push(...childItems.reverse());
+            } else if (match & internal_match_kind_1.MatchKind.File) {
+              yield yield __await4(item.path);
+            }
+          }
+        });
       }
-      var parts = number.toString().split("e");
-      if (parts.length === 2) {
-        if (parts[1][0] !== "-") {
-          return decimalPlaces;
-        } else {
-          decimalPlaces = Number(parts[1].slice(1));
-        }
+      /**
+       * Constructs a DefaultGlobber
+       */
+      static create(patterns, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const result = new _DefaultGlobber(options);
+          if (IS_WINDOWS) {
+            patterns = patterns.replace(/\r\n/g, "\n");
+            patterns = patterns.replace(/\r/g, "\n");
+          }
+          const lines = patterns.split("\n").map((x) => x.trim());
+          for (const line of lines) {
+            if (!line || line.startsWith("#")) {
+              continue;
+            } else {
+              result.patterns.push(new internal_pattern_1.Pattern(line));
+            }
+          }
+          result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns));
+          return result;
+        });
       }
-      var decimalParts = parts[0].split(".");
-      if (decimalParts.length === 2) {
-        decimalPlaces += decimalParts[1].length;
+      static stat(item, options, traversalChain) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          let stats;
+          if (options.followSymbolicLinks) {
+            try {
+              stats = yield fs2.promises.stat(item.path);
+            } catch (err) {
+              if (err.code === "ENOENT") {
+                if (options.omitBrokenSymbolicLinks) {
+                  core14.debug(`Broken symlink '${item.path}'`);
+                  return void 0;
+                }
+                throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`);
+              }
+              throw err;
+            }
+          } else {
+            stats = yield fs2.promises.lstat(item.path);
+          }
+          if (stats.isDirectory() && options.followSymbolicLinks) {
+            const realPath = yield fs2.promises.realpath(item.path);
+            while (traversalChain.length >= item.level) {
+              traversalChain.pop();
+            }
+            if (traversalChain.some((x) => x === realPath)) {
+              core14.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`);
+              return void 0;
+            }
+            traversalChain.push(realPath);
+          }
+          return stats;
+        });
       }
-      return decimalPlaces;
-    };
-    exports2.isSchema = function isSchema(val2) {
-      return typeof val2 === "object" && val2 || typeof val2 === "boolean";
     };
+    exports2.DefaultGlobber = DefaultGlobber;
   }
 });
 
-// node_modules/jsonschema/lib/attribute.js
-var require_attribute = __commonJS({
-  "node_modules/jsonschema/lib/attribute.js"(exports2, module2) {
+// node_modules/@actions/cache/node_modules/@actions/glob/lib/glob.js
+var require_glob2 = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/glob/lib/glob.js"(exports2) {
     "use strict";
-    var helpers = require_helpers3();
-    var ValidatorResult = helpers.ValidatorResult;
-    var SchemaError = helpers.SchemaError;
-    var attribute = {};
-    attribute.ignoreProperties = {
-      // informative properties
-      "id": true,
-      "default": true,
-      "description": true,
-      "title": true,
-      // arguments to other properties
-      "additionalItems": true,
-      "then": true,
-      "else": true,
-      // special-handled properties
-      "$schema": true,
-      "$ref": true,
-      "extends": true
-    };
-    var validators = attribute.validators = {};
-    validators.type = function validateType(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
-      }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var types = Array.isArray(schema2.type) ? schema2.type : [schema2.type];
-      if (!types.some(this.testType.bind(this, instance, schema2, options, ctx))) {
-        var list = types.map(function(v) {
-          if (!v) return;
-          var id = v.$id || v.id;
-          return id ? "<" + id + ">" : v + "";
-        });
-        result.addError({
-          name: "type",
-          argument: list,
-          message: "is not of a type(s) " + list
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
         });
       }
-      return result;
-    };
-    function testSchemaNoThrow(instance, options, ctx, callback, schema2) {
-      var throwError2 = options.throwError;
-      var throwAll = options.throwAll;
-      options.throwError = false;
-      options.throwAll = false;
-      var res = this.validateSchema(instance, schema2, options, ctx);
-      options.throwError = throwError2;
-      options.throwAll = throwAll;
-      if (!res.valid && callback instanceof Function) {
-        callback(res);
-      }
-      return res.valid;
-    }
-    validators.anyOf = function validateAnyOf(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
-      }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var inner = new ValidatorResult(instance, schema2, options, ctx);
-      if (!Array.isArray(schema2.anyOf)) {
-        throw new SchemaError("anyOf must be an array");
-      }
-      if (!schema2.anyOf.some(
-        testSchemaNoThrow.bind(
-          this,
-          instance,
-          options,
-          ctx,
-          function(res) {
-            inner.importErrors(res);
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
           }
-        )
-      )) {
-        var list = schema2.anyOf.map(function(v, i) {
-          var id = v.$id || v.id;
-          if (id) return "<" + id + ">";
-          return v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
-        });
-        if (options.nestedErrors) {
-          result.importErrors(inner);
         }
-        result.addError({
-          name: "anyOf",
-          argument: list,
-          message: "is not any of " + list.join(",")
-        });
-      }
-      return result;
-    };
-    validators.allOf = function validateAllOf(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
-      }
-      if (!Array.isArray(schema2.allOf)) {
-        throw new SchemaError("allOf must be an array");
-      }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var self2 = this;
-      schema2.allOf.forEach(function(v, i) {
-        var valid3 = self2.validateSchema(instance, v, options, ctx);
-        if (!valid3.valid) {
-          var id = v.$id || v.id;
-          var msg = id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
-          result.addError({
-            name: "allOf",
-            argument: { id: msg, length: valid3.errors.length, valid: valid3 },
-            message: "does not match allOf schema " + msg + " with " + valid3.errors.length + " error[s]:"
-          });
-          result.importErrors(valid3);
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
         }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
       });
-      return result;
     };
-    validators.oneOf = function validateOneOf(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
-      }
-      if (!Array.isArray(schema2.oneOf)) {
-        throw new SchemaError("oneOf must be an array");
-      }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var inner = new ValidatorResult(instance, schema2, options, ctx);
-      var count = schema2.oneOf.filter(
-        testSchemaNoThrow.bind(
-          this,
-          instance,
-          options,
-          ctx,
-          function(res) {
-            inner.importErrors(res);
-          }
-        )
-      ).length;
-      var list = schema2.oneOf.map(function(v, i) {
-        var id = v.$id || v.id;
-        return id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.create = void 0;
+    var internal_globber_1 = require_internal_globber();
+    function create3(patterns, options) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        return yield internal_globber_1.DefaultGlobber.create(patterns, options);
       });
-      if (count !== 1) {
-        if (options.nestedErrors) {
-          result.importErrors(inner);
-        }
-        result.addError({
-          name: "oneOf",
-          argument: list,
-          message: "is not exactly one from " + list.join(",")
-        });
-      }
-      return result;
-    };
-    validators.if = function validateIf(instance, schema2, options, ctx) {
-      if (instance === void 0) return null;
-      if (!helpers.isSchema(schema2.if)) throw new Error('Expected "if" keyword to be a schema');
-      var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema2.if);
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var res;
-      if (ifValid) {
-        if (schema2.then === void 0) return;
-        if (!helpers.isSchema(schema2.then)) throw new Error('Expected "then" keyword to be a schema');
-        res = this.validateSchema(instance, schema2.then, options, ctx.makeChild(schema2.then));
-        result.importErrors(res);
-      } else {
-        if (schema2.else === void 0) return;
-        if (!helpers.isSchema(schema2.else)) throw new Error('Expected "else" keyword to be a schema');
-        res = this.validateSchema(instance, schema2.else, options, ctx.makeChild(schema2.else));
-        result.importErrors(res);
-      }
-      return result;
-    };
-    function getEnumerableProperty(object, key) {
-      if (Object.hasOwnProperty.call(object, key)) return object[key];
-      if (!(key in object)) return;
-      while (object = Object.getPrototypeOf(object)) {
-        if (Object.propertyIsEnumerable.call(object, key)) return object[key];
-      }
     }
-    validators.propertyNames = function validatePropertyNames(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var subschema = schema2.propertyNames !== void 0 ? schema2.propertyNames : {};
-      if (!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)');
-      for (var property in instance) {
-        if (getEnumerableProperty(instance, property) !== void 0) {
-          var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema));
-          result.importErrors(res);
-        }
+    exports2.create = create3;
+  }
+});
+
+// node_modules/@actions/cache/node_modules/semver/semver.js
+var require_semver3 = __commonJS({
+  "node_modules/@actions/cache/node_modules/semver/semver.js"(exports2, module2) {
+    exports2 = module2.exports = SemVer;
+    var debug4;
+    if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
+      debug4 = function() {
+        var args = Array.prototype.slice.call(arguments, 0);
+        args.unshift("SEMVER");
+        console.log.apply(console, args);
+      };
+    } else {
+      debug4 = function() {
+      };
+    }
+    exports2.SEMVER_SPEC_VERSION = "2.0.0";
+    var MAX_LENGTH = 256;
+    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
+    9007199254740991;
+    var MAX_SAFE_COMPONENT_LENGTH = 16;
+    var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
+    var re = exports2.re = [];
+    var safeRe = exports2.safeRe = [];
+    var src = exports2.src = [];
+    var t = exports2.tokens = {};
+    var R = 0;
+    function tok(n) {
+      t[n] = R++;
+    }
+    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
+    var safeRegexReplacements = [
+      ["\\s", 1],
+      ["\\d", MAX_LENGTH],
+      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
+    ];
+    function makeSafeRe(value) {
+      for (var i2 = 0; i2 < safeRegexReplacements.length; i2++) {
+        var token = safeRegexReplacements[i2][0];
+        var max = safeRegexReplacements[i2][1];
+        value = value.split(token + "*").join(token + "{0," + max + "}").split(token + "+").join(token + "{1," + max + "}");
       }
-      return result;
-    };
-    validators.properties = function validateProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var properties = schema2.properties || {};
-      for (var property in properties) {
-        var subschema = properties[property];
-        if (subschema === void 0) {
-          continue;
-        } else if (subschema === null) {
-          throw new SchemaError('Unexpected null, expected schema in "properties"');
-        }
-        if (typeof options.preValidateProperty == "function") {
-          options.preValidateProperty(instance, property, subschema, options, ctx);
-        }
-        var prop = getEnumerableProperty(instance, property);
-        var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property));
-        if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
-        result.importErrors(res);
+      return value;
+    }
+    tok("NUMERICIDENTIFIER");
+    src[t.NUMERICIDENTIFIER] = "0|[1-9]\\d*";
+    tok("NUMERICIDENTIFIERLOOSE");
+    src[t.NUMERICIDENTIFIERLOOSE] = "\\d+";
+    tok("NONNUMERICIDENTIFIER");
+    src[t.NONNUMERICIDENTIFIER] = "\\d*[a-zA-Z-]" + LETTERDASHNUMBER + "*";
+    tok("MAINVERSION");
+    src[t.MAINVERSION] = "(" + src[t.NUMERICIDENTIFIER] + ")\\.(" + src[t.NUMERICIDENTIFIER] + ")\\.(" + src[t.NUMERICIDENTIFIER] + ")";
+    tok("MAINVERSIONLOOSE");
+    src[t.MAINVERSIONLOOSE] = "(" + src[t.NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[t.NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[t.NUMERICIDENTIFIERLOOSE] + ")";
+    tok("PRERELEASEIDENTIFIER");
+    src[t.PRERELEASEIDENTIFIER] = "(?:" + src[t.NUMERICIDENTIFIER] + "|" + src[t.NONNUMERICIDENTIFIER] + ")";
+    tok("PRERELEASEIDENTIFIERLOOSE");
+    src[t.PRERELEASEIDENTIFIERLOOSE] = "(?:" + src[t.NUMERICIDENTIFIERLOOSE] + "|" + src[t.NONNUMERICIDENTIFIER] + ")";
+    tok("PRERELEASE");
+    src[t.PRERELEASE] = "(?:-(" + src[t.PRERELEASEIDENTIFIER] + "(?:\\." + src[t.PRERELEASEIDENTIFIER] + ")*))";
+    tok("PRERELEASELOOSE");
+    src[t.PRERELEASELOOSE] = "(?:-?(" + src[t.PRERELEASEIDENTIFIERLOOSE] + "(?:\\." + src[t.PRERELEASEIDENTIFIERLOOSE] + ")*))";
+    tok("BUILDIDENTIFIER");
+    src[t.BUILDIDENTIFIER] = LETTERDASHNUMBER + "+";
+    tok("BUILD");
+    src[t.BUILD] = "(?:\\+(" + src[t.BUILDIDENTIFIER] + "(?:\\." + src[t.BUILDIDENTIFIER] + ")*))";
+    tok("FULL");
+    tok("FULLPLAIN");
+    src[t.FULLPLAIN] = "v?" + src[t.MAINVERSION] + src[t.PRERELEASE] + "?" + src[t.BUILD] + "?";
+    src[t.FULL] = "^" + src[t.FULLPLAIN] + "$";
+    tok("LOOSEPLAIN");
+    src[t.LOOSEPLAIN] = "[v=\\s]*" + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + "?" + src[t.BUILD] + "?";
+    tok("LOOSE");
+    src[t.LOOSE] = "^" + src[t.LOOSEPLAIN] + "$";
+    tok("GTLT");
+    src[t.GTLT] = "((?:<|>)?=?)";
+    tok("XRANGEIDENTIFIERLOOSE");
+    src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + "|x|X|\\*";
+    tok("XRANGEIDENTIFIER");
+    src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + "|x|X|\\*";
+    tok("XRANGEPLAIN");
+    src[t.XRANGEPLAIN] = "[v=\\s]*(" + src[t.XRANGEIDENTIFIER] + ")(?:\\.(" + src[t.XRANGEIDENTIFIER] + ")(?:\\.(" + src[t.XRANGEIDENTIFIER] + ")(?:" + src[t.PRERELEASE] + ")?" + src[t.BUILD] + "?)?)?";
+    tok("XRANGEPLAINLOOSE");
+    src[t.XRANGEPLAINLOOSE] = "[v=\\s]*(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:" + src[t.PRERELEASELOOSE] + ")?" + src[t.BUILD] + "?)?)?";
+    tok("XRANGE");
+    src[t.XRANGE] = "^" + src[t.GTLT] + "\\s*" + src[t.XRANGEPLAIN] + "$";
+    tok("XRANGELOOSE");
+    src[t.XRANGELOOSE] = "^" + src[t.GTLT] + "\\s*" + src[t.XRANGEPLAINLOOSE] + "$";
+    tok("COERCE");
+    src[t.COERCE] = "(^|[^\\d])(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "})(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:$|[^\\d])";
+    tok("COERCERTL");
+    re[t.COERCERTL] = new RegExp(src[t.COERCE], "g");
+    safeRe[t.COERCERTL] = new RegExp(makeSafeRe(src[t.COERCE]), "g");
+    tok("LONETILDE");
+    src[t.LONETILDE] = "(?:~>?)";
+    tok("TILDETRIM");
+    src[t.TILDETRIM] = "(\\s*)" + src[t.LONETILDE] + "\\s+";
+    re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], "g");
+    safeRe[t.TILDETRIM] = new RegExp(makeSafeRe(src[t.TILDETRIM]), "g");
+    var tildeTrimReplace = "$1~";
+    tok("TILDE");
+    src[t.TILDE] = "^" + src[t.LONETILDE] + src[t.XRANGEPLAIN] + "$";
+    tok("TILDELOOSE");
+    src[t.TILDELOOSE] = "^" + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + "$";
+    tok("LONECARET");
+    src[t.LONECARET] = "(?:\\^)";
+    tok("CARETTRIM");
+    src[t.CARETTRIM] = "(\\s*)" + src[t.LONECARET] + "\\s+";
+    re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], "g");
+    safeRe[t.CARETTRIM] = new RegExp(makeSafeRe(src[t.CARETTRIM]), "g");
+    var caretTrimReplace = "$1^";
+    tok("CARET");
+    src[t.CARET] = "^" + src[t.LONECARET] + src[t.XRANGEPLAIN] + "$";
+    tok("CARETLOOSE");
+    src[t.CARETLOOSE] = "^" + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + "$";
+    tok("COMPARATORLOOSE");
+    src[t.COMPARATORLOOSE] = "^" + src[t.GTLT] + "\\s*(" + src[t.LOOSEPLAIN] + ")$|^$";
+    tok("COMPARATOR");
+    src[t.COMPARATOR] = "^" + src[t.GTLT] + "\\s*(" + src[t.FULLPLAIN] + ")$|^$";
+    tok("COMPARATORTRIM");
+    src[t.COMPARATORTRIM] = "(\\s*)" + src[t.GTLT] + "\\s*(" + src[t.LOOSEPLAIN] + "|" + src[t.XRANGEPLAIN] + ")";
+    re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], "g");
+    safeRe[t.COMPARATORTRIM] = new RegExp(makeSafeRe(src[t.COMPARATORTRIM]), "g");
+    var comparatorTrimReplace = "$1$2$3";
+    tok("HYPHENRANGE");
+    src[t.HYPHENRANGE] = "^\\s*(" + src[t.XRANGEPLAIN] + ")\\s+-\\s+(" + src[t.XRANGEPLAIN] + ")\\s*$";
+    tok("HYPHENRANGELOOSE");
+    src[t.HYPHENRANGELOOSE] = "^\\s*(" + src[t.XRANGEPLAINLOOSE] + ")\\s+-\\s+(" + src[t.XRANGEPLAINLOOSE] + ")\\s*$";
+    tok("STAR");
+    src[t.STAR] = "(<|>)?=?\\s*\\*";
+    for (i = 0; i < R; i++) {
+      debug4(i, src[i]);
+      if (!re[i]) {
+        re[i] = new RegExp(src[i]);
+        safeRe[i] = new RegExp(makeSafeRe(src[i]));
       }
-      return result;
-    };
-    function testAdditionalProperty(instance, schema2, options, ctx, property, result) {
-      if (!this.types.object(instance)) return;
-      if (schema2.properties && schema2.properties[property] !== void 0) {
-        return;
+    }
+    var i;
+    exports2.parse = parse;
+    function parse(version, options) {
+      if (!options || typeof options !== "object") {
+        options = {
+          loose: !!options,
+          includePrerelease: false
+        };
       }
-      if (schema2.additionalProperties === false) {
-        result.addError({
-          name: "additionalProperties",
-          argument: property,
-          message: "is not allowed to have the additional property " + JSON.stringify(property)
-        });
-      } else {
-        var additionalProperties = schema2.additionalProperties || {};
-        if (typeof options.preValidateProperty == "function") {
-          options.preValidateProperty(instance, property, additionalProperties, options, ctx);
-        }
-        var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property));
-        if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
-        result.importErrors(res);
+      if (version instanceof SemVer) {
+        return version;
       }
-    }
-    validators.patternProperties = function validatePatternProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var patternProperties = schema2.patternProperties || {};
-      for (var property in instance) {
-        var test = true;
-        for (var pattern in patternProperties) {
-          var subschema = patternProperties[pattern];
-          if (subschema === void 0) {
-            continue;
-          } else if (subschema === null) {
-            throw new SchemaError('Unexpected null, expected schema in "patternProperties"');
-          }
-          try {
-            var regexp = new RegExp(pattern, "u");
-          } catch (_e) {
-            regexp = new RegExp(pattern);
-          }
-          if (!regexp.test(property)) {
-            continue;
-          }
-          test = false;
-          if (typeof options.preValidateProperty == "function") {
-            options.preValidateProperty(instance, property, subschema, options, ctx);
-          }
-          var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property));
-          if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
-          result.importErrors(res);
-        }
-        if (test) {
-          testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result);
-        }
+      if (typeof version !== "string") {
+        return null;
       }
-      return result;
-    };
-    validators.additionalProperties = function validateAdditionalProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      if (schema2.patternProperties) {
+      if (version.length > MAX_LENGTH) {
         return null;
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      for (var property in instance) {
-        testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result);
+      var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL];
+      if (!r.test(version)) {
+        return null;
       }
-      return result;
-    };
-    validators.minProperties = function validateMinProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var keys = Object.keys(instance);
-      if (!(keys.length >= schema2.minProperties)) {
-        result.addError({
-          name: "minProperties",
-          argument: schema2.minProperties,
-          message: "does not meet minimum property length of " + schema2.minProperties
-        });
+      try {
+        return new SemVer(version, options);
+      } catch (er) {
+        return null;
       }
-      return result;
-    };
-    validators.maxProperties = function validateMaxProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var keys = Object.keys(instance);
-      if (!(keys.length <= schema2.maxProperties)) {
-        result.addError({
-          name: "maxProperties",
-          argument: schema2.maxProperties,
-          message: "does not meet maximum property length of " + schema2.maxProperties
-        });
+    }
+    exports2.valid = valid3;
+    function valid3(version, options) {
+      var v = parse(version, options);
+      return v ? v.version : null;
+    }
+    exports2.clean = clean3;
+    function clean3(version, options) {
+      var s = parse(version.trim().replace(/^[=v]+/, ""), options);
+      return s ? s.version : null;
+    }
+    exports2.SemVer = SemVer;
+    function SemVer(version, options) {
+      if (!options || typeof options !== "object") {
+        options = {
+          loose: !!options,
+          includePrerelease: false
+        };
       }
-      return result;
-    };
-    validators.items = function validateItems(instance, schema2, options, ctx) {
-      var self2 = this;
-      if (!this.types.array(instance)) return;
-      if (schema2.items === void 0) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      instance.every(function(value, i) {
-        if (Array.isArray(schema2.items)) {
-          var items = schema2.items[i] === void 0 ? schema2.additionalItems : schema2.items[i];
+      if (version instanceof SemVer) {
+        if (version.loose === options.loose) {
+          return version;
         } else {
-          var items = schema2.items;
-        }
-        if (items === void 0) {
-          return true;
-        }
-        if (items === false) {
-          result.addError({
-            name: "items",
-            message: "additionalItems not permitted"
-          });
-          return false;
+          version = version.version;
         }
-        var res = self2.validateSchema(value, items, options, ctx.makeChild(items, i));
-        if (res.instance !== result.instance[i]) result.instance[i] = res.instance;
-        result.importErrors(res);
-        return true;
-      });
-      return result;
-    };
-    validators.contains = function validateContains(instance, schema2, options, ctx) {
-      var self2 = this;
-      if (!this.types.array(instance)) return;
-      if (schema2.contains === void 0) return;
-      if (!helpers.isSchema(schema2.contains)) throw new Error('Expected "contains" keyword to be a schema');
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var count = instance.some(function(value, i) {
-        var res = self2.validateSchema(value, schema2.contains, options, ctx.makeChild(schema2.contains, i));
-        return res.errors.length === 0;
-      });
-      if (count === false) {
-        result.addError({
-          name: "contains",
-          argument: schema2.contains,
-          message: "must contain an item matching given schema"
-        });
+      } else if (typeof version !== "string") {
+        throw new TypeError("Invalid Version: " + version);
       }
-      return result;
-    };
-    validators.minimum = function validateMinimum(instance, schema2, options, ctx) {
-      if (!this.types.number(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (schema2.exclusiveMinimum && schema2.exclusiveMinimum === true) {
-        if (!(instance > schema2.minimum)) {
-          result.addError({
-            name: "minimum",
-            argument: schema2.minimum,
-            message: "must be greater than " + schema2.minimum
-          });
-        }
-      } else {
-        if (!(instance >= schema2.minimum)) {
-          result.addError({
-            name: "minimum",
-            argument: schema2.minimum,
-            message: "must be greater than or equal to " + schema2.minimum
-          });
-        }
+      if (version.length > MAX_LENGTH) {
+        throw new TypeError("version is longer than " + MAX_LENGTH + " characters");
       }
-      return result;
-    };
-    validators.maximum = function validateMaximum(instance, schema2, options, ctx) {
-      if (!this.types.number(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (schema2.exclusiveMaximum && schema2.exclusiveMaximum === true) {
-        if (!(instance < schema2.maximum)) {
-          result.addError({
-            name: "maximum",
-            argument: schema2.maximum,
-            message: "must be less than " + schema2.maximum
-          });
-        }
-      } else {
-        if (!(instance <= schema2.maximum)) {
-          result.addError({
-            name: "maximum",
-            argument: schema2.maximum,
-            message: "must be less than or equal to " + schema2.maximum
-          });
-        }
+      if (!(this instanceof SemVer)) {
+        return new SemVer(version, options);
       }
-      return result;
-    };
-    validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema2, options, ctx) {
-      if (typeof schema2.exclusiveMinimum === "boolean") return;
-      if (!this.types.number(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var valid3 = instance > schema2.exclusiveMinimum;
-      if (!valid3) {
-        result.addError({
-          name: "exclusiveMinimum",
-          argument: schema2.exclusiveMinimum,
-          message: "must be strictly greater than " + schema2.exclusiveMinimum
-        });
+      debug4("SemVer", version, options);
+      this.options = options;
+      this.loose = !!options.loose;
+      var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]);
+      if (!m) {
+        throw new TypeError("Invalid Version: " + version);
       }
-      return result;
-    };
-    validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema2, options, ctx) {
-      if (typeof schema2.exclusiveMaximum === "boolean") return;
-      if (!this.types.number(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var valid3 = instance < schema2.exclusiveMaximum;
-      if (!valid3) {
-        result.addError({
-          name: "exclusiveMaximum",
-          argument: schema2.exclusiveMaximum,
-          message: "must be strictly less than " + schema2.exclusiveMaximum
-        });
+      this.raw = version;
+      this.major = +m[1];
+      this.minor = +m[2];
+      this.patch = +m[3];
+      if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
+        throw new TypeError("Invalid major version");
       }
-      return result;
-    };
-    var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema2, options, ctx, validationType, errorMessage) {
-      if (!this.types.number(instance)) return;
-      var validationArgument = schema2[validationType];
-      if (validationArgument == 0) {
-        throw new SchemaError(validationType + " cannot be zero");
+      if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
+        throw new TypeError("Invalid minor version");
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var instanceDecimals = helpers.getDecimalPlaces(instance);
-      var divisorDecimals = helpers.getDecimalPlaces(validationArgument);
-      var maxDecimals = Math.max(instanceDecimals, divisorDecimals);
-      var multiplier = Math.pow(10, maxDecimals);
-      if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) {
-        result.addError({
-          name: validationType,
-          argument: validationArgument,
-          message: errorMessage + JSON.stringify(validationArgument)
-        });
+      if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
+        throw new TypeError("Invalid patch version");
       }
-      return result;
-    };
-    validators.multipleOf = function validateMultipleOf(instance, schema2, options, ctx) {
-      return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "multipleOf", "is not a multiple of (divisible by) ");
-    };
-    validators.divisibleBy = function validateDivisibleBy(instance, schema2, options, ctx) {
-      return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "divisibleBy", "is not divisible by (multiple of) ");
-    };
-    validators.required = function validateRequired(instance, schema2, options, ctx) {
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (instance === void 0 && schema2.required === true) {
-        result.addError({
-          name: "required",
-          message: "is required"
-        });
-      } else if (this.types.object(instance) && Array.isArray(schema2.required)) {
-        schema2.required.forEach(function(n) {
-          if (getEnumerableProperty(instance, n) === void 0) {
-            result.addError({
-              name: "required",
-              argument: n,
-              message: "requires property " + JSON.stringify(n)
-            });
+      if (!m[4]) {
+        this.prerelease = [];
+      } else {
+        this.prerelease = m[4].split(".").map(function(id) {
+          if (/^[0-9]+$/.test(id)) {
+            var num = +id;
+            if (num >= 0 && num < MAX_SAFE_INTEGER) {
+              return num;
+            }
           }
+          return id;
         });
       }
-      return result;
-    };
-    validators.pattern = function validatePattern(instance, schema2, options, ctx) {
-      if (!this.types.string(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var pattern = schema2.pattern;
-      try {
-        var regexp = new RegExp(pattern, "u");
-      } catch (_e) {
-        regexp = new RegExp(pattern);
-      }
-      if (!instance.match(regexp)) {
-        result.addError({
-          name: "pattern",
-          argument: schema2.pattern,
-          message: "does not match pattern " + JSON.stringify(schema2.pattern.toString())
-        });
+      this.build = m[5] ? m[5].split(".") : [];
+      this.format();
+    }
+    SemVer.prototype.format = function() {
+      this.version = this.major + "." + this.minor + "." + this.patch;
+      if (this.prerelease.length) {
+        this.version += "-" + this.prerelease.join(".");
       }
-      return result;
+      return this.version;
     };
-    validators.format = function validateFormat(instance, schema2, options, ctx) {
-      if (instance === void 0) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!result.disableFormat && !helpers.isFormat(instance, schema2.format, this)) {
-        result.addError({
-          name: "format",
-          argument: schema2.format,
-          message: "does not conform to the " + JSON.stringify(schema2.format) + " format"
-        });
+    SemVer.prototype.toString = function() {
+      return this.version;
+    };
+    SemVer.prototype.compare = function(other) {
+      debug4("SemVer.compare", this.version, this.options, other);
+      if (!(other instanceof SemVer)) {
+        other = new SemVer(other, this.options);
       }
-      return result;
+      return this.compareMain(other) || this.comparePre(other);
     };
-    validators.minLength = function validateMinLength(instance, schema2, options, ctx) {
-      if (!this.types.string(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var hsp = instance.match(/[\uDC00-\uDFFF]/g);
-      var length = instance.length - (hsp ? hsp.length : 0);
-      if (!(length >= schema2.minLength)) {
-        result.addError({
-          name: "minLength",
-          argument: schema2.minLength,
-          message: "does not meet minimum length of " + schema2.minLength
-        });
+    SemVer.prototype.compareMain = function(other) {
+      if (!(other instanceof SemVer)) {
+        other = new SemVer(other, this.options);
       }
-      return result;
+      return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
     };
-    validators.maxLength = function validateMaxLength(instance, schema2, options, ctx) {
-      if (!this.types.string(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var hsp = instance.match(/[\uDC00-\uDFFF]/g);
-      var length = instance.length - (hsp ? hsp.length : 0);
-      if (!(length <= schema2.maxLength)) {
-        result.addError({
-          name: "maxLength",
-          argument: schema2.maxLength,
-          message: "does not meet maximum length of " + schema2.maxLength
-        });
+    SemVer.prototype.comparePre = function(other) {
+      if (!(other instanceof SemVer)) {
+        other = new SemVer(other, this.options);
       }
-      return result;
+      if (this.prerelease.length && !other.prerelease.length) {
+        return -1;
+      } else if (!this.prerelease.length && other.prerelease.length) {
+        return 1;
+      } else if (!this.prerelease.length && !other.prerelease.length) {
+        return 0;
+      }
+      var i2 = 0;
+      do {
+        var a = this.prerelease[i2];
+        var b = other.prerelease[i2];
+        debug4("prerelease compare", i2, a, b);
+        if (a === void 0 && b === void 0) {
+          return 0;
+        } else if (b === void 0) {
+          return 1;
+        } else if (a === void 0) {
+          return -1;
+        } else if (a === b) {
+          continue;
+        } else {
+          return compareIdentifiers(a, b);
+        }
+      } while (++i2);
     };
-    validators.minItems = function validateMinItems(instance, schema2, options, ctx) {
-      if (!this.types.array(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!(instance.length >= schema2.minItems)) {
-        result.addError({
-          name: "minItems",
-          argument: schema2.minItems,
-          message: "does not meet minimum length of " + schema2.minItems
-        });
+    SemVer.prototype.compareBuild = function(other) {
+      if (!(other instanceof SemVer)) {
+        other = new SemVer(other, this.options);
       }
-      return result;
+      var i2 = 0;
+      do {
+        var a = this.build[i2];
+        var b = other.build[i2];
+        debug4("prerelease compare", i2, a, b);
+        if (a === void 0 && b === void 0) {
+          return 0;
+        } else if (b === void 0) {
+          return 1;
+        } else if (a === void 0) {
+          return -1;
+        } else if (a === b) {
+          continue;
+        } else {
+          return compareIdentifiers(a, b);
+        }
+      } while (++i2);
     };
-    validators.maxItems = function validateMaxItems(instance, schema2, options, ctx) {
-      if (!this.types.array(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!(instance.length <= schema2.maxItems)) {
-        result.addError({
-          name: "maxItems",
-          argument: schema2.maxItems,
-          message: "does not meet maximum length of " + schema2.maxItems
-        });
+    SemVer.prototype.inc = function(release, identifier) {
+      switch (release) {
+        case "premajor":
+          this.prerelease.length = 0;
+          this.patch = 0;
+          this.minor = 0;
+          this.major++;
+          this.inc("pre", identifier);
+          break;
+        case "preminor":
+          this.prerelease.length = 0;
+          this.patch = 0;
+          this.minor++;
+          this.inc("pre", identifier);
+          break;
+        case "prepatch":
+          this.prerelease.length = 0;
+          this.inc("patch", identifier);
+          this.inc("pre", identifier);
+          break;
+        // If the input is a non-prerelease version, this acts the same as
+        // prepatch.
+        case "prerelease":
+          if (this.prerelease.length === 0) {
+            this.inc("patch", identifier);
+          }
+          this.inc("pre", identifier);
+          break;
+        case "major":
+          if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
+            this.major++;
+          }
+          this.minor = 0;
+          this.patch = 0;
+          this.prerelease = [];
+          break;
+        case "minor":
+          if (this.patch !== 0 || this.prerelease.length === 0) {
+            this.minor++;
+          }
+          this.patch = 0;
+          this.prerelease = [];
+          break;
+        case "patch":
+          if (this.prerelease.length === 0) {
+            this.patch++;
+          }
+          this.prerelease = [];
+          break;
+        // This probably shouldn't be used publicly.
+        // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
+        case "pre":
+          if (this.prerelease.length === 0) {
+            this.prerelease = [0];
+          } else {
+            var i2 = this.prerelease.length;
+            while (--i2 >= 0) {
+              if (typeof this.prerelease[i2] === "number") {
+                this.prerelease[i2]++;
+                i2 = -2;
+              }
+            }
+            if (i2 === -1) {
+              this.prerelease.push(0);
+            }
+          }
+          if (identifier) {
+            if (this.prerelease[0] === identifier) {
+              if (isNaN(this.prerelease[1])) {
+                this.prerelease = [identifier, 0];
+              }
+            } else {
+              this.prerelease = [identifier, 0];
+            }
+          }
+          break;
+        default:
+          throw new Error("invalid increment argument: " + release);
       }
-      return result;
+      this.format();
+      this.raw = this.version;
+      return this;
     };
-    function testArrays(v, i, a) {
-      var j, len = a.length;
-      for (j = i + 1, len; j < len; j++) {
-        if (helpers.deepCompareStrict(v, a[j])) {
-          return false;
+    exports2.inc = inc;
+    function inc(version, release, loose, identifier) {
+      if (typeof loose === "string") {
+        identifier = loose;
+        loose = void 0;
+      }
+      try {
+        return new SemVer(version, loose).inc(release, identifier).version;
+      } catch (er) {
+        return null;
+      }
+    }
+    exports2.diff = diff;
+    function diff(version1, version2) {
+      if (eq(version1, version2)) {
+        return null;
+      } else {
+        var v1 = parse(version1);
+        var v2 = parse(version2);
+        var prefix = "";
+        if (v1.prerelease.length || v2.prerelease.length) {
+          prefix = "pre";
+          var defaultResult = "prerelease";
+        }
+        for (var key in v1) {
+          if (key === "major" || key === "minor" || key === "patch") {
+            if (v1[key] !== v2[key]) {
+              return prefix + key;
+            }
+          }
         }
+        return defaultResult;
+      }
+    }
+    exports2.compareIdentifiers = compareIdentifiers;
+    var numeric = /^[0-9]+$/;
+    function compareIdentifiers(a, b) {
+      var anum = numeric.test(a);
+      var bnum = numeric.test(b);
+      if (anum && bnum) {
+        a = +a;
+        b = +b;
+      }
+      return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
+    }
+    exports2.rcompareIdentifiers = rcompareIdentifiers;
+    function rcompareIdentifiers(a, b) {
+      return compareIdentifiers(b, a);
+    }
+    exports2.major = major;
+    function major(a, loose) {
+      return new SemVer(a, loose).major;
+    }
+    exports2.minor = minor;
+    function minor(a, loose) {
+      return new SemVer(a, loose).minor;
+    }
+    exports2.patch = patch;
+    function patch(a, loose) {
+      return new SemVer(a, loose).patch;
+    }
+    exports2.compare = compare2;
+    function compare2(a, b, loose) {
+      return new SemVer(a, loose).compare(new SemVer(b, loose));
+    }
+    exports2.compareLoose = compareLoose;
+    function compareLoose(a, b) {
+      return compare2(a, b, true);
+    }
+    exports2.compareBuild = compareBuild;
+    function compareBuild(a, b, loose) {
+      var versionA = new SemVer(a, loose);
+      var versionB = new SemVer(b, loose);
+      return versionA.compare(versionB) || versionA.compareBuild(versionB);
+    }
+    exports2.rcompare = rcompare;
+    function rcompare(a, b, loose) {
+      return compare2(b, a, loose);
+    }
+    exports2.sort = sort;
+    function sort(list, loose) {
+      return list.sort(function(a, b) {
+        return exports2.compareBuild(a, b, loose);
+      });
+    }
+    exports2.rsort = rsort;
+    function rsort(list, loose) {
+      return list.sort(function(a, b) {
+        return exports2.compareBuild(b, a, loose);
+      });
+    }
+    exports2.gt = gt;
+    function gt(a, b, loose) {
+      return compare2(a, b, loose) > 0;
+    }
+    exports2.lt = lt;
+    function lt(a, b, loose) {
+      return compare2(a, b, loose) < 0;
+    }
+    exports2.eq = eq;
+    function eq(a, b, loose) {
+      return compare2(a, b, loose) === 0;
+    }
+    exports2.neq = neq;
+    function neq(a, b, loose) {
+      return compare2(a, b, loose) !== 0;
+    }
+    exports2.gte = gte5;
+    function gte5(a, b, loose) {
+      return compare2(a, b, loose) >= 0;
+    }
+    exports2.lte = lte;
+    function lte(a, b, loose) {
+      return compare2(a, b, loose) <= 0;
+    }
+    exports2.cmp = cmp;
+    function cmp(a, op, b, loose) {
+      switch (op) {
+        case "===":
+          if (typeof a === "object")
+            a = a.version;
+          if (typeof b === "object")
+            b = b.version;
+          return a === b;
+        case "!==":
+          if (typeof a === "object")
+            a = a.version;
+          if (typeof b === "object")
+            b = b.version;
+          return a !== b;
+        case "":
+        case "=":
+        case "==":
+          return eq(a, b, loose);
+        case "!=":
+          return neq(a, b, loose);
+        case ">":
+          return gt(a, b, loose);
+        case ">=":
+          return gte5(a, b, loose);
+        case "<":
+          return lt(a, b, loose);
+        case "<=":
+          return lte(a, b, loose);
+        default:
+          throw new TypeError("Invalid operator: " + op);
       }
-      return true;
     }
-    validators.uniqueItems = function validateUniqueItems(instance, schema2, options, ctx) {
-      if (schema2.uniqueItems !== true) return;
-      if (!this.types.array(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!instance.every(testArrays)) {
-        result.addError({
-          name: "uniqueItems",
-          message: "contains duplicate item"
-        });
+    exports2.Comparator = Comparator;
+    function Comparator(comp, options) {
+      if (!options || typeof options !== "object") {
+        options = {
+          loose: !!options,
+          includePrerelease: false
+        };
       }
-      return result;
-    };
-    validators.dependencies = function validateDependencies(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      for (var property in schema2.dependencies) {
-        if (instance[property] === void 0) {
-          continue;
-        }
-        var dep = schema2.dependencies[property];
-        var childContext = ctx.makeChild(dep, property);
-        if (typeof dep == "string") {
-          dep = [dep];
-        }
-        if (Array.isArray(dep)) {
-          dep.forEach(function(prop) {
-            if (instance[prop] === void 0) {
-              result.addError({
-                // FIXME there's two different "dependencies" errors here with slightly different outputs
-                // Can we make these the same? Or should we create different error types?
-                name: "dependencies",
-                argument: childContext.propertyPath,
-                message: "property " + prop + " not found, required by " + childContext.propertyPath
-              });
-            }
-          });
+      if (comp instanceof Comparator) {
+        if (comp.loose === !!options.loose) {
+          return comp;
         } else {
-          var res = this.validateSchema(instance, dep, options, childContext);
-          if (result.instance !== res.instance) result.instance = res.instance;
-          if (res && res.errors.length) {
-            result.addError({
-              name: "dependencies",
-              argument: childContext.propertyPath,
-              message: "does not meet dependency required by " + childContext.propertyPath
-            });
-            result.importErrors(res);
-          }
+          comp = comp.value;
         }
       }
-      return result;
-    };
-    validators["enum"] = function validateEnum(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
+      if (!(this instanceof Comparator)) {
+        return new Comparator(comp, options);
       }
-      if (!Array.isArray(schema2["enum"])) {
-        throw new SchemaError("enum expects an array", schema2);
+      comp = comp.trim().split(/\s+/).join(" ");
+      debug4("comparator", comp, options);
+      this.options = options;
+      this.loose = !!options.loose;
+      this.parse(comp);
+      if (this.semver === ANY) {
+        this.value = "";
+      } else {
+        this.value = this.operator + this.semver.version;
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!schema2["enum"].some(helpers.deepCompareStrict.bind(null, instance))) {
-        result.addError({
-          name: "enum",
-          argument: schema2["enum"],
-          message: "is not one of enum values: " + schema2["enum"].map(String).join(",")
-        });
+      debug4("comp", this);
+    }
+    var ANY = {};
+    Comparator.prototype.parse = function(comp) {
+      var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR];
+      var m = comp.match(r);
+      if (!m) {
+        throw new TypeError("Invalid comparator: " + comp);
       }
-      return result;
-    };
-    validators["const"] = function validateEnum(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
+      this.operator = m[1] !== void 0 ? m[1] : "";
+      if (this.operator === "=") {
+        this.operator = "";
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!helpers.deepCompareStrict(schema2["const"], instance)) {
-        result.addError({
-          name: "const",
-          argument: schema2["const"],
-          message: "does not exactly match expected constant: " + schema2["const"]
-        });
+      if (!m[2]) {
+        this.semver = ANY;
+      } else {
+        this.semver = new SemVer(m[2], this.options.loose);
       }
-      return result;
     };
-    validators.not = validators.disallow = function validateNot(instance, schema2, options, ctx) {
-      var self2 = this;
-      if (instance === void 0) return null;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var notTypes = schema2.not || schema2.disallow;
-      if (!notTypes) return null;
-      if (!Array.isArray(notTypes)) notTypes = [notTypes];
-      notTypes.forEach(function(type2) {
-        if (self2.testType(instance, schema2, options, ctx, type2)) {
-          var id = type2 && (type2.$id || type2.id);
-          var schemaId = id || type2;
-          result.addError({
-            name: "not",
-            argument: schemaId,
-            message: "is of prohibited type " + schemaId
-          });
-        }
-      });
-      return result;
+    Comparator.prototype.toString = function() {
+      return this.value;
     };
-    module2.exports = attribute;
-  }
-});
-
-// node_modules/jsonschema/lib/scan.js
-var require_scan = __commonJS({
-  "node_modules/jsonschema/lib/scan.js"(exports2, module2) {
-    "use strict";
-    var urilib = require("url");
-    var helpers = require_helpers3();
-    module2.exports.SchemaScanResult = SchemaScanResult;
-    function SchemaScanResult(found, ref) {
-      this.id = found;
-      this.ref = ref;
-    }
-    module2.exports.scan = function scan(base, schema2) {
-      function scanSchema(baseuri, schema3) {
-        if (!schema3 || typeof schema3 != "object") return;
-        if (schema3.$ref) {
-          var resolvedUri = urilib.resolve(baseuri, schema3.$ref);
-          ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0;
-          return;
-        }
-        var id = schema3.$id || schema3.id;
-        var ourBase = id ? urilib.resolve(baseuri, id) : baseuri;
-        if (ourBase) {
-          if (ourBase.indexOf("#") < 0) ourBase += "#";
-          if (found[ourBase]) {
-            if (!helpers.deepCompareStrict(found[ourBase], schema3)) {
-              throw new Error("Schema <" + ourBase + "> already exists with different definition");
-            }
-            return found[ourBase];
-          }
-          found[ourBase] = schema3;
-          if (ourBase[ourBase.length - 1] == "#") {
-            found[ourBase.substring(0, ourBase.length - 1)] = schema3;
-          }
-        }
-        scanArray(ourBase + "/items", Array.isArray(schema3.items) ? schema3.items : [schema3.items]);
-        scanArray(ourBase + "/extends", Array.isArray(schema3.extends) ? schema3.extends : [schema3.extends]);
-        scanSchema(ourBase + "/additionalItems", schema3.additionalItems);
-        scanObject(ourBase + "/properties", schema3.properties);
-        scanSchema(ourBase + "/additionalProperties", schema3.additionalProperties);
-        scanObject(ourBase + "/definitions", schema3.definitions);
-        scanObject(ourBase + "/patternProperties", schema3.patternProperties);
-        scanObject(ourBase + "/dependencies", schema3.dependencies);
-        scanArray(ourBase + "/disallow", schema3.disallow);
-        scanArray(ourBase + "/allOf", schema3.allOf);
-        scanArray(ourBase + "/anyOf", schema3.anyOf);
-        scanArray(ourBase + "/oneOf", schema3.oneOf);
-        scanSchema(ourBase + "/not", schema3.not);
+    Comparator.prototype.test = function(version) {
+      debug4("Comparator.test", version, this.options.loose);
+      if (this.semver === ANY || version === ANY) {
+        return true;
       }
-      function scanArray(baseuri, schemas) {
-        if (!Array.isArray(schemas)) return;
-        for (var i = 0; i < schemas.length; i++) {
-          scanSchema(baseuri + "/" + i, schemas[i]);
+      if (typeof version === "string") {
+        try {
+          version = new SemVer(version, this.options);
+        } catch (er) {
+          return false;
         }
       }
-      function scanObject(baseuri, schemas) {
-        if (!schemas || typeof schemas != "object") return;
-        for (var p in schemas) {
-          scanSchema(baseuri + "/" + p, schemas[p]);
+      return cmp(version, this.operator, this.semver, this.options);
+    };
+    Comparator.prototype.intersects = function(comp, options) {
+      if (!(comp instanceof Comparator)) {
+        throw new TypeError("a Comparator is required");
+      }
+      if (!options || typeof options !== "object") {
+        options = {
+          loose: !!options,
+          includePrerelease: false
+        };
+      }
+      var rangeTmp;
+      if (this.operator === "") {
+        if (this.value === "") {
+          return true;
+        }
+        rangeTmp = new Range2(comp.value, options);
+        return satisfies2(this.value, rangeTmp, options);
+      } else if (comp.operator === "") {
+        if (comp.value === "") {
+          return true;
         }
+        rangeTmp = new Range2(this.value, options);
+        return satisfies2(comp.semver, rangeTmp, options);
       }
-      var found = {};
-      var ref = {};
-      scanSchema(base, schema2);
-      return new SchemaScanResult(found, ref);
-    };
-  }
-});
-
-// node_modules/jsonschema/lib/validator.js
-var require_validator2 = __commonJS({
-  "node_modules/jsonschema/lib/validator.js"(exports2, module2) {
-    "use strict";
-    var urilib = require("url");
-    var attribute = require_attribute();
-    var helpers = require_helpers3();
-    var scanSchema = require_scan().scan;
-    var ValidatorResult = helpers.ValidatorResult;
-    var ValidatorResultError = helpers.ValidatorResultError;
-    var SchemaError = helpers.SchemaError;
-    var SchemaContext = helpers.SchemaContext;
-    var anonymousBase = "/";
-    var Validator2 = function Validator3() {
-      this.customFormats = Object.create(Validator3.prototype.customFormats);
-      this.schemas = {};
-      this.unresolvedRefs = [];
-      this.types = Object.create(types);
-      this.attributes = Object.create(attribute.validators);
+      var sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">");
+      var sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<");
+      var sameSemVer = this.semver.version === comp.semver.version;
+      var differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<=");
+      var oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && ((this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<"));
+      var oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && ((this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">"));
+      return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
     };
-    Validator2.prototype.customFormats = {};
-    Validator2.prototype.schemas = null;
-    Validator2.prototype.types = null;
-    Validator2.prototype.attributes = null;
-    Validator2.prototype.unresolvedRefs = null;
-    Validator2.prototype.addSchema = function addSchema(schema2, base) {
-      var self2 = this;
-      if (!schema2) {
-        return null;
+    exports2.Range = Range2;
+    function Range2(range, options) {
+      if (!options || typeof options !== "object") {
+        options = {
+          loose: !!options,
+          includePrerelease: false
+        };
       }
-      var scan = scanSchema(base || anonymousBase, schema2);
-      var ourUri = base || schema2.$id || schema2.id;
-      for (var uri in scan.id) {
-        this.schemas[uri] = scan.id[uri];
+      if (range instanceof Range2) {
+        if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
+          return range;
+        } else {
+          return new Range2(range.raw, options);
+        }
       }
-      for (var uri in scan.ref) {
-        this.unresolvedRefs.push(uri);
+      if (range instanceof Comparator) {
+        return new Range2(range.value, options);
       }
-      this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) {
-        return typeof self2.schemas[uri2] === "undefined";
-      });
-      return this.schemas[ourUri];
-    };
-    Validator2.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) {
-      if (!Array.isArray(schemas)) return;
-      for (var i = 0; i < schemas.length; i++) {
-        this.addSubSchema(baseuri, schemas[i]);
+      if (!(this instanceof Range2)) {
+        return new Range2(range, options);
       }
-    };
-    Validator2.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) {
-      if (!schemas || typeof schemas != "object") return;
-      for (var p in schemas) {
-        this.addSubSchema(baseuri, schemas[p]);
+      this.options = options;
+      this.loose = !!options.loose;
+      this.includePrerelease = !!options.includePrerelease;
+      this.raw = range.trim().split(/\s+/).join(" ");
+      this.set = this.raw.split("||").map(function(range2) {
+        return this.parseRange(range2.trim());
+      }, this).filter(function(c) {
+        return c.length;
+      });
+      if (!this.set.length) {
+        throw new TypeError("Invalid SemVer Range: " + this.raw);
       }
+      this.format();
+    }
+    Range2.prototype.format = function() {
+      this.range = this.set.map(function(comps) {
+        return comps.join(" ").trim();
+      }).join("||").trim();
+      return this.range;
     };
-    Validator2.prototype.setSchemas = function setSchemas(schemas) {
-      this.schemas = schemas;
+    Range2.prototype.toString = function() {
+      return this.range;
     };
-    Validator2.prototype.getSchema = function getSchema(urn) {
-      return this.schemas[urn];
+    Range2.prototype.parseRange = function(range) {
+      var loose = this.options.loose;
+      var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE];
+      range = range.replace(hr, hyphenReplace);
+      debug4("hyphen replace", range);
+      range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace);
+      debug4("comparator trim", range, safeRe[t.COMPARATORTRIM]);
+      range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace);
+      range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace);
+      range = range.split(/\s+/).join(" ");
+      var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR];
+      var set2 = range.split(" ").map(function(comp) {
+        return parseComparator(comp, this.options);
+      }, this).join(" ").split(/\s+/);
+      if (this.options.loose) {
+        set2 = set2.filter(function(comp) {
+          return !!comp.match(compRe);
+        });
+      }
+      set2 = set2.map(function(comp) {
+        return new Comparator(comp, this.options);
+      }, this);
+      return set2;
     };
-    Validator2.prototype.validate = function validate(instance, schema2, options, ctx) {
-      if (typeof schema2 !== "boolean" && typeof schema2 !== "object" || schema2 === null) {
-        throw new SchemaError("Expected `schema` to be an object or boolean");
+    Range2.prototype.intersects = function(range, options) {
+      if (!(range instanceof Range2)) {
+        throw new TypeError("a Range is required");
       }
-      if (!options) {
-        options = {};
+      return this.set.some(function(thisComparators) {
+        return isSatisfiable(thisComparators, options) && range.set.some(function(rangeComparators) {
+          return isSatisfiable(rangeComparators, options) && thisComparators.every(function(thisComparator) {
+            return rangeComparators.every(function(rangeComparator) {
+              return thisComparator.intersects(rangeComparator, options);
+            });
+          });
+        });
+      });
+    };
+    function isSatisfiable(comparators, options) {
+      var result = true;
+      var remainingComparators = comparators.slice();
+      var testComparator = remainingComparators.pop();
+      while (result && remainingComparators.length) {
+        result = remainingComparators.every(function(otherComparator) {
+          return testComparator.intersects(otherComparator, options);
+        });
+        testComparator = remainingComparators.pop();
       }
-      var id = schema2.$id || schema2.id;
-      var base = urilib.resolve(options.base || anonymousBase, id || "");
-      if (!ctx) {
-        ctx = new SchemaContext(schema2, options, [], base, Object.create(this.schemas));
-        if (!ctx.schemas[base]) {
-          ctx.schemas[base] = schema2;
+      return result;
+    }
+    exports2.toComparators = toComparators;
+    function toComparators(range, options) {
+      return new Range2(range, options).set.map(function(comp) {
+        return comp.map(function(c) {
+          return c.value;
+        }).join(" ").trim().split(" ");
+      });
+    }
+    function parseComparator(comp, options) {
+      debug4("comp", comp, options);
+      comp = replaceCarets(comp, options);
+      debug4("caret", comp);
+      comp = replaceTildes(comp, options);
+      debug4("tildes", comp);
+      comp = replaceXRanges(comp, options);
+      debug4("xrange", comp);
+      comp = replaceStars(comp, options);
+      debug4("stars", comp);
+      return comp;
+    }
+    function isX(id) {
+      return !id || id.toLowerCase() === "x" || id === "*";
+    }
+    function replaceTildes(comp, options) {
+      return comp.trim().split(/\s+/).map(function(comp2) {
+        return replaceTilde(comp2, options);
+      }).join(" ");
+    }
+    function replaceTilde(comp, options) {
+      var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE];
+      return comp.replace(r, function(_2, M, m, p, pr) {
+        debug4("tilde", comp, _2, M, m, p, pr);
+        var ret;
+        if (isX(M)) {
+          ret = "";
+        } else if (isX(m)) {
+          ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
+        } else if (isX(p)) {
+          ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
+        } else if (pr) {
+          debug4("replaceTilde pr", pr);
+          ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
+        } else {
+          ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
+        }
+        debug4("tilde return", ret);
+        return ret;
+      });
+    }
+    function replaceCarets(comp, options) {
+      return comp.trim().split(/\s+/).map(function(comp2) {
+        return replaceCaret(comp2, options);
+      }).join(" ");
+    }
+    function replaceCaret(comp, options) {
+      debug4("caret", comp, options);
+      var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET];
+      return comp.replace(r, function(_2, M, m, p, pr) {
+        debug4("caret", comp, _2, M, m, p, pr);
+        var ret;
+        if (isX(M)) {
+          ret = "";
+        } else if (isX(m)) {
+          ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
+        } else if (isX(p)) {
+          if (M === "0") {
+            ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
+          } else {
+            ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0";
+          }
+        } else if (pr) {
+          debug4("replaceCaret pr", pr);
+          if (M === "0") {
+            if (m === "0") {
+              ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1);
+            } else {
+              ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
+            }
+          } else {
+            ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0";
+          }
+        } else {
+          debug4("no pr");
+          if (M === "0") {
+            if (m === "0") {
+              ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1);
+            } else {
+              ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
+            }
+          } else {
+            ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0";
+          }
         }
-        var found = scanSchema(base, schema2);
-        for (var n in found.id) {
-          var sch = found.id[n];
-          ctx.schemas[n] = sch;
+        debug4("caret return", ret);
+        return ret;
+      });
+    }
+    function replaceXRanges(comp, options) {
+      debug4("replaceXRanges", comp, options);
+      return comp.split(/\s+/).map(function(comp2) {
+        return replaceXRange(comp2, options);
+      }).join(" ");
+    }
+    function replaceXRange(comp, options) {
+      comp = comp.trim();
+      var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE];
+      return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
+        debug4("xRange", comp, ret, gtlt, M, m, p, pr);
+        var xM = isX(M);
+        var xm = xM || isX(m);
+        var xp = xm || isX(p);
+        var anyX = xp;
+        if (gtlt === "=" && anyX) {
+          gtlt = "";
         }
+        pr = options.includePrerelease ? "-0" : "";
+        if (xM) {
+          if (gtlt === ">" || gtlt === "<") {
+            ret = "<0.0.0-0";
+          } else {
+            ret = "*";
+          }
+        } else if (gtlt && anyX) {
+          if (xm) {
+            m = 0;
+          }
+          p = 0;
+          if (gtlt === ">") {
+            gtlt = ">=";
+            if (xm) {
+              M = +M + 1;
+              m = 0;
+              p = 0;
+            } else {
+              m = +m + 1;
+              p = 0;
+            }
+          } else if (gtlt === "<=") {
+            gtlt = "<";
+            if (xm) {
+              M = +M + 1;
+            } else {
+              m = +m + 1;
+            }
+          }
+          ret = gtlt + M + "." + m + "." + p + pr;
+        } else if (xm) {
+          ret = ">=" + M + ".0.0" + pr + " <" + (+M + 1) + ".0.0" + pr;
+        } else if (xp) {
+          ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr;
+        }
+        debug4("xRange return", ret);
+        return ret;
+      });
+    }
+    function replaceStars(comp, options) {
+      debug4("replaceStars", comp, options);
+      return comp.trim().replace(safeRe[t.STAR], "");
+    }
+    function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
+      if (isX(fM)) {
+        from = "";
+      } else if (isX(fm)) {
+        from = ">=" + fM + ".0.0";
+      } else if (isX(fp)) {
+        from = ">=" + fM + "." + fm + ".0";
+      } else {
+        from = ">=" + from;
       }
-      if (options.required && instance === void 0) {
-        var result = new ValidatorResult(instance, schema2, options, ctx);
-        result.addError("is required, but is undefined");
-        return result;
-      }
-      var result = this.validateSchema(instance, schema2, options, ctx);
-      if (!result) {
-        throw new Error("Result undefined");
-      } else if (options.throwAll && result.errors.length) {
-        throw new ValidatorResultError(result);
+      if (isX(tM)) {
+        to = "";
+      } else if (isX(tm)) {
+        to = "<" + (+tM + 1) + ".0.0";
+      } else if (isX(tp)) {
+        to = "<" + tM + "." + (+tm + 1) + ".0";
+      } else if (tpr) {
+        to = "<=" + tM + "." + tm + "." + tp + "-" + tpr;
+      } else {
+        to = "<=" + to;
       }
-      return result;
-    };
-    function shouldResolve(schema2) {
-      var ref = typeof schema2 === "string" ? schema2 : schema2.$ref;
-      if (typeof ref == "string") return ref;
-      return false;
+      return (from + " " + to).trim();
     }
-    Validator2.prototype.validateSchema = function validateSchema(instance, schema2, options, ctx) {
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (typeof schema2 === "boolean") {
-        if (schema2 === true) {
-          schema2 = {};
-        } else if (schema2 === false) {
-          schema2 = { type: [] };
+    Range2.prototype.test = function(version) {
+      if (!version) {
+        return false;
+      }
+      if (typeof version === "string") {
+        try {
+          version = new SemVer(version, this.options);
+        } catch (er) {
+          return false;
         }
-      } else if (!schema2) {
-        throw new Error("schema is undefined");
       }
-      if (schema2["extends"]) {
-        if (Array.isArray(schema2["extends"])) {
-          var schemaobj = { schema: schema2, ctx };
-          schema2["extends"].forEach(this.schemaTraverser.bind(this, schemaobj));
-          schema2 = schemaobj.schema;
-          schemaobj.schema = null;
-          schemaobj.ctx = null;
-          schemaobj = null;
-        } else {
-          schema2 = helpers.deepMerge(schema2, this.superResolve(schema2["extends"], ctx));
+      for (var i2 = 0; i2 < this.set.length; i2++) {
+        if (testSet(this.set[i2], version, this.options)) {
+          return true;
         }
       }
-      var switchSchema = shouldResolve(schema2);
-      if (switchSchema) {
-        var resolved = this.resolve(schema2, switchSchema, ctx);
-        var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas);
-        return this.validateSchema(instance, resolved.subschema, options, subctx);
+      return false;
+    };
+    function testSet(set2, version, options) {
+      for (var i2 = 0; i2 < set2.length; i2++) {
+        if (!set2[i2].test(version)) {
+          return false;
+        }
       }
-      var skipAttributes = options && options.skipAttributes || [];
-      for (var key in schema2) {
-        if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) {
-          var validatorErr = null;
-          var validator = this.attributes[key];
-          if (validator) {
-            validatorErr = validator.call(this, instance, schema2, options, ctx);
-          } else if (options.allowUnknownAttributes === false) {
-            throw new SchemaError("Unsupported attribute: " + key, schema2);
+      if (version.prerelease.length && !options.includePrerelease) {
+        for (i2 = 0; i2 < set2.length; i2++) {
+          debug4(set2[i2].semver);
+          if (set2[i2].semver === ANY) {
+            continue;
           }
-          if (validatorErr) {
-            result.importErrors(validatorErr);
+          if (set2[i2].semver.prerelease.length > 0) {
+            var allowed = set2[i2].semver;
+            if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
+              return true;
+            }
           }
         }
+        return false;
       }
-      if (typeof options.rewrite == "function") {
-        var value = options.rewrite.call(this, instance, schema2, options, ctx);
-        result.instance = value;
-      }
-      return result;
-    };
-    Validator2.prototype.schemaTraverser = function schemaTraverser(schemaobj, s) {
-      schemaobj.schema = helpers.deepMerge(schemaobj.schema, this.superResolve(s, schemaobj.ctx));
-    };
-    Validator2.prototype.superResolve = function superResolve(schema2, ctx) {
-      var ref = shouldResolve(schema2);
-      if (ref) {
-        return this.resolve(schema2, ref, ctx).subschema;
-      }
-      return schema2;
-    };
-    Validator2.prototype.resolve = function resolve2(schema2, switchSchema, ctx) {
-      switchSchema = ctx.resolve(switchSchema);
-      if (ctx.schemas[switchSchema]) {
-        return { subschema: ctx.schemas[switchSchema], switchSchema };
-      }
-      var parsed = urilib.parse(switchSchema);
-      var fragment = parsed && parsed.hash;
-      var document2 = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length);
-      if (!document2 || !ctx.schemas[document2]) {
-        throw new SchemaError("no such schema <" + switchSchema + ">", schema2);
+      return true;
+    }
+    exports2.satisfies = satisfies2;
+    function satisfies2(version, range, options) {
+      try {
+        range = new Range2(range, options);
+      } catch (er) {
+        return false;
       }
-      var subschema = helpers.objectGetPath(ctx.schemas[document2], fragment.substr(1));
-      if (subschema === void 0) {
-        throw new SchemaError("no such schema " + fragment + " located in <" + document2 + ">", schema2);
+      return range.test(version);
+    }
+    exports2.maxSatisfying = maxSatisfying;
+    function maxSatisfying(versions, range, options) {
+      var max = null;
+      var maxSV = null;
+      try {
+        var rangeObj = new Range2(range, options);
+      } catch (er) {
+        return null;
       }
-      return { subschema, switchSchema };
-    };
-    Validator2.prototype.testType = function validateType(instance, schema2, options, ctx, type2) {
-      if (type2 === void 0) {
-        return;
-      } else if (type2 === null) {
-        throw new SchemaError('Unexpected null in "type" keyword');
+      versions.forEach(function(v) {
+        if (rangeObj.test(v)) {
+          if (!max || maxSV.compare(v) === -1) {
+            max = v;
+            maxSV = new SemVer(max, options);
+          }
+        }
+      });
+      return max;
+    }
+    exports2.minSatisfying = minSatisfying;
+    function minSatisfying(versions, range, options) {
+      var min = null;
+      var minSV = null;
+      try {
+        var rangeObj = new Range2(range, options);
+      } catch (er) {
+        return null;
       }
-      if (typeof this.types[type2] == "function") {
-        return this.types[type2].call(this, instance);
+      versions.forEach(function(v) {
+        if (rangeObj.test(v)) {
+          if (!min || minSV.compare(v) === 1) {
+            min = v;
+            minSV = new SemVer(min, options);
+          }
+        }
+      });
+      return min;
+    }
+    exports2.minVersion = minVersion;
+    function minVersion(range, loose) {
+      range = new Range2(range, loose);
+      var minver = new SemVer("0.0.0");
+      if (range.test(minver)) {
+        return minver;
       }
-      if (type2 && typeof type2 == "object") {
-        var res = this.validateSchema(instance, type2, options, ctx);
-        return res === void 0 || !(res && res.errors.length);
+      minver = new SemVer("0.0.0-0");
+      if (range.test(minver)) {
+        return minver;
       }
-      return true;
-    };
-    var types = Validator2.prototype.types = {};
-    types.string = function testString(instance) {
-      return typeof instance == "string";
-    };
-    types.number = function testNumber(instance) {
-      return typeof instance == "number" && isFinite(instance);
-    };
-    types.integer = function testInteger(instance) {
-      return typeof instance == "number" && instance % 1 === 0;
-    };
-    types.boolean = function testBoolean(instance) {
-      return typeof instance == "boolean";
-    };
-    types.array = function testArray(instance) {
-      return Array.isArray(instance);
-    };
-    types["null"] = function testNull(instance) {
-      return instance === null;
-    };
-    types.date = function testDate(instance) {
-      return instance instanceof Date;
-    };
-    types.any = function testAny(instance) {
-      return true;
-    };
-    types.object = function testObject(instance) {
-      return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date);
-    };
-    module2.exports = Validator2;
-  }
-});
-
-// node_modules/jsonschema/lib/index.js
-var require_lib3 = __commonJS({
-  "node_modules/jsonschema/lib/index.js"(exports2, module2) {
-    "use strict";
-    var Validator2 = module2.exports.Validator = require_validator2();
-    module2.exports.ValidatorResult = require_helpers3().ValidatorResult;
-    module2.exports.ValidatorResultError = require_helpers3().ValidatorResultError;
-    module2.exports.ValidationError = require_helpers3().ValidationError;
-    module2.exports.SchemaError = require_helpers3().SchemaError;
-    module2.exports.SchemaScanResult = require_scan().SchemaScanResult;
-    module2.exports.scan = require_scan().scan;
-    module2.exports.validate = function(instance, schema2, options) {
-      var v = new Validator2();
-      return v.validate(instance, schema2, options);
-    };
-  }
-});
-
-// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-glob-options-helper.js
-var require_internal_glob_options_helper = __commonJS({
-  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-glob-options-helper.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      Object.defineProperty(o, k2, { enumerable: true, get: function() {
-        return m[k];
-      } });
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      minver = null;
+      for (var i2 = 0; i2 < range.set.length; ++i2) {
+        var comparators = range.set[i2];
+        comparators.forEach(function(comparator) {
+          var compver = new SemVer(comparator.semver.version);
+          switch (comparator.operator) {
+            case ">":
+              if (compver.prerelease.length === 0) {
+                compver.patch++;
+              } else {
+                compver.prerelease.push(0);
+              }
+              compver.raw = compver.format();
+            /* fallthrough */
+            case "":
+            case ">=":
+              if (!minver || gt(minver, compver)) {
+                minver = compver;
+              }
+              break;
+            case "<":
+            case "<=":
+              break;
+            /* istanbul ignore next */
+            default:
+              throw new Error("Unexpected operation: " + comparator.operator);
+          }
+        });
       }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getOptions = void 0;
-    var core14 = __importStar4(require_core());
-    function getOptions(copy) {
-      const result = {
-        followSymbolicLinks: true,
-        implicitDescendants: true,
-        omitBrokenSymbolicLinks: true
-      };
-      if (copy) {
-        if (typeof copy.followSymbolicLinks === "boolean") {
-          result.followSymbolicLinks = copy.followSymbolicLinks;
-          core14.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`);
-        }
-        if (typeof copy.implicitDescendants === "boolean") {
-          result.implicitDescendants = copy.implicitDescendants;
-          core14.debug(`implicitDescendants '${result.implicitDescendants}'`);
-        }
-        if (typeof copy.omitBrokenSymbolicLinks === "boolean") {
-          result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks;
-          core14.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`);
-        }
+      if (minver && range.test(minver)) {
+        return minver;
       }
-      return result;
+      return null;
     }
-    exports2.getOptions = getOptions;
-  }
-});
-
-// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path-helper.js
-var require_internal_path_helper = __commonJS({
-  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path-helper.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      Object.defineProperty(o, k2, { enumerable: true, get: function() {
-        return m[k];
-      } });
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
-      return mod && mod.__esModule ? mod : { "default": mod };
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.safeTrimTrailingSeparator = exports2.normalizeSeparators = exports2.hasRoot = exports2.hasAbsoluteRoot = exports2.ensureAbsoluteRoot = exports2.dirname = void 0;
-    var path2 = __importStar4(require("path"));
-    var assert_1 = __importDefault4(require("assert"));
-    var IS_WINDOWS = process.platform === "win32";
-    function dirname(p) {
-      p = safeTrimTrailingSeparator(p);
-      if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) {
-        return p;
-      }
-      let result = path2.dirname(p);
-      if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) {
-        result = safeTrimTrailingSeparator(result);
+    exports2.validRange = validRange;
+    function validRange(range, options) {
+      try {
+        return new Range2(range, options).range || "*";
+      } catch (er) {
+        return null;
       }
-      return result;
     }
-    exports2.dirname = dirname;
-    function ensureAbsoluteRoot(root, itemPath) {
-      assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`);
-      assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`);
-      if (hasAbsoluteRoot(itemPath)) {
-        return itemPath;
+    exports2.ltr = ltr;
+    function ltr(version, range, options) {
+      return outside(version, range, "<", options);
+    }
+    exports2.gtr = gtr;
+    function gtr(version, range, options) {
+      return outside(version, range, ">", options);
+    }
+    exports2.outside = outside;
+    function outside(version, range, hilo, options) {
+      version = new SemVer(version, options);
+      range = new Range2(range, options);
+      var gtfn, ltefn, ltfn, comp, ecomp;
+      switch (hilo) {
+        case ">":
+          gtfn = gt;
+          ltefn = lte;
+          ltfn = lt;
+          comp = ">";
+          ecomp = ">=";
+          break;
+        case "<":
+          gtfn = lt;
+          ltefn = gte5;
+          ltfn = gt;
+          comp = "<";
+          ecomp = "<=";
+          break;
+        default:
+          throw new TypeError('Must provide a hilo val of "<" or ">"');
       }
-      if (IS_WINDOWS) {
-        if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) {
-          let cwd = process.cwd();
-          assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
-          if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) {
-            if (itemPath.length === 2) {
-              return `${itemPath[0]}:\\${cwd.substr(3)}`;
-            } else {
-              if (!cwd.endsWith("\\")) {
-                cwd += "\\";
-              }
-              return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`;
-            }
-          } else {
-            return `${itemPath[0]}:\\${itemPath.substr(2)}`;
+      if (satisfies2(version, range, options)) {
+        return false;
+      }
+      for (var i2 = 0; i2 < range.set.length; ++i2) {
+        var comparators = range.set[i2];
+        var high = null;
+        var low = null;
+        comparators.forEach(function(comparator) {
+          if (comparator.semver === ANY) {
+            comparator = new Comparator(">=0.0.0");
           }
-        } else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) {
-          const cwd = process.cwd();
-          assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
-          return `${cwd[0]}:\\${itemPath.substr(1)}`;
+          high = high || comparator;
+          low = low || comparator;
+          if (gtfn(comparator.semver, high.semver, options)) {
+            high = comparator;
+          } else if (ltfn(comparator.semver, low.semver, options)) {
+            low = comparator;
+          }
+        });
+        if (high.operator === comp || high.operator === ecomp) {
+          return false;
+        }
+        if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
+          return false;
+        } else if (low.operator === ecomp && ltfn(version, low.semver)) {
+          return false;
         }
       }
-      assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`);
-      if (root.endsWith("/") || IS_WINDOWS && root.endsWith("\\")) {
-      } else {
-        root += path2.sep;
-      }
-      return root + itemPath;
+      return true;
     }
-    exports2.ensureAbsoluteRoot = ensureAbsoluteRoot;
-    function hasAbsoluteRoot(itemPath) {
-      assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`);
-      itemPath = normalizeSeparators(itemPath);
-      if (IS_WINDOWS) {
-        return itemPath.startsWith("\\\\") || /^[A-Z]:\\/i.test(itemPath);
-      }
-      return itemPath.startsWith("/");
+    exports2.prerelease = prerelease;
+    function prerelease(version, options) {
+      var parsed = parse(version, options);
+      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
     }
-    exports2.hasAbsoluteRoot = hasAbsoluteRoot;
-    function hasRoot(itemPath) {
-      assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`);
-      itemPath = normalizeSeparators(itemPath);
-      if (IS_WINDOWS) {
-        return itemPath.startsWith("\\") || /^[A-Z]:/i.test(itemPath);
-      }
-      return itemPath.startsWith("/");
+    exports2.intersects = intersects;
+    function intersects(r1, r2, options) {
+      r1 = new Range2(r1, options);
+      r2 = new Range2(r2, options);
+      return r1.intersects(r2);
     }
-    exports2.hasRoot = hasRoot;
-    function normalizeSeparators(p) {
-      p = p || "";
-      if (IS_WINDOWS) {
-        p = p.replace(/\//g, "\\");
-        const isUnc = /^\\\\+[^\\]/.test(p);
-        return (isUnc ? "\\" : "") + p.replace(/\\\\+/g, "\\");
+    exports2.coerce = coerce3;
+    function coerce3(version, options) {
+      if (version instanceof SemVer) {
+        return version;
       }
-      return p.replace(/\/\/+/g, "/");
-    }
-    exports2.normalizeSeparators = normalizeSeparators;
-    function safeTrimTrailingSeparator(p) {
-      if (!p) {
-        return "";
+      if (typeof version === "number") {
+        version = String(version);
       }
-      p = normalizeSeparators(p);
-      if (!p.endsWith(path2.sep)) {
-        return p;
+      if (typeof version !== "string") {
+        return null;
       }
-      if (p === path2.sep) {
-        return p;
+      options = options || {};
+      var match = null;
+      if (!options.rtl) {
+        match = version.match(safeRe[t.COERCE]);
+      } else {
+        var next;
+        while ((next = safeRe[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) {
+          if (!match || next.index + next[0].length !== match.index + match[0].length) {
+            match = next;
+          }
+          safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
+        }
+        safeRe[t.COERCERTL].lastIndex = -1;
       }
-      if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) {
-        return p;
+      if (match === null) {
+        return null;
       }
-      return p.substr(0, p.length - 1);
+      return parse(match[2] + "." + (match[3] || "0") + "." + (match[4] || "0"), options);
     }
-    exports2.safeTrimTrailingSeparator = safeTrimTrailingSeparator;
   }
 });
 
-// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-match-kind.js
-var require_internal_match_kind = __commonJS({
-  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-match-kind.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/constants.js
+var require_constants10 = __commonJS({
+  "node_modules/@actions/cache/lib/internal/constants.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.MatchKind = void 0;
-    var MatchKind;
-    (function(MatchKind2) {
-      MatchKind2[MatchKind2["None"] = 0] = "None";
-      MatchKind2[MatchKind2["Directory"] = 1] = "Directory";
-      MatchKind2[MatchKind2["File"] = 2] = "File";
-      MatchKind2[MatchKind2["All"] = 3] = "All";
-    })(MatchKind = exports2.MatchKind || (exports2.MatchKind = {}));
+    exports2.CacheFileSizeLimit = exports2.ManifestFilename = exports2.TarFilename = exports2.SystemTarPathOnWindows = exports2.GnuTarPathOnWindows = exports2.SocketTimeout = exports2.DefaultRetryDelay = exports2.DefaultRetryAttempts = exports2.ArchiveToolType = exports2.CompressionMethod = exports2.CacheFilename = void 0;
+    var CacheFilename;
+    (function(CacheFilename2) {
+      CacheFilename2["Gzip"] = "cache.tgz";
+      CacheFilename2["Zstd"] = "cache.tzst";
+    })(CacheFilename || (exports2.CacheFilename = CacheFilename = {}));
+    var CompressionMethod;
+    (function(CompressionMethod2) {
+      CompressionMethod2["Gzip"] = "gzip";
+      CompressionMethod2["ZstdWithoutLong"] = "zstd-without-long";
+      CompressionMethod2["Zstd"] = "zstd";
+    })(CompressionMethod || (exports2.CompressionMethod = CompressionMethod = {}));
+    var ArchiveToolType;
+    (function(ArchiveToolType2) {
+      ArchiveToolType2["GNU"] = "gnu";
+      ArchiveToolType2["BSD"] = "bsd";
+    })(ArchiveToolType || (exports2.ArchiveToolType = ArchiveToolType = {}));
+    exports2.DefaultRetryAttempts = 2;
+    exports2.DefaultRetryDelay = 5e3;
+    exports2.SocketTimeout = 5e3;
+    exports2.GnuTarPathOnWindows = `${process.env["PROGRAMFILES"]}\\Git\\usr\\bin\\tar.exe`;
+    exports2.SystemTarPathOnWindows = `${process.env["SYSTEMDRIVE"]}\\Windows\\System32\\tar.exe`;
+    exports2.TarFilename = "cache.tar";
+    exports2.ManifestFilename = "manifest.txt";
+    exports2.CacheFileSizeLimit = 10 * Math.pow(1024, 3);
   }
 });
 
-// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern-helper.js
-var require_internal_pattern_helper = __commonJS({
-  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern-helper.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/cacheUtils.js
+var require_cacheUtils = __commonJS({
+  "node_modules/@actions/cache/lib/internal/cacheUtils.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
-      Object.defineProperty(o, k2, { enumerable: true, get: function() {
-        return m[k];
-      } });
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
     }) : (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
       o[k2] = m[k];
@@ -102423,908 +107365,1112 @@ var require_internal_pattern_helper = __commonJS({
       if (mod && mod.__esModule) return mod;
       var result = {};
       if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
       __setModuleDefault4(result, mod);
       return result;
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.partialMatch = exports2.match = exports2.getSearchPaths = void 0;
-    var pathHelper = __importStar4(require_internal_path_helper());
-    var internal_match_kind_1 = require_internal_match_kind();
-    var IS_WINDOWS = process.platform === "win32";
-    function getSearchPaths(patterns) {
-      patterns = patterns.filter((x) => !x.negate);
-      const searchPathMap = {};
-      for (const pattern of patterns) {
-        const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath;
-        searchPathMap[key] = "candidate";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      const result = [];
-      for (const pattern of patterns) {
-        const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath;
-        if (searchPathMap[key] === "included") {
-          continue;
-        }
-        let foundAncestor = false;
-        let tempKey = key;
-        let parent = pathHelper.dirname(tempKey);
-        while (parent !== tempKey) {
-          if (searchPathMap[parent]) {
-            foundAncestor = true;
-            break;
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
           }
-          tempKey = parent;
-          parent = pathHelper.dirname(tempKey);
         }
-        if (!foundAncestor) {
-          result.push(pattern.searchPath);
-          searchPathMap[key] = "included";
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
         }
-      }
-      return result;
-    }
-    exports2.getSearchPaths = getSearchPaths;
-    function match(patterns, itemPath) {
-      let result = internal_match_kind_1.MatchKind.None;
-      for (const pattern of patterns) {
-        if (pattern.negate) {
-          result &= ~pattern.match(itemPath);
-        } else {
-          result |= pattern.match(itemPath);
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
         }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) {
+      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+      var m = o[Symbol.asyncIterator], i;
+      return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
+        return this;
+      }, i);
+      function verb(n) {
+        i[n] = o[n] && function(v) {
+          return new Promise(function(resolve2, reject) {
+            v = o[n](v), settle(resolve2, reject, v.done, v.value);
+          });
+        };
       }
-      return result;
-    }
-    exports2.match = match;
-    function partialMatch(patterns, itemPath) {
-      return patterns.some((x) => !x.negate && x.partialMatch(itemPath));
-    }
-    exports2.partialMatch = partialMatch;
-  }
-});
-
-// node_modules/concat-map/index.js
-var require_concat_map = __commonJS({
-  "node_modules/concat-map/index.js"(exports2, module2) {
-    module2.exports = function(xs, fn) {
-      var res = [];
-      for (var i = 0; i < xs.length; i++) {
-        var x = fn(xs[i], i);
-        if (isArray(x)) res.push.apply(res, x);
-        else res.push(x);
+      function settle(resolve2, reject, d, v) {
+        Promise.resolve(v).then(function(v2) {
+          resolve2({ value: v2, done: d });
+        }, reject);
       }
-      return res;
-    };
-    var isArray = Array.isArray || function(xs) {
-      return Object.prototype.toString.call(xs) === "[object Array]";
     };
-  }
-});
-
-// node_modules/brace-expansion/index.js
-var require_brace_expansion3 = __commonJS({
-  "node_modules/brace-expansion/index.js"(exports2, module2) {
-    var concatMap = require_concat_map();
-    var balanced = require_balanced_match();
-    module2.exports = expandTop;
-    var escSlash = "\0SLASH" + Math.random() + "\0";
-    var escOpen = "\0OPEN" + Math.random() + "\0";
-    var escClose = "\0CLOSE" + Math.random() + "\0";
-    var escComma = "\0COMMA" + Math.random() + "\0";
-    var escPeriod = "\0PERIOD" + Math.random() + "\0";
-    function numeric(str2) {
-      return parseInt(str2, 10) == str2 ? parseInt(str2, 10) : str2.charCodeAt(0);
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getRuntimeToken = exports2.getCacheVersion = exports2.assertDefined = exports2.getGnuTarPathOnWindows = exports2.getCacheFileName = exports2.getCompressionMethod = exports2.unlinkFile = exports2.resolvePaths = exports2.getArchiveFileSizeInBytes = exports2.createTempDirectory = void 0;
+    var core14 = __importStar4(require_core());
+    var exec2 = __importStar4(require_exec());
+    var glob2 = __importStar4(require_glob2());
+    var io6 = __importStar4(require_io());
+    var crypto = __importStar4(require("crypto"));
+    var fs2 = __importStar4(require("fs"));
+    var path2 = __importStar4(require("path"));
+    var semver8 = __importStar4(require_semver3());
+    var util = __importStar4(require("util"));
+    var constants_1 = require_constants10();
+    var versionSalt = "1.0";
+    function createTempDirectory() {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const IS_WINDOWS = process.platform === "win32";
+        let tempDirectory = process.env["RUNNER_TEMP"] || "";
+        if (!tempDirectory) {
+          let baseLocation;
+          if (IS_WINDOWS) {
+            baseLocation = process.env["USERPROFILE"] || "C:\\";
+          } else {
+            if (process.platform === "darwin") {
+              baseLocation = "/Users";
+            } else {
+              baseLocation = "/home";
+            }
+          }
+          tempDirectory = path2.join(baseLocation, "actions", "temp");
+        }
+        const dest = path2.join(tempDirectory, crypto.randomUUID());
+        yield io6.mkdirP(dest);
+        return dest;
+      });
     }
-    function escapeBraces(str2) {
-      return str2.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
+    exports2.createTempDirectory = createTempDirectory;
+    function getArchiveFileSizeInBytes(filePath) {
+      return fs2.statSync(filePath).size;
     }
-    function unescapeBraces(str2) {
-      return str2.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
+    exports2.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes;
+    function resolvePaths(patterns) {
+      var _a, e_1, _b, _c;
+      var _d;
+      return __awaiter4(this, void 0, void 0, function* () {
+        const paths = [];
+        const workspace = (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd();
+        const globber = yield glob2.create(patterns.join("\n"), {
+          implicitDescendants: false
+        });
+        try {
+          for (var _e = true, _f = __asyncValues4(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {
+            _c = _g.value;
+            _e = false;
+            const file = _c;
+            const relativeFile = path2.relative(workspace, file).replace(new RegExp(`\\${path2.sep}`, "g"), "/");
+            core14.debug(`Matched: ${relativeFile}`);
+            if (relativeFile === "") {
+              paths.push(".");
+            } else {
+              paths.push(`${relativeFile}`);
+            }
+          }
+        } catch (e_1_1) {
+          e_1 = { error: e_1_1 };
+        } finally {
+          try {
+            if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
+          } finally {
+            if (e_1) throw e_1.error;
+          }
+        }
+        return paths;
+      });
     }
-    function parseCommaParts(str2) {
-      if (!str2)
-        return [""];
-      var parts = [];
-      var m = balanced("{", "}", str2);
-      if (!m)
-        return str2.split(",");
-      var pre = m.pre;
-      var body = m.body;
-      var post = m.post;
-      var p = pre.split(",");
-      p[p.length - 1] += "{" + body + "}";
-      var postParts = parseCommaParts(post);
-      if (post.length) {
-        p[p.length - 1] += postParts.shift();
-        p.push.apply(p, postParts);
-      }
-      parts.push.apply(parts, p);
-      return parts;
+    exports2.resolvePaths = resolvePaths;
+    function unlinkFile(filePath) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        return util.promisify(fs2.unlink)(filePath);
+      });
     }
-    function expandTop(str2) {
-      if (!str2)
-        return [];
-      if (str2.substr(0, 2) === "{}") {
-        str2 = "\\{\\}" + str2.substr(2);
-      }
-      return expand(escapeBraces(str2), true).map(unescapeBraces);
+    exports2.unlinkFile = unlinkFile;
+    function getVersion(app, additionalArgs = []) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        let versionOutput = "";
+        additionalArgs.push("--version");
+        core14.debug(`Checking ${app} ${additionalArgs.join(" ")}`);
+        try {
+          yield exec2.exec(`${app}`, additionalArgs, {
+            ignoreReturnCode: true,
+            silent: true,
+            listeners: {
+              stdout: (data) => versionOutput += data.toString(),
+              stderr: (data) => versionOutput += data.toString()
+            }
+          });
+        } catch (err) {
+          core14.debug(err.message);
+        }
+        versionOutput = versionOutput.trim();
+        core14.debug(versionOutput);
+        return versionOutput;
+      });
     }
-    function embrace(str2) {
-      return "{" + str2 + "}";
+    function getCompressionMethod() {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const versionOutput = yield getVersion("zstd", ["--quiet"]);
+        const version = semver8.clean(versionOutput);
+        core14.debug(`zstd version: ${version}`);
+        if (versionOutput === "") {
+          return constants_1.CompressionMethod.Gzip;
+        } else {
+          return constants_1.CompressionMethod.ZstdWithoutLong;
+        }
+      });
     }
-    function isPadded(el) {
-      return /^-?0\d/.test(el);
+    exports2.getCompressionMethod = getCompressionMethod;
+    function getCacheFileName(compressionMethod) {
+      return compressionMethod === constants_1.CompressionMethod.Gzip ? constants_1.CacheFilename.Gzip : constants_1.CacheFilename.Zstd;
     }
-    function lte(i, y) {
-      return i <= y;
+    exports2.getCacheFileName = getCacheFileName;
+    function getGnuTarPathOnWindows() {
+      return __awaiter4(this, void 0, void 0, function* () {
+        if (fs2.existsSync(constants_1.GnuTarPathOnWindows)) {
+          return constants_1.GnuTarPathOnWindows;
+        }
+        const versionOutput = yield getVersion("tar");
+        return versionOutput.toLowerCase().includes("gnu tar") ? io6.which("tar") : "";
+      });
     }
-    function gte5(i, y) {
-      return i >= y;
+    exports2.getGnuTarPathOnWindows = getGnuTarPathOnWindows;
+    function assertDefined(name, value) {
+      if (value === void 0) {
+        throw Error(`Expected ${name} but value was undefiend`);
+      }
+      return value;
     }
-    function expand(str2, isTop) {
-      var expansions = [];
-      var m = balanced("{", "}", str2);
-      if (!m || /\$$/.test(m.pre)) return [str2];
-      var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
-      var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
-      var isSequence = isNumericSequence || isAlphaSequence;
-      var isOptions = m.body.indexOf(",") >= 0;
-      if (!isSequence && !isOptions) {
-        if (m.post.match(/,(?!,).*\}/)) {
-          str2 = m.pre + "{" + m.body + escClose + m.post;
-          return expand(str2);
-        }
-        return [str2];
+    exports2.assertDefined = assertDefined;
+    function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) {
+      const components = paths.slice();
+      if (compressionMethod) {
+        components.push(compressionMethod);
       }
-      var n;
-      if (isSequence) {
-        n = m.body.split(/\.\./);
-      } else {
-        n = parseCommaParts(m.body);
-        if (n.length === 1) {
-          n = expand(n[0], false).map(embrace);
-          if (n.length === 1) {
-            var post = m.post.length ? expand(m.post, false) : [""];
-            return post.map(function(p) {
-              return m.pre + n[0] + p;
-            });
-          }
-        }
+      if (process.platform === "win32" && !enableCrossOsArchive) {
+        components.push("windows-only");
       }
-      var pre = m.pre;
-      var post = m.post.length ? expand(m.post, false) : [""];
-      var N;
-      if (isSequence) {
-        var x = numeric(n[0]);
-        var y = numeric(n[1]);
-        var width = Math.max(n[0].length, n[1].length);
-        var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
-        var test = lte;
-        var reverse = y < x;
-        if (reverse) {
-          incr *= -1;
-          test = gte5;
+      components.push(versionSalt);
+      return crypto.createHash("sha256").update(components.join("|")).digest("hex");
+    }
+    exports2.getCacheVersion = getCacheVersion;
+    function getRuntimeToken() {
+      const token = process.env["ACTIONS_RUNTIME_TOKEN"];
+      if (!token) {
+        throw new Error("Unable to get the ACTIONS_RUNTIME_TOKEN env variable");
+      }
+      return token;
+    }
+    exports2.getRuntimeToken = getRuntimeToken;
+  }
+});
+
+// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js
+var require_proxy5 = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.checkBypass = exports2.getProxyUrl = void 0;
+    function getProxyUrl(reqUrl) {
+      const usingSsl = reqUrl.protocol === "https:";
+      if (checkBypass(reqUrl)) {
+        return void 0;
+      }
+      const proxyVar = (() => {
+        if (usingSsl) {
+          return process.env["https_proxy"] || process.env["HTTPS_PROXY"];
+        } else {
+          return process.env["http_proxy"] || process.env["HTTP_PROXY"];
         }
-        var pad = n.some(isPadded);
-        N = [];
-        for (var i = x; test(i, y); i += incr) {
-          var c;
-          if (isAlphaSequence) {
-            c = String.fromCharCode(i);
-            if (c === "\\")
-              c = "";
-          } else {
-            c = String(i);
-            if (pad) {
-              var need = width - c.length;
-              if (need > 0) {
-                var z = new Array(need + 1).join("0");
-                if (i < 0)
-                  c = "-" + z + c.slice(1);
-                else
-                  c = z + c;
-              }
-            }
-          }
-          N.push(c);
+      })();
+      if (proxyVar) {
+        try {
+          return new DecodedURL(proxyVar);
+        } catch (_a) {
+          if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://"))
+            return new DecodedURL(`http://${proxyVar}`);
         }
       } else {
-        N = concatMap(n, function(el) {
-          return expand(el, false);
-        });
+        return void 0;
       }
-      for (var j = 0; j < N.length; j++) {
-        for (var k = 0; k < post.length; k++) {
-          var expansion = pre + N[j] + post[k];
-          if (!isTop || isSequence || expansion)
-            expansions.push(expansion);
+    }
+    exports2.getProxyUrl = getProxyUrl;
+    function checkBypass(reqUrl) {
+      if (!reqUrl.hostname) {
+        return false;
+      }
+      const reqHost = reqUrl.hostname;
+      if (isLoopbackAddress(reqHost)) {
+        return true;
+      }
+      const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || "";
+      if (!noProxy) {
+        return false;
+      }
+      let reqPort;
+      if (reqUrl.port) {
+        reqPort = Number(reqUrl.port);
+      } else if (reqUrl.protocol === "http:") {
+        reqPort = 80;
+      } else if (reqUrl.protocol === "https:") {
+        reqPort = 443;
+      }
+      const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+      if (typeof reqPort === "number") {
+        upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
+      }
+      for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) {
+        if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) {
+          return true;
         }
       }
-      return expansions;
+      return false;
+    }
+    exports2.checkBypass = checkBypass;
+    function isLoopbackAddress(host) {
+      const hostLower = host.toLowerCase();
+      return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]");
     }
+    var DecodedURL = class extends URL {
+      constructor(url, base) {
+        super(url, base);
+        this._decodedUsername = decodeURIComponent(super.username);
+        this._decodedPassword = decodeURIComponent(super.password);
+      }
+      get username() {
+        return this._decodedUsername;
+      }
+      get password() {
+        return this._decodedPassword;
+      }
+    };
   }
 });
 
-// node_modules/minimatch/minimatch.js
-var require_minimatch2 = __commonJS({
-  "node_modules/minimatch/minimatch.js"(exports2, module2) {
-    module2.exports = minimatch;
-    minimatch.Minimatch = Minimatch;
-    var path2 = (function() {
-      try {
-        return require("path");
-      } catch (e) {
+// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js
+var require_lib7 = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-    })() || {
-      sep: "/"
-    };
-    minimatch.sep = path2.sep;
-    var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
-    var expand = require_brace_expansion3();
-    var plTypes = {
-      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
-      "?": { open: "(?:", close: ")?" },
-      "+": { open: "(?:", close: ")+" },
-      "*": { open: "(?:", close: ")*" },
-      "@": { open: "(?:", close: ")" }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
     };
-    var qmark = "[^/]";
-    var star = qmark + "*?";
-    var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
-    var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
-    var reSpecials = charSet("().*{}+?[]^$\\!");
-    function charSet(s) {
-      return s.split("").reduce(function(set2, c) {
-        set2[c] = true;
-        return set2;
-      }, {});
-    }
-    var slashSplit = /\/+/;
-    minimatch.filter = filter;
-    function filter(pattern, options) {
-      options = options || {};
-      return function(p, i, list) {
-        return minimatch(p, pattern, options);
-      };
-    }
-    function ext(a, b) {
-      b = b || {};
-      var t = {};
-      Object.keys(a).forEach(function(k) {
-        t[k] = a[k];
-      });
-      Object.keys(b).forEach(function(k) {
-        t[k] = b[k];
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
       });
-      return t;
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0;
+    var http = __importStar4(require("http"));
+    var https2 = __importStar4(require("https"));
+    var pm = __importStar4(require_proxy5());
+    var tunnel = __importStar4(require_tunnel2());
+    var undici_1 = require_undici();
+    var HttpCodes;
+    (function(HttpCodes2) {
+      HttpCodes2[HttpCodes2["OK"] = 200] = "OK";
+      HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices";
+      HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently";
+      HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved";
+      HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther";
+      HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified";
+      HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy";
+      HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy";
+      HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+      HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect";
+      HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest";
+      HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized";
+      HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired";
+      HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden";
+      HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound";
+      HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+      HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable";
+      HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+      HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout";
+      HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict";
+      HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone";
+      HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests";
+      HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError";
+      HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented";
+      HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway";
+      HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+      HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout";
+    })(HttpCodes || (exports2.HttpCodes = HttpCodes = {}));
+    var Headers;
+    (function(Headers2) {
+      Headers2["Accept"] = "accept";
+      Headers2["ContentType"] = "content-type";
+    })(Headers || (exports2.Headers = Headers = {}));
+    var MediaTypes;
+    (function(MediaTypes2) {
+      MediaTypes2["ApplicationJson"] = "application/json";
+    })(MediaTypes || (exports2.MediaTypes = MediaTypes = {}));
+    function getProxyUrl(serverUrl) {
+      const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+      return proxyUrl ? proxyUrl.href : "";
     }
-    minimatch.defaults = function(def) {
-      if (!def || typeof def !== "object" || !Object.keys(def).length) {
-        return minimatch;
+    exports2.getProxyUrl = getProxyUrl;
+    var HttpRedirectCodes = [
+      HttpCodes.MovedPermanently,
+      HttpCodes.ResourceMoved,
+      HttpCodes.SeeOther,
+      HttpCodes.TemporaryRedirect,
+      HttpCodes.PermanentRedirect
+    ];
+    var HttpResponseRetryCodes = [
+      HttpCodes.BadGateway,
+      HttpCodes.ServiceUnavailable,
+      HttpCodes.GatewayTimeout
+    ];
+    var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"];
+    var ExponentialBackoffCeiling = 10;
+    var ExponentialBackoffTimeSlice = 5;
+    var HttpClientError = class _HttpClientError extends Error {
+      constructor(message, statusCode) {
+        super(message);
+        this.name = "HttpClientError";
+        this.statusCode = statusCode;
+        Object.setPrototypeOf(this, _HttpClientError.prototype);
       }
-      var orig = minimatch;
-      var m = function minimatch2(p, pattern, options) {
-        return orig(p, pattern, ext(def, options));
-      };
-      m.Minimatch = function Minimatch2(pattern, options) {
-        return new orig.Minimatch(pattern, ext(def, options));
-      };
-      m.Minimatch.defaults = function defaults(options) {
-        return orig.defaults(ext(def, options)).Minimatch;
-      };
-      m.filter = function filter2(pattern, options) {
-        return orig.filter(pattern, ext(def, options));
-      };
-      m.defaults = function defaults(options) {
-        return orig.defaults(ext(def, options));
-      };
-      m.makeRe = function makeRe2(pattern, options) {
-        return orig.makeRe(pattern, ext(def, options));
-      };
-      m.braceExpand = function braceExpand2(pattern, options) {
-        return orig.braceExpand(pattern, ext(def, options));
-      };
-      m.match = function(list, pattern, options) {
-        return orig.match(list, pattern, ext(def, options));
-      };
-      return m;
-    };
-    Minimatch.defaults = function(def) {
-      return minimatch.defaults(def).Minimatch;
     };
-    function minimatch(p, pattern, options) {
-      assertValidPattern(pattern);
-      if (!options) options = {};
-      if (!options.nocomment && pattern.charAt(0) === "#") {
-        return false;
+    exports2.HttpClientError = HttpClientError;
+    var HttpClientResponse = class {
+      constructor(message) {
+        this.message = message;
       }
-      return new Minimatch(pattern, options).match(p);
-    }
-    function Minimatch(pattern, options) {
-      if (!(this instanceof Minimatch)) {
-        return new Minimatch(pattern, options);
+      readBody() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
+            let output = Buffer.alloc(0);
+            this.message.on("data", (chunk) => {
+              output = Buffer.concat([output, chunk]);
+            });
+            this.message.on("end", () => {
+              resolve2(output.toString());
+            });
+          }));
+        });
       }
-      assertValidPattern(pattern);
-      if (!options) options = {};
-      pattern = pattern.trim();
-      if (!options.allowWindowsEscape && path2.sep !== "/") {
-        pattern = pattern.split(path2.sep).join("/");
+      readBodyBuffer() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
+            const chunks = [];
+            this.message.on("data", (chunk) => {
+              chunks.push(chunk);
+            });
+            this.message.on("end", () => {
+              resolve2(Buffer.concat(chunks));
+            });
+          }));
+        });
       }
-      this.options = options;
-      this.set = [];
-      this.pattern = pattern;
-      this.regexp = null;
-      this.negate = false;
-      this.comment = false;
-      this.empty = false;
-      this.partial = !!options.partial;
-      this.make();
-    }
-    Minimatch.prototype.debug = function() {
     };
-    Minimatch.prototype.make = make;
-    function make() {
-      var pattern = this.pattern;
-      var options = this.options;
-      if (!options.nocomment && pattern.charAt(0) === "#") {
-        this.comment = true;
-        return;
+    exports2.HttpClientResponse = HttpClientResponse;
+    function isHttps(requestUrl) {
+      const parsedUrl = new URL(requestUrl);
+      return parsedUrl.protocol === "https:";
+    }
+    exports2.isHttps = isHttps;
+    var HttpClient2 = class {
+      constructor(userAgent, handlers, requestOptions) {
+        this._ignoreSslError = false;
+        this._allowRedirects = true;
+        this._allowRedirectDowngrade = false;
+        this._maxRedirects = 50;
+        this._allowRetries = false;
+        this._maxRetries = 1;
+        this._keepAlive = false;
+        this._disposed = false;
+        this.userAgent = userAgent;
+        this.handlers = handlers || [];
+        this.requestOptions = requestOptions;
+        if (requestOptions) {
+          if (requestOptions.ignoreSslError != null) {
+            this._ignoreSslError = requestOptions.ignoreSslError;
+          }
+          this._socketTimeout = requestOptions.socketTimeout;
+          if (requestOptions.allowRedirects != null) {
+            this._allowRedirects = requestOptions.allowRedirects;
+          }
+          if (requestOptions.allowRedirectDowngrade != null) {
+            this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+          }
+          if (requestOptions.maxRedirects != null) {
+            this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+          }
+          if (requestOptions.keepAlive != null) {
+            this._keepAlive = requestOptions.keepAlive;
+          }
+          if (requestOptions.allowRetries != null) {
+            this._allowRetries = requestOptions.allowRetries;
+          }
+          if (requestOptions.maxRetries != null) {
+            this._maxRetries = requestOptions.maxRetries;
+          }
+        }
+      }
+      options(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("OPTIONS", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      get(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("GET", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      del(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("DELETE", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      post(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("POST", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      patch(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PATCH", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      put(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PUT", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      head(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("HEAD", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      sendStream(verb, requestUrl, stream, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request(verb, requestUrl, stream, additionalHeaders);
+        });
+      }
+      /**
+       * Gets a typed object from an endpoint
+       * Be aware that not found returns a null.  Other errors (4xx, 5xx) reject the promise
+       */
+      getJson(requestUrl, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          const res = yield this.get(requestUrl, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      postJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.post(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      putJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.put(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      patchJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.patch(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      /**
+       * Makes a raw http request.
+       * All other methods such as get, post, patch, and request ultimately call this.
+       * Prefer get, del, post and patch
+       */
+      request(verb, requestUrl, data, headers) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          if (this._disposed) {
+            throw new Error("Client has already been disposed.");
+          }
+          const parsedUrl = new URL(requestUrl);
+          let info7 = this._prepareRequest(verb, parsedUrl, headers);
+          const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1;
+          let numTries = 0;
+          let response;
+          do {
+            response = yield this.requestRaw(info7, data);
+            if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
+              let authenticationHandler;
+              for (const handler of this.handlers) {
+                if (handler.canHandleAuthentication(response)) {
+                  authenticationHandler = handler;
+                  break;
+                }
+              }
+              if (authenticationHandler) {
+                return authenticationHandler.handleAuthentication(this, info7, data);
+              } else {
+                return response;
+              }
+            }
+            let redirectsRemaining = this._maxRedirects;
+            while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) {
+              const redirectUrl = response.message.headers["location"];
+              if (!redirectUrl) {
+                break;
+              }
+              const parsedRedirectUrl = new URL(redirectUrl);
+              if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
+                throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
+              }
+              yield response.readBody();
+              if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+                for (const header in headers) {
+                  if (header.toLowerCase() === "authorization") {
+                    delete headers[header];
+                  }
+                }
+              }
+              info7 = this._prepareRequest(verb, parsedRedirectUrl, headers);
+              response = yield this.requestRaw(info7, data);
+              redirectsRemaining--;
+            }
+            if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+              return response;
+            }
+            numTries += 1;
+            if (numTries < maxTries) {
+              yield response.readBody();
+              yield this._performExponentialBackoff(numTries);
+            }
+          } while (numTries < maxTries);
+          return response;
+        });
       }
-      if (!pattern) {
-        this.empty = true;
-        return;
+      /**
+       * Needs to be called if keepAlive is set to true in request options.
+       */
+      dispose() {
+        if (this._agent) {
+          this._agent.destroy();
+        }
+        this._disposed = true;
       }
-      this.parseNegate();
-      var set2 = this.globSet = this.braceExpand();
-      if (options.debug) this.debug = function debug4() {
-        console.error.apply(console, arguments);
-      };
-      this.debug(this.pattern, set2);
-      set2 = this.globParts = set2.map(function(s) {
-        return s.split(slashSplit);
-      });
-      this.debug(this.pattern, set2);
-      set2 = set2.map(function(s, si, set3) {
-        return s.map(this.parse, this);
-      }, this);
-      this.debug(this.pattern, set2);
-      set2 = set2.filter(function(s) {
-        return s.indexOf(false) === -1;
-      });
-      this.debug(this.pattern, set2);
-      this.set = set2;
-    }
-    Minimatch.prototype.parseNegate = parseNegate;
-    function parseNegate() {
-      var pattern = this.pattern;
-      var negate = false;
-      var options = this.options;
-      var negateOffset = 0;
-      if (options.nonegate) return;
-      for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
-        negate = !negate;
-        negateOffset++;
+      /**
+       * Raw request.
+       * @param info
+       * @param data
+       */
+      requestRaw(info7, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2, reject) => {
+            function callbackForResult(err, res) {
+              if (err) {
+                reject(err);
+              } else if (!res) {
+                reject(new Error("Unknown error"));
+              } else {
+                resolve2(res);
+              }
+            }
+            this.requestRawWithCallback(info7, data, callbackForResult);
+          });
+        });
       }
-      if (negateOffset) this.pattern = pattern.substr(negateOffset);
-      this.negate = negate;
-    }
-    minimatch.braceExpand = function(pattern, options) {
-      return braceExpand(pattern, options);
-    };
-    Minimatch.prototype.braceExpand = braceExpand;
-    function braceExpand(pattern, options) {
-      if (!options) {
-        if (this instanceof Minimatch) {
-          options = this.options;
+      /**
+       * Raw request with callback.
+       * @param info
+       * @param data
+       * @param onResult
+       */
+      requestRawWithCallback(info7, data, onResult) {
+        if (typeof data === "string") {
+          if (!info7.options.headers) {
+            info7.options.headers = {};
+          }
+          info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8");
+        }
+        let callbackCalled = false;
+        function handleResult(err, res) {
+          if (!callbackCalled) {
+            callbackCalled = true;
+            onResult(err, res);
+          }
+        }
+        const req = info7.httpModule.request(info7.options, (msg) => {
+          const res = new HttpClientResponse(msg);
+          handleResult(void 0, res);
+        });
+        let socket;
+        req.on("socket", (sock) => {
+          socket = sock;
+        });
+        req.setTimeout(this._socketTimeout || 3 * 6e4, () => {
+          if (socket) {
+            socket.end();
+          }
+          handleResult(new Error(`Request timeout: ${info7.options.path}`));
+        });
+        req.on("error", function(err) {
+          handleResult(err);
+        });
+        if (data && typeof data === "string") {
+          req.write(data, "utf8");
+        }
+        if (data && typeof data !== "string") {
+          data.on("close", function() {
+            req.end();
+          });
+          data.pipe(req);
         } else {
-          options = {};
+          req.end();
         }
       }
-      pattern = typeof pattern === "undefined" ? this.pattern : pattern;
-      assertValidPattern(pattern);
-      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
-        return [pattern];
+      /**
+       * Gets an http agent. This function is useful when you need an http agent that handles
+       * routing through a proxy server - depending upon the url and proxy environment variables.
+       * @param serverUrl  The server URL where the request will be sent. For example, https://api.github.com
+       */
+      getAgent(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        return this._getAgent(parsedUrl);
       }
-      return expand(pattern);
-    }
-    var MAX_PATTERN_LENGTH = 1024 * 64;
-    var assertValidPattern = function(pattern) {
-      if (typeof pattern !== "string") {
-        throw new TypeError("invalid pattern");
+      getAgentDispatcher(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (!useProxy) {
+          return;
+        }
+        return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
       }
-      if (pattern.length > MAX_PATTERN_LENGTH) {
-        throw new TypeError("pattern is too long");
+      _prepareRequest(method, requestUrl, headers) {
+        const info7 = {};
+        info7.parsedUrl = requestUrl;
+        const usingSsl = info7.parsedUrl.protocol === "https:";
+        info7.httpModule = usingSsl ? https2 : http;
+        const defaultPort = usingSsl ? 443 : 80;
+        info7.options = {};
+        info7.options.host = info7.parsedUrl.hostname;
+        info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort;
+        info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || "");
+        info7.options.method = method;
+        info7.options.headers = this._mergeHeaders(headers);
+        if (this.userAgent != null) {
+          info7.options.headers["user-agent"] = this.userAgent;
+        }
+        info7.options.agent = this._getAgent(info7.parsedUrl);
+        if (this.handlers) {
+          for (const handler of this.handlers) {
+            handler.prepareRequest(info7.options);
+          }
+        }
+        return info7;
       }
-    };
-    Minimatch.prototype.parse = parse;
-    var SUBPARSE = {};
-    function parse(pattern, isSub) {
-      assertValidPattern(pattern);
-      var options = this.options;
-      if (pattern === "**") {
-        if (!options.noglobstar)
-          return GLOBSTAR;
-        else
-          pattern = "*";
+      _mergeHeaders(headers) {
+        if (this.requestOptions && this.requestOptions.headers) {
+          return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
+        }
+        return lowercaseKeys(headers || {});
       }
-      if (pattern === "") return "";
-      var re = "";
-      var hasMagic = !!options.nocase;
-      var escaping = false;
-      var patternListStack = [];
-      var negativeLists = [];
-      var stateChar;
-      var inClass = false;
-      var reClassStart = -1;
-      var classStart = -1;
-      var patternStart = pattern.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
-      var self2 = this;
-      function clearStateChar() {
-        if (stateChar) {
-          switch (stateChar) {
-            case "*":
-              re += star;
-              hasMagic = true;
-              break;
-            case "?":
-              re += qmark;
-              hasMagic = true;
-              break;
-            default:
-              re += "\\" + stateChar;
-              break;
-          }
-          self2.debug("clearStateChar %j %j", stateChar, re);
-          stateChar = false;
+      _getExistingOrDefaultHeader(additionalHeaders, header, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
         }
+        return additionalHeaders[header] || clientHeader || _default2;
       }
-      for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
-        this.debug("%s	%s %s %j", pattern, i, re, c);
-        if (escaping && reSpecials[c]) {
-          re += "\\" + c;
-          escaping = false;
-          continue;
+      _getAgent(parsedUrl) {
+        let agent;
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (this._keepAlive && useProxy) {
+          agent = this._proxyAgent;
         }
-        switch (c) {
-          /* istanbul ignore next */
-          case "/": {
-            return false;
+        if (!useProxy) {
+          agent = this._agent;
+        }
+        if (agent) {
+          return agent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        let maxSockets = 100;
+        if (this.requestOptions) {
+          maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
+        }
+        if (proxyUrl && proxyUrl.hostname) {
+          const agentOptions = {
+            maxSockets,
+            keepAlive: this._keepAlive,
+            proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && {
+              proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+            }), { host: proxyUrl.hostname, port: proxyUrl.port })
+          };
+          let tunnelAgent;
+          const overHttps = proxyUrl.protocol === "https:";
+          if (usingSsl) {
+            tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+          } else {
+            tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
           }
-          case "\\":
-            clearStateChar();
-            escaping = true;
-            continue;
-          // the various stateChar values
-          // for the "extglob" stuff.
-          case "?":
-          case "*":
-          case "+":
-          case "@":
-          case "!":
-            this.debug("%s	%s %s %j <-- stateChar", pattern, i, re, c);
-            if (inClass) {
-              this.debug("  in class");
-              if (c === "!" && i === classStart + 1) c = "^";
-              re += c;
-              continue;
-            }
-            self2.debug("call clearStateChar %j", stateChar);
-            clearStateChar();
-            stateChar = c;
-            if (options.noext) clearStateChar();
-            continue;
-          case "(":
-            if (inClass) {
-              re += "(";
-              continue;
-            }
-            if (!stateChar) {
-              re += "\\(";
-              continue;
-            }
-            patternListStack.push({
-              type: stateChar,
-              start: i - 1,
-              reStart: re.length,
-              open: plTypes[stateChar].open,
-              close: plTypes[stateChar].close
-            });
-            re += stateChar === "!" ? "(?:(?!(?:" : "(?:";
-            this.debug("plType %j %j", stateChar, re);
-            stateChar = false;
-            continue;
-          case ")":
-            if (inClass || !patternListStack.length) {
-              re += "\\)";
-              continue;
-            }
-            clearStateChar();
-            hasMagic = true;
-            var pl = patternListStack.pop();
-            re += pl.close;
-            if (pl.type === "!") {
-              negativeLists.push(pl);
-            }
-            pl.reEnd = re.length;
-            continue;
-          case "|":
-            if (inClass || !patternListStack.length || escaping) {
-              re += "\\|";
-              escaping = false;
-              continue;
-            }
-            clearStateChar();
-            re += "|";
-            continue;
-          // these are mostly the same in regexp and glob
-          case "[":
-            clearStateChar();
-            if (inClass) {
-              re += "\\" + c;
-              continue;
+          agent = tunnelAgent(agentOptions);
+          this._proxyAgent = agent;
+        }
+        if (!agent) {
+          const options = { keepAlive: this._keepAlive, maxSockets };
+          agent = usingSsl ? new https2.Agent(options) : new http.Agent(options);
+          this._agent = agent;
+        }
+        if (usingSsl && this._ignoreSslError) {
+          agent.options = Object.assign(agent.options || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return agent;
+      }
+      _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+        let proxyAgent;
+        if (this._keepAlive) {
+          proxyAgent = this._proxyAgentDispatcher;
+        }
+        if (proxyAgent) {
+          return proxyAgent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && {
+          token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}`
+        }));
+        this._proxyAgentDispatcher = proxyAgent;
+        if (usingSsl && this._ignoreSslError) {
+          proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return proxyAgent;
+      }
+      _performExponentialBackoff(retryNumber) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+          const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+          return new Promise((resolve2) => setTimeout(() => resolve2(), ms));
+        });
+      }
+      _processResponse(res, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () {
+            const statusCode = res.message.statusCode || 0;
+            const response = {
+              statusCode,
+              result: null,
+              headers: {}
+            };
+            if (statusCode === HttpCodes.NotFound) {
+              resolve2(response);
             }
-            inClass = true;
-            classStart = i;
-            reClassStart = re.length;
-            re += c;
-            continue;
-          case "]":
-            if (i === classStart + 1 || !inClass) {
-              re += "\\" + c;
-              escaping = false;
-              continue;
+            function dateTimeDeserializer(key, value) {
+              if (typeof value === "string") {
+                const a = new Date(value);
+                if (!isNaN(a.valueOf())) {
+                  return a;
+                }
+              }
+              return value;
             }
-            var cs = pattern.substring(classStart + 1, i);
+            let obj;
+            let contents;
             try {
-              RegExp("[" + cs + "]");
-            } catch (er) {
-              var sp = this.parse(cs, SUBPARSE);
-              re = re.substr(0, reClassStart) + "\\[" + sp[0] + "\\]";
-              hasMagic = hasMagic || sp[1];
-              inClass = false;
-              continue;
+              contents = yield res.readBody();
+              if (contents && contents.length > 0) {
+                if (options && options.deserializeDates) {
+                  obj = JSON.parse(contents, dateTimeDeserializer);
+                } else {
+                  obj = JSON.parse(contents);
+                }
+                response.result = obj;
+              }
+              response.headers = res.message.headers;
+            } catch (err) {
             }
-            hasMagic = true;
-            inClass = false;
-            re += c;
-            continue;
-          default:
-            clearStateChar();
-            if (escaping) {
-              escaping = false;
-            } else if (reSpecials[c] && !(c === "^" && inClass)) {
-              re += "\\";
+            if (statusCode > 299) {
+              let msg;
+              if (obj && obj.message) {
+                msg = obj.message;
+              } else if (contents && contents.length > 0) {
+                msg = contents;
+              } else {
+                msg = `Failed request: (${statusCode})`;
+              }
+              const err = new HttpClientError(msg, statusCode);
+              err.result = response.result;
+              reject(err);
+            } else {
+              resolve2(response);
             }
-            re += c;
-        }
-      }
-      if (inClass) {
-        cs = pattern.substr(classStart + 1);
-        sp = this.parse(cs, SUBPARSE);
-        re = re.substr(0, reClassStart) + "\\[" + sp[0];
-        hasMagic = hasMagic || sp[1];
-      }
-      for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
-        var tail = re.slice(pl.reStart + pl.open.length);
-        this.debug("setting tail", re, pl);
-        tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function(_2, $1, $2) {
-          if (!$2) {
-            $2 = "\\";
-          }
-          return $1 + $1 + $2 + "|";
+          }));
         });
-        this.debug("tail=%j\n   %s", tail, tail, pl, re);
-        var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
-        hasMagic = true;
-        re = re.slice(0, pl.reStart) + t + "\\(" + tail;
-      }
-      clearStateChar();
-      if (escaping) {
-        re += "\\\\";
       }
-      var addPatternStart = false;
-      switch (re.charAt(0)) {
-        case "[":
-        case ".":
-        case "(":
-          addPatternStart = true;
+    };
+    exports2.HttpClient = HttpClient2;
+    var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
+  }
+});
+
+// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js
+var require_auth4 = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      for (var n = negativeLists.length - 1; n > -1; n--) {
-        var nl = negativeLists[n];
-        var nlBefore = re.slice(0, nl.reStart);
-        var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
-        var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
-        var nlAfter = re.slice(nl.reEnd);
-        nlLast += nlAfter;
-        var openParensBefore = nlBefore.split("(").length - 1;
-        var cleanAfter = nlAfter;
-        for (i = 0; i < openParensBefore; i++) {
-          cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        nlAfter = cleanAfter;
-        var dollar = "";
-        if (nlAfter === "" && isSub !== SUBPARSE) {
-          dollar = "$";
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
-        re = newRe;
-      }
-      if (re !== "" && hasMagic) {
-        re = "(?=.)" + re;
-      }
-      if (addPatternStart) {
-        re = patternStart + re;
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0;
+    var BasicCredentialHandler = class {
+      constructor(username, password) {
+        this.username = username;
+        this.password = password;
       }
-      if (isSub === SUBPARSE) {
-        return [re, hasMagic];
+      prepareRequest(options) {
+        if (!options.headers) {
+          throw Error("The request has no headers");
+        }
+        options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`;
       }
-      if (!hasMagic) {
-        return globUnescape(pattern);
+      // This handler cannot handle 401
+      canHandleAuthentication() {
+        return false;
       }
-      var flags = options.nocase ? "i" : "";
-      try {
-        var regExp = new RegExp("^" + re + "$", flags);
-      } catch (er) {
-        return new RegExp("$.");
+      handleAuthentication() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          throw new Error("not implemented");
+        });
       }
-      regExp._glob = pattern;
-      regExp._src = re;
-      return regExp;
-    }
-    minimatch.makeRe = function(pattern, options) {
-      return new Minimatch(pattern, options || {}).makeRe();
     };
-    Minimatch.prototype.makeRe = makeRe;
-    function makeRe() {
-      if (this.regexp || this.regexp === false) return this.regexp;
-      var set2 = this.set;
-      if (!set2.length) {
-        this.regexp = false;
-        return this.regexp;
+    exports2.BasicCredentialHandler = BasicCredentialHandler;
+    var BearerCredentialHandler = class {
+      constructor(token) {
+        this.token = token;
       }
-      var options = this.options;
-      var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
-      var flags = options.nocase ? "i" : "";
-      var re = set2.map(function(pattern) {
-        return pattern.map(function(p) {
-          return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
-        }).join("\\/");
-      }).join("|");
-      re = "^(?:" + re + ")$";
-      if (this.negate) re = "^(?!" + re + ").*$";
-      try {
-        this.regexp = new RegExp(re, flags);
-      } catch (ex) {
-        this.regexp = false;
+      // currently implements pre-authorization
+      // TODO: support preAuth = false where it hooks on 401
+      prepareRequest(options) {
+        if (!options.headers) {
+          throw Error("The request has no headers");
+        }
+        options.headers["Authorization"] = `Bearer ${this.token}`;
       }
-      return this.regexp;
-    }
-    minimatch.match = function(list, pattern, options) {
-      options = options || {};
-      var mm = new Minimatch(pattern, options);
-      list = list.filter(function(f) {
-        return mm.match(f);
-      });
-      if (mm.options.nonull && !list.length) {
-        list.push(pattern);
+      // This handler cannot handle 401
+      canHandleAuthentication() {
+        return false;
       }
-      return list;
-    };
-    Minimatch.prototype.match = function match(f, partial) {
-      if (typeof partial === "undefined") partial = this.partial;
-      this.debug("match", f, this.pattern);
-      if (this.comment) return false;
-      if (this.empty) return f === "";
-      if (f === "/" && partial) return true;
-      var options = this.options;
-      if (path2.sep !== "/") {
-        f = f.split(path2.sep).join("/");
+      handleAuthentication() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          throw new Error("not implemented");
+        });
       }
-      f = f.split(slashSplit);
-      this.debug(this.pattern, "split", f);
-      var set2 = this.set;
-      this.debug(this.pattern, "set", set2);
-      var filename;
-      var i;
-      for (i = f.length - 1; i >= 0; i--) {
-        filename = f[i];
-        if (filename) break;
+    };
+    exports2.BearerCredentialHandler = BearerCredentialHandler;
+    var PersonalAccessTokenCredentialHandler = class {
+      constructor(token) {
+        this.token = token;
       }
-      for (i = 0; i < set2.length; i++) {
-        var pattern = set2[i];
-        var file = f;
-        if (options.matchBase && pattern.length === 1) {
-          file = [filename];
-        }
-        var hit = this.matchOne(file, pattern, partial);
-        if (hit) {
-          if (options.flipNegate) return true;
-          return !this.negate;
+      // currently implements pre-authorization
+      // TODO: support preAuth = false where it hooks on 401
+      prepareRequest(options) {
+        if (!options.headers) {
+          throw Error("The request has no headers");
         }
+        options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`;
       }
-      if (options.flipNegate) return false;
-      return this.negate;
-    };
-    Minimatch.prototype.matchOne = function(file, pattern, partial) {
-      var options = this.options;
-      this.debug(
-        "matchOne",
-        { "this": this, file, pattern }
-      );
-      this.debug("matchOne", file.length, pattern.length);
-      for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
-        this.debug("matchOne loop");
-        var p = pattern[pi];
-        var f = file[fi];
-        this.debug(pattern, p, f);
-        if (p === false) return false;
-        if (p === GLOBSTAR) {
-          this.debug("GLOBSTAR", [pattern, p, f]);
-          var fr = fi;
-          var pr = pi + 1;
-          if (pr === pl) {
-            this.debug("** at the end");
-            for (; fi < fl; fi++) {
-              if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
-            }
-            return true;
-          }
-          while (fr < fl) {
-            var swallowee = file[fr];
-            this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
-            if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
-              this.debug("globstar found match!", fr, fl, swallowee);
-              return true;
-            } else {
-              if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
-                this.debug("dot detected!", file, fr, pattern, pr);
-                break;
-              }
-              this.debug("globstar swallow a segment, and continue");
-              fr++;
-            }
-          }
-          if (partial) {
-            this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
-            if (fr === fl) return true;
-          }
-          return false;
-        }
-        var hit;
-        if (typeof p === "string") {
-          hit = f === p;
-          this.debug("string match", p, f, hit);
-        } else {
-          hit = f.match(p);
-          this.debug("pattern match", p, f, hit);
-        }
-        if (!hit) return false;
+      // This handler cannot handle 401
+      canHandleAuthentication() {
+        return false;
       }
-      if (fi === fl && pi === pl) {
-        return true;
-      } else if (fi === fl) {
-        return partial;
-      } else if (pi === pl) {
-        return fi === fl - 1 && file[fi] === "";
+      handleAuthentication() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          throw new Error("not implemented");
+        });
       }
-      throw new Error("wtf?");
     };
-    function globUnescape(s) {
-      return s.replace(/\\(.)/g, "$1");
-    }
-    function regExpEscape(s) {
-      return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
-    }
+    exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
   }
 });
 
-// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path.js
-var require_internal_path = __commonJS({
-  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/shared/errors.js
+var require_errors4 = __commonJS({
+  "node_modules/@actions/cache/lib/internal/shared/errors.js"(exports2) {
     "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      Object.defineProperty(o, k2, { enumerable: true, get: function() {
-        return m[k];
-      } });
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.UsageError = exports2.NetworkError = exports2.GHESNotSupportedError = exports2.CacheNotFoundError = exports2.InvalidResponseError = exports2.FilesNotFoundError = void 0;
+    var FilesNotFoundError = class extends Error {
+      constructor(files = []) {
+        let message = "No files were found to upload";
+        if (files.length > 0) {
+          message += `: ${files.join(", ")}`;
+        }
+        super(message);
+        this.files = files;
+        this.name = "FilesNotFoundError";
       }
-      __setModuleDefault4(result, mod);
-      return result;
     };
-    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
-      return mod && mod.__esModule ? mod : { "default": mod };
+    exports2.FilesNotFoundError = FilesNotFoundError;
+    var InvalidResponseError = class extends Error {
+      constructor(message) {
+        super(message);
+        this.name = "InvalidResponseError";
+      }
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Path = void 0;
-    var path2 = __importStar4(require("path"));
-    var pathHelper = __importStar4(require_internal_path_helper());
-    var assert_1 = __importDefault4(require("assert"));
-    var IS_WINDOWS = process.platform === "win32";
-    var Path = class {
-      /**
-       * Constructs a Path
-       * @param itemPath Path or array of segments
-       */
-      constructor(itemPath) {
-        this.segments = [];
-        if (typeof itemPath === "string") {
-          assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`);
-          itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);
-          if (!pathHelper.hasRoot(itemPath)) {
-            this.segments = itemPath.split(path2.sep);
-          } else {
-            let remaining = itemPath;
-            let dir = pathHelper.dirname(remaining);
-            while (dir !== remaining) {
-              const basename = path2.basename(remaining);
-              this.segments.unshift(basename);
-              remaining = dir;
-              dir = pathHelper.dirname(remaining);
-            }
-            this.segments.unshift(remaining);
-          }
-        } else {
-          assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`);
-          for (let i = 0; i < itemPath.length; i++) {
-            let segment = itemPath[i];
-            assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`);
-            segment = pathHelper.normalizeSeparators(itemPath[i]);
-            if (i === 0 && pathHelper.hasRoot(segment)) {
-              segment = pathHelper.safeTrimTrailingSeparator(segment);
-              assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`);
-              this.segments.push(segment);
-            } else {
-              assert_1.default(!segment.includes(path2.sep), `Parameter 'itemPath' contains unexpected path separators`);
-              this.segments.push(segment);
-            }
-          }
-        }
+    exports2.InvalidResponseError = InvalidResponseError;
+    var CacheNotFoundError = class extends Error {
+      constructor(message = "Cache not found") {
+        super(message);
+        this.name = "CacheNotFoundError";
       }
-      /**
-       * Converts the path to it's string representation
-       */
-      toString() {
-        let result = this.segments[0];
-        let skipSlash = result.endsWith(path2.sep) || IS_WINDOWS && /^[A-Z]:$/i.test(result);
-        for (let i = 1; i < this.segments.length; i++) {
-          if (skipSlash) {
-            skipSlash = false;
-          } else {
-            result += path2.sep;
-          }
-          result += this.segments[i];
-        }
-        return result;
+    };
+    exports2.CacheNotFoundError = CacheNotFoundError;
+    var GHESNotSupportedError = class extends Error {
+      constructor(message = "@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.") {
+        super(message);
+        this.name = "GHESNotSupportedError";
       }
     };
-    exports2.Path = Path;
+    exports2.GHESNotSupportedError = GHESNotSupportedError;
+    var NetworkError = class extends Error {
+      constructor(code) {
+        const message = `Unable to make request: ${code}
+If you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`;
+        super(message);
+        this.code = code;
+        this.name = "NetworkError";
+      }
+    };
+    exports2.NetworkError = NetworkError;
+    NetworkError.isNetworkErrorCode = (code) => {
+      if (!code)
+        return false;
+      return [
+        "ECONNRESET",
+        "ENOTFOUND",
+        "ETIMEDOUT",
+        "ECONNREFUSED",
+        "EHOSTUNREACH"
+      ].includes(code);
+    };
+    var UsageError = class extends Error {
+      constructor() {
+        const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours.
+More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`;
+        super(message);
+        this.name = "UsageError";
+      }
+    };
+    exports2.UsageError = UsageError;
+    UsageError.isUsageErrorMessage = (msg) => {
+      if (!msg)
+        return false;
+      return msg.includes("insufficient usage");
+    };
   }
 });
 
-// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern.js
-var require_internal_pattern = __commonJS({
-  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/uploadUtils.js
+var require_uploadUtils = __commonJS({
+  "node_modules/@actions/cache/lib/internal/uploadUtils.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
-      Object.defineProperty(o, k2, { enumerable: true, get: function() {
-        return m[k];
-      } });
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
     }) : (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
       o[k2] = m[k];
@@ -103338,210 +108484,168 @@ var require_internal_pattern = __commonJS({
       if (mod && mod.__esModule) return mod;
       var result = {};
       if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
       __setModuleDefault4(result, mod);
       return result;
     };
-    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
-      return mod && mod.__esModule ? mod : { "default": mod };
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Pattern = void 0;
-    var os = __importStar4(require("os"));
-    var path2 = __importStar4(require("path"));
-    var pathHelper = __importStar4(require_internal_path_helper());
-    var assert_1 = __importDefault4(require("assert"));
-    var minimatch_1 = require_minimatch2();
-    var internal_match_kind_1 = require_internal_match_kind();
-    var internal_path_1 = require_internal_path();
-    var IS_WINDOWS = process.platform === "win32";
-    var Pattern = class _Pattern {
-      constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) {
-        this.negate = false;
-        let pattern;
-        if (typeof patternOrNegate === "string") {
-          pattern = patternOrNegate.trim();
-        } else {
-          segments = segments || [];
-          assert_1.default(segments.length, `Parameter 'segments' must not empty`);
-          const root = _Pattern.getLiteral(segments[0]);
-          assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`);
-          pattern = new internal_path_1.Path(segments).toString().trim();
-          if (patternOrNegate) {
-            pattern = `!${pattern}`;
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
           }
         }
-        while (pattern.startsWith("!")) {
-          this.negate = !this.negate;
-          pattern = pattern.substr(1).trim();
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        pattern = _Pattern.fixupPattern(pattern, homedir);
-        this.segments = new internal_path_1.Path(pattern).segments;
-        this.trailingSeparator = pathHelper.normalizeSeparators(pattern).endsWith(path2.sep);
-        pattern = pathHelper.safeTrimTrailingSeparator(pattern);
-        let foundGlob = false;
-        const searchSegments = this.segments.map((x) => _Pattern.getLiteral(x)).filter((x) => !foundGlob && !(foundGlob = x === ""));
-        this.searchPath = new internal_path_1.Path(searchSegments).toString();
-        this.rootRegExp = new RegExp(_Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? "i" : "");
-        this.isImplicitPattern = isImplicitPattern;
-        const minimatchOptions = {
-          dot: true,
-          nobrace: true,
-          nocase: IS_WINDOWS,
-          nocomment: true,
-          noext: true,
-          nonegate: true
-        };
-        pattern = IS_WINDOWS ? pattern.replace(/\\/g, "/") : pattern;
-        this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions);
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.uploadCacheArchiveSDK = exports2.UploadProgress = void 0;
+    var core14 = __importStar4(require_core());
+    var storage_blob_1 = require_dist7();
+    var errors_1 = require_errors4();
+    var UploadProgress = class {
+      constructor(contentLength) {
+        this.contentLength = contentLength;
+        this.sentBytes = 0;
+        this.displayedComplete = false;
+        this.startTime = Date.now();
+      }
+      /**
+       * Sets the number of bytes sent
+       *
+       * @param sentBytes the number of bytes sent
+       */
+      setSentBytes(sentBytes) {
+        this.sentBytes = sentBytes;
       }
       /**
-       * Matches the pattern against the specified path
+       * Returns the total number of bytes transferred.
        */
-      match(itemPath) {
-        if (this.segments[this.segments.length - 1] === "**") {
-          itemPath = pathHelper.normalizeSeparators(itemPath);
-          if (!itemPath.endsWith(path2.sep) && this.isImplicitPattern === false) {
-            itemPath = `${itemPath}${path2.sep}`;
-          }
-        } else {
-          itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);
-        }
-        if (this.minimatch.match(itemPath)) {
-          return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All;
-        }
-        return internal_match_kind_1.MatchKind.None;
+      getTransferredBytes() {
+        return this.sentBytes;
       }
       /**
-       * Indicates whether the pattern may match descendants of the specified path
+       * Returns true if the upload is complete.
        */
-      partialMatch(itemPath) {
-        itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);
-        if (pathHelper.dirname(itemPath) === itemPath) {
-          return this.rootRegExp.test(itemPath);
-        }
-        return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true);
+      isDone() {
+        return this.getTransferredBytes() === this.contentLength;
       }
       /**
-       * Escapes glob patterns within a path
+       * Prints the current upload stats. Once the upload completes, this will print one
+       * last line and then stop.
        */
-      static globEscape(s) {
-        return (IS_WINDOWS ? s : s.replace(/\\/g, "\\\\")).replace(/(\[)(?=[^/]+\])/g, "[[]").replace(/\?/g, "[?]").replace(/\*/g, "[*]");
+      display() {
+        if (this.displayedComplete) {
+          return;
+        }
+        const transferredBytes = this.sentBytes;
+        const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1);
+        const elapsedTime = Date.now() - this.startTime;
+        const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1);
+        core14.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`);
+        if (this.isDone()) {
+          this.displayedComplete = true;
+        }
       }
       /**
-       * Normalizes slashes and ensures absolute root
+       * Returns a function used to handle TransferProgressEvents.
        */
-      static fixupPattern(pattern, homedir) {
-        assert_1.default(pattern, "pattern cannot be empty");
-        const literalSegments = new internal_path_1.Path(pattern).segments.map((x) => _Pattern.getLiteral(x));
-        assert_1.default(literalSegments.every((x, i) => (x !== "." || i === 0) && x !== ".."), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`);
-        assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`);
-        pattern = pathHelper.normalizeSeparators(pattern);
-        if (pattern === "." || pattern.startsWith(`.${path2.sep}`)) {
-          pattern = _Pattern.globEscape(process.cwd()) + pattern.substr(1);
-        } else if (pattern === "~" || pattern.startsWith(`~${path2.sep}`)) {
-          homedir = homedir || os.homedir();
-          assert_1.default(homedir, "Unable to determine HOME directory");
-          assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`);
-          pattern = _Pattern.globEscape(homedir) + pattern.substr(1);
-        } else if (IS_WINDOWS && (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) {
-          let root = pathHelper.ensureAbsoluteRoot("C:\\dummy-root", pattern.substr(0, 2));
-          if (pattern.length > 2 && !root.endsWith("\\")) {
-            root += "\\";
-          }
-          pattern = _Pattern.globEscape(root) + pattern.substr(2);
-        } else if (IS_WINDOWS && (pattern === "\\" || pattern.match(/^\\[^\\]/))) {
-          let root = pathHelper.ensureAbsoluteRoot("C:\\dummy-root", "\\");
-          if (!root.endsWith("\\")) {
-            root += "\\";
-          }
-          pattern = _Pattern.globEscape(root) + pattern.substr(1);
-        } else {
-          pattern = pathHelper.ensureAbsoluteRoot(_Pattern.globEscape(process.cwd()), pattern);
-        }
-        return pathHelper.normalizeSeparators(pattern);
+      onProgress() {
+        return (progress) => {
+          this.setSentBytes(progress.loadedBytes);
+        };
       }
       /**
-       * Attempts to unescape a pattern segment to create a literal path segment.
-       * Otherwise returns empty string.
+       * Starts the timer that displays the stats.
+       *
+       * @param delayInMs the delay between each write
        */
-      static getLiteral(segment) {
-        let literal = "";
-        for (let i = 0; i < segment.length; i++) {
-          const c = segment[i];
-          if (c === "\\" && !IS_WINDOWS && i + 1 < segment.length) {
-            literal += segment[++i];
-            continue;
-          } else if (c === "*" || c === "?") {
-            return "";
-          } else if (c === "[" && i + 1 < segment.length) {
-            let set2 = "";
-            let closed = -1;
-            for (let i2 = i + 1; i2 < segment.length; i2++) {
-              const c2 = segment[i2];
-              if (c2 === "\\" && !IS_WINDOWS && i2 + 1 < segment.length) {
-                set2 += segment[++i2];
-                continue;
-              } else if (c2 === "]") {
-                closed = i2;
-                break;
-              } else {
-                set2 += c2;
-              }
-            }
-            if (closed >= 0) {
-              if (set2.length > 1) {
-                return "";
-              }
-              if (set2) {
-                literal += set2;
-                i = closed;
-                continue;
-              }
-            }
+      startDisplayTimer(delayInMs = 1e3) {
+        const displayCallback = () => {
+          this.display();
+          if (!this.isDone()) {
+            this.timeoutHandle = setTimeout(displayCallback, delayInMs);
           }
-          literal += c;
-        }
-        return literal;
+        };
+        this.timeoutHandle = setTimeout(displayCallback, delayInMs);
       }
       /**
-       * Escapes regexp special characters
-       * https://javascript.info/regexp-escaping
+       * Stops the timer that displays the stats. As this typically indicates the upload
+       * is complete, this will display one last line, unless the last line has already
+       * been written.
        */
-      static regExpEscape(s) {
-        return s.replace(/[[\\^$.|?*+()]/g, "\\$&");
-      }
-    };
-    exports2.Pattern = Pattern;
-  }
-});
-
-// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-search-state.js
-var require_internal_search_state = __commonJS({
-  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-search-state.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.SearchState = void 0;
-    var SearchState = class {
-      constructor(path2, level) {
-        this.path = path2;
-        this.level = level;
+      stopDisplayTimer() {
+        if (this.timeoutHandle) {
+          clearTimeout(this.timeoutHandle);
+          this.timeoutHandle = void 0;
+        }
+        this.display();
       }
     };
-    exports2.SearchState = SearchState;
+    exports2.UploadProgress = UploadProgress;
+    function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) {
+      var _a;
+      return __awaiter4(this, void 0, void 0, function* () {
+        const blobClient = new storage_blob_1.BlobClient(signedUploadURL);
+        const blockBlobClient = blobClient.getBlockBlobClient();
+        const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0);
+        const uploadOptions = {
+          blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize,
+          concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency,
+          maxSingleShotSize: 128 * 1024 * 1024,
+          onProgress: uploadProgress.onProgress()
+        };
+        try {
+          uploadProgress.startDisplayTimer();
+          core14.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`);
+          const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions);
+          if (response._response.status >= 400) {
+            throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`);
+          }
+          return response;
+        } catch (error4) {
+          core14.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error4.message}`);
+          throw error4;
+        } finally {
+          uploadProgress.stopDisplayTimer();
+        }
+      });
+    }
+    exports2.uploadCacheArchiveSDK = uploadCacheArchiveSDK;
   }
 });
 
-// node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-globber.js
-var require_internal_globber = __commonJS({
-  "node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-globber.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/requestUtils.js
+var require_requestUtils2 = __commonJS({
+  "node_modules/@actions/cache/lib/internal/requestUtils.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
-      Object.defineProperty(o, k2, { enumerable: true, get: function() {
-        return m[k];
-      } });
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
     }) : (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
       o[k2] = m[k];
@@ -103555,7 +108659,7 @@ var require_internal_globber = __commonJS({
       if (mod && mod.__esModule) return mod;
       var result = {};
       if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
       __setModuleDefault4(result, mod);
       return result;
@@ -103587,219 +108691,147 @@ var require_internal_globber = __commonJS({
         step((generator = generator.apply(thisArg, _arguments || [])).next());
       });
     };
-    var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) {
-      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
-      var m = o[Symbol.asyncIterator], i;
-      return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
-        return this;
-      }, i);
-      function verb(n) {
-        i[n] = o[n] && function(v) {
-          return new Promise(function(resolve2, reject) {
-            v = o[n](v), settle(resolve2, reject, v.done, v.value);
-          });
-        };
-      }
-      function settle(resolve2, reject, d, v) {
-        Promise.resolve(v).then(function(v2) {
-          resolve2({ value: v2, done: d });
-        }, reject);
-      }
-    };
-    var __await4 = exports2 && exports2.__await || function(v) {
-      return this instanceof __await4 ? (this.v = v, this) : new __await4(v);
-    };
-    var __asyncGenerator4 = exports2 && exports2.__asyncGenerator || function(thisArg, _arguments, generator) {
-      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
-      var g = generator.apply(thisArg, _arguments || []), i, q = [];
-      return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
-        return this;
-      }, i;
-      function verb(n) {
-        if (g[n]) i[n] = function(v) {
-          return new Promise(function(a, b) {
-            q.push([n, v, a, b]) > 1 || resume(n, v);
-          });
-        };
-      }
-      function resume(n, v) {
-        try {
-          step(g[n](v));
-        } catch (e) {
-          settle(q[0][3], e);
-        }
-      }
-      function step(r) {
-        r.value instanceof __await4 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
-      }
-      function fulfill(value) {
-        resume("next", value);
-      }
-      function reject(value) {
-        resume("throw", value);
-      }
-      function settle(f, v) {
-        if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
-      }
-    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.DefaultGlobber = void 0;
+    exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0;
     var core14 = __importStar4(require_core());
-    var fs2 = __importStar4(require("fs"));
-    var globOptionsHelper = __importStar4(require_internal_glob_options_helper());
-    var path2 = __importStar4(require("path"));
-    var patternHelper = __importStar4(require_internal_pattern_helper());
-    var internal_match_kind_1 = require_internal_match_kind();
-    var internal_pattern_1 = require_internal_pattern();
-    var internal_search_state_1 = require_internal_search_state();
-    var IS_WINDOWS = process.platform === "win32";
-    var DefaultGlobber = class _DefaultGlobber {
-      constructor(options) {
-        this.patterns = [];
-        this.searchPaths = [];
-        this.options = globOptionsHelper.getOptions(options);
+    var http_client_1 = require_lib7();
+    var constants_1 = require_constants10();
+    function isSuccessStatusCode(statusCode) {
+      if (!statusCode) {
+        return false;
       }
-      getSearchPaths() {
-        return this.searchPaths.slice();
+      return statusCode >= 200 && statusCode < 300;
+    }
+    exports2.isSuccessStatusCode = isSuccessStatusCode;
+    function isServerErrorStatusCode(statusCode) {
+      if (!statusCode) {
+        return true;
       }
-      glob() {
-        var e_1, _a;
-        return __awaiter4(this, void 0, void 0, function* () {
-          const result = [];
-          try {
-            for (var _b = __asyncValues4(this.globGenerator()), _c; _c = yield _b.next(), !_c.done; ) {
-              const itemPath = _c.value;
-              result.push(itemPath);
-            }
-          } catch (e_1_1) {
-            e_1 = { error: e_1_1 };
-          } finally {
-            try {
-              if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
-            } finally {
-              if (e_1) throw e_1.error;
-            }
-          }
-          return result;
-        });
+      return statusCode >= 500;
+    }
+    exports2.isServerErrorStatusCode = isServerErrorStatusCode;
+    function isRetryableStatusCode(statusCode) {
+      if (!statusCode) {
+        return false;
       }
-      globGenerator() {
-        return __asyncGenerator4(this, arguments, function* globGenerator_1() {
-          const options = globOptionsHelper.getOptions(this.options);
-          const patterns = [];
-          for (const pattern of this.patterns) {
-            patterns.push(pattern);
-            if (options.implicitDescendants && (pattern.trailingSeparator || pattern.segments[pattern.segments.length - 1] !== "**")) {
-              patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat("**")));
+      const retryableStatusCodes = [
+        http_client_1.HttpCodes.BadGateway,
+        http_client_1.HttpCodes.ServiceUnavailable,
+        http_client_1.HttpCodes.GatewayTimeout
+      ];
+      return retryableStatusCodes.includes(statusCode);
+    }
+    exports2.isRetryableStatusCode = isRetryableStatusCode;
+    function sleep(milliseconds) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
+      });
+    }
+    function retry3(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = void 0) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        let errorMessage = "";
+        let attempt = 1;
+        while (attempt <= maxAttempts) {
+          let response = void 0;
+          let statusCode = void 0;
+          let isRetryable = false;
+          try {
+            response = yield method();
+          } catch (error4) {
+            if (onError) {
+              response = onError(error4);
             }
+            isRetryable = true;
+            errorMessage = error4.message;
           }
-          const stack = [];
-          for (const searchPath of patternHelper.getSearchPaths(patterns)) {
-            core14.debug(`Search path '${searchPath}'`);
-            try {
-              yield __await4(fs2.promises.lstat(searchPath));
-            } catch (err) {
-              if (err.code === "ENOENT") {
-                continue;
-              }
-              throw err;
+          if (response) {
+            statusCode = getStatusCode(response);
+            if (!isServerErrorStatusCode(statusCode)) {
+              return response;
             }
-            stack.unshift(new internal_search_state_1.SearchState(searchPath, 1));
           }
-          const traversalChain = [];
-          while (stack.length) {
-            const item = stack.pop();
-            const match = patternHelper.match(patterns, item.path);
-            const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path);
-            if (!match && !partialMatch) {
-              continue;
-            }
-            const stats = yield __await4(
-              _DefaultGlobber.stat(item, options, traversalChain)
-              // Broken symlink, or symlink cycle detected, or no longer exists
-            );
-            if (!stats) {
-              continue;
-            }
-            if (stats.isDirectory()) {
-              if (match & internal_match_kind_1.MatchKind.Directory) {
-                yield yield __await4(item.path);
-              } else if (!partialMatch) {
-                continue;
-              }
-              const childLevel = item.level + 1;
-              const childItems = (yield __await4(fs2.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path2.join(item.path, x), childLevel));
-              stack.push(...childItems.reverse());
-            } else if (match & internal_match_kind_1.MatchKind.File) {
-              yield yield __await4(item.path);
-            }
+          if (statusCode) {
+            isRetryable = isRetryableStatusCode(statusCode);
+            errorMessage = `Cache service responded with ${statusCode}`;
           }
-        });
-      }
-      /**
-       * Constructs a DefaultGlobber
-       */
-      static create(patterns, options) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const result = new _DefaultGlobber(options);
-          if (IS_WINDOWS) {
-            patterns = patterns.replace(/\r\n/g, "\n");
-            patterns = patterns.replace(/\r/g, "\n");
+          core14.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`);
+          if (!isRetryable) {
+            core14.debug(`${name} - Error is not retryable`);
+            break;
           }
-          const lines = patterns.split("\n").map((x) => x.trim());
-          for (const line of lines) {
-            if (!line || line.startsWith("#")) {
-              continue;
+          yield sleep(delay);
+          attempt++;
+        }
+        throw Error(`${name} failed: ${errorMessage}`);
+      });
+    }
+    exports2.retry = retry3;
+    function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        return yield retry3(
+          name,
+          method,
+          (response) => response.statusCode,
+          maxAttempts,
+          delay,
+          // If the error object contains the statusCode property, extract it and return
+          // an TypedResponse so it can be processed by the retry logic.
+          (error4) => {
+            if (error4 instanceof http_client_1.HttpClientError) {
+              return {
+                statusCode: error4.statusCode,
+                result: null,
+                headers: {},
+                error: error4
+              };
             } else {
-              result.patterns.push(new internal_pattern_1.Pattern(line));
-            }
-          }
-          result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns));
-          return result;
-        });
-      }
-      static stat(item, options, traversalChain) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          let stats;
-          if (options.followSymbolicLinks) {
-            try {
-              stats = yield fs2.promises.stat(item.path);
-            } catch (err) {
-              if (err.code === "ENOENT") {
-                if (options.omitBrokenSymbolicLinks) {
-                  core14.debug(`Broken symlink '${item.path}'`);
-                  return void 0;
-                }
-                throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`);
-              }
-              throw err;
-            }
-          } else {
-            stats = yield fs2.promises.lstat(item.path);
-          }
-          if (stats.isDirectory() && options.followSymbolicLinks) {
-            const realPath = yield fs2.promises.realpath(item.path);
-            while (traversalChain.length >= item.level) {
-              traversalChain.pop();
-            }
-            if (traversalChain.some((x) => x === realPath)) {
-              core14.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`);
               return void 0;
             }
-            traversalChain.push(realPath);
           }
-          return stats;
-        });
+        );
+      });
+    }
+    exports2.retryTypedResponse = retryTypedResponse;
+    function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        return yield retry3(name, method, (response) => response.message.statusCode, maxAttempts, delay);
+      });
+    }
+    exports2.retryHttpClientResponse = retryHttpClientResponse;
+  }
+});
+
+// node_modules/@actions/cache/lib/internal/downloadUtils.js
+var require_downloadUtils = __commonJS({
+  "node_modules/@actions/cache/lib/internal/downloadUtils.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
+      __setModuleDefault4(result, mod);
+      return result;
     };
-    exports2.DefaultGlobber = DefaultGlobber;
-  }
-});
-
-// node_modules/@actions/cache/node_modules/@actions/glob/lib/glob.js
-var require_glob2 = __commonJS({
-  "node_modules/@actions/cache/node_modules/@actions/glob/lib/glob.js"(exports2) {
-    "use strict";
     var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
       function adopt(value) {
         return value instanceof P ? value : new P(function(resolve2) {
@@ -103828,1551 +108860,1532 @@ var require_glob2 = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.create = void 0;
-    var internal_globber_1 = require_internal_globber();
-    function create3(patterns, options) {
+    exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0;
+    var core14 = __importStar4(require_core());
+    var http_client_1 = require_lib7();
+    var storage_blob_1 = require_dist7();
+    var buffer = __importStar4(require("buffer"));
+    var fs2 = __importStar4(require("fs"));
+    var stream = __importStar4(require("stream"));
+    var util = __importStar4(require("util"));
+    var utils = __importStar4(require_cacheUtils());
+    var constants_1 = require_constants10();
+    var requestUtils_1 = require_requestUtils2();
+    var abort_controller_1 = require_dist5();
+    function pipeResponseToStream(response, output) {
       return __awaiter4(this, void 0, void 0, function* () {
-        return yield internal_globber_1.DefaultGlobber.create(patterns, options);
+        const pipeline = util.promisify(stream.pipeline);
+        yield pipeline(response.message, output);
       });
     }
-    exports2.create = create3;
-  }
-});
-
-// node_modules/@actions/cache/node_modules/semver/semver.js
-var require_semver3 = __commonJS({
-  "node_modules/@actions/cache/node_modules/semver/semver.js"(exports2, module2) {
-    exports2 = module2.exports = SemVer;
-    var debug4;
-    if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
-      debug4 = function() {
-        var args = Array.prototype.slice.call(arguments, 0);
-        args.unshift("SEMVER");
-        console.log.apply(console, args);
-      };
-    } else {
-      debug4 = function() {
-      };
-    }
-    exports2.SEMVER_SPEC_VERSION = "2.0.0";
-    var MAX_LENGTH = 256;
-    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
-    9007199254740991;
-    var MAX_SAFE_COMPONENT_LENGTH = 16;
-    var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
-    var re = exports2.re = [];
-    var safeRe = exports2.safeRe = [];
-    var src = exports2.src = [];
-    var t = exports2.tokens = {};
-    var R = 0;
-    function tok(n) {
-      t[n] = R++;
-    }
-    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
-    var safeRegexReplacements = [
-      ["\\s", 1],
-      ["\\d", MAX_LENGTH],
-      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
-    ];
-    function makeSafeRe(value) {
-      for (var i2 = 0; i2 < safeRegexReplacements.length; i2++) {
-        var token = safeRegexReplacements[i2][0];
-        var max = safeRegexReplacements[i2][1];
-        value = value.split(token + "*").join(token + "{0," + max + "}").split(token + "+").join(token + "{1," + max + "}");
-      }
-      return value;
-    }
-    tok("NUMERICIDENTIFIER");
-    src[t.NUMERICIDENTIFIER] = "0|[1-9]\\d*";
-    tok("NUMERICIDENTIFIERLOOSE");
-    src[t.NUMERICIDENTIFIERLOOSE] = "\\d+";
-    tok("NONNUMERICIDENTIFIER");
-    src[t.NONNUMERICIDENTIFIER] = "\\d*[a-zA-Z-]" + LETTERDASHNUMBER + "*";
-    tok("MAINVERSION");
-    src[t.MAINVERSION] = "(" + src[t.NUMERICIDENTIFIER] + ")\\.(" + src[t.NUMERICIDENTIFIER] + ")\\.(" + src[t.NUMERICIDENTIFIER] + ")";
-    tok("MAINVERSIONLOOSE");
-    src[t.MAINVERSIONLOOSE] = "(" + src[t.NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[t.NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[t.NUMERICIDENTIFIERLOOSE] + ")";
-    tok("PRERELEASEIDENTIFIER");
-    src[t.PRERELEASEIDENTIFIER] = "(?:" + src[t.NUMERICIDENTIFIER] + "|" + src[t.NONNUMERICIDENTIFIER] + ")";
-    tok("PRERELEASEIDENTIFIERLOOSE");
-    src[t.PRERELEASEIDENTIFIERLOOSE] = "(?:" + src[t.NUMERICIDENTIFIERLOOSE] + "|" + src[t.NONNUMERICIDENTIFIER] + ")";
-    tok("PRERELEASE");
-    src[t.PRERELEASE] = "(?:-(" + src[t.PRERELEASEIDENTIFIER] + "(?:\\." + src[t.PRERELEASEIDENTIFIER] + ")*))";
-    tok("PRERELEASELOOSE");
-    src[t.PRERELEASELOOSE] = "(?:-?(" + src[t.PRERELEASEIDENTIFIERLOOSE] + "(?:\\." + src[t.PRERELEASEIDENTIFIERLOOSE] + ")*))";
-    tok("BUILDIDENTIFIER");
-    src[t.BUILDIDENTIFIER] = LETTERDASHNUMBER + "+";
-    tok("BUILD");
-    src[t.BUILD] = "(?:\\+(" + src[t.BUILDIDENTIFIER] + "(?:\\." + src[t.BUILDIDENTIFIER] + ")*))";
-    tok("FULL");
-    tok("FULLPLAIN");
-    src[t.FULLPLAIN] = "v?" + src[t.MAINVERSION] + src[t.PRERELEASE] + "?" + src[t.BUILD] + "?";
-    src[t.FULL] = "^" + src[t.FULLPLAIN] + "$";
-    tok("LOOSEPLAIN");
-    src[t.LOOSEPLAIN] = "[v=\\s]*" + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + "?" + src[t.BUILD] + "?";
-    tok("LOOSE");
-    src[t.LOOSE] = "^" + src[t.LOOSEPLAIN] + "$";
-    tok("GTLT");
-    src[t.GTLT] = "((?:<|>)?=?)";
-    tok("XRANGEIDENTIFIERLOOSE");
-    src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + "|x|X|\\*";
-    tok("XRANGEIDENTIFIER");
-    src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + "|x|X|\\*";
-    tok("XRANGEPLAIN");
-    src[t.XRANGEPLAIN] = "[v=\\s]*(" + src[t.XRANGEIDENTIFIER] + ")(?:\\.(" + src[t.XRANGEIDENTIFIER] + ")(?:\\.(" + src[t.XRANGEIDENTIFIER] + ")(?:" + src[t.PRERELEASE] + ")?" + src[t.BUILD] + "?)?)?";
-    tok("XRANGEPLAINLOOSE");
-    src[t.XRANGEPLAINLOOSE] = "[v=\\s]*(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:" + src[t.PRERELEASELOOSE] + ")?" + src[t.BUILD] + "?)?)?";
-    tok("XRANGE");
-    src[t.XRANGE] = "^" + src[t.GTLT] + "\\s*" + src[t.XRANGEPLAIN] + "$";
-    tok("XRANGELOOSE");
-    src[t.XRANGELOOSE] = "^" + src[t.GTLT] + "\\s*" + src[t.XRANGEPLAINLOOSE] + "$";
-    tok("COERCE");
-    src[t.COERCE] = "(^|[^\\d])(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "})(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:$|[^\\d])";
-    tok("COERCERTL");
-    re[t.COERCERTL] = new RegExp(src[t.COERCE], "g");
-    safeRe[t.COERCERTL] = new RegExp(makeSafeRe(src[t.COERCE]), "g");
-    tok("LONETILDE");
-    src[t.LONETILDE] = "(?:~>?)";
-    tok("TILDETRIM");
-    src[t.TILDETRIM] = "(\\s*)" + src[t.LONETILDE] + "\\s+";
-    re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], "g");
-    safeRe[t.TILDETRIM] = new RegExp(makeSafeRe(src[t.TILDETRIM]), "g");
-    var tildeTrimReplace = "$1~";
-    tok("TILDE");
-    src[t.TILDE] = "^" + src[t.LONETILDE] + src[t.XRANGEPLAIN] + "$";
-    tok("TILDELOOSE");
-    src[t.TILDELOOSE] = "^" + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + "$";
-    tok("LONECARET");
-    src[t.LONECARET] = "(?:\\^)";
-    tok("CARETTRIM");
-    src[t.CARETTRIM] = "(\\s*)" + src[t.LONECARET] + "\\s+";
-    re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], "g");
-    safeRe[t.CARETTRIM] = new RegExp(makeSafeRe(src[t.CARETTRIM]), "g");
-    var caretTrimReplace = "$1^";
-    tok("CARET");
-    src[t.CARET] = "^" + src[t.LONECARET] + src[t.XRANGEPLAIN] + "$";
-    tok("CARETLOOSE");
-    src[t.CARETLOOSE] = "^" + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + "$";
-    tok("COMPARATORLOOSE");
-    src[t.COMPARATORLOOSE] = "^" + src[t.GTLT] + "\\s*(" + src[t.LOOSEPLAIN] + ")$|^$";
-    tok("COMPARATOR");
-    src[t.COMPARATOR] = "^" + src[t.GTLT] + "\\s*(" + src[t.FULLPLAIN] + ")$|^$";
-    tok("COMPARATORTRIM");
-    src[t.COMPARATORTRIM] = "(\\s*)" + src[t.GTLT] + "\\s*(" + src[t.LOOSEPLAIN] + "|" + src[t.XRANGEPLAIN] + ")";
-    re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], "g");
-    safeRe[t.COMPARATORTRIM] = new RegExp(makeSafeRe(src[t.COMPARATORTRIM]), "g");
-    var comparatorTrimReplace = "$1$2$3";
-    tok("HYPHENRANGE");
-    src[t.HYPHENRANGE] = "^\\s*(" + src[t.XRANGEPLAIN] + ")\\s+-\\s+(" + src[t.XRANGEPLAIN] + ")\\s*$";
-    tok("HYPHENRANGELOOSE");
-    src[t.HYPHENRANGELOOSE] = "^\\s*(" + src[t.XRANGEPLAINLOOSE] + ")\\s+-\\s+(" + src[t.XRANGEPLAINLOOSE] + ")\\s*$";
-    tok("STAR");
-    src[t.STAR] = "(<|>)?=?\\s*\\*";
-    for (i = 0; i < R; i++) {
-      debug4(i, src[i]);
-      if (!re[i]) {
-        re[i] = new RegExp(src[i]);
-        safeRe[i] = new RegExp(makeSafeRe(src[i]));
-      }
-    }
-    var i;
-    exports2.parse = parse;
-    function parse(version, options) {
-      if (!options || typeof options !== "object") {
-        options = {
-          loose: !!options,
-          includePrerelease: false
-        };
-      }
-      if (version instanceof SemVer) {
-        return version;
-      }
-      if (typeof version !== "string") {
-        return null;
+    var DownloadProgress = class {
+      constructor(contentLength) {
+        this.contentLength = contentLength;
+        this.segmentIndex = 0;
+        this.segmentSize = 0;
+        this.segmentOffset = 0;
+        this.receivedBytes = 0;
+        this.displayedComplete = false;
+        this.startTime = Date.now();
       }
-      if (version.length > MAX_LENGTH) {
-        return null;
+      /**
+       * Progress to the next segment. Only call this method when the previous segment
+       * is complete.
+       *
+       * @param segmentSize the length of the next segment
+       */
+      nextSegment(segmentSize) {
+        this.segmentOffset = this.segmentOffset + this.segmentSize;
+        this.segmentIndex = this.segmentIndex + 1;
+        this.segmentSize = segmentSize;
+        this.receivedBytes = 0;
+        core14.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`);
       }
-      var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL];
-      if (!r.test(version)) {
-        return null;
+      /**
+       * Sets the number of bytes received for the current segment.
+       *
+       * @param receivedBytes the number of bytes received
+       */
+      setReceivedBytes(receivedBytes) {
+        this.receivedBytes = receivedBytes;
       }
-      try {
-        return new SemVer(version, options);
-      } catch (er) {
-        return null;
+      /**
+       * Returns the total number of bytes transferred.
+       */
+      getTransferredBytes() {
+        return this.segmentOffset + this.receivedBytes;
       }
-    }
-    exports2.valid = valid3;
-    function valid3(version, options) {
-      var v = parse(version, options);
-      return v ? v.version : null;
-    }
-    exports2.clean = clean3;
-    function clean3(version, options) {
-      var s = parse(version.trim().replace(/^[=v]+/, ""), options);
-      return s ? s.version : null;
-    }
-    exports2.SemVer = SemVer;
-    function SemVer(version, options) {
-      if (!options || typeof options !== "object") {
-        options = {
-          loose: !!options,
-          includePrerelease: false
-        };
+      /**
+       * Returns true if the download is complete.
+       */
+      isDone() {
+        return this.getTransferredBytes() === this.contentLength;
       }
-      if (version instanceof SemVer) {
-        if (version.loose === options.loose) {
-          return version;
-        } else {
-          version = version.version;
+      /**
+       * Prints the current download stats. Once the download completes, this will print one
+       * last line and then stop.
+       */
+      display() {
+        if (this.displayedComplete) {
+          return;
+        }
+        const transferredBytes = this.segmentOffset + this.receivedBytes;
+        const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1);
+        const elapsedTime = Date.now() - this.startTime;
+        const downloadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1);
+        core14.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`);
+        if (this.isDone()) {
+          this.displayedComplete = true;
         }
-      } else if (typeof version !== "string") {
-        throw new TypeError("Invalid Version: " + version);
-      }
-      if (version.length > MAX_LENGTH) {
-        throw new TypeError("version is longer than " + MAX_LENGTH + " characters");
-      }
-      if (!(this instanceof SemVer)) {
-        return new SemVer(version, options);
-      }
-      debug4("SemVer", version, options);
-      this.options = options;
-      this.loose = !!options.loose;
-      var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]);
-      if (!m) {
-        throw new TypeError("Invalid Version: " + version);
-      }
-      this.raw = version;
-      this.major = +m[1];
-      this.minor = +m[2];
-      this.patch = +m[3];
-      if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
-        throw new TypeError("Invalid major version");
-      }
-      if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
-        throw new TypeError("Invalid minor version");
       }
-      if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
-        throw new TypeError("Invalid patch version");
+      /**
+       * Returns a function used to handle TransferProgressEvents.
+       */
+      onProgress() {
+        return (progress) => {
+          this.setReceivedBytes(progress.loadedBytes);
+        };
       }
-      if (!m[4]) {
-        this.prerelease = [];
-      } else {
-        this.prerelease = m[4].split(".").map(function(id) {
-          if (/^[0-9]+$/.test(id)) {
-            var num = +id;
-            if (num >= 0 && num < MAX_SAFE_INTEGER) {
-              return num;
-            }
+      /**
+       * Starts the timer that displays the stats.
+       *
+       * @param delayInMs the delay between each write
+       */
+      startDisplayTimer(delayInMs = 1e3) {
+        const displayCallback = () => {
+          this.display();
+          if (!this.isDone()) {
+            this.timeoutHandle = setTimeout(displayCallback, delayInMs);
           }
-          return id;
-        });
-      }
-      this.build = m[5] ? m[5].split(".") : [];
-      this.format();
-    }
-    SemVer.prototype.format = function() {
-      this.version = this.major + "." + this.minor + "." + this.patch;
-      if (this.prerelease.length) {
-        this.version += "-" + this.prerelease.join(".");
-      }
-      return this.version;
-    };
-    SemVer.prototype.toString = function() {
-      return this.version;
-    };
-    SemVer.prototype.compare = function(other) {
-      debug4("SemVer.compare", this.version, this.options, other);
-      if (!(other instanceof SemVer)) {
-        other = new SemVer(other, this.options);
-      }
-      return this.compareMain(other) || this.comparePre(other);
-    };
-    SemVer.prototype.compareMain = function(other) {
-      if (!(other instanceof SemVer)) {
-        other = new SemVer(other, this.options);
-      }
-      return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
-    };
-    SemVer.prototype.comparePre = function(other) {
-      if (!(other instanceof SemVer)) {
-        other = new SemVer(other, this.options);
-      }
-      if (this.prerelease.length && !other.prerelease.length) {
-        return -1;
-      } else if (!this.prerelease.length && other.prerelease.length) {
-        return 1;
-      } else if (!this.prerelease.length && !other.prerelease.length) {
-        return 0;
+        };
+        this.timeoutHandle = setTimeout(displayCallback, delayInMs);
       }
-      var i2 = 0;
-      do {
-        var a = this.prerelease[i2];
-        var b = other.prerelease[i2];
-        debug4("prerelease compare", i2, a, b);
-        if (a === void 0 && b === void 0) {
-          return 0;
-        } else if (b === void 0) {
-          return 1;
-        } else if (a === void 0) {
-          return -1;
-        } else if (a === b) {
-          continue;
-        } else {
-          return compareIdentifiers(a, b);
+      /**
+       * Stops the timer that displays the stats. As this typically indicates the download
+       * is complete, this will display one last line, unless the last line has already
+       * been written.
+       */
+      stopDisplayTimer() {
+        if (this.timeoutHandle) {
+          clearTimeout(this.timeoutHandle);
+          this.timeoutHandle = void 0;
         }
-      } while (++i2);
-    };
-    SemVer.prototype.compareBuild = function(other) {
-      if (!(other instanceof SemVer)) {
-        other = new SemVer(other, this.options);
+        this.display();
       }
-      var i2 = 0;
-      do {
-        var a = this.build[i2];
-        var b = other.build[i2];
-        debug4("prerelease compare", i2, a, b);
-        if (a === void 0 && b === void 0) {
-          return 0;
-        } else if (b === void 0) {
-          return 1;
-        } else if (a === void 0) {
-          return -1;
-        } else if (a === b) {
-          continue;
+    };
+    exports2.DownloadProgress = DownloadProgress;
+    function downloadCacheHttpClient(archiveLocation, archivePath) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const writeStream = fs2.createWriteStream(archivePath);
+        const httpClient = new http_client_1.HttpClient("actions/cache");
+        const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter4(this, void 0, void 0, function* () {
+          return httpClient.get(archiveLocation);
+        }));
+        downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => {
+          downloadResponse.message.destroy();
+          core14.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`);
+        });
+        yield pipeResponseToStream(downloadResponse, writeStream);
+        const contentLengthHeader = downloadResponse.message.headers["content-length"];
+        if (contentLengthHeader) {
+          const expectedLength = parseInt(contentLengthHeader);
+          const actualLength = utils.getArchiveFileSizeInBytes(archivePath);
+          if (actualLength !== expectedLength) {
+            throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`);
+          }
         } else {
-          return compareIdentifiers(a, b);
+          core14.debug("Unable to validate download, no Content-Length header");
         }
-      } while (++i2);
-    };
-    SemVer.prototype.inc = function(release, identifier) {
-      switch (release) {
-        case "premajor":
-          this.prerelease.length = 0;
-          this.patch = 0;
-          this.minor = 0;
-          this.major++;
-          this.inc("pre", identifier);
-          break;
-        case "preminor":
-          this.prerelease.length = 0;
-          this.patch = 0;
-          this.minor++;
-          this.inc("pre", identifier);
-          break;
-        case "prepatch":
-          this.prerelease.length = 0;
-          this.inc("patch", identifier);
-          this.inc("pre", identifier);
-          break;
-        // If the input is a non-prerelease version, this acts the same as
-        // prepatch.
-        case "prerelease":
-          if (this.prerelease.length === 0) {
-            this.inc("patch", identifier);
+      });
+    }
+    exports2.downloadCacheHttpClient = downloadCacheHttpClient;
+    function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) {
+      var _a;
+      return __awaiter4(this, void 0, void 0, function* () {
+        const archiveDescriptor = yield fs2.promises.open(archivePath, "w");
+        const httpClient = new http_client_1.HttpClient("actions/cache", void 0, {
+          socketTimeout: options.timeoutInMs,
+          keepAlive: true
+        });
+        try {
+          const res = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCacheMetadata", () => __awaiter4(this, void 0, void 0, function* () {
+            return yield httpClient.request("HEAD", archiveLocation, null, {});
+          }));
+          const lengthHeader = res.message.headers["content-length"];
+          if (lengthHeader === void 0 || lengthHeader === null) {
+            throw new Error("Content-Length not found on blob response");
           }
-          this.inc("pre", identifier);
-          break;
-        case "major":
-          if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
-            this.major++;
+          const length = parseInt(lengthHeader);
+          if (Number.isNaN(length)) {
+            throw new Error(`Could not interpret Content-Length: ${length}`);
           }
-          this.minor = 0;
-          this.patch = 0;
-          this.prerelease = [];
-          break;
-        case "minor":
-          if (this.patch !== 0 || this.prerelease.length === 0) {
-            this.minor++;
+          const downloads = [];
+          const blockSize = 4 * 1024 * 1024;
+          for (let offset = 0; offset < length; offset += blockSize) {
+            const count = Math.min(blockSize, length - offset);
+            downloads.push({
+              offset,
+              promiseGetter: () => __awaiter4(this, void 0, void 0, function* () {
+                return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count);
+              })
+            });
+          }
+          downloads.reverse();
+          let actives = 0;
+          let bytesDownloaded = 0;
+          const progress = new DownloadProgress(length);
+          progress.startDisplayTimer();
+          const progressFn = progress.onProgress();
+          const activeDownloads = [];
+          let nextDownload;
+          const waitAndWrite = () => __awaiter4(this, void 0, void 0, function* () {
+            const segment = yield Promise.race(Object.values(activeDownloads));
+            yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset);
+            actives--;
+            delete activeDownloads[segment.offset];
+            bytesDownloaded += segment.count;
+            progressFn({ loadedBytes: bytesDownloaded });
+          });
+          while (nextDownload = downloads.pop()) {
+            activeDownloads[nextDownload.offset] = nextDownload.promiseGetter();
+            actives++;
+            if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) {
+              yield waitAndWrite();
+            }
           }
-          this.patch = 0;
-          this.prerelease = [];
-          break;
-        case "patch":
-          if (this.prerelease.length === 0) {
-            this.patch++;
+          while (actives > 0) {
+            yield waitAndWrite();
           }
-          this.prerelease = [];
-          break;
-        // This probably shouldn't be used publicly.
-        // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
-        case "pre":
-          if (this.prerelease.length === 0) {
-            this.prerelease = [0];
-          } else {
-            var i2 = this.prerelease.length;
-            while (--i2 >= 0) {
-              if (typeof this.prerelease[i2] === "number") {
-                this.prerelease[i2]++;
-                i2 = -2;
-              }
+        } finally {
+          httpClient.dispose();
+          yield archiveDescriptor.close();
+        }
+      });
+    }
+    exports2.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent;
+    function downloadSegmentRetry(httpClient, archiveLocation, offset, count) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const retries = 5;
+        let failures = 0;
+        while (true) {
+          try {
+            const timeout = 3e4;
+            const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count));
+            if (typeof result === "string") {
+              throw new Error("downloadSegmentRetry failed due to timeout");
             }
-            if (i2 === -1) {
-              this.prerelease.push(0);
+            return result;
+          } catch (err) {
+            if (failures >= retries) {
+              throw err;
             }
+            failures++;
           }
-          if (identifier) {
-            if (this.prerelease[0] === identifier) {
-              if (isNaN(this.prerelease[1])) {
-                this.prerelease = [identifier, 0];
+        }
+      });
+    }
+    function downloadSegment(httpClient, archiveLocation, offset, count) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const partRes = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCachePart", () => __awaiter4(this, void 0, void 0, function* () {
+          return yield httpClient.get(archiveLocation, {
+            Range: `bytes=${offset}-${offset + count - 1}`
+          });
+        }));
+        if (!partRes.readBodyBuffer) {
+          throw new Error("Expected HttpClientResponse to implement readBodyBuffer");
+        }
+        return {
+          offset,
+          count,
+          buffer: yield partRes.readBodyBuffer()
+        };
+      });
+    }
+    function downloadCacheStorageSDK(archiveLocation, archivePath, options) {
+      var _a;
+      return __awaiter4(this, void 0, void 0, function* () {
+        const client = new storage_blob_1.BlockBlobClient(archiveLocation, void 0, {
+          retryOptions: {
+            // Override the timeout used when downloading each 4 MB chunk
+            // The default is 2 min / MB, which is way too slow
+            tryTimeoutInMs: options.timeoutInMs
+          }
+        });
+        const properties = yield client.getProperties();
+        const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1;
+        if (contentLength < 0) {
+          core14.debug("Unable to determine content length, downloading file with http-client...");
+          yield downloadCacheHttpClient(archiveLocation, archivePath);
+        } else {
+          const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH);
+          const downloadProgress = new DownloadProgress(contentLength);
+          const fd = fs2.openSync(archivePath, "w");
+          try {
+            downloadProgress.startDisplayTimer();
+            const controller = new abort_controller_1.AbortController();
+            const abortSignal = controller.signal;
+            while (!downloadProgress.isDone()) {
+              const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize;
+              const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart);
+              downloadProgress.nextSegment(segmentSize);
+              const result = yield promiseWithTimeout(options.segmentTimeoutInMs || 36e5, client.downloadToBuffer(segmentStart, segmentSize, {
+                abortSignal,
+                concurrency: options.downloadConcurrency,
+                onProgress: downloadProgress.onProgress()
+              }));
+              if (result === "timeout") {
+                controller.abort();
+                throw new Error("Aborting cache download as the download time exceeded the timeout.");
+              } else if (Buffer.isBuffer(result)) {
+                fs2.writeFileSync(fd, result);
               }
-            } else {
-              this.prerelease = [identifier, 0];
             }
+          } finally {
+            downloadProgress.stopDisplayTimer();
+            fs2.closeSync(fd);
           }
-          break;
-        default:
-          throw new Error("invalid increment argument: " + release);
+        }
+      });
+    }
+    exports2.downloadCacheStorageSDK = downloadCacheStorageSDK;
+    var promiseWithTimeout = (timeoutMs, promise) => __awaiter4(void 0, void 0, void 0, function* () {
+      let timeoutHandle;
+      const timeoutPromise = new Promise((resolve2) => {
+        timeoutHandle = setTimeout(() => resolve2("timeout"), timeoutMs);
+      });
+      return Promise.race([promise, timeoutPromise]).then((result) => {
+        clearTimeout(timeoutHandle);
+        return result;
+      });
+    });
+  }
+});
+
+// node_modules/@actions/cache/lib/options.js
+var require_options = __commonJS({
+  "node_modules/@actions/cache/lib/options.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      this.format();
-      this.raw = this.version;
-      return this;
-    };
-    exports2.inc = inc;
-    function inc(version, release, loose, identifier) {
-      if (typeof loose === "string") {
-        identifier = loose;
-        loose = void 0;
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-      try {
-        return new SemVer(version, loose).inc(release, identifier).version;
-      } catch (er) {
-        return null;
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getDownloadOptions = exports2.getUploadOptions = void 0;
+    var core14 = __importStar4(require_core());
+    function getUploadOptions(copy) {
+      const result = {
+        useAzureSdk: false,
+        uploadConcurrency: 4,
+        uploadChunkSize: 32 * 1024 * 1024
+      };
+      if (copy) {
+        if (typeof copy.useAzureSdk === "boolean") {
+          result.useAzureSdk = copy.useAzureSdk;
+        }
+        if (typeof copy.uploadConcurrency === "number") {
+          result.uploadConcurrency = copy.uploadConcurrency;
+        }
+        if (typeof copy.uploadChunkSize === "number") {
+          result.uploadChunkSize = copy.uploadChunkSize;
+        }
       }
+      result.uploadConcurrency = !isNaN(Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) ? Math.min(32, Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) : result.uploadConcurrency;
+      result.uploadChunkSize = !isNaN(Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"])) ? Math.min(128 * 1024 * 1024, Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"]) * 1024 * 1024) : result.uploadChunkSize;
+      core14.debug(`Use Azure SDK: ${result.useAzureSdk}`);
+      core14.debug(`Upload concurrency: ${result.uploadConcurrency}`);
+      core14.debug(`Upload chunk size: ${result.uploadChunkSize}`);
+      return result;
     }
-    exports2.diff = diff;
-    function diff(version1, version2) {
-      if (eq(version1, version2)) {
-        return null;
-      } else {
-        var v1 = parse(version1);
-        var v2 = parse(version2);
-        var prefix = "";
-        if (v1.prerelease.length || v2.prerelease.length) {
-          prefix = "pre";
-          var defaultResult = "prerelease";
+    exports2.getUploadOptions = getUploadOptions;
+    function getDownloadOptions(copy) {
+      const result = {
+        useAzureSdk: false,
+        concurrentBlobDownloads: true,
+        downloadConcurrency: 8,
+        timeoutInMs: 3e4,
+        segmentTimeoutInMs: 6e5,
+        lookupOnly: false
+      };
+      if (copy) {
+        if (typeof copy.useAzureSdk === "boolean") {
+          result.useAzureSdk = copy.useAzureSdk;
         }
-        for (var key in v1) {
-          if (key === "major" || key === "minor" || key === "patch") {
-            if (v1[key] !== v2[key]) {
-              return prefix + key;
-            }
-          }
+        if (typeof copy.concurrentBlobDownloads === "boolean") {
+          result.concurrentBlobDownloads = copy.concurrentBlobDownloads;
+        }
+        if (typeof copy.downloadConcurrency === "number") {
+          result.downloadConcurrency = copy.downloadConcurrency;
+        }
+        if (typeof copy.timeoutInMs === "number") {
+          result.timeoutInMs = copy.timeoutInMs;
+        }
+        if (typeof copy.segmentTimeoutInMs === "number") {
+          result.segmentTimeoutInMs = copy.segmentTimeoutInMs;
+        }
+        if (typeof copy.lookupOnly === "boolean") {
+          result.lookupOnly = copy.lookupOnly;
         }
-        return defaultResult;
       }
-    }
-    exports2.compareIdentifiers = compareIdentifiers;
-    var numeric = /^[0-9]+$/;
-    function compareIdentifiers(a, b) {
-      var anum = numeric.test(a);
-      var bnum = numeric.test(b);
-      if (anum && bnum) {
-        a = +a;
-        b = +b;
+      const segmentDownloadTimeoutMins = process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"];
+      if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) {
+        result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1e3;
       }
-      return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
-    }
-    exports2.rcompareIdentifiers = rcompareIdentifiers;
-    function rcompareIdentifiers(a, b) {
-      return compareIdentifiers(b, a);
-    }
-    exports2.major = major;
-    function major(a, loose) {
-      return new SemVer(a, loose).major;
-    }
-    exports2.minor = minor;
-    function minor(a, loose) {
-      return new SemVer(a, loose).minor;
-    }
-    exports2.patch = patch;
-    function patch(a, loose) {
-      return new SemVer(a, loose).patch;
-    }
-    exports2.compare = compare2;
-    function compare2(a, b, loose) {
-      return new SemVer(a, loose).compare(new SemVer(b, loose));
-    }
-    exports2.compareLoose = compareLoose;
-    function compareLoose(a, b) {
-      return compare2(a, b, true);
-    }
-    exports2.compareBuild = compareBuild;
-    function compareBuild(a, b, loose) {
-      var versionA = new SemVer(a, loose);
-      var versionB = new SemVer(b, loose);
-      return versionA.compare(versionB) || versionA.compareBuild(versionB);
-    }
-    exports2.rcompare = rcompare;
-    function rcompare(a, b, loose) {
-      return compare2(b, a, loose);
-    }
-    exports2.sort = sort;
-    function sort(list, loose) {
-      return list.sort(function(a, b) {
-        return exports2.compareBuild(a, b, loose);
-      });
-    }
-    exports2.rsort = rsort;
-    function rsort(list, loose) {
-      return list.sort(function(a, b) {
-        return exports2.compareBuild(b, a, loose);
-      });
-    }
-    exports2.gt = gt;
-    function gt(a, b, loose) {
-      return compare2(a, b, loose) > 0;
-    }
-    exports2.lt = lt;
-    function lt(a, b, loose) {
-      return compare2(a, b, loose) < 0;
-    }
-    exports2.eq = eq;
-    function eq(a, b, loose) {
-      return compare2(a, b, loose) === 0;
-    }
-    exports2.neq = neq;
-    function neq(a, b, loose) {
-      return compare2(a, b, loose) !== 0;
+      core14.debug(`Use Azure SDK: ${result.useAzureSdk}`);
+      core14.debug(`Download concurrency: ${result.downloadConcurrency}`);
+      core14.debug(`Request timeout (ms): ${result.timeoutInMs}`);
+      core14.debug(`Cache segment download timeout mins env var: ${process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]}`);
+      core14.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`);
+      core14.debug(`Lookup only: ${result.lookupOnly}`);
+      return result;
     }
-    exports2.gte = gte5;
-    function gte5(a, b, loose) {
-      return compare2(a, b, loose) >= 0;
+    exports2.getDownloadOptions = getDownloadOptions;
+  }
+});
+
+// node_modules/@actions/cache/lib/internal/config.js
+var require_config2 = __commonJS({
+  "node_modules/@actions/cache/lib/internal/config.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getCacheServiceURL = exports2.getCacheServiceVersion = exports2.isGhes = void 0;
+    function isGhes() {
+      const ghUrl = new URL(process.env["GITHUB_SERVER_URL"] || "https://github.com");
+      const hostname = ghUrl.hostname.trimEnd().toUpperCase();
+      const isGitHubHost = hostname === "GITHUB.COM";
+      const isGheHost = hostname.endsWith(".GHE.COM");
+      const isLocalHost = hostname.endsWith(".LOCALHOST");
+      return !isGitHubHost && !isGheHost && !isLocalHost;
     }
-    exports2.lte = lte;
-    function lte(a, b, loose) {
-      return compare2(a, b, loose) <= 0;
+    exports2.isGhes = isGhes;
+    function getCacheServiceVersion() {
+      if (isGhes())
+        return "v1";
+      return process.env["ACTIONS_CACHE_SERVICE_V2"] ? "v2" : "v1";
     }
-    exports2.cmp = cmp;
-    function cmp(a, op, b, loose) {
-      switch (op) {
-        case "===":
-          if (typeof a === "object")
-            a = a.version;
-          if (typeof b === "object")
-            b = b.version;
-          return a === b;
-        case "!==":
-          if (typeof a === "object")
-            a = a.version;
-          if (typeof b === "object")
-            b = b.version;
-          return a !== b;
-        case "":
-        case "=":
-        case "==":
-          return eq(a, b, loose);
-        case "!=":
-          return neq(a, b, loose);
-        case ">":
-          return gt(a, b, loose);
-        case ">=":
-          return gte5(a, b, loose);
-        case "<":
-          return lt(a, b, loose);
-        case "<=":
-          return lte(a, b, loose);
+    exports2.getCacheServiceVersion = getCacheServiceVersion;
+    function getCacheServiceURL() {
+      const version = getCacheServiceVersion();
+      switch (version) {
+        case "v1":
+          return process.env["ACTIONS_CACHE_URL"] || process.env["ACTIONS_RESULTS_URL"] || "";
+        case "v2":
+          return process.env["ACTIONS_RESULTS_URL"] || "";
         default:
-          throw new TypeError("Invalid operator: " + op);
-      }
-    }
-    exports2.Comparator = Comparator;
-    function Comparator(comp, options) {
-      if (!options || typeof options !== "object") {
-        options = {
-          loose: !!options,
-          includePrerelease: false
-        };
-      }
-      if (comp instanceof Comparator) {
-        if (comp.loose === !!options.loose) {
-          return comp;
-        } else {
-          comp = comp.value;
-        }
-      }
-      if (!(this instanceof Comparator)) {
-        return new Comparator(comp, options);
-      }
-      comp = comp.trim().split(/\s+/).join(" ");
-      debug4("comparator", comp, options);
-      this.options = options;
-      this.loose = !!options.loose;
-      this.parse(comp);
-      if (this.semver === ANY) {
-        this.value = "";
-      } else {
-        this.value = this.operator + this.semver.version;
+          throw new Error(`Unsupported cache service version: ${version}`);
       }
-      debug4("comp", this);
     }
-    var ANY = {};
-    Comparator.prototype.parse = function(comp) {
-      var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR];
-      var m = comp.match(r);
-      if (!m) {
-        throw new TypeError("Invalid comparator: " + comp);
-      }
-      this.operator = m[1] !== void 0 ? m[1] : "";
-      if (this.operator === "=") {
-        this.operator = "";
-      }
-      if (!m[2]) {
-        this.semver = ANY;
-      } else {
-        this.semver = new SemVer(m[2], this.options.loose);
+    exports2.getCacheServiceURL = getCacheServiceURL;
+  }
+});
+
+// node_modules/@actions/cache/package.json
+var require_package3 = __commonJS({
+  "node_modules/@actions/cache/package.json"(exports2, module2) {
+    module2.exports = {
+      name: "@actions/cache",
+      version: "4.1.0",
+      preview: true,
+      description: "Actions cache lib",
+      keywords: [
+        "github",
+        "actions",
+        "cache"
+      ],
+      homepage: "https://github.com/actions/toolkit/tree/main/packages/cache",
+      license: "MIT",
+      main: "lib/cache.js",
+      types: "lib/cache.d.ts",
+      directories: {
+        lib: "lib",
+        test: "__tests__"
+      },
+      files: [
+        "lib",
+        "!.DS_Store"
+      ],
+      publishConfig: {
+        access: "public"
+      },
+      repository: {
+        type: "git",
+        url: "git+https://github.com/actions/toolkit.git",
+        directory: "packages/cache"
+      },
+      scripts: {
+        "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json",
+        test: 'echo "Error: run tests from root" && exit 1',
+        tsc: "tsc"
+      },
+      bugs: {
+        url: "https://github.com/actions/toolkit/issues"
+      },
+      dependencies: {
+        "@actions/core": "^1.11.1",
+        "@actions/exec": "^1.0.1",
+        "@actions/glob": "^0.1.0",
+        "@protobuf-ts/runtime-rpc": "^2.11.1",
+        "@actions/http-client": "^2.1.1",
+        "@actions/io": "^1.0.1",
+        "@azure/abort-controller": "^1.1.0",
+        "@azure/ms-rest-js": "^2.6.0",
+        "@azure/storage-blob": "^12.13.0",
+        semver: "^6.3.1"
+      },
+      devDependencies: {
+        "@types/node": "^22.13.9",
+        "@types/semver": "^6.0.0",
+        "@protobuf-ts/plugin": "^2.9.4",
+        typescript: "^5.2.2"
       }
     };
-    Comparator.prototype.toString = function() {
-      return this.value;
-    };
-    Comparator.prototype.test = function(version) {
-      debug4("Comparator.test", version, this.options.loose);
-      if (this.semver === ANY || version === ANY) {
-        return true;
+  }
+});
+
+// node_modules/@actions/cache/lib/internal/shared/user-agent.js
+var require_user_agent2 = __commonJS({
+  "node_modules/@actions/cache/lib/internal/shared/user-agent.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getUserAgentString = void 0;
+    var packageJson = require_package3();
+    function getUserAgentString() {
+      return `@actions/cache-${packageJson.version}`;
+    }
+    exports2.getUserAgentString = getUserAgentString;
+  }
+});
+
+// node_modules/@actions/cache/lib/internal/cacheHttpClient.js
+var require_cacheHttpClient = __commonJS({
+  "node_modules/@actions/cache/lib/internal/cacheHttpClient.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      if (typeof version === "string") {
-        try {
-          version = new SemVer(version, this.options);
-        } catch (er) {
-          return false;
-        }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-      return cmp(version, this.operator, this.semver, this.options);
+      __setModuleDefault4(result, mod);
+      return result;
     };
-    Comparator.prototype.intersects = function(comp, options) {
-      if (!(comp instanceof Comparator)) {
-        throw new TypeError("a Comparator is required");
-      }
-      if (!options || typeof options !== "object") {
-        options = {
-          loose: !!options,
-          includePrerelease: false
-        };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
       }
-      var rangeTmp;
-      if (this.operator === "") {
-        if (this.value === "") {
-          return true;
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        rangeTmp = new Range2(comp.value, options);
-        return satisfies2(this.value, rangeTmp, options);
-      } else if (comp.operator === "") {
-        if (comp.value === "") {
-          return true;
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        rangeTmp = new Range2(this.value, options);
-        return satisfies2(comp.semver, rangeTmp, options);
-      }
-      var sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">");
-      var sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<");
-      var sameSemVer = this.semver.version === comp.semver.version;
-      var differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<=");
-      var oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && ((this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<"));
-      var oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && ((this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">"));
-      return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
-    };
-    exports2.Range = Range2;
-    function Range2(range, options) {
-      if (!options || typeof options !== "object") {
-        options = {
-          loose: !!options,
-          includePrerelease: false
-        };
-      }
-      if (range instanceof Range2) {
-        if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
-          return range;
-        } else {
-          return new Range2(range.raw, options);
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
         }
-      }
-      if (range instanceof Comparator) {
-        return new Range2(range.value, options);
-      }
-      if (!(this instanceof Range2)) {
-        return new Range2(range, options);
-      }
-      this.options = options;
-      this.loose = !!options.loose;
-      this.includePrerelease = !!options.includePrerelease;
-      this.raw = range.trim().split(/\s+/).join(" ");
-      this.set = this.raw.split("||").map(function(range2) {
-        return this.parseRange(range2.trim());
-      }, this).filter(function(c) {
-        return c.length;
-      });
-      if (!this.set.length) {
-        throw new TypeError("Invalid SemVer Range: " + this.raw);
-      }
-      this.format();
-    }
-    Range2.prototype.format = function() {
-      this.range = this.set.map(function(comps) {
-        return comps.join(" ").trim();
-      }).join("||").trim();
-      return this.range;
-    };
-    Range2.prototype.toString = function() {
-      return this.range;
-    };
-    Range2.prototype.parseRange = function(range) {
-      var loose = this.options.loose;
-      var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE];
-      range = range.replace(hr, hyphenReplace);
-      debug4("hyphen replace", range);
-      range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace);
-      debug4("comparator trim", range, safeRe[t.COMPARATORTRIM]);
-      range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace);
-      range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace);
-      range = range.split(/\s+/).join(" ");
-      var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR];
-      var set2 = range.split(" ").map(function(comp) {
-        return parseComparator(comp, this.options);
-      }, this).join(" ").split(/\s+/);
-      if (this.options.loose) {
-        set2 = set2.filter(function(comp) {
-          return !!comp.match(compRe);
-        });
-      }
-      set2 = set2.map(function(comp) {
-        return new Comparator(comp, this.options);
-      }, this);
-      return set2;
-    };
-    Range2.prototype.intersects = function(range, options) {
-      if (!(range instanceof Range2)) {
-        throw new TypeError("a Range is required");
-      }
-      return this.set.some(function(thisComparators) {
-        return isSatisfiable(thisComparators, options) && range.set.some(function(rangeComparators) {
-          return isSatisfiable(rangeComparators, options) && thisComparators.every(function(thisComparator) {
-            return rangeComparators.every(function(rangeComparator) {
-              return thisComparator.intersects(rangeComparator, options);
-            });
-          });
-        });
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
       });
     };
-    function isSatisfiable(comparators, options) {
-      var result = true;
-      var remainingComparators = comparators.slice();
-      var testComparator = remainingComparators.pop();
-      while (result && remainingComparators.length) {
-        result = remainingComparators.every(function(otherComparator) {
-          return testComparator.intersects(otherComparator, options);
-        });
-        testComparator = remainingComparators.pop();
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0;
+    var core14 = __importStar4(require_core());
+    var http_client_1 = require_lib7();
+    var auth_1 = require_auth4();
+    var fs2 = __importStar4(require("fs"));
+    var url_1 = require("url");
+    var utils = __importStar4(require_cacheUtils());
+    var uploadUtils_1 = require_uploadUtils();
+    var downloadUtils_1 = require_downloadUtils();
+    var options_1 = require_options();
+    var requestUtils_1 = require_requestUtils2();
+    var config_1 = require_config2();
+    var user_agent_1 = require_user_agent2();
+    function getCacheApiUrl(resource) {
+      const baseUrl = (0, config_1.getCacheServiceURL)();
+      if (!baseUrl) {
+        throw new Error("Cache Service Url not found, unable to restore cache.");
       }
-      return result;
-    }
-    exports2.toComparators = toComparators;
-    function toComparators(range, options) {
-      return new Range2(range, options).set.map(function(comp) {
-        return comp.map(function(c) {
-          return c.value;
-        }).join(" ").trim().split(" ");
-      });
+      const url = `${baseUrl}_apis/artifactcache/${resource}`;
+      core14.debug(`Resource Url: ${url}`);
+      return url;
     }
-    function parseComparator(comp, options) {
-      debug4("comp", comp, options);
-      comp = replaceCarets(comp, options);
-      debug4("caret", comp);
-      comp = replaceTildes(comp, options);
-      debug4("tildes", comp);
-      comp = replaceXRanges(comp, options);
-      debug4("xrange", comp);
-      comp = replaceStars(comp, options);
-      debug4("stars", comp);
-      return comp;
+    function createAcceptHeader(type2, apiVersion) {
+      return `${type2};api-version=${apiVersion}`;
     }
-    function isX(id) {
-      return !id || id.toLowerCase() === "x" || id === "*";
+    function getRequestOptions() {
+      const requestOptions = {
+        headers: {
+          Accept: createAcceptHeader("application/json", "6.0-preview.1")
+        }
+      };
+      return requestOptions;
     }
-    function replaceTildes(comp, options) {
-      return comp.trim().split(/\s+/).map(function(comp2) {
-        return replaceTilde(comp2, options);
-      }).join(" ");
+    function createHttpClient() {
+      const token = process.env["ACTIONS_RUNTIME_TOKEN"] || "";
+      const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token);
+      return new http_client_1.HttpClient((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions());
     }
-    function replaceTilde(comp, options) {
-      var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE];
-      return comp.replace(r, function(_2, M, m, p, pr) {
-        debug4("tilde", comp, _2, M, m, p, pr);
-        var ret;
-        if (isX(M)) {
-          ret = "";
-        } else if (isX(m)) {
-          ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
-        } else if (isX(p)) {
-          ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
-        } else if (pr) {
-          debug4("replaceTilde pr", pr);
-          ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
-        } else {
-          ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
+    function getCacheEntry(keys, paths, options) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const httpClient = createHttpClient();
+        const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
+        const resource = `cache?keys=${encodeURIComponent(keys.join(","))}&version=${version}`;
+        const response = yield (0, requestUtils_1.retryTypedResponse)("getCacheEntry", () => __awaiter4(this, void 0, void 0, function* () {
+          return httpClient.getJson(getCacheApiUrl(resource));
+        }));
+        if (response.statusCode === 204) {
+          if (core14.isDebug()) {
+            yield printCachesListForDiagnostics(keys[0], httpClient, version);
+          }
+          return null;
         }
-        debug4("tilde return", ret);
-        return ret;
+        if (!(0, requestUtils_1.isSuccessStatusCode)(response.statusCode)) {
+          throw new Error(`Cache service responded with ${response.statusCode}`);
+        }
+        const cacheResult = response.result;
+        const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation;
+        if (!cacheDownloadUrl) {
+          throw new Error("Cache not found.");
+        }
+        core14.setSecret(cacheDownloadUrl);
+        core14.debug(`Cache Result:`);
+        core14.debug(JSON.stringify(cacheResult));
+        return cacheResult;
       });
     }
-    function replaceCarets(comp, options) {
-      return comp.trim().split(/\s+/).map(function(comp2) {
-        return replaceCaret(comp2, options);
-      }).join(" ");
-    }
-    function replaceCaret(comp, options) {
-      debug4("caret", comp, options);
-      var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET];
-      return comp.replace(r, function(_2, M, m, p, pr) {
-        debug4("caret", comp, _2, M, m, p, pr);
-        var ret;
-        if (isX(M)) {
-          ret = "";
-        } else if (isX(m)) {
-          ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
-        } else if (isX(p)) {
-          if (M === "0") {
-            ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
-          } else {
-            ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0";
-          }
-        } else if (pr) {
-          debug4("replaceCaret pr", pr);
-          if (M === "0") {
-            if (m === "0") {
-              ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1);
-            } else {
-              ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
+    exports2.getCacheEntry = getCacheEntry;
+    function printCachesListForDiagnostics(key, httpClient, version) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const resource = `caches?key=${encodeURIComponent(key)}`;
+        const response = yield (0, requestUtils_1.retryTypedResponse)("listCache", () => __awaiter4(this, void 0, void 0, function* () {
+          return httpClient.getJson(getCacheApiUrl(resource));
+        }));
+        if (response.statusCode === 200) {
+          const cacheListResult = response.result;
+          const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount;
+          if (totalCount && totalCount > 0) {
+            core14.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env["GITHUB_REF"]}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key 
+Other caches with similar key:`);
+            for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) {
+              core14.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`);
             }
-          } else {
-            ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0";
           }
-        } else {
-          debug4("no pr");
-          if (M === "0") {
-            if (m === "0") {
-              ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1);
-            } else {
-              ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
-            }
+        }
+      });
+    }
+    function downloadCache(archiveLocation, archivePath, options) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const archiveUrl = new url_1.URL(archiveLocation);
+        const downloadOptions = (0, options_1.getDownloadOptions)(options);
+        if (archiveUrl.hostname.endsWith(".blob.core.windows.net")) {
+          if (downloadOptions.useAzureSdk) {
+            yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions);
+          } else if (downloadOptions.concurrentBlobDownloads) {
+            yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions);
           } else {
-            ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0";
+            yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath);
           }
+        } else {
+          yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath);
         }
-        debug4("caret return", ret);
-        return ret;
       });
     }
-    function replaceXRanges(comp, options) {
-      debug4("replaceXRanges", comp, options);
-      return comp.split(/\s+/).map(function(comp2) {
-        return replaceXRange(comp2, options);
-      }).join(" ");
+    exports2.downloadCache = downloadCache;
+    function reserveCache(key, paths, options) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const httpClient = createHttpClient();
+        const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
+        const reserveCacheRequest = {
+          key,
+          version,
+          cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize
+        };
+        const response = yield (0, requestUtils_1.retryTypedResponse)("reserveCache", () => __awaiter4(this, void 0, void 0, function* () {
+          return httpClient.postJson(getCacheApiUrl("caches"), reserveCacheRequest);
+        }));
+        return response;
+      });
     }
-    function replaceXRange(comp, options) {
-      comp = comp.trim();
-      var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE];
-      return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
-        debug4("xRange", comp, ret, gtlt, M, m, p, pr);
-        var xM = isX(M);
-        var xm = xM || isX(m);
-        var xp = xm || isX(p);
-        var anyX = xp;
-        if (gtlt === "=" && anyX) {
-          gtlt = "";
+    exports2.reserveCache = reserveCache;
+    function getContentRange(start, end) {
+      return `bytes ${start}-${end}/*`;
+    }
+    function uploadChunk(httpClient, resourceUrl, openStream, start, end) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        core14.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`);
+        const additionalHeaders = {
+          "Content-Type": "application/octet-stream",
+          "Content-Range": getContentRange(start, end)
+        };
+        const uploadChunkResponse = yield (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter4(this, void 0, void 0, function* () {
+          return httpClient.sendStream("PATCH", resourceUrl, openStream(), additionalHeaders);
+        }));
+        if (!(0, requestUtils_1.isSuccessStatusCode)(uploadChunkResponse.message.statusCode)) {
+          throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`);
         }
-        pr = options.includePrerelease ? "-0" : "";
-        if (xM) {
-          if (gtlt === ">" || gtlt === "<") {
-            ret = "<0.0.0-0";
-          } else {
-            ret = "*";
-          }
-        } else if (gtlt && anyX) {
-          if (xm) {
-            m = 0;
-          }
-          p = 0;
-          if (gtlt === ">") {
-            gtlt = ">=";
-            if (xm) {
-              M = +M + 1;
-              m = 0;
-              p = 0;
-            } else {
-              m = +m + 1;
-              p = 0;
-            }
-          } else if (gtlt === "<=") {
-            gtlt = "<";
-            if (xm) {
-              M = +M + 1;
-            } else {
-              m = +m + 1;
+      });
+    }
+    function uploadFile(httpClient, cacheId, archivePath, options) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const fileSize = utils.getArchiveFileSizeInBytes(archivePath);
+        const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`);
+        const fd = fs2.openSync(archivePath, "r");
+        const uploadOptions = (0, options_1.getUploadOptions)(options);
+        const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency);
+        const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize);
+        const parallelUploads = [...new Array(concurrency).keys()];
+        core14.debug("Awaiting all uploads");
+        let offset = 0;
+        try {
+          yield Promise.all(parallelUploads.map(() => __awaiter4(this, void 0, void 0, function* () {
+            while (offset < fileSize) {
+              const chunkSize = Math.min(fileSize - offset, maxChunkSize);
+              const start = offset;
+              const end = offset + chunkSize - 1;
+              offset += maxChunkSize;
+              yield uploadChunk(httpClient, resourceUrl, () => fs2.createReadStream(archivePath, {
+                fd,
+                start,
+                end,
+                autoClose: false
+              }).on("error", (error4) => {
+                throw new Error(`Cache upload failed because file read failed with ${error4.message}`);
+              }), start, end);
             }
+          })));
+        } finally {
+          fs2.closeSync(fd);
+        }
+        return;
+      });
+    }
+    function commitCache(httpClient, cacheId, filesize) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const commitCacheRequest = { size: filesize };
+        return yield (0, requestUtils_1.retryTypedResponse)("commitCache", () => __awaiter4(this, void 0, void 0, function* () {
+          return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest);
+        }));
+      });
+    }
+    function saveCache4(cacheId, archivePath, signedUploadURL, options) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const uploadOptions = (0, options_1.getUploadOptions)(options);
+        if (uploadOptions.useAzureSdk) {
+          if (!signedUploadURL) {
+            throw new Error("Azure Storage SDK can only be used when a signed URL is provided.");
           }
-          ret = gtlt + M + "." + m + "." + p + pr;
-        } else if (xm) {
-          ret = ">=" + M + ".0.0" + pr + " <" + (+M + 1) + ".0.0" + pr;
-        } else if (xp) {
-          ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr;
+          yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options);
+        } else {
+          const httpClient = createHttpClient();
+          core14.debug("Upload cache");
+          yield uploadFile(httpClient, cacheId, archivePath, options);
+          core14.debug("Commiting cache");
+          const cacheSize = utils.getArchiveFileSizeInBytes(archivePath);
+          core14.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`);
+          const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize);
+          if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) {
+            throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`);
+          }
+          core14.info("Cache saved successfully");
         }
-        debug4("xRange return", ret);
-        return ret;
       });
     }
-    function replaceStars(comp, options) {
-      debug4("replaceStars", comp, options);
-      return comp.trim().replace(safeRe[t.STAR], "");
-    }
-    function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
-      if (isX(fM)) {
-        from = "";
-      } else if (isX(fm)) {
-        from = ">=" + fM + ".0.0";
-      } else if (isX(fp)) {
-        from = ">=" + fM + "." + fm + ".0";
-      } else {
-        from = ">=" + from;
-      }
-      if (isX(tM)) {
-        to = "";
-      } else if (isX(tm)) {
-        to = "<" + (+tM + 1) + ".0.0";
-      } else if (isX(tp)) {
-        to = "<" + tM + "." + (+tm + 1) + ".0";
-      } else if (tpr) {
-        to = "<=" + tM + "." + tm + "." + tp + "-" + tpr;
-      } else {
-        to = "<=" + to;
+    exports2.saveCache = saveCache4;
+  }
+});
+
+// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js
+var require_cachescope = __commonJS({
+  "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.CacheScope = void 0;
+    var runtime_1 = require_commonjs();
+    var runtime_2 = require_commonjs();
+    var runtime_3 = require_commonjs();
+    var runtime_4 = require_commonjs();
+    var runtime_5 = require_commonjs();
+    var CacheScope$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.entities.v1.CacheScope", [
+          {
+            no: 1,
+            name: "scope",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 2,
+            name: "permission",
+            kind: "scalar",
+            T: 3
+            /*ScalarType.INT64*/
+          }
+        ]);
       }
-      return (from + " " + to).trim();
-    }
-    Range2.prototype.test = function(version) {
-      if (!version) {
-        return false;
+      create(value) {
+        const message = { scope: "", permission: "0" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
       }
-      if (typeof version === "string") {
-        try {
-          version = new SemVer(version, this.options);
-        } catch (er) {
-          return false;
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* string scope */
+            1:
+              message.scope = reader.string();
+              break;
+            case /* int64 permission */
+            2:
+              message.permission = reader.int64().toString();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
+          }
         }
+        return message;
       }
-      for (var i2 = 0; i2 < this.set.length; i2++) {
-        if (testSet(this.set[i2], version, this.options)) {
-          return true;
-        }
+      internalBinaryWrite(message, writer, options) {
+        if (message.scope !== "")
+          writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope);
+        if (message.permission !== "0")
+          writer.tag(2, runtime_1.WireType.Varint).int64(message.permission);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
-      return false;
     };
-    function testSet(set2, version, options) {
-      for (var i2 = 0; i2 < set2.length; i2++) {
-        if (!set2[i2].test(version)) {
-          return false;
-        }
+    exports2.CacheScope = new CacheScope$Type();
+  }
+});
+
+// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js
+var require_cachemetadata = __commonJS({
+  "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.CacheMetadata = void 0;
+    var runtime_1 = require_commonjs();
+    var runtime_2 = require_commonjs();
+    var runtime_3 = require_commonjs();
+    var runtime_4 = require_commonjs();
+    var runtime_5 = require_commonjs();
+    var cachescope_1 = require_cachescope();
+    var CacheMetadata$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.entities.v1.CacheMetadata", [
+          {
+            no: 1,
+            name: "repository_id",
+            kind: "scalar",
+            T: 3
+            /*ScalarType.INT64*/
+          },
+          { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope }
+        ]);
       }
-      if (version.prerelease.length && !options.includePrerelease) {
-        for (i2 = 0; i2 < set2.length; i2++) {
-          debug4(set2[i2].semver);
-          if (set2[i2].semver === ANY) {
-            continue;
-          }
-          if (set2[i2].semver.prerelease.length > 0) {
-            var allowed = set2[i2].semver;
-            if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
-              return true;
-            }
+      create(value) {
+        const message = { repositoryId: "0", scope: [] };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
+      }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* int64 repository_id */
+            1:
+              message.repositoryId = reader.int64().toString();
+              break;
+            case /* repeated github.actions.results.entities.v1.CacheScope scope */
+            2:
+              message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options));
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-        return false;
+        return message;
       }
-      return true;
-    }
-    exports2.satisfies = satisfies2;
-    function satisfies2(version, range, options) {
-      try {
-        range = new Range2(range, options);
-      } catch (er) {
-        return false;
+      internalBinaryWrite(message, writer, options) {
+        if (message.repositoryId !== "0")
+          writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId);
+        for (let i = 0; i < message.scope.length; i++)
+          cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join();
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
-      return range.test(version);
-    }
-    exports2.maxSatisfying = maxSatisfying;
-    function maxSatisfying(versions, range, options) {
-      var max = null;
-      var maxSV = null;
-      try {
-        var rangeObj = new Range2(range, options);
-      } catch (er) {
-        return null;
+    };
+    exports2.CacheMetadata = new CacheMetadata$Type();
+  }
+});
+
+// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js
+var require_cache2 = __commonJS({
+  "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0;
+    var runtime_rpc_1 = require_commonjs2();
+    var runtime_1 = require_commonjs();
+    var runtime_2 = require_commonjs();
+    var runtime_3 = require_commonjs();
+    var runtime_4 = require_commonjs();
+    var runtime_5 = require_commonjs();
+    var cachemetadata_1 = require_cachemetadata();
+    var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.CreateCacheEntryRequest", [
+          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
+          {
+            no: 2,
+            name: "key",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "version",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          }
+        ]);
       }
-      versions.forEach(function(v) {
-        if (rangeObj.test(v)) {
-          if (!max || maxSV.compare(v) === -1) {
-            max = v;
-            maxSV = new SemVer(max, options);
+      create(value) {
+        const message = { key: "", version: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
+      }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* github.actions.results.entities.v1.CacheMetadata metadata */
+            1:
+              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
+              break;
+            case /* string key */
+            2:
+              message.key = reader.string();
+              break;
+            case /* string version */
+            3:
+              message.version = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-      });
-      return max;
-    }
-    exports2.minSatisfying = minSatisfying;
-    function minSatisfying(versions, range, options) {
-      var min = null;
-      var minSV = null;
-      try {
-        var rangeObj = new Range2(range, options);
-      } catch (er) {
-        return null;
+        return message;
       }
-      versions.forEach(function(v) {
-        if (rangeObj.test(v)) {
-          if (!min || minSV.compare(v) === 1) {
-            min = v;
-            minSV = new SemVer(min, options);
+      internalBinaryWrite(message, writer, options) {
+        if (message.metadata)
+          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
+        if (message.key !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
+        if (message.version !== "")
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
+      }
+    };
+    exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type();
+    var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.CreateCacheEntryResponse", [
+          {
+            no: 1,
+            name: "ok",
+            kind: "scalar",
+            T: 8
+            /*ScalarType.BOOL*/
+          },
+          {
+            no: 2,
+            name: "signed_upload_url",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "message",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
           }
-        }
-      });
-      return min;
-    }
-    exports2.minVersion = minVersion;
-    function minVersion(range, loose) {
-      range = new Range2(range, loose);
-      var minver = new SemVer("0.0.0");
-      if (range.test(minver)) {
-        return minver;
+        ]);
       }
-      minver = new SemVer("0.0.0-0");
-      if (range.test(minver)) {
-        return minver;
+      create(value) {
+        const message = { ok: false, signedUploadUrl: "", message: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
       }
-      minver = null;
-      for (var i2 = 0; i2 < range.set.length; ++i2) {
-        var comparators = range.set[i2];
-        comparators.forEach(function(comparator) {
-          var compver = new SemVer(comparator.semver.version);
-          switch (comparator.operator) {
-            case ">":
-              if (compver.prerelease.length === 0) {
-                compver.patch++;
-              } else {
-                compver.prerelease.push(0);
-              }
-              compver.raw = compver.format();
-            /* fallthrough */
-            case "":
-            case ">=":
-              if (!minver || gt(minver, compver)) {
-                minver = compver;
-              }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* bool ok */
+            1:
+              message.ok = reader.bool();
               break;
-            case "<":
-            case "<=":
+            case /* string signed_upload_url */
+            2:
+              message.signedUploadUrl = reader.string();
+              break;
+            case /* string message */
+            3:
+              message.message = reader.string();
               break;
-            /* istanbul ignore next */
             default:
-              throw new Error("Unexpected operation: " + comparator.operator);
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
-        });
-      }
-      if (minver && range.test(minver)) {
-        return minver;
+        }
+        return message;
       }
-      return null;
-    }
-    exports2.validRange = validRange;
-    function validRange(range, options) {
-      try {
-        return new Range2(range, options).range || "*";
-      } catch (er) {
-        return null;
+      internalBinaryWrite(message, writer, options) {
+        if (message.ok !== false)
+          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
+        if (message.signedUploadUrl !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl);
+        if (message.message !== "")
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
-    }
-    exports2.ltr = ltr;
-    function ltr(version, range, options) {
-      return outside(version, range, "<", options);
-    }
-    exports2.gtr = gtr;
-    function gtr(version, range, options) {
-      return outside(version, range, ">", options);
-    }
-    exports2.outside = outside;
-    function outside(version, range, hilo, options) {
-      version = new SemVer(version, options);
-      range = new Range2(range, options);
-      var gtfn, ltefn, ltfn, comp, ecomp;
-      switch (hilo) {
-        case ">":
-          gtfn = gt;
-          ltefn = lte;
-          ltfn = lt;
-          comp = ">";
-          ecomp = ">=";
-          break;
-        case "<":
-          gtfn = lt;
-          ltefn = gte5;
-          ltfn = gt;
-          comp = "<";
-          ecomp = "<=";
-          break;
-        default:
-          throw new TypeError('Must provide a hilo val of "<" or ">"');
+    };
+    exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type();
+    var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [
+          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
+          {
+            no: 2,
+            name: "key",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "size_bytes",
+            kind: "scalar",
+            T: 3
+            /*ScalarType.INT64*/
+          },
+          {
+            no: 4,
+            name: "version",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          }
+        ]);
       }
-      if (satisfies2(version, range, options)) {
-        return false;
+      create(value) {
+        const message = { key: "", sizeBytes: "0", version: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
       }
-      for (var i2 = 0; i2 < range.set.length; ++i2) {
-        var comparators = range.set[i2];
-        var high = null;
-        var low = null;
-        comparators.forEach(function(comparator) {
-          if (comparator.semver === ANY) {
-            comparator = new Comparator(">=0.0.0");
-          }
-          high = high || comparator;
-          low = low || comparator;
-          if (gtfn(comparator.semver, high.semver, options)) {
-            high = comparator;
-          } else if (ltfn(comparator.semver, low.semver, options)) {
-            low = comparator;
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* github.actions.results.entities.v1.CacheMetadata metadata */
+            1:
+              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
+              break;
+            case /* string key */
+            2:
+              message.key = reader.string();
+              break;
+            case /* int64 size_bytes */
+            3:
+              message.sizeBytes = reader.int64().toString();
+              break;
+            case /* string version */
+            4:
+              message.version = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
-        });
-        if (high.operator === comp || high.operator === ecomp) {
-          return false;
-        }
-        if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
-          return false;
-        } else if (low.operator === ecomp && ltfn(version, low.semver)) {
-          return false;
         }
+        return message;
       }
-      return true;
-    }
-    exports2.prerelease = prerelease;
-    function prerelease(version, options) {
-      var parsed = parse(version, options);
-      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
-    }
-    exports2.intersects = intersects;
-    function intersects(r1, r2, options) {
-      r1 = new Range2(r1, options);
-      r2 = new Range2(r2, options);
-      return r1.intersects(r2);
-    }
-    exports2.coerce = coerce3;
-    function coerce3(version, options) {
-      if (version instanceof SemVer) {
-        return version;
+      internalBinaryWrite(message, writer, options) {
+        if (message.metadata)
+          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
+        if (message.key !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
+        if (message.sizeBytes !== "0")
+          writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes);
+        if (message.version !== "")
+          writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
-      if (typeof version === "number") {
-        version = String(version);
+    };
+    exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type();
+    var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [
+          {
+            no: 1,
+            name: "ok",
+            kind: "scalar",
+            T: 8
+            /*ScalarType.BOOL*/
+          },
+          {
+            no: 2,
+            name: "entry_id",
+            kind: "scalar",
+            T: 3
+            /*ScalarType.INT64*/
+          },
+          {
+            no: 3,
+            name: "message",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          }
+        ]);
       }
-      if (typeof version !== "string") {
-        return null;
+      create(value) {
+        const message = { ok: false, entryId: "0", message: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
       }
-      options = options || {};
-      var match = null;
-      if (!options.rtl) {
-        match = version.match(safeRe[t.COERCE]);
-      } else {
-        var next;
-        while ((next = safeRe[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) {
-          if (!match || next.index + next[0].length !== match.index + match[0].length) {
-            match = next;
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* bool ok */
+            1:
+              message.ok = reader.bool();
+              break;
+            case /* int64 entry_id */
+            2:
+              message.entryId = reader.int64().toString();
+              break;
+            case /* string message */
+            3:
+              message.message = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
-          safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
         }
-        safeRe[t.COERCERTL].lastIndex = -1;
-      }
-      if (match === null) {
-        return null;
-      }
-      return parse(match[2] + "." + (match[3] || "0") + "." + (match[4] || "0"), options);
-    }
-  }
-});
-
-// node_modules/@actions/cache/lib/internal/constants.js
-var require_constants10 = __commonJS({
-  "node_modules/@actions/cache/lib/internal/constants.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.CacheFileSizeLimit = exports2.ManifestFilename = exports2.TarFilename = exports2.SystemTarPathOnWindows = exports2.GnuTarPathOnWindows = exports2.SocketTimeout = exports2.DefaultRetryDelay = exports2.DefaultRetryAttempts = exports2.ArchiveToolType = exports2.CompressionMethod = exports2.CacheFilename = void 0;
-    var CacheFilename;
-    (function(CacheFilename2) {
-      CacheFilename2["Gzip"] = "cache.tgz";
-      CacheFilename2["Zstd"] = "cache.tzst";
-    })(CacheFilename || (exports2.CacheFilename = CacheFilename = {}));
-    var CompressionMethod;
-    (function(CompressionMethod2) {
-      CompressionMethod2["Gzip"] = "gzip";
-      CompressionMethod2["ZstdWithoutLong"] = "zstd-without-long";
-      CompressionMethod2["Zstd"] = "zstd";
-    })(CompressionMethod || (exports2.CompressionMethod = CompressionMethod = {}));
-    var ArchiveToolType;
-    (function(ArchiveToolType2) {
-      ArchiveToolType2["GNU"] = "gnu";
-      ArchiveToolType2["BSD"] = "bsd";
-    })(ArchiveToolType || (exports2.ArchiveToolType = ArchiveToolType = {}));
-    exports2.DefaultRetryAttempts = 2;
-    exports2.DefaultRetryDelay = 5e3;
-    exports2.SocketTimeout = 5e3;
-    exports2.GnuTarPathOnWindows = `${process.env["PROGRAMFILES"]}\\Git\\usr\\bin\\tar.exe`;
-    exports2.SystemTarPathOnWindows = `${process.env["SYSTEMDRIVE"]}\\Windows\\System32\\tar.exe`;
-    exports2.TarFilename = "cache.tar";
-    exports2.ManifestFilename = "manifest.txt";
-    exports2.CacheFileSizeLimit = 10 * Math.pow(1024, 3);
-  }
-});
-
-// node_modules/@actions/cache/lib/internal/cacheUtils.js
-var require_cacheUtils = __commonJS({
-  "node_modules/@actions/cache/lib/internal/cacheUtils.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+        return message;
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      internalBinaryWrite(message, writer, options) {
+        if (message.ok !== false)
+          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
+        if (message.entryId !== "0")
+          writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId);
+        if (message.message !== "")
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
-      __setModuleDefault4(result, mod);
-      return result;
     };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
+    exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type();
+    var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [
+          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
+          {
+            no: 2,
+            name: "key",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "restore_keys",
+            kind: "scalar",
+            repeat: 2,
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 4,
+            name: "version",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
           }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+        ]);
+      }
+      create(value) {
+        const message = { key: "", restoreKeys: [], version: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
+      }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* github.actions.results.entities.v1.CacheMetadata metadata */
+            1:
+              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
+              break;
+            case /* string key */
+            2:
+              message.key = reader.string();
+              break;
+            case /* repeated string restore_keys */
+            3:
+              message.restoreKeys.push(reader.string());
+              break;
+            case /* string version */
+            4:
+              message.version = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
-    };
-    var __asyncValues4 = exports2 && exports2.__asyncValues || function(o) {
-      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
-      var m = o[Symbol.asyncIterator], i;
-      return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
-        return this;
-      }, i);
-      function verb(n) {
-        i[n] = o[n] && function(v) {
-          return new Promise(function(resolve2, reject) {
-            v = o[n](v), settle(resolve2, reject, v.done, v.value);
-          });
-        };
+        return message;
       }
-      function settle(resolve2, reject, d, v) {
-        Promise.resolve(v).then(function(v2) {
-          resolve2({ value: v2, done: d });
-        }, reject);
+      internalBinaryWrite(message, writer, options) {
+        if (message.metadata)
+          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
+        if (message.key !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
+        for (let i = 0; i < message.restoreKeys.length; i++)
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]);
+        if (message.version !== "")
+          writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getRuntimeToken = exports2.getCacheVersion = exports2.assertDefined = exports2.getGnuTarPathOnWindows = exports2.getCacheFileName = exports2.getCompressionMethod = exports2.unlinkFile = exports2.resolvePaths = exports2.getArchiveFileSizeInBytes = exports2.createTempDirectory = void 0;
-    var core14 = __importStar4(require_core());
-    var exec2 = __importStar4(require_exec());
-    var glob2 = __importStar4(require_glob2());
-    var io6 = __importStar4(require_io());
-    var crypto = __importStar4(require("crypto"));
-    var fs2 = __importStar4(require("fs"));
-    var path2 = __importStar4(require("path"));
-    var semver8 = __importStar4(require_semver3());
-    var util = __importStar4(require("util"));
-    var constants_1 = require_constants10();
-    var versionSalt = "1.0";
-    function createTempDirectory() {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const IS_WINDOWS = process.platform === "win32";
-        let tempDirectory = process.env["RUNNER_TEMP"] || "";
-        if (!tempDirectory) {
-          let baseLocation;
-          if (IS_WINDOWS) {
-            baseLocation = process.env["USERPROFILE"] || "C:\\";
-          } else {
-            if (process.platform === "darwin") {
-              baseLocation = "/Users";
-            } else {
-              baseLocation = "/home";
-            }
-          }
-          tempDirectory = path2.join(baseLocation, "actions", "temp");
-        }
-        const dest = path2.join(tempDirectory, crypto.randomUUID());
-        yield io6.mkdirP(dest);
-        return dest;
-      });
-    }
-    exports2.createTempDirectory = createTempDirectory;
-    function getArchiveFileSizeInBytes(filePath) {
-      return fs2.statSync(filePath).size;
-    }
-    exports2.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes;
-    function resolvePaths(patterns) {
-      var _a, e_1, _b, _c;
-      var _d;
-      return __awaiter4(this, void 0, void 0, function* () {
-        const paths = [];
-        const workspace = (_d = process.env["GITHUB_WORKSPACE"]) !== null && _d !== void 0 ? _d : process.cwd();
-        const globber = yield glob2.create(patterns.join("\n"), {
-          implicitDescendants: false
-        });
-        try {
-          for (var _e = true, _f = __asyncValues4(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {
-            _c = _g.value;
-            _e = false;
-            const file = _c;
-            const relativeFile = path2.relative(workspace, file).replace(new RegExp(`\\${path2.sep}`, "g"), "/");
-            core14.debug(`Matched: ${relativeFile}`);
-            if (relativeFile === "") {
-              paths.push(".");
-            } else {
-              paths.push(`${relativeFile}`);
-            }
-          }
-        } catch (e_1_1) {
-          e_1 = { error: e_1_1 };
-        } finally {
-          try {
-            if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
-          } finally {
-            if (e_1) throw e_1.error;
+    exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type();
+    var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [
+          {
+            no: 1,
+            name: "ok",
+            kind: "scalar",
+            T: 8
+            /*ScalarType.BOOL*/
+          },
+          {
+            no: 2,
+            name: "signed_download_url",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "matched_key",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          }
+        ]);
+      }
+      create(value) {
+        const message = { ok: false, signedDownloadUrl: "", matchedKey: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
+      }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* bool ok */
+            1:
+              message.ok = reader.bool();
+              break;
+            case /* string signed_download_url */
+            2:
+              message.signedDownloadUrl = reader.string();
+              break;
+            case /* string matched_key */
+            3:
+              message.matchedKey = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-        return paths;
-      });
-    }
-    exports2.resolvePaths = resolvePaths;
-    function unlinkFile(filePath) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        return util.promisify(fs2.unlink)(filePath);
-      });
-    }
-    exports2.unlinkFile = unlinkFile;
-    function getVersion(app, additionalArgs = []) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        let versionOutput = "";
-        additionalArgs.push("--version");
-        core14.debug(`Checking ${app} ${additionalArgs.join(" ")}`);
-        try {
-          yield exec2.exec(`${app}`, additionalArgs, {
-            ignoreReturnCode: true,
-            silent: true,
-            listeners: {
-              stdout: (data) => versionOutput += data.toString(),
-              stderr: (data) => versionOutput += data.toString()
-            }
-          });
-        } catch (err) {
-          core14.debug(err.message);
-        }
-        versionOutput = versionOutput.trim();
-        core14.debug(versionOutput);
-        return versionOutput;
-      });
-    }
-    function getCompressionMethod() {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const versionOutput = yield getVersion("zstd", ["--quiet"]);
-        const version = semver8.clean(versionOutput);
-        core14.debug(`zstd version: ${version}`);
-        if (versionOutput === "") {
-          return constants_1.CompressionMethod.Gzip;
-        } else {
-          return constants_1.CompressionMethod.ZstdWithoutLong;
-        }
-      });
-    }
-    exports2.getCompressionMethod = getCompressionMethod;
-    function getCacheFileName(compressionMethod) {
-      return compressionMethod === constants_1.CompressionMethod.Gzip ? constants_1.CacheFilename.Gzip : constants_1.CacheFilename.Zstd;
-    }
-    exports2.getCacheFileName = getCacheFileName;
-    function getGnuTarPathOnWindows() {
-      return __awaiter4(this, void 0, void 0, function* () {
-        if (fs2.existsSync(constants_1.GnuTarPathOnWindows)) {
-          return constants_1.GnuTarPathOnWindows;
-        }
-        const versionOutput = yield getVersion("tar");
-        return versionOutput.toLowerCase().includes("gnu tar") ? io6.which("tar") : "";
-      });
-    }
-    exports2.getGnuTarPathOnWindows = getGnuTarPathOnWindows;
-    function assertDefined(name, value) {
-      if (value === void 0) {
-        throw Error(`Expected ${name} but value was undefiend`);
-      }
-      return value;
-    }
-    exports2.assertDefined = assertDefined;
-    function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) {
-      const components = paths.slice();
-      if (compressionMethod) {
-        components.push(compressionMethod);
-      }
-      if (process.platform === "win32" && !enableCrossOsArchive) {
-        components.push("windows-only");
+        return message;
       }
-      components.push(versionSalt);
-      return crypto.createHash("sha256").update(components.join("|")).digest("hex");
-    }
-    exports2.getCacheVersion = getCacheVersion;
-    function getRuntimeToken() {
-      const token = process.env["ACTIONS_RUNTIME_TOKEN"];
-      if (!token) {
-        throw new Error("Unable to get the ACTIONS_RUNTIME_TOKEN env variable");
+      internalBinaryWrite(message, writer, options) {
+        if (message.ok !== false)
+          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
+        if (message.signedDownloadUrl !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl);
+        if (message.matchedKey !== "")
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
-      return token;
-    }
-    exports2.getRuntimeToken = getRuntimeToken;
+    };
+    exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type();
+    exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [
+      { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse },
+      { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse },
+      { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse }
+    ]);
   }
 });
 
-// node_modules/@actions/cache/lib/internal/shared/errors.js
-var require_errors4 = __commonJS({
-  "node_modules/@actions/cache/lib/internal/shared/errors.js"(exports2) {
+// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js
+var require_cache_twirp_client = __commonJS({
+  "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.UsageError = exports2.NetworkError = exports2.GHESNotSupportedError = exports2.CacheNotFoundError = exports2.InvalidResponseError = exports2.FilesNotFoundError = void 0;
-    var FilesNotFoundError = class extends Error {
-      constructor(files = []) {
-        let message = "No files were found to upload";
-        if (files.length > 0) {
-          message += `: ${files.join(", ")}`;
-        }
-        super(message);
-        this.files = files;
-        this.name = "FilesNotFoundError";
+    exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0;
+    var cache_1 = require_cache2();
+    var CacheServiceClientJSON = class {
+      constructor(rpc) {
+        this.rpc = rpc;
+        this.CreateCacheEntry.bind(this);
+        this.FinalizeCacheEntryUpload.bind(this);
+        this.GetCacheEntryDownloadURL.bind(this);
       }
-    };
-    exports2.FilesNotFoundError = FilesNotFoundError;
-    var InvalidResponseError = class extends Error {
-      constructor(message) {
-        super(message);
-        this.name = "InvalidResponseError";
+      CreateCacheEntry(request) {
+        const data = cache_1.CreateCacheEntryRequest.toJson(request, {
+          useProtoFieldName: true,
+          emitDefaultValues: false
+        });
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data);
+        return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, {
+          ignoreUnknownFields: true
+        }));
       }
-    };
-    exports2.InvalidResponseError = InvalidResponseError;
-    var CacheNotFoundError = class extends Error {
-      constructor(message = "Cache not found") {
-        super(message);
-        this.name = "CacheNotFoundError";
+      FinalizeCacheEntryUpload(request) {
+        const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, {
+          useProtoFieldName: true,
+          emitDefaultValues: false
+        });
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data);
+        return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, {
+          ignoreUnknownFields: true
+        }));
       }
-    };
-    exports2.CacheNotFoundError = CacheNotFoundError;
-    var GHESNotSupportedError = class extends Error {
-      constructor(message = "@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.") {
-        super(message);
-        this.name = "GHESNotSupportedError";
+      GetCacheEntryDownloadURL(request) {
+        const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, {
+          useProtoFieldName: true,
+          emitDefaultValues: false
+        });
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data);
+        return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, {
+          ignoreUnknownFields: true
+        }));
       }
     };
-    exports2.GHESNotSupportedError = GHESNotSupportedError;
-    var NetworkError = class extends Error {
-      constructor(code) {
-        const message = `Unable to make request: ${code}
-If you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`;
-        super(message);
-        this.code = code;
-        this.name = "NetworkError";
+    exports2.CacheServiceClientJSON = CacheServiceClientJSON;
+    var CacheServiceClientProtobuf = class {
+      constructor(rpc) {
+        this.rpc = rpc;
+        this.CreateCacheEntry.bind(this);
+        this.FinalizeCacheEntryUpload.bind(this);
+        this.GetCacheEntryDownloadURL.bind(this);
       }
-    };
-    exports2.NetworkError = NetworkError;
-    NetworkError.isNetworkErrorCode = (code) => {
-      if (!code)
-        return false;
-      return [
-        "ECONNRESET",
-        "ENOTFOUND",
-        "ETIMEDOUT",
-        "ECONNREFUSED",
-        "EHOSTUNREACH"
-      ].includes(code);
-    };
-    var UsageError = class extends Error {
-      constructor() {
-        const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours.
-More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`;
-        super(message);
-        this.name = "UsageError";
+      CreateCacheEntry(request) {
+        const data = cache_1.CreateCacheEntryRequest.toBinary(request);
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data);
+        return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2));
+      }
+      FinalizeCacheEntryUpload(request) {
+        const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request);
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data);
+        return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2));
+      }
+      GetCacheEntryDownloadURL(request) {
+        const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request);
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data);
+        return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2));
       }
     };
-    exports2.UsageError = UsageError;
-    UsageError.isUsageErrorMessage = (msg) => {
-      if (!msg)
-        return false;
-      return msg.includes("insufficient usage");
-    };
+    exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf;
   }
 });
 
-// node_modules/@actions/cache/lib/internal/uploadUtils.js
-var require_uploadUtils = __commonJS({
-  "node_modules/@actions/cache/lib/internal/uploadUtils.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/shared/util.js
+var require_util15 = __commonJS({
+  "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) {
     "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.maskSecretUrls = exports2.maskSigUrl = void 0;
+    var core_1 = require_core();
+    function maskSigUrl(url) {
+      if (!url)
+        return;
+      try {
+        const parsedUrl = new URL(url);
+        const signature = parsedUrl.searchParams.get("sig");
+        if (signature) {
+          (0, core_1.setSecret)(signature);
+          (0, core_1.setSecret)(encodeURIComponent(signature));
+        }
+      } catch (error4) {
+        (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`);
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+    }
+    exports2.maskSigUrl = maskSigUrl;
+    function maskSecretUrls(body) {
+      if (typeof body !== "object" || body === null) {
+        (0, core_1.debug)("body is not an object or is null");
+        return;
       }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
+      if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") {
+        maskSigUrl(body.signed_upload_url);
+      }
+      if ("signed_download_url" in body && typeof body.signed_download_url === "string") {
+        maskSigUrl(body.signed_download_url);
+      }
+    }
+    exports2.maskSecretUrls = maskSecretUrls;
+  }
+});
+
+// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js
+var require_cacheTwirpClient = __commonJS({
+  "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) {
+    "use strict";
     var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
       function adopt(value) {
         return value instanceof P ? value : new P(function(resolve2) {
@@ -105401,125 +110414,154 @@ var require_uploadUtils = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.uploadCacheArchiveSDK = exports2.UploadProgress = void 0;
-    var core14 = __importStar4(require_core());
-    var storage_blob_1 = require_dist7();
+    exports2.internalCacheTwirpClient = void 0;
+    var core_1 = require_core();
+    var user_agent_1 = require_user_agent2();
     var errors_1 = require_errors4();
-    var UploadProgress = class {
-      constructor(contentLength) {
-        this.contentLength = contentLength;
-        this.sentBytes = 0;
-        this.displayedComplete = false;
-        this.startTime = Date.now();
-      }
-      /**
-       * Sets the number of bytes sent
-       *
-       * @param sentBytes the number of bytes sent
-       */
-      setSentBytes(sentBytes) {
-        this.sentBytes = sentBytes;
-      }
-      /**
-       * Returns the total number of bytes transferred.
-       */
-      getTransferredBytes() {
-        return this.sentBytes;
-      }
-      /**
-       * Returns true if the upload is complete.
-       */
-      isDone() {
-        return this.getTransferredBytes() === this.contentLength;
-      }
-      /**
-       * Prints the current upload stats. Once the upload completes, this will print one
-       * last line and then stop.
-       */
-      display() {
-        if (this.displayedComplete) {
-          return;
+    var config_1 = require_config2();
+    var cacheUtils_1 = require_cacheUtils();
+    var auth_1 = require_auth4();
+    var http_client_1 = require_lib7();
+    var cache_twirp_client_1 = require_cache_twirp_client();
+    var util_1 = require_util15();
+    var CacheServiceClient = class {
+      constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) {
+        this.maxAttempts = 5;
+        this.baseRetryIntervalMilliseconds = 3e3;
+        this.retryMultiplier = 1.5;
+        const token = (0, cacheUtils_1.getRuntimeToken)();
+        this.baseUrl = (0, config_1.getCacheServiceURL)();
+        if (maxAttempts) {
+          this.maxAttempts = maxAttempts;
         }
-        const transferredBytes = this.sentBytes;
-        const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1);
-        const elapsedTime = Date.now() - this.startTime;
-        const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1);
-        core14.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`);
-        if (this.isDone()) {
-          this.displayedComplete = true;
+        if (baseRetryIntervalMilliseconds) {
+          this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds;
+        }
+        if (retryMultiplier) {
+          this.retryMultiplier = retryMultiplier;
         }
+        this.httpClient = new http_client_1.HttpClient(userAgent, [
+          new auth_1.BearerCredentialHandler(token)
+        ]);
       }
-      /**
-       * Returns a function used to handle TransferProgressEvents.
-       */
-      onProgress() {
-        return (progress) => {
-          this.setSentBytes(progress.loadedBytes);
-        };
+      // This function satisfies the Rpc interface. It is compatible with the JSON
+      // JSON generated client.
+      request(service, method, contentType, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href;
+          (0, core_1.debug)(`[Request] ${method} ${url}`);
+          const headers = {
+            "Content-Type": contentType
+          };
+          try {
+            const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () {
+              return this.httpClient.post(url, JSON.stringify(data), headers);
+            }));
+            return body;
+          } catch (error4) {
+            throw new Error(`Failed to ${method}: ${error4.message}`);
+          }
+        });
       }
-      /**
-       * Starts the timer that displays the stats.
-       *
-       * @param delayInMs the delay between each write
-       */
-      startDisplayTimer(delayInMs = 1e3) {
-        const displayCallback = () => {
-          this.display();
-          if (!this.isDone()) {
-            this.timeoutHandle = setTimeout(displayCallback, delayInMs);
+      retryableRequest(operation) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          let attempt = 0;
+          let errorMessage = "";
+          let rawBody = "";
+          while (attempt < this.maxAttempts) {
+            let isRetryable = false;
+            try {
+              const response = yield operation();
+              const statusCode = response.message.statusCode;
+              rawBody = yield response.readBody();
+              (0, core_1.debug)(`[Response] - ${response.message.statusCode}`);
+              (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`);
+              const body = JSON.parse(rawBody);
+              (0, util_1.maskSecretUrls)(body);
+              (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`);
+              if (this.isSuccessStatusCode(statusCode)) {
+                return { response, body };
+              }
+              isRetryable = this.isRetryableHttpStatusCode(statusCode);
+              errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`;
+              if (body.msg) {
+                if (errors_1.UsageError.isUsageErrorMessage(body.msg)) {
+                  throw new errors_1.UsageError();
+                }
+                errorMessage = `${errorMessage}: ${body.msg}`;
+              }
+            } catch (error4) {
+              if (error4 instanceof SyntaxError) {
+                (0, core_1.debug)(`Raw Body: ${rawBody}`);
+              }
+              if (error4 instanceof errors_1.UsageError) {
+                throw error4;
+              }
+              if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) {
+                throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code);
+              }
+              isRetryable = true;
+              errorMessage = error4.message;
+            }
+            if (!isRetryable) {
+              throw new Error(`Received non-retryable error: ${errorMessage}`);
+            }
+            if (attempt + 1 === this.maxAttempts) {
+              throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`);
+            }
+            const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt);
+            (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`);
+            yield this.sleep(retryTimeMilliseconds);
+            attempt++;
           }
-        };
-        this.timeoutHandle = setTimeout(displayCallback, delayInMs);
+          throw new Error(`Request failed`);
+        });
       }
-      /**
-       * Stops the timer that displays the stats. As this typically indicates the upload
-       * is complete, this will display one last line, unless the last line has already
-       * been written.
-       */
-      stopDisplayTimer() {
-        if (this.timeoutHandle) {
-          clearTimeout(this.timeoutHandle);
-          this.timeoutHandle = void 0;
+      isSuccessStatusCode(statusCode) {
+        if (!statusCode)
+          return false;
+        return statusCode >= 200 && statusCode < 300;
+      }
+      isRetryableHttpStatusCode(statusCode) {
+        if (!statusCode)
+          return false;
+        const retryableStatusCodes = [
+          http_client_1.HttpCodes.BadGateway,
+          http_client_1.HttpCodes.GatewayTimeout,
+          http_client_1.HttpCodes.InternalServerError,
+          http_client_1.HttpCodes.ServiceUnavailable,
+          http_client_1.HttpCodes.TooManyRequests
+        ];
+        return retryableStatusCodes.includes(statusCode);
+      }
+      sleep(milliseconds) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
+        });
+      }
+      getExponentialRetryTimeMilliseconds(attempt) {
+        if (attempt < 0) {
+          throw new Error("attempt should be a positive integer");
         }
-        this.display();
+        if (attempt === 0) {
+          return this.baseRetryIntervalMilliseconds;
+        }
+        const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt);
+        const maxTime = minTime * this.retryMultiplier;
+        return Math.trunc(Math.random() * (maxTime - minTime) + minTime);
       }
     };
-    exports2.UploadProgress = UploadProgress;
-    function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) {
-      var _a;
-      return __awaiter4(this, void 0, void 0, function* () {
-        const blobClient = new storage_blob_1.BlobClient(signedUploadURL);
-        const blockBlobClient = blobClient.getBlockBlobClient();
-        const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0);
-        const uploadOptions = {
-          blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize,
-          concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency,
-          maxSingleShotSize: 128 * 1024 * 1024,
-          onProgress: uploadProgress.onProgress()
-        };
-        try {
-          uploadProgress.startDisplayTimer();
-          core14.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`);
-          const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions);
-          if (response._response.status >= 400) {
-            throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`);
-          }
-          return response;
-        } catch (error4) {
-          core14.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error4.message}`);
-          throw error4;
-        } finally {
-          uploadProgress.stopDisplayTimer();
-        }
-      });
+    function internalCacheTwirpClient(options) {
+      const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier);
+      return new cache_twirp_client_1.CacheServiceClientJSON(client);
     }
-    exports2.uploadCacheArchiveSDK = uploadCacheArchiveSDK;
+    exports2.internalCacheTwirpClient = internalCacheTwirpClient;
   }
 });
 
-// node_modules/@actions/cache/lib/internal/requestUtils.js
-var require_requestUtils2 = __commonJS({
-  "node_modules/@actions/cache/lib/internal/requestUtils.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/tar.js
+var require_tar2 = __commonJS({
+  "node_modules/@actions/cache/lib/internal/tar.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -105562,132 +110604,207 @@ var require_requestUtils2 = __commonJS({
             reject(e);
           }
         }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.createTar = exports2.extractTar = exports2.listTar = void 0;
+    var exec_1 = require_exec();
+    var io6 = __importStar4(require_io());
+    var fs_1 = require("fs");
+    var path2 = __importStar4(require("path"));
+    var utils = __importStar4(require_cacheUtils());
+    var constants_1 = require_constants10();
+    var IS_WINDOWS = process.platform === "win32";
+    function getTarPath() {
+      return __awaiter4(this, void 0, void 0, function* () {
+        switch (process.platform) {
+          case "win32": {
+            const gnuTar = yield utils.getGnuTarPathOnWindows();
+            const systemTar = constants_1.SystemTarPathOnWindows;
+            if (gnuTar) {
+              return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
+            } else if ((0, fs_1.existsSync)(systemTar)) {
+              return { path: systemTar, type: constants_1.ArchiveToolType.BSD };
+            }
+            break;
+          }
+          case "darwin": {
+            const gnuTar = yield io6.which("gtar", false);
+            if (gnuTar) {
+              return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
+            } else {
+              return {
+                path: yield io6.which("tar", true),
+                type: constants_1.ArchiveToolType.BSD
+              };
+            }
+          }
+          default:
+            break;
+        }
+        return {
+          path: yield io6.which("tar", true),
+          type: constants_1.ArchiveToolType.GNU
+        };
+      });
+    }
+    function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const args = [`"${tarPath.path}"`];
+        const cacheFileName = utils.getCacheFileName(compressionMethod);
+        const tarFile = "cache.tar";
+        const workingDirectory = getWorkingDirectory();
+        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
+        switch (type2) {
+          case "create":
+            args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename);
+            break;
+          case "extract":
+            args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path2.sep}`, "g"), "/"));
+            break;
+          case "list":
+            args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "-P");
+            break;
+        }
+        if (tarPath.type === constants_1.ArchiveToolType.GNU) {
+          switch (process.platform) {
+            case "win32":
+              args.push("--force-local");
+              break;
+            case "darwin":
+              args.push("--delay-directory-restore");
+              break;
           }
         }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        return args;
+      });
+    }
+    function getCommands(compressionMethod, type2, archivePath = "") {
+      return __awaiter4(this, void 0, void 0, function* () {
+        let args;
+        const tarPath = yield getTarPath();
+        const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath);
+        const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod);
+        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
+        if (BSD_TAR_ZSTD && type2 !== "create") {
+          args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")];
+        } else {
+          args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")];
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
+        if (BSD_TAR_ZSTD) {
+          return args;
+        }
+        return [args.join(" ")];
       });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0;
-    var core14 = __importStar4(require_core());
-    var http_client_1 = require_lib();
-    var constants_1 = require_constants10();
-    function isSuccessStatusCode(statusCode) {
-      if (!statusCode) {
-        return false;
-      }
-      return statusCode >= 200 && statusCode < 300;
     }
-    exports2.isSuccessStatusCode = isSuccessStatusCode;
-    function isServerErrorStatusCode(statusCode) {
-      if (!statusCode) {
-        return true;
-      }
-      return statusCode >= 500;
+    function getWorkingDirectory() {
+      var _a;
+      return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd();
     }
-    exports2.isServerErrorStatusCode = isServerErrorStatusCode;
-    function isRetryableStatusCode(statusCode) {
-      if (!statusCode) {
-        return false;
-      }
-      const retryableStatusCodes = [
-        http_client_1.HttpCodes.BadGateway,
-        http_client_1.HttpCodes.ServiceUnavailable,
-        http_client_1.HttpCodes.GatewayTimeout
-      ];
-      return retryableStatusCodes.includes(statusCode);
+    function getDecompressionProgram(tarPath, compressionMethod, archivePath) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
+        switch (compressionMethod) {
+          case constants_1.CompressionMethod.Zstd:
+            return BSD_TAR_ZSTD ? [
+              "zstd -d --long=30 --force -o",
+              constants_1.TarFilename,
+              archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/")
+            ] : [
+              "--use-compress-program",
+              IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30"
+            ];
+          case constants_1.CompressionMethod.ZstdWithoutLong:
+            return BSD_TAR_ZSTD ? [
+              "zstd -d --force -o",
+              constants_1.TarFilename,
+              archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/")
+            ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"];
+          default:
+            return ["-z"];
+        }
+      });
     }
-    exports2.isRetryableStatusCode = isRetryableStatusCode;
-    function sleep(milliseconds) {
+    function getCompressionProgram(tarPath, compressionMethod) {
       return __awaiter4(this, void 0, void 0, function* () {
-        return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
+        const cacheFileName = utils.getCacheFileName(compressionMethod);
+        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
+        switch (compressionMethod) {
+          case constants_1.CompressionMethod.Zstd:
+            return BSD_TAR_ZSTD ? [
+              "zstd -T0 --long=30 --force -o",
+              cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"),
+              constants_1.TarFilename
+            ] : [
+              "--use-compress-program",
+              IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30"
+            ];
+          case constants_1.CompressionMethod.ZstdWithoutLong:
+            return BSD_TAR_ZSTD ? [
+              "zstd -T0 --force -o",
+              cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"),
+              constants_1.TarFilename
+            ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"];
+          default:
+            return ["-z"];
+        }
       });
     }
-    function retry3(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = void 0) {
+    function execCommands(commands, cwd) {
       return __awaiter4(this, void 0, void 0, function* () {
-        let errorMessage = "";
-        let attempt = 1;
-        while (attempt <= maxAttempts) {
-          let response = void 0;
-          let statusCode = void 0;
-          let isRetryable = false;
+        for (const command of commands) {
           try {
-            response = yield method();
+            yield (0, exec_1.exec)(command, void 0, {
+              cwd,
+              env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" })
+            });
           } catch (error4) {
-            if (onError) {
-              response = onError(error4);
-            }
-            isRetryable = true;
-            errorMessage = error4.message;
-          }
-          if (response) {
-            statusCode = getStatusCode(response);
-            if (!isServerErrorStatusCode(statusCode)) {
-              return response;
-            }
-          }
-          if (statusCode) {
-            isRetryable = isRetryableStatusCode(statusCode);
-            errorMessage = `Cache service responded with ${statusCode}`;
-          }
-          core14.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`);
-          if (!isRetryable) {
-            core14.debug(`${name} - Error is not retryable`);
-            break;
+            throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`);
           }
-          yield sleep(delay);
-          attempt++;
         }
-        throw Error(`${name} failed: ${errorMessage}`);
       });
     }
-    exports2.retry = retry3;
-    function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) {
+    function listTar(archivePath, compressionMethod) {
       return __awaiter4(this, void 0, void 0, function* () {
-        return yield retry3(
-          name,
-          method,
-          (response) => response.statusCode,
-          maxAttempts,
-          delay,
-          // If the error object contains the statusCode property, extract it and return
-          // an TypedResponse so it can be processed by the retry logic.
-          (error4) => {
-            if (error4 instanceof http_client_1.HttpClientError) {
-              return {
-                statusCode: error4.statusCode,
-                result: null,
-                headers: {},
-                error: error4
-              };
-            } else {
-              return void 0;
-            }
-          }
-        );
+        const commands = yield getCommands(compressionMethod, "list", archivePath);
+        yield execCommands(commands);
       });
     }
-    exports2.retryTypedResponse = retryTypedResponse;
-    function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) {
+    exports2.listTar = listTar;
+    function extractTar2(archivePath, compressionMethod) {
       return __awaiter4(this, void 0, void 0, function* () {
-        return yield retry3(name, method, (response) => response.message.statusCode, maxAttempts, delay);
+        const workingDirectory = getWorkingDirectory();
+        yield io6.mkdirP(workingDirectory);
+        const commands = yield getCommands(compressionMethod, "extract", archivePath);
+        yield execCommands(commands);
       });
     }
-    exports2.retryHttpClientResponse = retryHttpClientResponse;
+    exports2.extractTar = extractTar2;
+    function createTar(archiveFolder, sourceDirectories, compressionMethod) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        (0, fs_1.writeFileSync)(path2.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n"));
+        const commands = yield getCommands(compressionMethod, "create");
+        yield execCommands(commands, archiveFolder);
+      });
+    }
+    exports2.createTar = createTar;
   }
 });
 
-// node_modules/@actions/cache/lib/internal/downloadUtils.js
-var require_downloadUtils = __commonJS({
-  "node_modules/@actions/cache/lib/internal/downloadUtils.js"(exports2) {
+// node_modules/@actions/cache/lib/cache.js
+var require_cache3 = __commonJS({
+  "node_modules/@actions/cache/lib/cache.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -105744,527 +110861,378 @@ var require_downloadUtils = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0;
+    exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0;
     var core14 = __importStar4(require_core());
-    var http_client_1 = require_lib();
-    var storage_blob_1 = require_dist7();
-    var buffer = __importStar4(require("buffer"));
-    var fs2 = __importStar4(require("fs"));
-    var stream = __importStar4(require("stream"));
-    var util = __importStar4(require("util"));
+    var path2 = __importStar4(require("path"));
     var utils = __importStar4(require_cacheUtils());
-    var constants_1 = require_constants10();
-    var requestUtils_1 = require_requestUtils2();
-    var abort_controller_1 = require_dist5();
-    function pipeResponseToStream(response, output) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const pipeline = util.promisify(stream.pipeline);
-        yield pipeline(response.message, output);
-      });
-    }
-    var DownloadProgress = class {
-      constructor(contentLength) {
-        this.contentLength = contentLength;
-        this.segmentIndex = 0;
-        this.segmentSize = 0;
-        this.segmentOffset = 0;
-        this.receivedBytes = 0;
-        this.displayedComplete = false;
-        this.startTime = Date.now();
+    var cacheHttpClient = __importStar4(require_cacheHttpClient());
+    var cacheTwirpClient = __importStar4(require_cacheTwirpClient());
+    var config_1 = require_config2();
+    var tar_1 = require_tar2();
+    var http_client_1 = require_lib7();
+    var ValidationError = class _ValidationError extends Error {
+      constructor(message) {
+        super(message);
+        this.name = "ValidationError";
+        Object.setPrototypeOf(this, _ValidationError.prototype);
       }
-      /**
-       * Progress to the next segment. Only call this method when the previous segment
-       * is complete.
-       *
-       * @param segmentSize the length of the next segment
-       */
-      nextSegment(segmentSize) {
-        this.segmentOffset = this.segmentOffset + this.segmentSize;
-        this.segmentIndex = this.segmentIndex + 1;
-        this.segmentSize = segmentSize;
-        this.receivedBytes = 0;
-        core14.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`);
+    };
+    exports2.ValidationError = ValidationError;
+    var ReserveCacheError2 = class _ReserveCacheError extends Error {
+      constructor(message) {
+        super(message);
+        this.name = "ReserveCacheError";
+        Object.setPrototypeOf(this, _ReserveCacheError.prototype);
       }
-      /**
-       * Sets the number of bytes received for the current segment.
-       *
-       * @param receivedBytes the number of bytes received
-       */
-      setReceivedBytes(receivedBytes) {
-        this.receivedBytes = receivedBytes;
+    };
+    exports2.ReserveCacheError = ReserveCacheError2;
+    var FinalizeCacheError = class _FinalizeCacheError extends Error {
+      constructor(message) {
+        super(message);
+        this.name = "FinalizeCacheError";
+        Object.setPrototypeOf(this, _FinalizeCacheError.prototype);
       }
-      /**
-       * Returns the total number of bytes transferred.
-       */
-      getTransferredBytes() {
-        return this.segmentOffset + this.receivedBytes;
+    };
+    exports2.FinalizeCacheError = FinalizeCacheError;
+    function checkPaths(paths) {
+      if (!paths || paths.length === 0) {
+        throw new ValidationError(`Path Validation Error: At least one directory or file path is required`);
       }
-      /**
-       * Returns true if the download is complete.
-       */
-      isDone() {
-        return this.getTransferredBytes() === this.contentLength;
+    }
+    function checkKey(key) {
+      if (key.length > 512) {
+        throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`);
       }
-      /**
-       * Prints the current download stats. Once the download completes, this will print one
-       * last line and then stop.
-       */
-      display() {
-        if (this.displayedComplete) {
-          return;
-        }
-        const transferredBytes = this.segmentOffset + this.receivedBytes;
-        const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1);
-        const elapsedTime = Date.now() - this.startTime;
-        const downloadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1e3)).toFixed(1);
-        core14.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`);
-        if (this.isDone()) {
-          this.displayedComplete = true;
-        }
+      const regex = /^[^,]*$/;
+      if (!regex.test(key)) {
+        throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`);
       }
-      /**
-       * Returns a function used to handle TransferProgressEvents.
-       */
-      onProgress() {
-        return (progress) => {
-          this.setReceivedBytes(progress.loadedBytes);
-        };
+    }
+    function isFeatureAvailable() {
+      const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
+      switch (cacheServiceVersion) {
+        case "v2":
+          return !!process.env["ACTIONS_RESULTS_URL"];
+        case "v1":
+        default:
+          return !!process.env["ACTIONS_CACHE_URL"];
       }
-      /**
-       * Starts the timer that displays the stats.
-       *
-       * @param delayInMs the delay between each write
-       */
-      startDisplayTimer(delayInMs = 1e3) {
-        const displayCallback = () => {
-          this.display();
-          if (!this.isDone()) {
-            this.timeoutHandle = setTimeout(displayCallback, delayInMs);
+    }
+    exports2.isFeatureAvailable = isFeatureAvailable;
+    function restoreCache4(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
+        core14.debug(`Cache service version: ${cacheServiceVersion}`);
+        checkPaths(paths);
+        switch (cacheServiceVersion) {
+          case "v2":
+            return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
+          case "v1":
+          default:
+            return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
+        }
+      });
+    }
+    exports2.restoreCache = restoreCache4;
+    function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        restoreKeys = restoreKeys || [];
+        const keys = [primaryKey, ...restoreKeys];
+        core14.debug("Resolved Keys:");
+        core14.debug(JSON.stringify(keys));
+        if (keys.length > 10) {
+          throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`);
+        }
+        for (const key of keys) {
+          checkKey(key);
+        }
+        const compressionMethod = yield utils.getCompressionMethod();
+        let archivePath = "";
+        try {
+          const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, {
+            compressionMethod,
+            enableCrossOsArchive
+          });
+          if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) {
+            return void 0;
+          }
+          if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
+            core14.info("Lookup only - skipping download");
+            return cacheEntry.cacheKey;
+          }
+          archivePath = path2.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
+          core14.debug(`Archive Path: ${archivePath}`);
+          yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options);
+          if (core14.isDebug()) {
+            yield (0, tar_1.listTar)(archivePath, compressionMethod);
+          }
+          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
+          core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
+          yield (0, tar_1.extractTar)(archivePath, compressionMethod);
+          core14.info("Cache restored successfully");
+          return cacheEntry.cacheKey;
+        } catch (error4) {
+          const typedError = error4;
+          if (typedError.name === ValidationError.name) {
+            throw error4;
+          } else {
+            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
+              core14.error(`Failed to restore: ${error4.message}`);
+            } else {
+              core14.warning(`Failed to restore: ${error4.message}`);
+            }
+          }
+        } finally {
+          try {
+            yield utils.unlinkFile(archivePath);
+          } catch (error4) {
+            core14.debug(`Failed to delete archive: ${error4}`);
+          }
+        }
+        return void 0;
+      });
+    }
+    function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        options = Object.assign(Object.assign({}, options), { useAzureSdk: true });
+        restoreKeys = restoreKeys || [];
+        const keys = [primaryKey, ...restoreKeys];
+        core14.debug("Resolved Keys:");
+        core14.debug(JSON.stringify(keys));
+        if (keys.length > 10) {
+          throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`);
+        }
+        for (const key of keys) {
+          checkKey(key);
+        }
+        let archivePath = "";
+        try {
+          const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
+          const compressionMethod = yield utils.getCompressionMethod();
+          const request = {
+            key: primaryKey,
+            restoreKeys,
+            version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive)
+          };
+          const response = yield twirpClient.GetCacheEntryDownloadURL(request);
+          if (!response.ok) {
+            core14.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`);
+            return void 0;
+          }
+          const isRestoreKeyMatch = request.key !== response.matchedKey;
+          if (isRestoreKeyMatch) {
+            core14.info(`Cache hit for restore-key: ${response.matchedKey}`);
+          } else {
+            core14.info(`Cache hit for: ${response.matchedKey}`);
+          }
+          if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
+            core14.info("Lookup only - skipping download");
+            return response.matchedKey;
+          }
+          archivePath = path2.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
+          core14.debug(`Archive path: ${archivePath}`);
+          core14.debug(`Starting download of archive to: ${archivePath}`);
+          yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options);
+          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
+          core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
+          if (core14.isDebug()) {
+            yield (0, tar_1.listTar)(archivePath, compressionMethod);
+          }
+          yield (0, tar_1.extractTar)(archivePath, compressionMethod);
+          core14.info("Cache restored successfully");
+          return response.matchedKey;
+        } catch (error4) {
+          const typedError = error4;
+          if (typedError.name === ValidationError.name) {
+            throw error4;
+          } else {
+            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
+              core14.error(`Failed to restore: ${error4.message}`);
+            } else {
+              core14.warning(`Failed to restore: ${error4.message}`);
+            }
+          }
+        } finally {
+          try {
+            if (archivePath) {
+              yield utils.unlinkFile(archivePath);
+            }
+          } catch (error4) {
+            core14.debug(`Failed to delete archive: ${error4}`);
           }
-        };
-        this.timeoutHandle = setTimeout(displayCallback, delayInMs);
-      }
-      /**
-       * Stops the timer that displays the stats. As this typically indicates the download
-       * is complete, this will display one last line, unless the last line has already
-       * been written.
-       */
-      stopDisplayTimer() {
-        if (this.timeoutHandle) {
-          clearTimeout(this.timeoutHandle);
-          this.timeoutHandle = void 0;
         }
-        this.display();
-      }
-    };
-    exports2.DownloadProgress = DownloadProgress;
-    function downloadCacheHttpClient(archiveLocation, archivePath) {
+        return void 0;
+      });
+    }
+    function saveCache4(paths, key, options, enableCrossOsArchive = false) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const writeStream = fs2.createWriteStream(archivePath);
-        const httpClient = new http_client_1.HttpClient("actions/cache");
-        const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter4(this, void 0, void 0, function* () {
-          return httpClient.get(archiveLocation);
-        }));
-        downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => {
-          downloadResponse.message.destroy();
-          core14.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`);
-        });
-        yield pipeResponseToStream(downloadResponse, writeStream);
-        const contentLengthHeader = downloadResponse.message.headers["content-length"];
-        if (contentLengthHeader) {
-          const expectedLength = parseInt(contentLengthHeader);
-          const actualLength = utils.getArchiveFileSizeInBytes(archivePath);
-          if (actualLength !== expectedLength) {
-            throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`);
-          }
-        } else {
-          core14.debug("Unable to validate download, no Content-Length header");
+        const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
+        core14.debug(`Cache service version: ${cacheServiceVersion}`);
+        checkPaths(paths);
+        checkKey(key);
+        switch (cacheServiceVersion) {
+          case "v2":
+            return yield saveCacheV2(paths, key, options, enableCrossOsArchive);
+          case "v1":
+          default:
+            return yield saveCacheV1(paths, key, options, enableCrossOsArchive);
         }
       });
     }
-    exports2.downloadCacheHttpClient = downloadCacheHttpClient;
-    function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) {
-      var _a;
+    exports2.saveCache = saveCache4;
+    function saveCacheV1(paths, key, options, enableCrossOsArchive = false) {
+      var _a, _b, _c, _d, _e;
       return __awaiter4(this, void 0, void 0, function* () {
-        const archiveDescriptor = yield fs2.promises.open(archivePath, "w");
-        const httpClient = new http_client_1.HttpClient("actions/cache", void 0, {
-          socketTimeout: options.timeoutInMs,
-          keepAlive: true
-        });
+        const compressionMethod = yield utils.getCompressionMethod();
+        let cacheId = -1;
+        const cachePaths = yield utils.resolvePaths(paths);
+        core14.debug("Cache Paths:");
+        core14.debug(`${JSON.stringify(cachePaths)}`);
+        if (cachePaths.length === 0) {
+          throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);
+        }
+        const archiveFolder = yield utils.createTempDirectory();
+        const archivePath = path2.join(archiveFolder, utils.getCacheFileName(compressionMethod));
+        core14.debug(`Archive Path: ${archivePath}`);
         try {
-          const res = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCacheMetadata", () => __awaiter4(this, void 0, void 0, function* () {
-            return yield httpClient.request("HEAD", archiveLocation, null, {});
-          }));
-          const lengthHeader = res.message.headers["content-length"];
-          if (lengthHeader === void 0 || lengthHeader === null) {
-            throw new Error("Content-Length not found on blob response");
-          }
-          const length = parseInt(lengthHeader);
-          if (Number.isNaN(length)) {
-            throw new Error(`Could not interpret Content-Length: ${length}`);
+          yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
+          if (core14.isDebug()) {
+            yield (0, tar_1.listTar)(archivePath, compressionMethod);
           }
-          const downloads = [];
-          const blockSize = 4 * 1024 * 1024;
-          for (let offset = 0; offset < length; offset += blockSize) {
-            const count = Math.min(blockSize, length - offset);
-            downloads.push({
-              offset,
-              promiseGetter: () => __awaiter4(this, void 0, void 0, function* () {
-                return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count);
-              })
-            });
+          const fileSizeLimit = 10 * 1024 * 1024 * 1024;
+          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
+          core14.debug(`File Size: ${archiveFileSize}`);
+          if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) {
+            throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`);
           }
-          downloads.reverse();
-          let actives = 0;
-          let bytesDownloaded = 0;
-          const progress = new DownloadProgress(length);
-          progress.startDisplayTimer();
-          const progressFn = progress.onProgress();
-          const activeDownloads = [];
-          let nextDownload;
-          const waitAndWrite = () => __awaiter4(this, void 0, void 0, function* () {
-            const segment = yield Promise.race(Object.values(activeDownloads));
-            yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset);
-            actives--;
-            delete activeDownloads[segment.offset];
-            bytesDownloaded += segment.count;
-            progressFn({ loadedBytes: bytesDownloaded });
+          core14.debug("Reserving Cache");
+          const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, {
+            compressionMethod,
+            enableCrossOsArchive,
+            cacheSize: archiveFileSize
           });
-          while (nextDownload = downloads.pop()) {
-            activeDownloads[nextDownload.offset] = nextDownload.promiseGetter();
-            actives++;
-            if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) {
-              yield waitAndWrite();
-            }
+          if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) {
+            cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId;
+          } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) {
+            throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`);
+          } else {
+            throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`);
           }
-          while (actives > 0) {
-            yield waitAndWrite();
+          core14.debug(`Saving Cache (ID: ${cacheId})`);
+          yield cacheHttpClient.saveCache(cacheId, archivePath, "", options);
+        } catch (error4) {
+          const typedError = error4;
+          if (typedError.name === ValidationError.name) {
+            throw error4;
+          } else if (typedError.name === ReserveCacheError2.name) {
+            core14.info(`Failed to save: ${typedError.message}`);
+          } else {
+            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
+              core14.error(`Failed to save: ${typedError.message}`);
+            } else {
+              core14.warning(`Failed to save: ${typedError.message}`);
+            }
           }
         } finally {
-          httpClient.dispose();
-          yield archiveDescriptor.close();
-        }
-      });
-    }
-    exports2.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent;
-    function downloadSegmentRetry(httpClient, archiveLocation, offset, count) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const retries = 5;
-        let failures = 0;
-        while (true) {
           try {
-            const timeout = 3e4;
-            const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count));
-            if (typeof result === "string") {
-              throw new Error("downloadSegmentRetry failed due to timeout");
-            }
-            return result;
-          } catch (err) {
-            if (failures >= retries) {
-              throw err;
-            }
-            failures++;
+            yield utils.unlinkFile(archivePath);
+          } catch (error4) {
+            core14.debug(`Failed to delete archive: ${error4}`);
           }
         }
+        return cacheId;
       });
     }
-    function downloadSegment(httpClient, archiveLocation, offset, count) {
+    function saveCacheV2(paths, key, options, enableCrossOsArchive = false) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const partRes = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCachePart", () => __awaiter4(this, void 0, void 0, function* () {
-          return yield httpClient.get(archiveLocation, {
-            Range: `bytes=${offset}-${offset + count - 1}`
-          });
-        }));
-        if (!partRes.readBodyBuffer) {
-          throw new Error("Expected HttpClientResponse to implement readBodyBuffer");
+        options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true });
+        const compressionMethod = yield utils.getCompressionMethod();
+        const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
+        let cacheId = -1;
+        const cachePaths = yield utils.resolvePaths(paths);
+        core14.debug("Cache Paths:");
+        core14.debug(`${JSON.stringify(cachePaths)}`);
+        if (cachePaths.length === 0) {
+          throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);
         }
-        return {
-          offset,
-          count,
-          buffer: yield partRes.readBodyBuffer()
-        };
-      });
-    }
-    function downloadCacheStorageSDK(archiveLocation, archivePath, options) {
-      var _a;
-      return __awaiter4(this, void 0, void 0, function* () {
-        const client = new storage_blob_1.BlockBlobClient(archiveLocation, void 0, {
-          retryOptions: {
-            // Override the timeout used when downloading each 4 MB chunk
-            // The default is 2 min / MB, which is way too slow
-            tryTimeoutInMs: options.timeoutInMs
+        const archiveFolder = yield utils.createTempDirectory();
+        const archivePath = path2.join(archiveFolder, utils.getCacheFileName(compressionMethod));
+        core14.debug(`Archive Path: ${archivePath}`);
+        try {
+          yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
+          if (core14.isDebug()) {
+            yield (0, tar_1.listTar)(archivePath, compressionMethod);
           }
-        });
-        const properties = yield client.getProperties();
-        const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1;
-        if (contentLength < 0) {
-          core14.debug("Unable to determine content length, downloading file with http-client...");
-          yield downloadCacheHttpClient(archiveLocation, archivePath);
-        } else {
-          const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH);
-          const downloadProgress = new DownloadProgress(contentLength);
-          const fd = fs2.openSync(archivePath, "w");
+          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
+          core14.debug(`File Size: ${archiveFileSize}`);
+          options.archiveSizeBytes = archiveFileSize;
+          core14.debug("Reserving Cache");
+          const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive);
+          const request = {
+            key,
+            version
+          };
+          let signedUploadUrl;
           try {
-            downloadProgress.startDisplayTimer();
-            const controller = new abort_controller_1.AbortController();
-            const abortSignal = controller.signal;
-            while (!downloadProgress.isDone()) {
-              const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize;
-              const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart);
-              downloadProgress.nextSegment(segmentSize);
-              const result = yield promiseWithTimeout(options.segmentTimeoutInMs || 36e5, client.downloadToBuffer(segmentStart, segmentSize, {
-                abortSignal,
-                concurrency: options.downloadConcurrency,
-                onProgress: downloadProgress.onProgress()
-              }));
-              if (result === "timeout") {
-                controller.abort();
-                throw new Error("Aborting cache download as the download time exceeded the timeout.");
-              } else if (Buffer.isBuffer(result)) {
-                fs2.writeFileSync(fd, result);
+            const response = yield twirpClient.CreateCacheEntry(request);
+            if (!response.ok) {
+              if (response.message) {
+                core14.warning(`Cache reservation failed: ${response.message}`);
               }
+              throw new Error(response.message || "Response was not ok");
             }
-          } finally {
-            downloadProgress.stopDisplayTimer();
-            fs2.closeSync(fd);
+            signedUploadUrl = response.signedUploadUrl;
+          } catch (error4) {
+            core14.debug(`Failed to reserve cache: ${error4}`);
+            throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache.`);
           }
-        }
-      });
-    }
-    exports2.downloadCacheStorageSDK = downloadCacheStorageSDK;
-    var promiseWithTimeout = (timeoutMs, promise) => __awaiter4(void 0, void 0, void 0, function* () {
-      let timeoutHandle;
-      const timeoutPromise = new Promise((resolve2) => {
-        timeoutHandle = setTimeout(() => resolve2("timeout"), timeoutMs);
-      });
-      return Promise.race([promise, timeoutPromise]).then((result) => {
-        clearTimeout(timeoutHandle);
-        return result;
-      });
-    });
-  }
-});
-
-// node_modules/@actions/cache/lib/options.js
-var require_options = __commonJS({
-  "node_modules/@actions/cache/lib/options.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getDownloadOptions = exports2.getUploadOptions = void 0;
-    var core14 = __importStar4(require_core());
-    function getUploadOptions(copy) {
-      const result = {
-        useAzureSdk: false,
-        uploadConcurrency: 4,
-        uploadChunkSize: 32 * 1024 * 1024
-      };
-      if (copy) {
-        if (typeof copy.useAzureSdk === "boolean") {
-          result.useAzureSdk = copy.useAzureSdk;
-        }
-        if (typeof copy.uploadConcurrency === "number") {
-          result.uploadConcurrency = copy.uploadConcurrency;
-        }
-        if (typeof copy.uploadChunkSize === "number") {
-          result.uploadChunkSize = copy.uploadChunkSize;
-        }
-      }
-      result.uploadConcurrency = !isNaN(Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) ? Math.min(32, Number(process.env["CACHE_UPLOAD_CONCURRENCY"])) : result.uploadConcurrency;
-      result.uploadChunkSize = !isNaN(Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"])) ? Math.min(128 * 1024 * 1024, Number(process.env["CACHE_UPLOAD_CHUNK_SIZE"]) * 1024 * 1024) : result.uploadChunkSize;
-      core14.debug(`Use Azure SDK: ${result.useAzureSdk}`);
-      core14.debug(`Upload concurrency: ${result.uploadConcurrency}`);
-      core14.debug(`Upload chunk size: ${result.uploadChunkSize}`);
-      return result;
-    }
-    exports2.getUploadOptions = getUploadOptions;
-    function getDownloadOptions(copy) {
-      const result = {
-        useAzureSdk: false,
-        concurrentBlobDownloads: true,
-        downloadConcurrency: 8,
-        timeoutInMs: 3e4,
-        segmentTimeoutInMs: 6e5,
-        lookupOnly: false
-      };
-      if (copy) {
-        if (typeof copy.useAzureSdk === "boolean") {
-          result.useAzureSdk = copy.useAzureSdk;
-        }
-        if (typeof copy.concurrentBlobDownloads === "boolean") {
-          result.concurrentBlobDownloads = copy.concurrentBlobDownloads;
-        }
-        if (typeof copy.downloadConcurrency === "number") {
-          result.downloadConcurrency = copy.downloadConcurrency;
-        }
-        if (typeof copy.timeoutInMs === "number") {
-          result.timeoutInMs = copy.timeoutInMs;
-        }
-        if (typeof copy.segmentTimeoutInMs === "number") {
-          result.segmentTimeoutInMs = copy.segmentTimeoutInMs;
-        }
-        if (typeof copy.lookupOnly === "boolean") {
-          result.lookupOnly = copy.lookupOnly;
-        }
-      }
-      const segmentDownloadTimeoutMins = process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"];
-      if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) {
-        result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1e3;
-      }
-      core14.debug(`Use Azure SDK: ${result.useAzureSdk}`);
-      core14.debug(`Download concurrency: ${result.downloadConcurrency}`);
-      core14.debug(`Request timeout (ms): ${result.timeoutInMs}`);
-      core14.debug(`Cache segment download timeout mins env var: ${process.env["SEGMENT_DOWNLOAD_TIMEOUT_MINS"]}`);
-      core14.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`);
-      core14.debug(`Lookup only: ${result.lookupOnly}`);
-      return result;
-    }
-    exports2.getDownloadOptions = getDownloadOptions;
-  }
-});
-
-// node_modules/@actions/cache/lib/internal/config.js
-var require_config2 = __commonJS({
-  "node_modules/@actions/cache/lib/internal/config.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getCacheServiceURL = exports2.getCacheServiceVersion = exports2.isGhes = void 0;
-    function isGhes() {
-      const ghUrl = new URL(process.env["GITHUB_SERVER_URL"] || "https://github.com");
-      const hostname = ghUrl.hostname.trimEnd().toUpperCase();
-      const isGitHubHost = hostname === "GITHUB.COM";
-      const isGheHost = hostname.endsWith(".GHE.COM");
-      const isLocalHost = hostname.endsWith(".LOCALHOST");
-      return !isGitHubHost && !isGheHost && !isLocalHost;
-    }
-    exports2.isGhes = isGhes;
-    function getCacheServiceVersion() {
-      if (isGhes())
-        return "v1";
-      return process.env["ACTIONS_CACHE_SERVICE_V2"] ? "v2" : "v1";
-    }
-    exports2.getCacheServiceVersion = getCacheServiceVersion;
-    function getCacheServiceURL() {
-      const version = getCacheServiceVersion();
-      switch (version) {
-        case "v1":
-          return process.env["ACTIONS_CACHE_URL"] || process.env["ACTIONS_RESULTS_URL"] || "";
-        case "v2":
-          return process.env["ACTIONS_RESULTS_URL"] || "";
-        default:
-          throw new Error(`Unsupported cache service version: ${version}`);
-      }
-    }
-    exports2.getCacheServiceURL = getCacheServiceURL;
-  }
-});
-
-// node_modules/@actions/cache/package.json
-var require_package3 = __commonJS({
-  "node_modules/@actions/cache/package.json"(exports2, module2) {
-    module2.exports = {
-      name: "@actions/cache",
-      version: "4.1.0",
-      preview: true,
-      description: "Actions cache lib",
-      keywords: [
-        "github",
-        "actions",
-        "cache"
-      ],
-      homepage: "https://github.com/actions/toolkit/tree/main/packages/cache",
-      license: "MIT",
-      main: "lib/cache.js",
-      types: "lib/cache.d.ts",
-      directories: {
-        lib: "lib",
-        test: "__tests__"
-      },
-      files: [
-        "lib",
-        "!.DS_Store"
-      ],
-      publishConfig: {
-        access: "public"
-      },
-      repository: {
-        type: "git",
-        url: "git+https://github.com/actions/toolkit.git",
-        directory: "packages/cache"
-      },
-      scripts: {
-        "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json",
-        test: 'echo "Error: run tests from root" && exit 1',
-        tsc: "tsc"
-      },
-      bugs: {
-        url: "https://github.com/actions/toolkit/issues"
-      },
-      dependencies: {
-        "@actions/core": "^1.11.1",
-        "@actions/exec": "^1.0.1",
-        "@actions/glob": "^0.1.0",
-        "@protobuf-ts/runtime-rpc": "^2.11.1",
-        "@actions/http-client": "^2.1.1",
-        "@actions/io": "^1.0.1",
-        "@azure/abort-controller": "^1.1.0",
-        "@azure/ms-rest-js": "^2.6.0",
-        "@azure/storage-blob": "^12.13.0",
-        semver: "^6.3.1"
-      },
-      devDependencies: {
-        "@types/node": "^22.13.9",
-        "@types/semver": "^6.0.0",
-        "@protobuf-ts/plugin": "^2.9.4",
-        typescript: "^5.2.2"
-      }
-    };
-  }
-});
-
-// node_modules/@actions/cache/lib/internal/shared/user-agent.js
-var require_user_agent2 = __commonJS({
-  "node_modules/@actions/cache/lib/internal/shared/user-agent.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getUserAgentString = void 0;
-    var packageJson = require_package3();
-    function getUserAgentString() {
-      return `@actions/cache-${packageJson.version}`;
+          core14.debug(`Attempting to upload cache located at: ${archivePath}`);
+          yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options);
+          const finalizeRequest = {
+            key,
+            version,
+            sizeBytes: `${archiveFileSize}`
+          };
+          const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest);
+          core14.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`);
+          if (!finalizeResponse.ok) {
+            if (finalizeResponse.message) {
+              throw new FinalizeCacheError(finalizeResponse.message);
+            }
+            throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`);
+          }
+          cacheId = parseInt(finalizeResponse.entryId);
+        } catch (error4) {
+          const typedError = error4;
+          if (typedError.name === ValidationError.name) {
+            throw error4;
+          } else if (typedError.name === ReserveCacheError2.name) {
+            core14.info(`Failed to save: ${typedError.message}`);
+          } else if (typedError.name === FinalizeCacheError.name) {
+            core14.warning(typedError.message);
+          } else {
+            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
+              core14.error(`Failed to save: ${typedError.message}`);
+            } else {
+              core14.warning(`Failed to save: ${typedError.message}`);
+            }
+          }
+        } finally {
+          try {
+            yield utils.unlinkFile(archivePath);
+          } catch (error4) {
+            core14.debug(`Failed to delete archive: ${error4}`);
+          }
+        }
+        return cacheId;
+      });
     }
-    exports2.getUserAgentString = getUserAgentString;
   }
 });
 
-// node_modules/@actions/cache/lib/internal/cacheHttpClient.js
-var require_cacheHttpClient = __commonJS({
-  "node_modules/@actions/cache/lib/internal/cacheHttpClient.js"(exports2) {
+// node_modules/@actions/tool-cache/lib/manifest.js
+var require_manifest = __commonJS({
+  "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -106321,955 +111289,818 @@ var require_cacheHttpClient = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0;
-    var core14 = __importStar4(require_core());
-    var http_client_1 = require_lib();
-    var auth_1 = require_auth();
-    var fs2 = __importStar4(require("fs"));
-    var url_1 = require("url");
-    var utils = __importStar4(require_cacheUtils());
-    var uploadUtils_1 = require_uploadUtils();
-    var downloadUtils_1 = require_downloadUtils();
-    var options_1 = require_options();
-    var requestUtils_1 = require_requestUtils2();
-    var config_1 = require_config2();
-    var user_agent_1 = require_user_agent2();
-    function getCacheApiUrl(resource) {
-      const baseUrl = (0, config_1.getCacheServiceURL)();
-      if (!baseUrl) {
-        throw new Error("Cache Service Url not found, unable to restore cache.");
-      }
-      const url = `${baseUrl}_apis/artifactcache/${resource}`;
-      core14.debug(`Resource Url: ${url}`);
-      return url;
-    }
-    function createAcceptHeader(type2, apiVersion) {
-      return `${type2};api-version=${apiVersion}`;
-    }
-    function getRequestOptions() {
-      const requestOptions = {
-        headers: {
-          Accept: createAcceptHeader("application/json", "6.0-preview.1")
-        }
-      };
-      return requestOptions;
-    }
-    function createHttpClient() {
-      const token = process.env["ACTIONS_RUNTIME_TOKEN"] || "";
-      const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token);
-      return new http_client_1.HttpClient((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions());
-    }
-    function getCacheEntry(keys, paths, options) {
+    exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0;
+    var semver8 = __importStar4(require_semver2());
+    var core_1 = require_core();
+    var os = require("os");
+    var cp = require("child_process");
+    var fs2 = require("fs");
+    function _findMatch(versionSpec, stable, candidates, archFilter) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const httpClient = createHttpClient();
-        const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
-        const resource = `cache?keys=${encodeURIComponent(keys.join(","))}&version=${version}`;
-        const response = yield (0, requestUtils_1.retryTypedResponse)("getCacheEntry", () => __awaiter4(this, void 0, void 0, function* () {
-          return httpClient.getJson(getCacheApiUrl(resource));
-        }));
-        if (response.statusCode === 204) {
-          if (core14.isDebug()) {
-            yield printCachesListForDiagnostics(keys[0], httpClient, version);
+        const platFilter = os.platform();
+        let result;
+        let match;
+        let file;
+        for (const candidate of candidates) {
+          const version = candidate.version;
+          (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`);
+          if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) {
+            file = candidate.files.find((item) => {
+              (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`);
+              let chk = item.arch === archFilter && item.platform === platFilter;
+              if (chk && item.platform_version) {
+                const osVersion = module2.exports._getOsVersion();
+                if (osVersion === item.platform_version) {
+                  chk = true;
+                } else {
+                  chk = semver8.satisfies(osVersion, item.platform_version);
+                }
+              }
+              return chk;
+            });
+            if (file) {
+              (0, core_1.debug)(`matched ${candidate.version}`);
+              match = candidate;
+              break;
+            }
           }
-          return null;
-        }
-        if (!(0, requestUtils_1.isSuccessStatusCode)(response.statusCode)) {
-          throw new Error(`Cache service responded with ${response.statusCode}`);
         }
-        const cacheResult = response.result;
-        const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation;
-        if (!cacheDownloadUrl) {
-          throw new Error("Cache not found.");
+        if (match && file) {
+          result = Object.assign({}, match);
+          result.files = [file];
         }
-        core14.setSecret(cacheDownloadUrl);
-        core14.debug(`Cache Result:`);
-        core14.debug(JSON.stringify(cacheResult));
-        return cacheResult;
+        return result;
       });
     }
-    exports2.getCacheEntry = getCacheEntry;
-    function printCachesListForDiagnostics(key, httpClient, version) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const resource = `caches?key=${encodeURIComponent(key)}`;
-        const response = yield (0, requestUtils_1.retryTypedResponse)("listCache", () => __awaiter4(this, void 0, void 0, function* () {
-          return httpClient.getJson(getCacheApiUrl(resource));
-        }));
-        if (response.statusCode === 200) {
-          const cacheListResult = response.result;
-          const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount;
-          if (totalCount && totalCount > 0) {
-            core14.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env["GITHUB_REF"]}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key 
-Other caches with similar key:`);
-            for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) {
-              core14.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`);
+    exports2._findMatch = _findMatch;
+    function _getOsVersion() {
+      const plat = os.platform();
+      let version = "";
+      if (plat === "darwin") {
+        version = cp.execSync("sw_vers -productVersion").toString();
+      } else if (plat === "linux") {
+        const lsbContents = module2.exports._readLinuxVersionFile();
+        if (lsbContents) {
+          const lines = lsbContents.split("\n");
+          for (const line of lines) {
+            const parts = line.split("=");
+            if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) {
+              version = parts[1].trim().replace(/^"/, "").replace(/"$/, "");
+              break;
             }
           }
         }
-      });
-    }
-    function downloadCache(archiveLocation, archivePath, options) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const archiveUrl = new url_1.URL(archiveLocation);
-        const downloadOptions = (0, options_1.getDownloadOptions)(options);
-        if (archiveUrl.hostname.endsWith(".blob.core.windows.net")) {
-          if (downloadOptions.useAzureSdk) {
-            yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions);
-          } else if (downloadOptions.concurrentBlobDownloads) {
-            yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions);
-          } else {
-            yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath);
-          }
-        } else {
-          yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath);
-        }
-      });
-    }
-    exports2.downloadCache = downloadCache;
-    function reserveCache(key, paths, options) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const httpClient = createHttpClient();
-        const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
-        const reserveCacheRequest = {
-          key,
-          version,
-          cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize
-        };
-        const response = yield (0, requestUtils_1.retryTypedResponse)("reserveCache", () => __awaiter4(this, void 0, void 0, function* () {
-          return httpClient.postJson(getCacheApiUrl("caches"), reserveCacheRequest);
-        }));
-        return response;
-      });
+      }
+      return version;
     }
-    exports2.reserveCache = reserveCache;
-    function getContentRange(start, end) {
-      return `bytes ${start}-${end}/*`;
+    exports2._getOsVersion = _getOsVersion;
+    function _readLinuxVersionFile() {
+      const lsbReleaseFile = "/etc/lsb-release";
+      const osReleaseFile = "/etc/os-release";
+      let contents = "";
+      if (fs2.existsSync(lsbReleaseFile)) {
+        contents = fs2.readFileSync(lsbReleaseFile).toString();
+      } else if (fs2.existsSync(osReleaseFile)) {
+        contents = fs2.readFileSync(osReleaseFile).toString();
+      }
+      return contents;
     }
-    function uploadChunk(httpClient, resourceUrl, openStream, start, end) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        core14.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`);
-        const additionalHeaders = {
-          "Content-Type": "application/octet-stream",
-          "Content-Range": getContentRange(start, end)
-        };
-        const uploadChunkResponse = yield (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter4(this, void 0, void 0, function* () {
-          return httpClient.sendStream("PATCH", resourceUrl, openStream(), additionalHeaders);
-        }));
-        if (!(0, requestUtils_1.isSuccessStatusCode)(uploadChunkResponse.message.statusCode)) {
-          throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`);
+    exports2._readLinuxVersionFile = _readLinuxVersionFile;
+  }
+});
+
+// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js
+var require_proxy6 = __commonJS({
+  "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.checkBypass = exports2.getProxyUrl = void 0;
+    function getProxyUrl(reqUrl) {
+      const usingSsl = reqUrl.protocol === "https:";
+      if (checkBypass(reqUrl)) {
+        return void 0;
+      }
+      const proxyVar = (() => {
+        if (usingSsl) {
+          return process.env["https_proxy"] || process.env["HTTPS_PROXY"];
+        } else {
+          return process.env["http_proxy"] || process.env["HTTP_PROXY"];
         }
-      });
-    }
-    function uploadFile(httpClient, cacheId, archivePath, options) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const fileSize = utils.getArchiveFileSizeInBytes(archivePath);
-        const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`);
-        const fd = fs2.openSync(archivePath, "r");
-        const uploadOptions = (0, options_1.getUploadOptions)(options);
-        const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency);
-        const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize);
-        const parallelUploads = [...new Array(concurrency).keys()];
-        core14.debug("Awaiting all uploads");
-        let offset = 0;
+      })();
+      if (proxyVar) {
         try {
-          yield Promise.all(parallelUploads.map(() => __awaiter4(this, void 0, void 0, function* () {
-            while (offset < fileSize) {
-              const chunkSize = Math.min(fileSize - offset, maxChunkSize);
-              const start = offset;
-              const end = offset + chunkSize - 1;
-              offset += maxChunkSize;
-              yield uploadChunk(httpClient, resourceUrl, () => fs2.createReadStream(archivePath, {
-                fd,
-                start,
-                end,
-                autoClose: false
-              }).on("error", (error4) => {
-                throw new Error(`Cache upload failed because file read failed with ${error4.message}`);
-              }), start, end);
-            }
-          })));
-        } finally {
-          fs2.closeSync(fd);
+          return new DecodedURL(proxyVar);
+        } catch (_a) {
+          if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://"))
+            return new DecodedURL(`http://${proxyVar}`);
         }
-        return;
-      });
-    }
-    function commitCache(httpClient, cacheId, filesize) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const commitCacheRequest = { size: filesize };
-        return yield (0, requestUtils_1.retryTypedResponse)("commitCache", () => __awaiter4(this, void 0, void 0, function* () {
-          return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest);
-        }));
-      });
+      } else {
+        return void 0;
+      }
     }
-    function saveCache4(cacheId, archivePath, signedUploadURL, options) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const uploadOptions = (0, options_1.getUploadOptions)(options);
-        if (uploadOptions.useAzureSdk) {
-          if (!signedUploadURL) {
-            throw new Error("Azure Storage SDK can only be used when a signed URL is provided.");
-          }
-          yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options);
-        } else {
-          const httpClient = createHttpClient();
-          core14.debug("Upload cache");
-          yield uploadFile(httpClient, cacheId, archivePath, options);
-          core14.debug("Commiting cache");
-          const cacheSize = utils.getArchiveFileSizeInBytes(archivePath);
-          core14.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`);
-          const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize);
-          if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) {
-            throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`);
-          }
-          core14.info("Cache saved successfully");
+    exports2.getProxyUrl = getProxyUrl;
+    function checkBypass(reqUrl) {
+      if (!reqUrl.hostname) {
+        return false;
+      }
+      const reqHost = reqUrl.hostname;
+      if (isLoopbackAddress(reqHost)) {
+        return true;
+      }
+      const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || "";
+      if (!noProxy) {
+        return false;
+      }
+      let reqPort;
+      if (reqUrl.port) {
+        reqPort = Number(reqUrl.port);
+      } else if (reqUrl.protocol === "http:") {
+        reqPort = 80;
+      } else if (reqUrl.protocol === "https:") {
+        reqPort = 443;
+      }
+      const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+      if (typeof reqPort === "number") {
+        upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
+      }
+      for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) {
+        if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) {
+          return true;
         }
-      });
+      }
+      return false;
     }
-    exports2.saveCache = saveCache4;
+    exports2.checkBypass = checkBypass;
+    function isLoopbackAddress(host) {
+      const hostLower = host.toLowerCase();
+      return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]");
+    }
+    var DecodedURL = class extends URL {
+      constructor(url, base) {
+        super(url, base);
+        this._decodedUsername = decodeURIComponent(super.username);
+        this._decodedPassword = decodeURIComponent(super.password);
+      }
+      get username() {
+        return this._decodedUsername;
+      }
+      get password() {
+        return this._decodedPassword;
+      }
+    };
   }
 });
 
-// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js
-var require_cachescope = __commonJS({
-  "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) {
+// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js
+var require_lib8 = __commonJS({
+  "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.CacheScope = void 0;
-    var runtime_1 = require_commonjs();
-    var runtime_2 = require_commonjs();
-    var runtime_3 = require_commonjs();
-    var runtime_4 = require_commonjs();
-    var runtime_5 = require_commonjs();
-    var CacheScope$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.entities.v1.CacheScope", [
-          {
-            no: 1,
-            name: "scope",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 2,
-            name: "permission",
-            kind: "scalar",
-            T: 3
-            /*ScalarType.INT64*/
-          }
-        ]);
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      create(value) {
-        const message = { scope: "", permission: "0" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* string scope */
-            1:
-              message.scope = reader.string();
-              break;
-            case /* int64 permission */
-            2:
-              message.permission = reader.int64().toString();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve2) {
+          resolve2(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve2, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
           }
         }
-        return message;
-      }
-      internalBinaryWrite(message, writer, options) {
-        if (message.scope !== "")
-          writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope);
-        if (message.permission !== "0")
-          writer.tag(2, runtime_1.WireType.Varint).int64(message.permission);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0;
+    var http = __importStar4(require("http"));
+    var https2 = __importStar4(require("https"));
+    var pm = __importStar4(require_proxy6());
+    var tunnel = __importStar4(require_tunnel2());
+    var undici_1 = require_undici();
+    var HttpCodes;
+    (function(HttpCodes2) {
+      HttpCodes2[HttpCodes2["OK"] = 200] = "OK";
+      HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices";
+      HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently";
+      HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved";
+      HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther";
+      HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified";
+      HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy";
+      HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy";
+      HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+      HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect";
+      HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest";
+      HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized";
+      HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired";
+      HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden";
+      HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound";
+      HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+      HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable";
+      HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+      HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout";
+      HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict";
+      HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone";
+      HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests";
+      HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError";
+      HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented";
+      HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway";
+      HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+      HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout";
+    })(HttpCodes || (exports2.HttpCodes = HttpCodes = {}));
+    var Headers;
+    (function(Headers2) {
+      Headers2["Accept"] = "accept";
+      Headers2["ContentType"] = "content-type";
+    })(Headers || (exports2.Headers = Headers = {}));
+    var MediaTypes;
+    (function(MediaTypes2) {
+      MediaTypes2["ApplicationJson"] = "application/json";
+    })(MediaTypes || (exports2.MediaTypes = MediaTypes = {}));
+    function getProxyUrl(serverUrl) {
+      const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+      return proxyUrl ? proxyUrl.href : "";
+    }
+    exports2.getProxyUrl = getProxyUrl;
+    var HttpRedirectCodes = [
+      HttpCodes.MovedPermanently,
+      HttpCodes.ResourceMoved,
+      HttpCodes.SeeOther,
+      HttpCodes.TemporaryRedirect,
+      HttpCodes.PermanentRedirect
+    ];
+    var HttpResponseRetryCodes = [
+      HttpCodes.BadGateway,
+      HttpCodes.ServiceUnavailable,
+      HttpCodes.GatewayTimeout
+    ];
+    var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"];
+    var ExponentialBackoffCeiling = 10;
+    var ExponentialBackoffTimeSlice = 5;
+    var HttpClientError = class _HttpClientError extends Error {
+      constructor(message, statusCode) {
+        super(message);
+        this.name = "HttpClientError";
+        this.statusCode = statusCode;
+        Object.setPrototypeOf(this, _HttpClientError.prototype);
       }
     };
-    exports2.CacheScope = new CacheScope$Type();
-  }
-});
-
-// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js
-var require_cachemetadata = __commonJS({
-  "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.CacheMetadata = void 0;
-    var runtime_1 = require_commonjs();
-    var runtime_2 = require_commonjs();
-    var runtime_3 = require_commonjs();
-    var runtime_4 = require_commonjs();
-    var runtime_5 = require_commonjs();
-    var cachescope_1 = require_cachescope();
-    var CacheMetadata$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.entities.v1.CacheMetadata", [
-          {
-            no: 1,
-            name: "repository_id",
-            kind: "scalar",
-            T: 3
-            /*ScalarType.INT64*/
-          },
-          { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope }
-        ]);
+    exports2.HttpClientError = HttpClientError;
+    var HttpClientResponse = class {
+      constructor(message) {
+        this.message = message;
       }
-      create(value) {
-        const message = { repositoryId: "0", scope: [] };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      readBody() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
+            let output = Buffer.alloc(0);
+            this.message.on("data", (chunk) => {
+              output = Buffer.concat([output, chunk]);
+            });
+            this.message.on("end", () => {
+              resolve2(output.toString());
+            });
+          }));
+        });
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* int64 repository_id */
-            1:
-              message.repositoryId = reader.int64().toString();
-              break;
-            case /* repeated github.actions.results.entities.v1.CacheScope scope */
-            2:
-              message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options));
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
+      readBodyBuffer() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
+            const chunks = [];
+            this.message.on("data", (chunk) => {
+              chunks.push(chunk);
+            });
+            this.message.on("end", () => {
+              resolve2(Buffer.concat(chunks));
+            });
+          }));
+        });
+      }
+    };
+    exports2.HttpClientResponse = HttpClientResponse;
+    function isHttps(requestUrl) {
+      const parsedUrl = new URL(requestUrl);
+      return parsedUrl.protocol === "https:";
+    }
+    exports2.isHttps = isHttps;
+    var HttpClient2 = class {
+      constructor(userAgent, handlers, requestOptions) {
+        this._ignoreSslError = false;
+        this._allowRedirects = true;
+        this._allowRedirectDowngrade = false;
+        this._maxRedirects = 50;
+        this._allowRetries = false;
+        this._maxRetries = 1;
+        this._keepAlive = false;
+        this._disposed = false;
+        this.userAgent = userAgent;
+        this.handlers = handlers || [];
+        this.requestOptions = requestOptions;
+        if (requestOptions) {
+          if (requestOptions.ignoreSslError != null) {
+            this._ignoreSslError = requestOptions.ignoreSslError;
+          }
+          this._socketTimeout = requestOptions.socketTimeout;
+          if (requestOptions.allowRedirects != null) {
+            this._allowRedirects = requestOptions.allowRedirects;
+          }
+          if (requestOptions.allowRedirectDowngrade != null) {
+            this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+          }
+          if (requestOptions.maxRedirects != null) {
+            this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+          }
+          if (requestOptions.keepAlive != null) {
+            this._keepAlive = requestOptions.keepAlive;
+          }
+          if (requestOptions.allowRetries != null) {
+            this._allowRetries = requestOptions.allowRetries;
+          }
+          if (requestOptions.maxRetries != null) {
+            this._maxRetries = requestOptions.maxRetries;
           }
         }
-        return message;
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.repositoryId !== "0")
-          writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId);
-        for (let i = 0; i < message.scope.length; i++)
-          cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join();
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+      options(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("OPTIONS", requestUrl, null, additionalHeaders || {});
+        });
       }
-    };
-    exports2.CacheMetadata = new CacheMetadata$Type();
-  }
-});
-
-// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js
-var require_cache2 = __commonJS({
-  "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0;
-    var runtime_rpc_1 = require_commonjs2();
-    var runtime_1 = require_commonjs();
-    var runtime_2 = require_commonjs();
-    var runtime_3 = require_commonjs();
-    var runtime_4 = require_commonjs();
-    var runtime_5 = require_commonjs();
-    var cachemetadata_1 = require_cachemetadata();
-    var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.CreateCacheEntryRequest", [
-          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
-          {
-            no: 2,
-            name: "key",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "version",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          }
-        ]);
+      get(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("GET", requestUrl, null, additionalHeaders || {});
+        });
       }
-      create(value) {
-        const message = { key: "", version: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      del(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("DELETE", requestUrl, null, additionalHeaders || {});
+        });
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* github.actions.results.entities.v1.CacheMetadata metadata */
-            1:
-              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
-              break;
-            case /* string key */
-            2:
-              message.key = reader.string();
-              break;
-            case /* string version */
-            3:
-              message.version = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
-          }
-        }
-        return message;
+      post(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("POST", requestUrl, data, additionalHeaders || {});
+        });
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.metadata)
-          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
-        if (message.key !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
-        if (message.version !== "")
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+      patch(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PATCH", requestUrl, data, additionalHeaders || {});
+        });
       }
-    };
-    exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type();
-    var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.CreateCacheEntryResponse", [
-          {
-            no: 1,
-            name: "ok",
-            kind: "scalar",
-            T: 8
-            /*ScalarType.BOOL*/
-          },
-          {
-            no: 2,
-            name: "signed_upload_url",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "message",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          }
-        ]);
+      put(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PUT", requestUrl, data, additionalHeaders || {});
+        });
       }
-      create(value) {
-        const message = { ok: false, signedUploadUrl: "", message: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      head(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("HEAD", requestUrl, null, additionalHeaders || {});
+        });
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* bool ok */
-            1:
-              message.ok = reader.bool();
-              break;
-            case /* string signed_upload_url */
-            2:
-              message.signedUploadUrl = reader.string();
-              break;
-            case /* string message */
-            3:
-              message.message = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
-          }
-        }
-        return message;
+      sendStream(verb, requestUrl, stream, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request(verb, requestUrl, stream, additionalHeaders);
+        });
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.ok !== false)
-          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
-        if (message.signedUploadUrl !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl);
-        if (message.message !== "")
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+      /**
+       * Gets a typed object from an endpoint
+       * Be aware that not found returns a null.  Other errors (4xx, 5xx) reject the promise
+       */
+      getJson(requestUrl, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          const res = yield this.get(requestUrl, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-    };
-    exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type();
-    var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [
-          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
-          {
-            no: 2,
-            name: "key",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "size_bytes",
-            kind: "scalar",
-            T: 3
-            /*ScalarType.INT64*/
-          },
-          {
-            no: 4,
-            name: "version",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          }
-        ]);
+      postJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.post(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      create(value) {
-        const message = { key: "", sizeBytes: "0", version: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      putJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.put(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* github.actions.results.entities.v1.CacheMetadata metadata */
-            1:
-              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
-              break;
-            case /* string key */
-            2:
-              message.key = reader.string();
-              break;
-            case /* int64 size_bytes */
-            3:
-              message.sizeBytes = reader.int64().toString();
-              break;
-            case /* string version */
-            4:
-              message.version = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
+      patchJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.patch(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      /**
+       * Makes a raw http request.
+       * All other methods such as get, post, patch, and request ultimately call this.
+       * Prefer get, del, post and patch
+       */
+      request(verb, requestUrl, data, headers) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          if (this._disposed) {
+            throw new Error("Client has already been disposed.");
           }
+          const parsedUrl = new URL(requestUrl);
+          let info7 = this._prepareRequest(verb, parsedUrl, headers);
+          const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1;
+          let numTries = 0;
+          let response;
+          do {
+            response = yield this.requestRaw(info7, data);
+            if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
+              let authenticationHandler;
+              for (const handler of this.handlers) {
+                if (handler.canHandleAuthentication(response)) {
+                  authenticationHandler = handler;
+                  break;
+                }
+              }
+              if (authenticationHandler) {
+                return authenticationHandler.handleAuthentication(this, info7, data);
+              } else {
+                return response;
+              }
+            }
+            let redirectsRemaining = this._maxRedirects;
+            while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) {
+              const redirectUrl = response.message.headers["location"];
+              if (!redirectUrl) {
+                break;
+              }
+              const parsedRedirectUrl = new URL(redirectUrl);
+              if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
+                throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
+              }
+              yield response.readBody();
+              if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+                for (const header in headers) {
+                  if (header.toLowerCase() === "authorization") {
+                    delete headers[header];
+                  }
+                }
+              }
+              info7 = this._prepareRequest(verb, parsedRedirectUrl, headers);
+              response = yield this.requestRaw(info7, data);
+              redirectsRemaining--;
+            }
+            if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+              return response;
+            }
+            numTries += 1;
+            if (numTries < maxTries) {
+              yield response.readBody();
+              yield this._performExponentialBackoff(numTries);
+            }
+          } while (numTries < maxTries);
+          return response;
+        });
+      }
+      /**
+       * Needs to be called if keepAlive is set to true in request options.
+       */
+      dispose() {
+        if (this._agent) {
+          this._agent.destroy();
         }
-        return message;
+        this._disposed = true;
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.metadata)
-          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
-        if (message.key !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
-        if (message.sizeBytes !== "0")
-          writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes);
-        if (message.version !== "")
-          writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+      /**
+       * Raw request.
+       * @param info
+       * @param data
+       */
+      requestRaw(info7, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2, reject) => {
+            function callbackForResult(err, res) {
+              if (err) {
+                reject(err);
+              } else if (!res) {
+                reject(new Error("Unknown error"));
+              } else {
+                resolve2(res);
+              }
+            }
+            this.requestRawWithCallback(info7, data, callbackForResult);
+          });
+        });
       }
-    };
-    exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type();
-    var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [
-          {
-            no: 1,
-            name: "ok",
-            kind: "scalar",
-            T: 8
-            /*ScalarType.BOOL*/
-          },
-          {
-            no: 2,
-            name: "entry_id",
-            kind: "scalar",
-            T: 3
-            /*ScalarType.INT64*/
-          },
-          {
-            no: 3,
-            name: "message",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
+      /**
+       * Raw request with callback.
+       * @param info
+       * @param data
+       * @param onResult
+       */
+      requestRawWithCallback(info7, data, onResult) {
+        if (typeof data === "string") {
+          if (!info7.options.headers) {
+            info7.options.headers = {};
           }
-        ]);
-      }
-      create(value) {
-        const message = { ok: false, entryId: "0", message: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
-      }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* bool ok */
-            1:
-              message.ok = reader.bool();
-              break;
-            case /* int64 entry_id */
-            2:
-              message.entryId = reader.int64().toString();
-              break;
-            case /* string message */
-            3:
-              message.message = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
+          info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8");
+        }
+        let callbackCalled = false;
+        function handleResult(err, res) {
+          if (!callbackCalled) {
+            callbackCalled = true;
+            onResult(err, res);
           }
         }
-        return message;
-      }
-      internalBinaryWrite(message, writer, options) {
-        if (message.ok !== false)
-          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
-        if (message.entryId !== "0")
-          writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId);
-        if (message.message !== "")
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
-      }
-    };
-    exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type();
-    var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [
-          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
-          {
-            no: 2,
-            name: "key",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "restore_keys",
-            kind: "scalar",
-            repeat: 2,
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 4,
-            name: "version",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
+        const req = info7.httpModule.request(info7.options, (msg) => {
+          const res = new HttpClientResponse(msg);
+          handleResult(void 0, res);
+        });
+        let socket;
+        req.on("socket", (sock) => {
+          socket = sock;
+        });
+        req.setTimeout(this._socketTimeout || 3 * 6e4, () => {
+          if (socket) {
+            socket.end();
           }
-        ]);
+          handleResult(new Error(`Request timeout: ${info7.options.path}`));
+        });
+        req.on("error", function(err) {
+          handleResult(err);
+        });
+        if (data && typeof data === "string") {
+          req.write(data, "utf8");
+        }
+        if (data && typeof data !== "string") {
+          data.on("close", function() {
+            req.end();
+          });
+          data.pipe(req);
+        } else {
+          req.end();
+        }
       }
-      create(value) {
-        const message = { key: "", restoreKeys: [], version: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      /**
+       * Gets an http agent. This function is useful when you need an http agent that handles
+       * routing through a proxy server - depending upon the url and proxy environment variables.
+       * @param serverUrl  The server URL where the request will be sent. For example, https://api.github.com
+       */
+      getAgent(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        return this._getAgent(parsedUrl);
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* github.actions.results.entities.v1.CacheMetadata metadata */
-            1:
-              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
-              break;
-            case /* string key */
-            2:
-              message.key = reader.string();
-              break;
-            case /* repeated string restore_keys */
-            3:
-              message.restoreKeys.push(reader.string());
-              break;
-            case /* string version */
-            4:
-              message.version = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
-          }
+      getAgentDispatcher(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (!useProxy) {
+          return;
         }
-        return message;
-      }
-      internalBinaryWrite(message, writer, options) {
-        if (message.metadata)
-          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
-        if (message.key !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
-        for (let i = 0; i < message.restoreKeys.length; i++)
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]);
-        if (message.version !== "")
-          writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+        return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
       }
-    };
-    exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type();
-    var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [
-          {
-            no: 1,
-            name: "ok",
-            kind: "scalar",
-            T: 8
-            /*ScalarType.BOOL*/
-          },
-          {
-            no: 2,
-            name: "signed_download_url",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "matched_key",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
+      _prepareRequest(method, requestUrl, headers) {
+        const info7 = {};
+        info7.parsedUrl = requestUrl;
+        const usingSsl = info7.parsedUrl.protocol === "https:";
+        info7.httpModule = usingSsl ? https2 : http;
+        const defaultPort = usingSsl ? 443 : 80;
+        info7.options = {};
+        info7.options.host = info7.parsedUrl.hostname;
+        info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort;
+        info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || "");
+        info7.options.method = method;
+        info7.options.headers = this._mergeHeaders(headers);
+        if (this.userAgent != null) {
+          info7.options.headers["user-agent"] = this.userAgent;
+        }
+        info7.options.agent = this._getAgent(info7.parsedUrl);
+        if (this.handlers) {
+          for (const handler of this.handlers) {
+            handler.prepareRequest(info7.options);
           }
-        ]);
-      }
-      create(value) {
-        const message = { ok: false, signedDownloadUrl: "", matchedKey: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+        }
+        return info7;
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* bool ok */
-            1:
-              message.ok = reader.bool();
-              break;
-            case /* string signed_download_url */
-            2:
-              message.signedDownloadUrl = reader.string();
-              break;
-            case /* string matched_key */
-            3:
-              message.matchedKey = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
-          }
+      _mergeHeaders(headers) {
+        if (this.requestOptions && this.requestOptions.headers) {
+          return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
         }
-        return message;
+        return lowercaseKeys(headers || {});
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.ok !== false)
-          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
-        if (message.signedDownloadUrl !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl);
-        if (message.matchedKey !== "")
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+      _getExistingOrDefaultHeader(additionalHeaders, header, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
+        }
+        return additionalHeaders[header] || clientHeader || _default2;
       }
-    };
-    exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type();
-    exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [
-      { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse },
-      { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse },
-      { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse }
-    ]);
-  }
-});
-
-// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js
-var require_cache_twirp_client = __commonJS({
-  "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0;
-    var cache_1 = require_cache2();
-    var CacheServiceClientJSON = class {
-      constructor(rpc) {
-        this.rpc = rpc;
-        this.CreateCacheEntry.bind(this);
-        this.FinalizeCacheEntryUpload.bind(this);
-        this.GetCacheEntryDownloadURL.bind(this);
+      _getAgent(parsedUrl) {
+        let agent;
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (this._keepAlive && useProxy) {
+          agent = this._proxyAgent;
+        }
+        if (!useProxy) {
+          agent = this._agent;
+        }
+        if (agent) {
+          return agent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        let maxSockets = 100;
+        if (this.requestOptions) {
+          maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
+        }
+        if (proxyUrl && proxyUrl.hostname) {
+          const agentOptions = {
+            maxSockets,
+            keepAlive: this._keepAlive,
+            proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && {
+              proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+            }), { host: proxyUrl.hostname, port: proxyUrl.port })
+          };
+          let tunnelAgent;
+          const overHttps = proxyUrl.protocol === "https:";
+          if (usingSsl) {
+            tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+          } else {
+            tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
+          }
+          agent = tunnelAgent(agentOptions);
+          this._proxyAgent = agent;
+        }
+        if (!agent) {
+          const options = { keepAlive: this._keepAlive, maxSockets };
+          agent = usingSsl ? new https2.Agent(options) : new http.Agent(options);
+          this._agent = agent;
+        }
+        if (usingSsl && this._ignoreSslError) {
+          agent.options = Object.assign(agent.options || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return agent;
       }
-      CreateCacheEntry(request) {
-        const data = cache_1.CreateCacheEntryRequest.toJson(request, {
-          useProtoFieldName: true,
-          emitDefaultValues: false
-        });
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data);
-        return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, {
-          ignoreUnknownFields: true
+      _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+        let proxyAgent;
+        if (this._keepAlive) {
+          proxyAgent = this._proxyAgentDispatcher;
+        }
+        if (proxyAgent) {
+          return proxyAgent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && {
+          token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}`
         }));
+        this._proxyAgentDispatcher = proxyAgent;
+        if (usingSsl && this._ignoreSslError) {
+          proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return proxyAgent;
       }
-      FinalizeCacheEntryUpload(request) {
-        const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, {
-          useProtoFieldName: true,
-          emitDefaultValues: false
+      _performExponentialBackoff(retryNumber) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+          const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+          return new Promise((resolve2) => setTimeout(() => resolve2(), ms));
         });
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data);
-        return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, {
-          ignoreUnknownFields: true
-        }));
       }
-      GetCacheEntryDownloadURL(request) {
-        const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, {
-          useProtoFieldName: true,
-          emitDefaultValues: false
+      _processResponse(res, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () {
+            const statusCode = res.message.statusCode || 0;
+            const response = {
+              statusCode,
+              result: null,
+              headers: {}
+            };
+            if (statusCode === HttpCodes.NotFound) {
+              resolve2(response);
+            }
+            function dateTimeDeserializer(key, value) {
+              if (typeof value === "string") {
+                const a = new Date(value);
+                if (!isNaN(a.valueOf())) {
+                  return a;
+                }
+              }
+              return value;
+            }
+            let obj;
+            let contents;
+            try {
+              contents = yield res.readBody();
+              if (contents && contents.length > 0) {
+                if (options && options.deserializeDates) {
+                  obj = JSON.parse(contents, dateTimeDeserializer);
+                } else {
+                  obj = JSON.parse(contents);
+                }
+                response.result = obj;
+              }
+              response.headers = res.message.headers;
+            } catch (err) {
+            }
+            if (statusCode > 299) {
+              let msg;
+              if (obj && obj.message) {
+                msg = obj.message;
+              } else if (contents && contents.length > 0) {
+                msg = contents;
+              } else {
+                msg = `Failed request: (${statusCode})`;
+              }
+              const err = new HttpClientError(msg, statusCode);
+              err.result = response.result;
+              reject(err);
+            } else {
+              resolve2(response);
+            }
+          }));
         });
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data);
-        return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, {
-          ignoreUnknownFields: true
-        }));
-      }
-    };
-    exports2.CacheServiceClientJSON = CacheServiceClientJSON;
-    var CacheServiceClientProtobuf = class {
-      constructor(rpc) {
-        this.rpc = rpc;
-        this.CreateCacheEntry.bind(this);
-        this.FinalizeCacheEntryUpload.bind(this);
-        this.GetCacheEntryDownloadURL.bind(this);
-      }
-      CreateCacheEntry(request) {
-        const data = cache_1.CreateCacheEntryRequest.toBinary(request);
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data);
-        return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2));
-      }
-      FinalizeCacheEntryUpload(request) {
-        const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request);
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data);
-        return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2));
-      }
-      GetCacheEntryDownloadURL(request) {
-        const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request);
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data);
-        return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2));
       }
     };
-    exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf;
+    exports2.HttpClient = HttpClient2;
+    var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
   }
 });
 
-// node_modules/@actions/cache/lib/internal/shared/util.js
-var require_util15 = __commonJS({
-  "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) {
+// node_modules/@actions/tool-cache/lib/retry-helper.js
+var require_retry_helper = __commonJS({
+  "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.maskSecretUrls = exports2.maskSigUrl = void 0;
-    var core_1 = require_core();
-    function maskSigUrl(url) {
-      if (!url)
-        return;
-      try {
-        const parsedUrl = new URL(url);
-        const signature = parsedUrl.searchParams.get("sig");
-        if (signature) {
-          (0, core_1.setSecret)(signature);
-          (0, core_1.setSecret)(encodeURIComponent(signature));
-        }
-      } catch (error4) {
-        (0, core_1.debug)(`Failed to parse URL: ${url} ${error4 instanceof Error ? error4.message : String(error4)}`);
-      }
-    }
-    exports2.maskSigUrl = maskSigUrl;
-    function maskSecretUrls(body) {
-      if (typeof body !== "object" || body === null) {
-        (0, core_1.debug)("body is not an object or is null");
-        return;
-      }
-      if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") {
-        maskSigUrl(body.signed_upload_url);
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      if ("signed_download_url" in body && typeof body.signed_download_url === "string") {
-        maskSigUrl(body.signed_download_url);
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-    }
-    exports2.maskSecretUrls = maskSecretUrls;
-  }
-});
-
-// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js
-var require_cacheTwirpClient = __commonJS({
-  "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) {
-    "use strict";
+      __setModuleDefault4(result, mod);
+      return result;
+    };
     var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
       function adopt(value) {
         return value instanceof P ? value : new P(function(resolve2) {
@@ -107298,154 +112129,56 @@ var require_cacheTwirpClient = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.internalCacheTwirpClient = void 0;
-    var core_1 = require_core();
-    var user_agent_1 = require_user_agent2();
-    var errors_1 = require_errors4();
-    var config_1 = require_config2();
-    var cacheUtils_1 = require_cacheUtils();
-    var auth_1 = require_auth();
-    var http_client_1 = require_lib();
-    var cache_twirp_client_1 = require_cache_twirp_client();
-    var util_1 = require_util15();
-    var CacheServiceClient = class {
-      constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) {
-        this.maxAttempts = 5;
-        this.baseRetryIntervalMilliseconds = 3e3;
-        this.retryMultiplier = 1.5;
-        const token = (0, cacheUtils_1.getRuntimeToken)();
-        this.baseUrl = (0, config_1.getCacheServiceURL)();
-        if (maxAttempts) {
-          this.maxAttempts = maxAttempts;
-        }
-        if (baseRetryIntervalMilliseconds) {
-          this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds;
+    exports2.RetryHelper = void 0;
+    var core14 = __importStar4(require_core());
+    var RetryHelper = class {
+      constructor(maxAttempts, minSeconds, maxSeconds) {
+        if (maxAttempts < 1) {
+          throw new Error("max attempts should be greater than or equal to 1");
         }
-        if (retryMultiplier) {
-          this.retryMultiplier = retryMultiplier;
+        this.maxAttempts = maxAttempts;
+        this.minSeconds = Math.floor(minSeconds);
+        this.maxSeconds = Math.floor(maxSeconds);
+        if (this.minSeconds > this.maxSeconds) {
+          throw new Error("min seconds should be less than or equal to max seconds");
         }
-        this.httpClient = new http_client_1.HttpClient(userAgent, [
-          new auth_1.BearerCredentialHandler(token)
-        ]);
-      }
-      // This function satisfies the Rpc interface. It is compatible with the JSON
-      // JSON generated client.
-      request(service, method, contentType, data) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href;
-          (0, core_1.debug)(`[Request] ${method} ${url}`);
-          const headers = {
-            "Content-Type": contentType
-          };
-          try {
-            const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () {
-              return this.httpClient.post(url, JSON.stringify(data), headers);
-            }));
-            return body;
-          } catch (error4) {
-            throw new Error(`Failed to ${method}: ${error4.message}`);
-          }
-        });
       }
-      retryableRequest(operation) {
+      execute(action, isRetryable) {
         return __awaiter4(this, void 0, void 0, function* () {
-          let attempt = 0;
-          let errorMessage = "";
-          let rawBody = "";
+          let attempt = 1;
           while (attempt < this.maxAttempts) {
-            let isRetryable = false;
             try {
-              const response = yield operation();
-              const statusCode = response.message.statusCode;
-              rawBody = yield response.readBody();
-              (0, core_1.debug)(`[Response] - ${response.message.statusCode}`);
-              (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`);
-              const body = JSON.parse(rawBody);
-              (0, util_1.maskSecretUrls)(body);
-              (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`);
-              if (this.isSuccessStatusCode(statusCode)) {
-                return { response, body };
-              }
-              isRetryable = this.isRetryableHttpStatusCode(statusCode);
-              errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`;
-              if (body.msg) {
-                if (errors_1.UsageError.isUsageErrorMessage(body.msg)) {
-                  throw new errors_1.UsageError();
-                }
-                errorMessage = `${errorMessage}: ${body.msg}`;
-              }
-            } catch (error4) {
-              if (error4 instanceof SyntaxError) {
-                (0, core_1.debug)(`Raw Body: ${rawBody}`);
-              }
-              if (error4 instanceof errors_1.UsageError) {
-                throw error4;
-              }
-              if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) {
-                throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code);
+              return yield action();
+            } catch (err) {
+              if (isRetryable && !isRetryable(err)) {
+                throw err;
               }
-              isRetryable = true;
-              errorMessage = error4.message;
-            }
-            if (!isRetryable) {
-              throw new Error(`Received non-retryable error: ${errorMessage}`);
-            }
-            if (attempt + 1 === this.maxAttempts) {
-              throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`);
+              core14.info(err.message);
             }
-            const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt);
-            (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`);
-            yield this.sleep(retryTimeMilliseconds);
+            const seconds = this.getSleepAmount();
+            core14.info(`Waiting ${seconds} seconds before trying again`);
+            yield this.sleep(seconds);
             attempt++;
           }
-          throw new Error(`Request failed`);
+          return yield action();
         });
       }
-      isSuccessStatusCode(statusCode) {
-        if (!statusCode)
-          return false;
-        return statusCode >= 200 && statusCode < 300;
-      }
-      isRetryableHttpStatusCode(statusCode) {
-        if (!statusCode)
-          return false;
-        const retryableStatusCodes = [
-          http_client_1.HttpCodes.BadGateway,
-          http_client_1.HttpCodes.GatewayTimeout,
-          http_client_1.HttpCodes.InternalServerError,
-          http_client_1.HttpCodes.ServiceUnavailable,
-          http_client_1.HttpCodes.TooManyRequests
-        ];
-        return retryableStatusCodes.includes(statusCode);
+      getSleepAmount() {
+        return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds;
       }
-      sleep(milliseconds) {
+      sleep(seconds) {
         return __awaiter4(this, void 0, void 0, function* () {
-          return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
+          return new Promise((resolve2) => setTimeout(resolve2, seconds * 1e3));
         });
       }
-      getExponentialRetryTimeMilliseconds(attempt) {
-        if (attempt < 0) {
-          throw new Error("attempt should be a positive integer");
-        }
-        if (attempt === 0) {
-          return this.baseRetryIntervalMilliseconds;
-        }
-        const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt);
-        const maxTime = minTime * this.retryMultiplier;
-        return Math.trunc(Math.random() * (maxTime - minTime) + minTime);
-      }
     };
-    function internalCacheTwirpClient(options) {
-      const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier);
-      return new cache_twirp_client_1.CacheServiceClientJSON(client);
-    }
-    exports2.internalCacheTwirpClient = internalCacheTwirpClient;
+    exports2.RetryHelper = RetryHelper;
   }
 });
 
-// node_modules/@actions/cache/lib/internal/tar.js
-var require_tar2 = __commonJS({
-  "node_modules/@actions/cache/lib/internal/tar.js"(exports2) {
+// node_modules/@actions/tool-cache/lib/tool-cache.js
+var require_tool_cache = __commonJS({
+  "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -107502,866 +112235,610 @@ var require_tar2 = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createTar = exports2.extractTar = exports2.listTar = void 0;
-    var exec_1 = require_exec();
+    exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0;
+    var core14 = __importStar4(require_core());
     var io6 = __importStar4(require_io());
-    var fs_1 = require("fs");
+    var crypto = __importStar4(require("crypto"));
+    var fs2 = __importStar4(require("fs"));
+    var mm = __importStar4(require_manifest());
+    var os = __importStar4(require("os"));
     var path2 = __importStar4(require("path"));
-    var utils = __importStar4(require_cacheUtils());
-    var constants_1 = require_constants10();
+    var httpm = __importStar4(require_lib8());
+    var semver8 = __importStar4(require_semver2());
+    var stream = __importStar4(require("stream"));
+    var util = __importStar4(require("util"));
+    var assert_1 = require("assert");
+    var exec_1 = require_exec();
+    var retry_helper_1 = require_retry_helper();
+    var HTTPError = class extends Error {
+      constructor(httpStatusCode) {
+        super(`Unexpected HTTP response: ${httpStatusCode}`);
+        this.httpStatusCode = httpStatusCode;
+        Object.setPrototypeOf(this, new.target.prototype);
+      }
+    };
+    exports2.HTTPError = HTTPError;
     var IS_WINDOWS = process.platform === "win32";
-    function getTarPath() {
+    var IS_MAC = process.platform === "darwin";
+    var userAgent = "actions/tool-cache";
+    function downloadTool2(url, dest, auth, headers) {
       return __awaiter4(this, void 0, void 0, function* () {
-        switch (process.platform) {
-          case "win32": {
-            const gnuTar = yield utils.getGnuTarPathOnWindows();
-            const systemTar = constants_1.SystemTarPathOnWindows;
-            if (gnuTar) {
-              return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
-            } else if ((0, fs_1.existsSync)(systemTar)) {
-              return { path: systemTar, type: constants_1.ArchiveToolType.BSD };
-            }
-            break;
-          }
-          case "darwin": {
-            const gnuTar = yield io6.which("gtar", false);
-            if (gnuTar) {
-              return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
-            } else {
-              return {
-                path: yield io6.which("tar", true),
-                type: constants_1.ArchiveToolType.BSD
-              };
+        dest = dest || path2.join(_getTempDirectory(), crypto.randomUUID());
+        yield io6.mkdirP(path2.dirname(dest));
+        core14.debug(`Downloading ${url}`);
+        core14.debug(`Destination ${dest}`);
+        const maxAttempts = 3;
+        const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10);
+        const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20);
+        const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds);
+        return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () {
+          return yield downloadToolAttempt(url, dest || "", auth, headers);
+        }), (err) => {
+          if (err instanceof HTTPError && err.httpStatusCode) {
+            if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) {
+              return false;
             }
           }
-          default:
-            break;
-        }
-        return {
-          path: yield io6.which("tar", true),
-          type: constants_1.ArchiveToolType.GNU
-        };
+          return true;
+        });
       });
     }
-    function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") {
+    exports2.downloadTool = downloadTool2;
+    function downloadToolAttempt(url, dest, auth, headers) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const args = [`"${tarPath.path}"`];
-        const cacheFileName = utils.getCacheFileName(compressionMethod);
-        const tarFile = "cache.tar";
-        const workingDirectory = getWorkingDirectory();
-        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
-        switch (type2) {
-          case "create":
-            args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename);
-            break;
-          case "extract":
-            args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path2.sep}`, "g"), "/"));
-            break;
-          case "list":
-            args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/"), "-P");
-            break;
+        if (fs2.existsSync(dest)) {
+          throw new Error(`Destination file path ${dest} already exists`);
         }
-        if (tarPath.type === constants_1.ArchiveToolType.GNU) {
-          switch (process.platform) {
-            case "win32":
-              args.push("--force-local");
-              break;
-            case "darwin":
-              args.push("--delay-directory-restore");
-              break;
+        const http = new httpm.HttpClient(userAgent, [], {
+          allowRetries: false
+        });
+        if (auth) {
+          core14.debug("set auth");
+          if (headers === void 0) {
+            headers = {};
           }
+          headers.authorization = auth;
         }
-        return args;
-      });
-    }
-    function getCommands(compressionMethod, type2, archivePath = "") {
-      return __awaiter4(this, void 0, void 0, function* () {
-        let args;
-        const tarPath = yield getTarPath();
-        const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath);
-        const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod);
-        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
-        if (BSD_TAR_ZSTD && type2 !== "create") {
-          args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")];
-        } else {
-          args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")];
-        }
-        if (BSD_TAR_ZSTD) {
-          return args;
+        const response = yield http.get(url, headers);
+        if (response.message.statusCode !== 200) {
+          const err = new HTTPError(response.message.statusCode);
+          core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
+          throw err;
         }
-        return [args.join(" ")];
-      });
-    }
-    function getWorkingDirectory() {
-      var _a;
-      return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd();
-    }
-    function getDecompressionProgram(tarPath, compressionMethod, archivePath) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
-        switch (compressionMethod) {
-          case constants_1.CompressionMethod.Zstd:
-            return BSD_TAR_ZSTD ? [
-              "zstd -d --long=30 --force -o",
-              constants_1.TarFilename,
-              archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/")
-            ] : [
-              "--use-compress-program",
-              IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30"
-            ];
-          case constants_1.CompressionMethod.ZstdWithoutLong:
-            return BSD_TAR_ZSTD ? [
-              "zstd -d --force -o",
-              constants_1.TarFilename,
-              archivePath.replace(new RegExp(`\\${path2.sep}`, "g"), "/")
-            ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"];
-          default:
-            return ["-z"];
+        const pipeline = util.promisify(stream.pipeline);
+        const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message);
+        const readStream = responseMessageFactory();
+        let succeeded = false;
+        try {
+          yield pipeline(readStream, fs2.createWriteStream(dest));
+          core14.debug("download complete");
+          succeeded = true;
+          return dest;
+        } finally {
+          if (!succeeded) {
+            core14.debug("download failed");
+            try {
+              yield io6.rmRF(dest);
+            } catch (err) {
+              core14.debug(`Failed to delete '${dest}'. ${err.message}`);
+            }
+          }
         }
       });
     }
-    function getCompressionProgram(tarPath, compressionMethod) {
+    function extract7z(file, dest, _7zPath) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const cacheFileName = utils.getCacheFileName(compressionMethod);
-        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
-        switch (compressionMethod) {
-          case constants_1.CompressionMethod.Zstd:
-            return BSD_TAR_ZSTD ? [
-              "zstd -T0 --long=30 --force -o",
-              cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"),
-              constants_1.TarFilename
-            ] : [
-              "--use-compress-program",
-              IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30"
+        (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS");
+        (0, assert_1.ok)(file, 'parameter "file" is required');
+        dest = yield _createExtractFolder(dest);
+        const originalCwd = process.cwd();
+        process.chdir(dest);
+        if (_7zPath) {
+          try {
+            const logLevel = core14.isDebug() ? "-bb1" : "-bb0";
+            const args = [
+              "x",
+              logLevel,
+              "-bd",
+              "-sccUTF-8",
+              file
             ];
-          case constants_1.CompressionMethod.ZstdWithoutLong:
-            return BSD_TAR_ZSTD ? [
-              "zstd -T0 --force -o",
-              cacheFileName.replace(new RegExp(`\\${path2.sep}`, "g"), "/"),
-              constants_1.TarFilename
-            ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"];
-          default:
-            return ["-z"];
-        }
-      });
-    }
-    function execCommands(commands, cwd) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        for (const command of commands) {
+            const options = {
+              silent: true
+            };
+            yield (0, exec_1.exec)(`"${_7zPath}"`, args, options);
+          } finally {
+            process.chdir(originalCwd);
+          }
+        } else {
+          const escapedScript = path2.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, "");
+          const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, "");
+          const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, "");
+          const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`;
+          const args = [
+            "-NoLogo",
+            "-Sta",
+            "-NoProfile",
+            "-NonInteractive",
+            "-ExecutionPolicy",
+            "Unrestricted",
+            "-Command",
+            command
+          ];
+          const options = {
+            silent: true
+          };
           try {
-            yield (0, exec_1.exec)(command, void 0, {
-              cwd,
-              env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" })
-            });
-          } catch (error4) {
-            throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`);
+            const powershellPath = yield io6.which("powershell", true);
+            yield (0, exec_1.exec)(`"${powershellPath}"`, args, options);
+          } finally {
+            process.chdir(originalCwd);
           }
         }
+        return dest;
       });
     }
-    function listTar(archivePath, compressionMethod) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const commands = yield getCommands(compressionMethod, "list", archivePath);
-        yield execCommands(commands);
-      });
-    }
-    exports2.listTar = listTar;
-    function extractTar2(archivePath, compressionMethod) {
+    exports2.extract7z = extract7z;
+    function extractTar2(file, dest, flags = "xz") {
       return __awaiter4(this, void 0, void 0, function* () {
-        const workingDirectory = getWorkingDirectory();
-        yield io6.mkdirP(workingDirectory);
-        const commands = yield getCommands(compressionMethod, "extract", archivePath);
-        yield execCommands(commands);
+        if (!file) {
+          throw new Error("parameter 'file' is required");
+        }
+        dest = yield _createExtractFolder(dest);
+        core14.debug("Checking tar --version");
+        let versionOutput = "";
+        yield (0, exec_1.exec)("tar --version", [], {
+          ignoreReturnCode: true,
+          silent: true,
+          listeners: {
+            stdout: (data) => versionOutput += data.toString(),
+            stderr: (data) => versionOutput += data.toString()
+          }
+        });
+        core14.debug(versionOutput.trim());
+        const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR");
+        let args;
+        if (flags instanceof Array) {
+          args = flags;
+        } else {
+          args = [flags];
+        }
+        if (core14.isDebug() && !flags.includes("v")) {
+          args.push("-v");
+        }
+        let destArg = dest;
+        let fileArg = file;
+        if (IS_WINDOWS && isGnuTar) {
+          args.push("--force-local");
+          destArg = dest.replace(/\\/g, "/");
+          fileArg = file.replace(/\\/g, "/");
+        }
+        if (isGnuTar) {
+          args.push("--warning=no-unknown-keyword");
+          args.push("--overwrite");
+        }
+        args.push("-C", destArg, "-f", fileArg);
+        yield (0, exec_1.exec)(`tar`, args);
+        return dest;
       });
     }
     exports2.extractTar = extractTar2;
-    function createTar(archiveFolder, sourceDirectories, compressionMethod) {
+    function extractXar(file, dest, flags = []) {
       return __awaiter4(this, void 0, void 0, function* () {
-        (0, fs_1.writeFileSync)(path2.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n"));
-        const commands = yield getCommands(compressionMethod, "create");
-        yield execCommands(commands, archiveFolder);
+        (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS");
+        (0, assert_1.ok)(file, 'parameter "file" is required');
+        dest = yield _createExtractFolder(dest);
+        let args;
+        if (flags instanceof Array) {
+          args = flags;
+        } else {
+          args = [flags];
+        }
+        args.push("-x", "-C", dest, "-f", file);
+        if (core14.isDebug()) {
+          args.push("-v");
+        }
+        const xarPath = yield io6.which("xar", true);
+        yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args));
+        return dest;
       });
     }
-    exports2.createTar = createTar;
-  }
-});
-
-// node_modules/@actions/cache/lib/cache.js
-var require_cache3 = __commonJS({
-  "node_modules/@actions/cache/lib/cache.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
+    exports2.extractXar = extractXar;
+    function extractZip(file, dest) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        if (!file) {
+          throw new Error("parameter 'file' is required");
         }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        dest = yield _createExtractFolder(dest);
+        if (IS_WINDOWS) {
+          yield extractZipWin(file, dest);
+        } else {
+          yield extractZipNix(file, dest);
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
+        return dest;
       });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0;
-    var core14 = __importStar4(require_core());
-    var path2 = __importStar4(require("path"));
-    var utils = __importStar4(require_cacheUtils());
-    var cacheHttpClient = __importStar4(require_cacheHttpClient());
-    var cacheTwirpClient = __importStar4(require_cacheTwirpClient());
-    var config_1 = require_config2();
-    var tar_1 = require_tar2();
-    var http_client_1 = require_lib();
-    var ValidationError = class _ValidationError extends Error {
-      constructor(message) {
-        super(message);
-        this.name = "ValidationError";
-        Object.setPrototypeOf(this, _ValidationError.prototype);
-      }
-    };
-    exports2.ValidationError = ValidationError;
-    var ReserveCacheError2 = class _ReserveCacheError extends Error {
-      constructor(message) {
-        super(message);
-        this.name = "ReserveCacheError";
-        Object.setPrototypeOf(this, _ReserveCacheError.prototype);
-      }
-    };
-    exports2.ReserveCacheError = ReserveCacheError2;
-    var FinalizeCacheError = class _FinalizeCacheError extends Error {
-      constructor(message) {
-        super(message);
-        this.name = "FinalizeCacheError";
-        Object.setPrototypeOf(this, _FinalizeCacheError.prototype);
-      }
-    };
-    exports2.FinalizeCacheError = FinalizeCacheError;
-    function checkPaths(paths) {
-      if (!paths || paths.length === 0) {
-        throw new ValidationError(`Path Validation Error: At least one directory or file path is required`);
-      }
-    }
-    function checkKey(key) {
-      if (key.length > 512) {
-        throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`);
-      }
-      const regex = /^[^,]*$/;
-      if (!regex.test(key)) {
-        throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`);
-      }
-    }
-    function isFeatureAvailable() {
-      const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
-      switch (cacheServiceVersion) {
-        case "v2":
-          return !!process.env["ACTIONS_RESULTS_URL"];
-        case "v1":
-        default:
-          return !!process.env["ACTIONS_CACHE_URL"];
-      }
     }
-    exports2.isFeatureAvailable = isFeatureAvailable;
-    function restoreCache4(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
+    exports2.extractZip = extractZip;
+    function extractZipWin(file, dest) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
-        core14.debug(`Cache service version: ${cacheServiceVersion}`);
-        checkPaths(paths);
-        switch (cacheServiceVersion) {
-          case "v2":
-            return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
-          case "v1":
-          default:
-            return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
+        const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, "");
+        const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, "");
+        const pwshPath = yield io6.which("pwsh", false);
+        if (pwshPath) {
+          const pwshCommand = [
+            `$ErrorActionPreference = 'Stop' ;`,
+            `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`,
+            `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`,
+            `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;`
+          ].join(" ");
+          const args = [
+            "-NoLogo",
+            "-NoProfile",
+            "-NonInteractive",
+            "-ExecutionPolicy",
+            "Unrestricted",
+            "-Command",
+            pwshCommand
+          ];
+          core14.debug(`Using pwsh at path: ${pwshPath}`);
+          yield (0, exec_1.exec)(`"${pwshPath}"`, args);
+        } else {
+          const powershellCommand = [
+            `$ErrorActionPreference = 'Stop' ;`,
+            `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`,
+            `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`,
+            `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`
+          ].join(" ");
+          const args = [
+            "-NoLogo",
+            "-Sta",
+            "-NoProfile",
+            "-NonInteractive",
+            "-ExecutionPolicy",
+            "Unrestricted",
+            "-Command",
+            powershellCommand
+          ];
+          const powershellPath = yield io6.which("powershell", true);
+          core14.debug(`Using powershell at path: ${powershellPath}`);
+          yield (0, exec_1.exec)(`"${powershellPath}"`, args);
         }
       });
     }
-    exports2.restoreCache = restoreCache4;
-    function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
+    function extractZipNix(file, dest) {
       return __awaiter4(this, void 0, void 0, function* () {
-        restoreKeys = restoreKeys || [];
-        const keys = [primaryKey, ...restoreKeys];
-        core14.debug("Resolved Keys:");
-        core14.debug(JSON.stringify(keys));
-        if (keys.length > 10) {
-          throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`);
-        }
-        for (const key of keys) {
-          checkKey(key);
-        }
-        const compressionMethod = yield utils.getCompressionMethod();
-        let archivePath = "";
-        try {
-          const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, {
-            compressionMethod,
-            enableCrossOsArchive
-          });
-          if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) {
-            return void 0;
-          }
-          if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
-            core14.info("Lookup only - skipping download");
-            return cacheEntry.cacheKey;
-          }
-          archivePath = path2.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
-          core14.debug(`Archive Path: ${archivePath}`);
-          yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options);
-          if (core14.isDebug()) {
-            yield (0, tar_1.listTar)(archivePath, compressionMethod);
-          }
-          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
-          core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
-          yield (0, tar_1.extractTar)(archivePath, compressionMethod);
-          core14.info("Cache restored successfully");
-          return cacheEntry.cacheKey;
-        } catch (error4) {
-          const typedError = error4;
-          if (typedError.name === ValidationError.name) {
-            throw error4;
-          } else {
-            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
-              core14.error(`Failed to restore: ${error4.message}`);
-            } else {
-              core14.warning(`Failed to restore: ${error4.message}`);
-            }
-          }
-        } finally {
-          try {
-            yield utils.unlinkFile(archivePath);
-          } catch (error4) {
-            core14.debug(`Failed to delete archive: ${error4}`);
-          }
+        const unzipPath = yield io6.which("unzip", true);
+        const args = [file];
+        if (!core14.isDebug()) {
+          args.unshift("-q");
         }
-        return void 0;
+        args.unshift("-o");
+        yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest });
       });
     }
-    function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
+    function cacheDir(sourceDir, tool, version, arch) {
       return __awaiter4(this, void 0, void 0, function* () {
-        options = Object.assign(Object.assign({}, options), { useAzureSdk: true });
-        restoreKeys = restoreKeys || [];
-        const keys = [primaryKey, ...restoreKeys];
-        core14.debug("Resolved Keys:");
-        core14.debug(JSON.stringify(keys));
-        if (keys.length > 10) {
-          throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`);
-        }
-        for (const key of keys) {
-          checkKey(key);
+        version = semver8.clean(version) || version;
+        arch = arch || os.arch();
+        core14.debug(`Caching tool ${tool} ${version} ${arch}`);
+        core14.debug(`source dir: ${sourceDir}`);
+        if (!fs2.statSync(sourceDir).isDirectory()) {
+          throw new Error("sourceDir is not a directory");
         }
-        let archivePath = "";
-        try {
-          const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
-          const compressionMethod = yield utils.getCompressionMethod();
-          const request = {
-            key: primaryKey,
-            restoreKeys,
-            version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive)
-          };
-          const response = yield twirpClient.GetCacheEntryDownloadURL(request);
-          if (!response.ok) {
-            core14.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`);
-            return void 0;
-          }
-          const isRestoreKeyMatch = request.key !== response.matchedKey;
-          if (isRestoreKeyMatch) {
-            core14.info(`Cache hit for restore-key: ${response.matchedKey}`);
-          } else {
-            core14.info(`Cache hit for: ${response.matchedKey}`);
-          }
-          if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
-            core14.info("Lookup only - skipping download");
-            return response.matchedKey;
-          }
-          archivePath = path2.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
-          core14.debug(`Archive path: ${archivePath}`);
-          core14.debug(`Starting download of archive to: ${archivePath}`);
-          yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options);
-          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
-          core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
-          if (core14.isDebug()) {
-            yield (0, tar_1.listTar)(archivePath, compressionMethod);
-          }
-          yield (0, tar_1.extractTar)(archivePath, compressionMethod);
-          core14.info("Cache restored successfully");
-          return response.matchedKey;
-        } catch (error4) {
-          const typedError = error4;
-          if (typedError.name === ValidationError.name) {
-            throw error4;
-          } else {
-            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
-              core14.error(`Failed to restore: ${error4.message}`);
-            } else {
-              core14.warning(`Failed to restore: ${error4.message}`);
-            }
-          }
-        } finally {
-          try {
-            if (archivePath) {
-              yield utils.unlinkFile(archivePath);
-            }
-          } catch (error4) {
-            core14.debug(`Failed to delete archive: ${error4}`);
-          }
+        const destPath = yield _createToolPath(tool, version, arch);
+        for (const itemName of fs2.readdirSync(sourceDir)) {
+          const s = path2.join(sourceDir, itemName);
+          yield io6.cp(s, destPath, { recursive: true });
         }
-        return void 0;
+        _completeToolPath(tool, version, arch);
+        return destPath;
       });
     }
-    function saveCache4(paths, key, options, enableCrossOsArchive = false) {
+    exports2.cacheDir = cacheDir;
+    function cacheFile(sourceFile, targetFile, tool, version, arch) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
-        core14.debug(`Cache service version: ${cacheServiceVersion}`);
-        checkPaths(paths);
-        checkKey(key);
-        switch (cacheServiceVersion) {
-          case "v2":
-            return yield saveCacheV2(paths, key, options, enableCrossOsArchive);
-          case "v1":
-          default:
-            return yield saveCacheV1(paths, key, options, enableCrossOsArchive);
+        version = semver8.clean(version) || version;
+        arch = arch || os.arch();
+        core14.debug(`Caching tool ${tool} ${version} ${arch}`);
+        core14.debug(`source file: ${sourceFile}`);
+        if (!fs2.statSync(sourceFile).isFile()) {
+          throw new Error("sourceFile is not a file");
         }
+        const destFolder = yield _createToolPath(tool, version, arch);
+        const destPath = path2.join(destFolder, targetFile);
+        core14.debug(`destination file ${destPath}`);
+        yield io6.cp(sourceFile, destPath);
+        _completeToolPath(tool, version, arch);
+        return destFolder;
       });
     }
-    exports2.saveCache = saveCache4;
-    function saveCacheV1(paths, key, options, enableCrossOsArchive = false) {
-      var _a, _b, _c, _d, _e;
-      return __awaiter4(this, void 0, void 0, function* () {
-        const compressionMethod = yield utils.getCompressionMethod();
-        let cacheId = -1;
-        const cachePaths = yield utils.resolvePaths(paths);
-        core14.debug("Cache Paths:");
-        core14.debug(`${JSON.stringify(cachePaths)}`);
-        if (cachePaths.length === 0) {
-          throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);
+    exports2.cacheFile = cacheFile;
+    function find2(toolName, versionSpec, arch) {
+      if (!toolName) {
+        throw new Error("toolName parameter is required");
+      }
+      if (!versionSpec) {
+        throw new Error("versionSpec parameter is required");
+      }
+      arch = arch || os.arch();
+      if (!isExplicitVersion(versionSpec)) {
+        const localVersions = findAllVersions2(toolName, arch);
+        const match = evaluateVersions(localVersions, versionSpec);
+        versionSpec = match;
+      }
+      let toolPath = "";
+      if (versionSpec) {
+        versionSpec = semver8.clean(versionSpec) || "";
+        const cachePath = path2.join(_getCacheDirectory(), toolName, versionSpec, arch);
+        core14.debug(`checking cache: ${cachePath}`);
+        if (fs2.existsSync(cachePath) && fs2.existsSync(`${cachePath}.complete`)) {
+          core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
+          toolPath = cachePath;
+        } else {
+          core14.debug("not found");
         }
-        const archiveFolder = yield utils.createTempDirectory();
-        const archivePath = path2.join(archiveFolder, utils.getCacheFileName(compressionMethod));
-        core14.debug(`Archive Path: ${archivePath}`);
-        try {
-          yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
-          if (core14.isDebug()) {
-            yield (0, tar_1.listTar)(archivePath, compressionMethod);
-          }
-          const fileSizeLimit = 10 * 1024 * 1024 * 1024;
-          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
-          core14.debug(`File Size: ${archiveFileSize}`);
-          if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) {
-            throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`);
-          }
-          core14.debug("Reserving Cache");
-          const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, {
-            compressionMethod,
-            enableCrossOsArchive,
-            cacheSize: archiveFileSize
-          });
-          if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) {
-            cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId;
-          } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) {
-            throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`);
-          } else {
-            throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`);
-          }
-          core14.debug(`Saving Cache (ID: ${cacheId})`);
-          yield cacheHttpClient.saveCache(cacheId, archivePath, "", options);
-        } catch (error4) {
-          const typedError = error4;
-          if (typedError.name === ValidationError.name) {
-            throw error4;
-          } else if (typedError.name === ReserveCacheError2.name) {
-            core14.info(`Failed to save: ${typedError.message}`);
-          } else {
-            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
-              core14.error(`Failed to save: ${typedError.message}`);
-            } else {
-              core14.warning(`Failed to save: ${typedError.message}`);
+      }
+      return toolPath;
+    }
+    exports2.find = find2;
+    function findAllVersions2(toolName, arch) {
+      const versions = [];
+      arch = arch || os.arch();
+      const toolPath = path2.join(_getCacheDirectory(), toolName);
+      if (fs2.existsSync(toolPath)) {
+        const children = fs2.readdirSync(toolPath);
+        for (const child of children) {
+          if (isExplicitVersion(child)) {
+            const fullPath = path2.join(toolPath, child, arch || "");
+            if (fs2.existsSync(fullPath) && fs2.existsSync(`${fullPath}.complete`)) {
+              versions.push(child);
             }
           }
-        } finally {
-          try {
-            yield utils.unlinkFile(archivePath);
-          } catch (error4) {
-            core14.debug(`Failed to delete archive: ${error4}`);
-          }
         }
-        return cacheId;
-      });
+      }
+      return versions;
     }
-    function saveCacheV2(paths, key, options, enableCrossOsArchive = false) {
+    exports2.findAllVersions = findAllVersions2;
+    function getManifestFromRepo(owner, repo, auth, branch = "master") {
       return __awaiter4(this, void 0, void 0, function* () {
-        options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true });
-        const compressionMethod = yield utils.getCompressionMethod();
-        const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
-        let cacheId = -1;
-        const cachePaths = yield utils.resolvePaths(paths);
-        core14.debug("Cache Paths:");
-        core14.debug(`${JSON.stringify(cachePaths)}`);
-        if (cachePaths.length === 0) {
-          throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);
+        let releases = [];
+        const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`;
+        const http = new httpm.HttpClient("tool-cache");
+        const headers = {};
+        if (auth) {
+          core14.debug("set auth");
+          headers.authorization = auth;
         }
-        const archiveFolder = yield utils.createTempDirectory();
-        const archivePath = path2.join(archiveFolder, utils.getCacheFileName(compressionMethod));
-        core14.debug(`Archive Path: ${archivePath}`);
-        try {
-          yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
-          if (core14.isDebug()) {
-            yield (0, tar_1.listTar)(archivePath, compressionMethod);
-          }
-          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
-          core14.debug(`File Size: ${archiveFileSize}`);
-          options.archiveSizeBytes = archiveFileSize;
-          core14.debug("Reserving Cache");
-          const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive);
-          const request = {
-            key,
-            version
-          };
-          let signedUploadUrl;
-          try {
-            const response = yield twirpClient.CreateCacheEntry(request);
-            if (!response.ok) {
-              if (response.message) {
-                core14.warning(`Cache reservation failed: ${response.message}`);
-              }
-              throw new Error(response.message || "Response was not ok");
-            }
-            signedUploadUrl = response.signedUploadUrl;
-          } catch (error4) {
-            core14.debug(`Failed to reserve cache: ${error4}`);
-            throw new ReserveCacheError2(`Unable to reserve cache with key ${key}, another job may be creating this cache.`);
-          }
-          core14.debug(`Attempting to upload cache located at: ${archivePath}`);
-          yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options);
-          const finalizeRequest = {
-            key,
-            version,
-            sizeBytes: `${archiveFileSize}`
-          };
-          const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest);
-          core14.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`);
-          if (!finalizeResponse.ok) {
-            if (finalizeResponse.message) {
-              throw new FinalizeCacheError(finalizeResponse.message);
-            }
-            throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`);
-          }
-          cacheId = parseInt(finalizeResponse.entryId);
-        } catch (error4) {
-          const typedError = error4;
-          if (typedError.name === ValidationError.name) {
-            throw error4;
-          } else if (typedError.name === ReserveCacheError2.name) {
-            core14.info(`Failed to save: ${typedError.message}`);
-          } else if (typedError.name === FinalizeCacheError.name) {
-            core14.warning(typedError.message);
-          } else {
-            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
-              core14.error(`Failed to save: ${typedError.message}`);
-            } else {
-              core14.warning(`Failed to save: ${typedError.message}`);
-            }
-          }
-        } finally {
-          try {
-            yield utils.unlinkFile(archivePath);
-          } catch (error4) {
-            core14.debug(`Failed to delete archive: ${error4}`);
-          }
+        const response = yield http.getJson(treeUrl, headers);
+        if (!response.result) {
+          return releases;
         }
-        return cacheId;
-      });
-    }
-  }
-});
-
-// node_modules/@actions/tool-cache/lib/manifest.js
-var require_manifest = __commonJS({
-  "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
+        let manifestUrl = "";
+        for (const item of response.result.tree) {
+          if (item.path === "versions-manifest.json") {
+            manifestUrl = item.url;
+            break;
           }
         }
-        function rejected(value) {
+        headers["accept"] = "application/vnd.github.VERSION.raw";
+        let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody();
+        if (versionsRaw) {
+          versionsRaw = versionsRaw.replace(/^\uFEFF/, "");
           try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+            releases = JSON.parse(versionsRaw);
+          } catch (_a) {
+            core14.debug("Invalid json");
           }
         }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
+        return releases;
       });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0;
-    var semver8 = __importStar4(require_semver2());
-    var core_1 = require_core();
-    var os = require("os");
-    var cp = require("child_process");
-    var fs2 = require("fs");
-    function _findMatch(versionSpec, stable, candidates, archFilter) {
+    }
+    exports2.getManifestFromRepo = getManifestFromRepo;
+    function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const platFilter = os.platform();
-        let result;
-        let match;
-        let file;
-        for (const candidate of candidates) {
-          const version = candidate.version;
-          (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`);
-          if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) {
-            file = candidate.files.find((item) => {
-              (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`);
-              let chk = item.arch === archFilter && item.platform === platFilter;
-              if (chk && item.platform_version) {
-                const osVersion = module2.exports._getOsVersion();
-                if (osVersion === item.platform_version) {
-                  chk = true;
-                } else {
-                  chk = semver8.satisfies(osVersion, item.platform_version);
-                }
-              }
-              return chk;
-            });
-            if (file) {
-              (0, core_1.debug)(`matched ${candidate.version}`);
-              match = candidate;
-              break;
-            }
-          }
-        }
-        if (match && file) {
-          result = Object.assign({}, match);
-          result.files = [file];
+        const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter);
+        return match;
+      });
+    }
+    exports2.findFromManifest = findFromManifest;
+    function _createExtractFolder(dest) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        if (!dest) {
+          dest = path2.join(_getTempDirectory(), crypto.randomUUID());
         }
-        return result;
+        yield io6.mkdirP(dest);
+        return dest;
       });
     }
-    exports2._findMatch = _findMatch;
-    function _getOsVersion() {
-      const plat = os.platform();
+    function _createToolPath(tool, version, arch) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const folderPath = path2.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || "");
+        core14.debug(`destination ${folderPath}`);
+        const markerPath = `${folderPath}.complete`;
+        yield io6.rmRF(folderPath);
+        yield io6.rmRF(markerPath);
+        yield io6.mkdirP(folderPath);
+        return folderPath;
+      });
+    }
+    function _completeToolPath(tool, version, arch) {
+      const folderPath = path2.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || "");
+      const markerPath = `${folderPath}.complete`;
+      fs2.writeFileSync(markerPath, "");
+      core14.debug("finished caching tool");
+    }
+    function isExplicitVersion(versionSpec) {
+      const c = semver8.clean(versionSpec) || "";
+      core14.debug(`isExplicit: ${c}`);
+      const valid3 = semver8.valid(c) != null;
+      core14.debug(`explicit? ${valid3}`);
+      return valid3;
+    }
+    exports2.isExplicitVersion = isExplicitVersion;
+    function evaluateVersions(versions, versionSpec) {
       let version = "";
-      if (plat === "darwin") {
-        version = cp.execSync("sw_vers -productVersion").toString();
-      } else if (plat === "linux") {
-        const lsbContents = module2.exports._readLinuxVersionFile();
-        if (lsbContents) {
-          const lines = lsbContents.split("\n");
-          for (const line of lines) {
-            const parts = line.split("=");
-            if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) {
-              version = parts[1].trim().replace(/^"/, "").replace(/"$/, "");
-              break;
-            }
-          }
+      core14.debug(`evaluating ${versions.length} versions`);
+      versions = versions.sort((a, b) => {
+        if (semver8.gt(a, b)) {
+          return 1;
+        }
+        return -1;
+      });
+      for (let i = versions.length - 1; i >= 0; i--) {
+        const potential = versions[i];
+        const satisfied = semver8.satisfies(potential, versionSpec);
+        if (satisfied) {
+          version = potential;
+          break;
         }
       }
+      if (version) {
+        core14.debug(`matched: ${version}`);
+      } else {
+        core14.debug("match not found");
+      }
       return version;
     }
-    exports2._getOsVersion = _getOsVersion;
-    function _readLinuxVersionFile() {
-      const lsbReleaseFile = "/etc/lsb-release";
-      const osReleaseFile = "/etc/os-release";
-      let contents = "";
-      if (fs2.existsSync(lsbReleaseFile)) {
-        contents = fs2.readFileSync(lsbReleaseFile).toString();
-      } else if (fs2.existsSync(osReleaseFile)) {
-        contents = fs2.readFileSync(osReleaseFile).toString();
-      }
-      return contents;
+    exports2.evaluateVersions = evaluateVersions;
+    function _getCacheDirectory() {
+      const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || "";
+      (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined");
+      return cacheDirectory;
+    }
+    function _getTempDirectory() {
+      const tempDirectory = process.env["RUNNER_TEMP"] || "";
+      (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined");
+      return tempDirectory;
+    }
+    function _getGlobal(key, defaultValue) {
+      const value = global[key];
+      return value !== void 0 ? value : defaultValue;
+    }
+    function _unique(values) {
+      return Array.from(new Set(values));
     }
-    exports2._readLinuxVersionFile = _readLinuxVersionFile;
   }
 });
 
-// node_modules/@actions/tool-cache/lib/retry-helper.js
-var require_retry_helper = __commonJS({
-  "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) {
+// node_modules/fast-deep-equal/index.js
+var require_fast_deep_equal = __commonJS({
+  "node_modules/fast-deep-equal/index.js"(exports2, module2) {
     "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve2) {
-          resolve2(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve2, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
+    module2.exports = function equal(a, b) {
+      if (a === b) return true;
+      if (a && b && typeof a == "object" && typeof b == "object") {
+        if (a.constructor !== b.constructor) return false;
+        var length, i, keys;
+        if (Array.isArray(a)) {
+          length = a.length;
+          if (length != b.length) return false;
+          for (i = length; i-- !== 0; )
+            if (!equal(a[i], b[i])) return false;
+          return true;
         }
-        function step(result) {
-          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
+        if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
+        if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
+        if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
+        keys = Object.keys(a);
+        length = keys.length;
+        if (length !== Object.keys(b).length) return false;
+        for (i = length; i-- !== 0; )
+          if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
+        for (i = length; i-- !== 0; ) {
+          var key = keys[i];
+          if (!equal(a[key], b[key])) return false;
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
+        return true;
+      }
+      return a !== a && b !== b;
     };
+  }
+});
+
+// node_modules/@actions/http-client/lib/proxy.js
+var require_proxy7 = __commonJS({
+  "node_modules/@actions/http-client/lib/proxy.js"(exports2) {
+    "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.RetryHelper = void 0;
-    var core14 = __importStar4(require_core());
-    var RetryHelper = class {
-      constructor(maxAttempts, minSeconds, maxSeconds) {
-        if (maxAttempts < 1) {
-          throw new Error("max attempts should be greater than or equal to 1");
+    exports2.getProxyUrl = getProxyUrl;
+    exports2.checkBypass = checkBypass;
+    function getProxyUrl(reqUrl) {
+      const usingSsl = reqUrl.protocol === "https:";
+      if (checkBypass(reqUrl)) {
+        return void 0;
+      }
+      const proxyVar = (() => {
+        if (usingSsl) {
+          return process.env["https_proxy"] || process.env["HTTPS_PROXY"];
+        } else {
+          return process.env["http_proxy"] || process.env["HTTP_PROXY"];
         }
-        this.maxAttempts = maxAttempts;
-        this.minSeconds = Math.floor(minSeconds);
-        this.maxSeconds = Math.floor(maxSeconds);
-        if (this.minSeconds > this.maxSeconds) {
-          throw new Error("min seconds should be less than or equal to max seconds");
+      })();
+      if (proxyVar) {
+        try {
+          return new DecodedURL(proxyVar);
+        } catch (_a) {
+          if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://"))
+            return new DecodedURL(`http://${proxyVar}`);
         }
+      } else {
+        return void 0;
       }
-      execute(action, isRetryable) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          let attempt = 1;
-          while (attempt < this.maxAttempts) {
-            try {
-              return yield action();
-            } catch (err) {
-              if (isRetryable && !isRetryable(err)) {
-                throw err;
-              }
-              core14.info(err.message);
-            }
-            const seconds = this.getSleepAmount();
-            core14.info(`Waiting ${seconds} seconds before trying again`);
-            yield this.sleep(seconds);
-            attempt++;
-          }
-          return yield action();
-        });
+    }
+    function checkBypass(reqUrl) {
+      if (!reqUrl.hostname) {
+        return false;
       }
-      getSleepAmount() {
-        return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds;
+      const reqHost = reqUrl.hostname;
+      if (isLoopbackAddress(reqHost)) {
+        return true;
       }
-      sleep(seconds) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          return new Promise((resolve2) => setTimeout(resolve2, seconds * 1e3));
-        });
+      const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || "";
+      if (!noProxy) {
+        return false;
+      }
+      let reqPort;
+      if (reqUrl.port) {
+        reqPort = Number(reqUrl.port);
+      } else if (reqUrl.protocol === "http:") {
+        reqPort = 80;
+      } else if (reqUrl.protocol === "https:") {
+        reqPort = 443;
+      }
+      const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+      if (typeof reqPort === "number") {
+        upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
+      }
+      for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) {
+        if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) {
+          return true;
+        }
+      }
+      return false;
+    }
+    function isLoopbackAddress(host) {
+      const hostLower = host.toLowerCase();
+      return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]");
+    }
+    var DecodedURL = class extends URL {
+      constructor(url, base) {
+        super(url, base);
+        this._decodedUsername = decodeURIComponent(super.username);
+        this._decodedPassword = decodeURIComponent(super.password);
+      }
+      get username() {
+        return this._decodedUsername;
+      }
+      get password() {
+        return this._decodedPassword;
       }
     };
-    exports2.RetryHelper = RetryHelper;
   }
 });
 
-// node_modules/@actions/tool-cache/lib/tool-cache.js
-var require_tool_cache = __commonJS({
-  "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) {
+// node_modules/@actions/http-client/lib/index.js
+var require_lib9 = __commonJS({
+  "node_modules/@actions/http-client/lib/index.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -108381,15 +112858,25 @@ var require_tool_cache = __commonJS({
     }) : function(o, v) {
       o["default"] = v;
     });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
+    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
+      var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function(o2) {
+          var ar = [];
+          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
+          return ar;
+        };
+        return ownKeys(o);
+      };
+      return function(mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) {
+          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
+        }
+        __setModuleDefault4(result, mod);
+        return result;
+      };
+    })();
     var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
       function adopt(value) {
         return value instanceof P ? value : new P(function(resolve2) {
@@ -108418,523 +112905,616 @@ var require_tool_cache = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0;
-    var core14 = __importStar4(require_core());
-    var io6 = __importStar4(require_io());
-    var crypto = __importStar4(require("crypto"));
-    var fs2 = __importStar4(require("fs"));
-    var mm = __importStar4(require_manifest());
-    var os = __importStar4(require("os"));
-    var path2 = __importStar4(require("path"));
-    var httpm = __importStar4(require_lib());
-    var semver8 = __importStar4(require_semver2());
-    var stream = __importStar4(require("stream"));
-    var util = __importStar4(require("util"));
-    var assert_1 = require("assert");
-    var exec_1 = require_exec();
-    var retry_helper_1 = require_retry_helper();
-    var HTTPError = class extends Error {
-      constructor(httpStatusCode) {
-        super(`Unexpected HTTP response: ${httpStatusCode}`);
-        this.httpStatusCode = httpStatusCode;
-        Object.setPrototypeOf(this, new.target.prototype);
+    exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0;
+    exports2.getProxyUrl = getProxyUrl;
+    exports2.isHttps = isHttps;
+    var http = __importStar4(require("http"));
+    var https2 = __importStar4(require("https"));
+    var pm = __importStar4(require_proxy7());
+    var tunnel = __importStar4(require_tunnel2());
+    var undici_1 = require_undici();
+    var HttpCodes;
+    (function(HttpCodes2) {
+      HttpCodes2[HttpCodes2["OK"] = 200] = "OK";
+      HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices";
+      HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently";
+      HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved";
+      HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther";
+      HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified";
+      HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy";
+      HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy";
+      HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+      HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect";
+      HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest";
+      HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized";
+      HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired";
+      HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden";
+      HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound";
+      HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+      HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable";
+      HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+      HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout";
+      HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict";
+      HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone";
+      HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests";
+      HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError";
+      HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented";
+      HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway";
+      HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+      HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout";
+    })(HttpCodes || (exports2.HttpCodes = HttpCodes = {}));
+    var Headers;
+    (function(Headers2) {
+      Headers2["Accept"] = "accept";
+      Headers2["ContentType"] = "content-type";
+    })(Headers || (exports2.Headers = Headers = {}));
+    var MediaTypes;
+    (function(MediaTypes2) {
+      MediaTypes2["ApplicationJson"] = "application/json";
+    })(MediaTypes || (exports2.MediaTypes = MediaTypes = {}));
+    function getProxyUrl(serverUrl) {
+      const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+      return proxyUrl ? proxyUrl.href : "";
+    }
+    var HttpRedirectCodes = [
+      HttpCodes.MovedPermanently,
+      HttpCodes.ResourceMoved,
+      HttpCodes.SeeOther,
+      HttpCodes.TemporaryRedirect,
+      HttpCodes.PermanentRedirect
+    ];
+    var HttpResponseRetryCodes = [
+      HttpCodes.BadGateway,
+      HttpCodes.ServiceUnavailable,
+      HttpCodes.GatewayTimeout
+    ];
+    var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"];
+    var ExponentialBackoffCeiling = 10;
+    var ExponentialBackoffTimeSlice = 5;
+    var HttpClientError = class _HttpClientError extends Error {
+      constructor(message, statusCode) {
+        super(message);
+        this.name = "HttpClientError";
+        this.statusCode = statusCode;
+        Object.setPrototypeOf(this, _HttpClientError.prototype);
       }
     };
-    exports2.HTTPError = HTTPError;
-    var IS_WINDOWS = process.platform === "win32";
-    var IS_MAC = process.platform === "darwin";
-    var userAgent = "actions/tool-cache";
-    function downloadTool2(url, dest, auth, headers) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        dest = dest || path2.join(_getTempDirectory(), crypto.randomUUID());
-        yield io6.mkdirP(path2.dirname(dest));
-        core14.debug(`Downloading ${url}`);
-        core14.debug(`Destination ${dest}`);
-        const maxAttempts = 3;
-        const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10);
-        const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20);
-        const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds);
-        return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () {
-          return yield downloadToolAttempt(url, dest || "", auth, headers);
-        }), (err) => {
-          if (err instanceof HTTPError && err.httpStatusCode) {
-            if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) {
-              return false;
-            }
-          }
-          return true;
+    exports2.HttpClientError = HttpClientError;
+    var HttpClientResponse = class {
+      constructor(message) {
+        this.message = message;
+      }
+      readBody() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
+            let output = Buffer.alloc(0);
+            this.message.on("data", (chunk) => {
+              output = Buffer.concat([output, chunk]);
+            });
+            this.message.on("end", () => {
+              resolve2(output.toString());
+            });
+          }));
         });
-      });
-    }
-    exports2.downloadTool = downloadTool2;
-    function downloadToolAttempt(url, dest, auth, headers) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        if (fs2.existsSync(dest)) {
-          throw new Error(`Destination file path ${dest} already exists`);
-        }
-        const http = new httpm.HttpClient(userAgent, [], {
-          allowRetries: false
+      }
+      readBodyBuffer() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2) => __awaiter4(this, void 0, void 0, function* () {
+            const chunks = [];
+            this.message.on("data", (chunk) => {
+              chunks.push(chunk);
+            });
+            this.message.on("end", () => {
+              resolve2(Buffer.concat(chunks));
+            });
+          }));
         });
-        if (auth) {
-          core14.debug("set auth");
-          if (headers === void 0) {
-            headers = {};
+      }
+    };
+    exports2.HttpClientResponse = HttpClientResponse;
+    function isHttps(requestUrl) {
+      const parsedUrl = new URL(requestUrl);
+      return parsedUrl.protocol === "https:";
+    }
+    var HttpClient2 = class {
+      constructor(userAgent, handlers, requestOptions) {
+        this._ignoreSslError = false;
+        this._allowRedirects = true;
+        this._allowRedirectDowngrade = false;
+        this._maxRedirects = 50;
+        this._allowRetries = false;
+        this._maxRetries = 1;
+        this._keepAlive = false;
+        this._disposed = false;
+        this.userAgent = userAgent;
+        this.handlers = handlers || [];
+        this.requestOptions = requestOptions;
+        if (requestOptions) {
+          if (requestOptions.ignoreSslError != null) {
+            this._ignoreSslError = requestOptions.ignoreSslError;
           }
-          headers.authorization = auth;
-        }
-        const response = yield http.get(url, headers);
-        if (response.message.statusCode !== 200) {
-          const err = new HTTPError(response.message.statusCode);
-          core14.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
-          throw err;
-        }
-        const pipeline = util.promisify(stream.pipeline);
-        const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message);
-        const readStream = responseMessageFactory();
-        let succeeded = false;
-        try {
-          yield pipeline(readStream, fs2.createWriteStream(dest));
-          core14.debug("download complete");
-          succeeded = true;
-          return dest;
-        } finally {
-          if (!succeeded) {
-            core14.debug("download failed");
-            try {
-              yield io6.rmRF(dest);
-            } catch (err) {
-              core14.debug(`Failed to delete '${dest}'. ${err.message}`);
-            }
+          this._socketTimeout = requestOptions.socketTimeout;
+          if (requestOptions.allowRedirects != null) {
+            this._allowRedirects = requestOptions.allowRedirects;
           }
-        }
-      });
-    }
-    function extract7z(file, dest, _7zPath) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS");
-        (0, assert_1.ok)(file, 'parameter "file" is required');
-        dest = yield _createExtractFolder(dest);
-        const originalCwd = process.cwd();
-        process.chdir(dest);
-        if (_7zPath) {
-          try {
-            const logLevel = core14.isDebug() ? "-bb1" : "-bb0";
-            const args = [
-              "x",
-              logLevel,
-              "-bd",
-              "-sccUTF-8",
-              file
-            ];
-            const options = {
-              silent: true
-            };
-            yield (0, exec_1.exec)(`"${_7zPath}"`, args, options);
-          } finally {
-            process.chdir(originalCwd);
+          if (requestOptions.allowRedirectDowngrade != null) {
+            this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
           }
-        } else {
-          const escapedScript = path2.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, "");
-          const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, "");
-          const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, "");
-          const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`;
-          const args = [
-            "-NoLogo",
-            "-Sta",
-            "-NoProfile",
-            "-NonInteractive",
-            "-ExecutionPolicy",
-            "Unrestricted",
-            "-Command",
-            command
-          ];
-          const options = {
-            silent: true
-          };
-          try {
-            const powershellPath = yield io6.which("powershell", true);
-            yield (0, exec_1.exec)(`"${powershellPath}"`, args, options);
-          } finally {
-            process.chdir(originalCwd);
+          if (requestOptions.maxRedirects != null) {
+            this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+          }
+          if (requestOptions.keepAlive != null) {
+            this._keepAlive = requestOptions.keepAlive;
+          }
+          if (requestOptions.allowRetries != null) {
+            this._allowRetries = requestOptions.allowRetries;
+          }
+          if (requestOptions.maxRetries != null) {
+            this._maxRetries = requestOptions.maxRetries;
           }
         }
-        return dest;
-      });
-    }
-    exports2.extract7z = extract7z;
-    function extractTar2(file, dest, flags = "xz") {
-      return __awaiter4(this, void 0, void 0, function* () {
-        if (!file) {
-          throw new Error("parameter 'file' is required");
-        }
-        dest = yield _createExtractFolder(dest);
-        core14.debug("Checking tar --version");
-        let versionOutput = "";
-        yield (0, exec_1.exec)("tar --version", [], {
-          ignoreReturnCode: true,
-          silent: true,
-          listeners: {
-            stdout: (data) => versionOutput += data.toString(),
-            stderr: (data) => versionOutput += data.toString()
+      }
+      options(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("OPTIONS", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      get(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("GET", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      del(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("DELETE", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      post(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("POST", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      patch(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PATCH", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      put(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PUT", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      head(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("HEAD", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      sendStream(verb, requestUrl, stream, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request(verb, requestUrl, stream, additionalHeaders);
+        });
+      }
+      /**
+       * Gets a typed object from an endpoint
+       * Be aware that not found returns a null.  Other errors (4xx, 5xx) reject the promise
+       */
+      getJson(requestUrl_1) {
+        return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) {
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          const res = yield this.get(requestUrl, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      postJson(requestUrl_1, obj_1) {
+        return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
+          const res = yield this.post(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      putJson(requestUrl_1, obj_1) {
+        return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
+          const res = yield this.put(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      patchJson(requestUrl_1, obj_1) {
+        return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
+          const res = yield this.patch(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      /**
+       * Makes a raw http request.
+       * All other methods such as get, post, patch, and request ultimately call this.
+       * Prefer get, del, post and patch
+       */
+      request(verb, requestUrl, data, headers) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          if (this._disposed) {
+            throw new Error("Client has already been disposed.");
           }
+          const parsedUrl = new URL(requestUrl);
+          let info7 = this._prepareRequest(verb, parsedUrl, headers);
+          const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1;
+          let numTries = 0;
+          let response;
+          do {
+            response = yield this.requestRaw(info7, data);
+            if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
+              let authenticationHandler;
+              for (const handler of this.handlers) {
+                if (handler.canHandleAuthentication(response)) {
+                  authenticationHandler = handler;
+                  break;
+                }
+              }
+              if (authenticationHandler) {
+                return authenticationHandler.handleAuthentication(this, info7, data);
+              } else {
+                return response;
+              }
+            }
+            let redirectsRemaining = this._maxRedirects;
+            while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) {
+              const redirectUrl = response.message.headers["location"];
+              if (!redirectUrl) {
+                break;
+              }
+              const parsedRedirectUrl = new URL(redirectUrl);
+              if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
+                throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
+              }
+              yield response.readBody();
+              if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+                for (const header in headers) {
+                  if (header.toLowerCase() === "authorization") {
+                    delete headers[header];
+                  }
+                }
+              }
+              info7 = this._prepareRequest(verb, parsedRedirectUrl, headers);
+              response = yield this.requestRaw(info7, data);
+              redirectsRemaining--;
+            }
+            if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+              return response;
+            }
+            numTries += 1;
+            if (numTries < maxTries) {
+              yield response.readBody();
+              yield this._performExponentialBackoff(numTries);
+            }
+          } while (numTries < maxTries);
+          return response;
         });
-        core14.debug(versionOutput.trim());
-        const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR");
-        let args;
-        if (flags instanceof Array) {
-          args = flags;
-        } else {
-          args = [flags];
-        }
-        if (core14.isDebug() && !flags.includes("v")) {
-          args.push("-v");
-        }
-        let destArg = dest;
-        let fileArg = file;
-        if (IS_WINDOWS && isGnuTar) {
-          args.push("--force-local");
-          destArg = dest.replace(/\\/g, "/");
-          fileArg = file.replace(/\\/g, "/");
-        }
-        if (isGnuTar) {
-          args.push("--warning=no-unknown-keyword");
-          args.push("--overwrite");
-        }
-        args.push("-C", destArg, "-f", fileArg);
-        yield (0, exec_1.exec)(`tar`, args);
-        return dest;
-      });
-    }
-    exports2.extractTar = extractTar2;
-    function extractXar(file, dest, flags = []) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS");
-        (0, assert_1.ok)(file, 'parameter "file" is required');
-        dest = yield _createExtractFolder(dest);
-        let args;
-        if (flags instanceof Array) {
-          args = flags;
-        } else {
-          args = [flags];
+      }
+      /**
+       * Needs to be called if keepAlive is set to true in request options.
+       */
+      dispose() {
+        if (this._agent) {
+          this._agent.destroy();
         }
-        args.push("-x", "-C", dest, "-f", file);
-        if (core14.isDebug()) {
-          args.push("-v");
+        this._disposed = true;
+      }
+      /**
+       * Raw request.
+       * @param info
+       * @param data
+       */
+      requestRaw(info7, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2, reject) => {
+            function callbackForResult(err, res) {
+              if (err) {
+                reject(err);
+              } else if (!res) {
+                reject(new Error("Unknown error"));
+              } else {
+                resolve2(res);
+              }
+            }
+            this.requestRawWithCallback(info7, data, callbackForResult);
+          });
+        });
+      }
+      /**
+       * Raw request with callback.
+       * @param info
+       * @param data
+       * @param onResult
+       */
+      requestRawWithCallback(info7, data, onResult) {
+        if (typeof data === "string") {
+          if (!info7.options.headers) {
+            info7.options.headers = {};
+          }
+          info7.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8");
         }
-        const xarPath = yield io6.which("xar", true);
-        yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args));
-        return dest;
-      });
-    }
-    exports2.extractXar = extractXar;
-    function extractZip(file, dest) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        if (!file) {
-          throw new Error("parameter 'file' is required");
+        let callbackCalled = false;
+        function handleResult(err, res) {
+          if (!callbackCalled) {
+            callbackCalled = true;
+            onResult(err, res);
+          }
         }
-        dest = yield _createExtractFolder(dest);
-        if (IS_WINDOWS) {
-          yield extractZipWin(file, dest);
-        } else {
-          yield extractZipNix(file, dest);
+        const req = info7.httpModule.request(info7.options, (msg) => {
+          const res = new HttpClientResponse(msg);
+          handleResult(void 0, res);
+        });
+        let socket;
+        req.on("socket", (sock) => {
+          socket = sock;
+        });
+        req.setTimeout(this._socketTimeout || 3 * 6e4, () => {
+          if (socket) {
+            socket.end();
+          }
+          handleResult(new Error(`Request timeout: ${info7.options.path}`));
+        });
+        req.on("error", function(err) {
+          handleResult(err);
+        });
+        if (data && typeof data === "string") {
+          req.write(data, "utf8");
         }
-        return dest;
-      });
-    }
-    exports2.extractZip = extractZip;
-    function extractZipWin(file, dest) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, "");
-        const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, "");
-        const pwshPath = yield io6.which("pwsh", false);
-        if (pwshPath) {
-          const pwshCommand = [
-            `$ErrorActionPreference = 'Stop' ;`,
-            `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`,
-            `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`,
-            `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;`
-          ].join(" ");
-          const args = [
-            "-NoLogo",
-            "-NoProfile",
-            "-NonInteractive",
-            "-ExecutionPolicy",
-            "Unrestricted",
-            "-Command",
-            pwshCommand
-          ];
-          core14.debug(`Using pwsh at path: ${pwshPath}`);
-          yield (0, exec_1.exec)(`"${pwshPath}"`, args);
+        if (data && typeof data !== "string") {
+          data.on("close", function() {
+            req.end();
+          });
+          data.pipe(req);
         } else {
-          const powershellCommand = [
-            `$ErrorActionPreference = 'Stop' ;`,
-            `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`,
-            `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`,
-            `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`
-          ].join(" ");
-          const args = [
-            "-NoLogo",
-            "-Sta",
-            "-NoProfile",
-            "-NonInteractive",
-            "-ExecutionPolicy",
-            "Unrestricted",
-            "-Command",
-            powershellCommand
-          ];
-          const powershellPath = yield io6.which("powershell", true);
-          core14.debug(`Using powershell at path: ${powershellPath}`);
-          yield (0, exec_1.exec)(`"${powershellPath}"`, args);
-        }
-      });
-    }
-    function extractZipNix(file, dest) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const unzipPath = yield io6.which("unzip", true);
-        const args = [file];
-        if (!core14.isDebug()) {
-          args.unshift("-q");
+          req.end();
         }
-        args.unshift("-o");
-        yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest });
-      });
-    }
-    function cacheDir(sourceDir, tool, version, arch) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        version = semver8.clean(version) || version;
-        arch = arch || os.arch();
-        core14.debug(`Caching tool ${tool} ${version} ${arch}`);
-        core14.debug(`source dir: ${sourceDir}`);
-        if (!fs2.statSync(sourceDir).isDirectory()) {
-          throw new Error("sourceDir is not a directory");
+      }
+      /**
+       * Gets an http agent. This function is useful when you need an http agent that handles
+       * routing through a proxy server - depending upon the url and proxy environment variables.
+       * @param serverUrl  The server URL where the request will be sent. For example, https://api.github.com
+       */
+      getAgent(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        return this._getAgent(parsedUrl);
+      }
+      getAgentDispatcher(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (!useProxy) {
+          return;
         }
-        const destPath = yield _createToolPath(tool, version, arch);
-        for (const itemName of fs2.readdirSync(sourceDir)) {
-          const s = path2.join(sourceDir, itemName);
-          yield io6.cp(s, destPath, { recursive: true });
+        return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
+      }
+      _prepareRequest(method, requestUrl, headers) {
+        const info7 = {};
+        info7.parsedUrl = requestUrl;
+        const usingSsl = info7.parsedUrl.protocol === "https:";
+        info7.httpModule = usingSsl ? https2 : http;
+        const defaultPort = usingSsl ? 443 : 80;
+        info7.options = {};
+        info7.options.host = info7.parsedUrl.hostname;
+        info7.options.port = info7.parsedUrl.port ? parseInt(info7.parsedUrl.port) : defaultPort;
+        info7.options.path = (info7.parsedUrl.pathname || "") + (info7.parsedUrl.search || "");
+        info7.options.method = method;
+        info7.options.headers = this._mergeHeaders(headers);
+        if (this.userAgent != null) {
+          info7.options.headers["user-agent"] = this.userAgent;
         }
-        _completeToolPath(tool, version, arch);
-        return destPath;
-      });
-    }
-    exports2.cacheDir = cacheDir;
-    function cacheFile(sourceFile, targetFile, tool, version, arch) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        version = semver8.clean(version) || version;
-        arch = arch || os.arch();
-        core14.debug(`Caching tool ${tool} ${version} ${arch}`);
-        core14.debug(`source file: ${sourceFile}`);
-        if (!fs2.statSync(sourceFile).isFile()) {
-          throw new Error("sourceFile is not a file");
+        info7.options.agent = this._getAgent(info7.parsedUrl);
+        if (this.handlers) {
+          for (const handler of this.handlers) {
+            handler.prepareRequest(info7.options);
+          }
         }
-        const destFolder = yield _createToolPath(tool, version, arch);
-        const destPath = path2.join(destFolder, targetFile);
-        core14.debug(`destination file ${destPath}`);
-        yield io6.cp(sourceFile, destPath);
-        _completeToolPath(tool, version, arch);
-        return destFolder;
-      });
-    }
-    exports2.cacheFile = cacheFile;
-    function find2(toolName, versionSpec, arch) {
-      if (!toolName) {
-        throw new Error("toolName parameter is required");
-      }
-      if (!versionSpec) {
-        throw new Error("versionSpec parameter is required");
+        return info7;
       }
-      arch = arch || os.arch();
-      if (!isExplicitVersion(versionSpec)) {
-        const localVersions = findAllVersions2(toolName, arch);
-        const match = evaluateVersions(localVersions, versionSpec);
-        versionSpec = match;
+      _mergeHeaders(headers) {
+        if (this.requestOptions && this.requestOptions.headers) {
+          return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
+        }
+        return lowercaseKeys(headers || {});
       }
-      let toolPath = "";
-      if (versionSpec) {
-        versionSpec = semver8.clean(versionSpec) || "";
-        const cachePath = path2.join(_getCacheDirectory(), toolName, versionSpec, arch);
-        core14.debug(`checking cache: ${cachePath}`);
-        if (fs2.existsSync(cachePath) && fs2.existsSync(`${cachePath}.complete`)) {
-          core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
-          toolPath = cachePath;
-        } else {
-          core14.debug("not found");
+      /**
+       * Gets an existing header value or returns a default.
+       * Handles converting number header values to strings since HTTP headers must be strings.
+       * Note: This returns string | string[] since some headers can have multiple values.
+       * For headers that must always be a single string (like Content-Type), use the
+       * specialized _getExistingOrDefaultContentTypeHeader method instead.
+       */
+      _getExistingOrDefaultHeader(additionalHeaders, header, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          const headerValue = lowercaseKeys(this.requestOptions.headers)[header];
+          if (headerValue) {
+            clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue;
+          }
+        }
+        const additionalValue = additionalHeaders[header];
+        if (additionalValue !== void 0) {
+          return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue;
         }
+        if (clientHeader !== void 0) {
+          return clientHeader;
+        }
+        return _default2;
       }
-      return toolPath;
-    }
-    exports2.find = find2;
-    function findAllVersions2(toolName, arch) {
-      const versions = [];
-      arch = arch || os.arch();
-      const toolPath = path2.join(_getCacheDirectory(), toolName);
-      if (fs2.existsSync(toolPath)) {
-        const children = fs2.readdirSync(toolPath);
-        for (const child of children) {
-          if (isExplicitVersion(child)) {
-            const fullPath = path2.join(toolPath, child, arch || "");
-            if (fs2.existsSync(fullPath) && fs2.existsSync(`${fullPath}.complete`)) {
-              versions.push(child);
+      /**
+       * Specialized version of _getExistingOrDefaultHeader for Content-Type header.
+       * Always returns a single string (not an array) since Content-Type should be a single value.
+       * Converts arrays to comma-separated strings and numbers to strings to ensure type safety.
+       * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers
+       * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]).
+       */
+      _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType];
+          if (headerValue) {
+            if (typeof headerValue === "number") {
+              clientHeader = String(headerValue);
+            } else if (Array.isArray(headerValue)) {
+              clientHeader = headerValue.join(", ");
+            } else {
+              clientHeader = headerValue;
             }
           }
         }
+        const additionalValue = additionalHeaders[Headers.ContentType];
+        if (additionalValue !== void 0) {
+          if (typeof additionalValue === "number") {
+            return String(additionalValue);
+          } else if (Array.isArray(additionalValue)) {
+            return additionalValue.join(", ");
+          } else {
+            return additionalValue;
+          }
+        }
+        if (clientHeader !== void 0) {
+          return clientHeader;
+        }
+        return _default2;
       }
-      return versions;
-    }
-    exports2.findAllVersions = findAllVersions2;
-    function getManifestFromRepo(owner, repo, auth, branch = "master") {
-      return __awaiter4(this, void 0, void 0, function* () {
-        let releases = [];
-        const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`;
-        const http = new httpm.HttpClient("tool-cache");
-        const headers = {};
-        if (auth) {
-          core14.debug("set auth");
-          headers.authorization = auth;
+      _getAgent(parsedUrl) {
+        let agent;
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (this._keepAlive && useProxy) {
+          agent = this._proxyAgent;
         }
-        const response = yield http.getJson(treeUrl, headers);
-        if (!response.result) {
-          return releases;
+        if (!useProxy) {
+          agent = this._agent;
         }
-        let manifestUrl = "";
-        for (const item of response.result.tree) {
-          if (item.path === "versions-manifest.json") {
-            manifestUrl = item.url;
-            break;
-          }
+        if (agent) {
+          return agent;
         }
-        headers["accept"] = "application/vnd.github.VERSION.raw";
-        let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody();
-        if (versionsRaw) {
-          versionsRaw = versionsRaw.replace(/^\uFEFF/, "");
-          try {
-            releases = JSON.parse(versionsRaw);
-          } catch (_a) {
-            core14.debug("Invalid json");
-          }
+        const usingSsl = parsedUrl.protocol === "https:";
+        let maxSockets = 100;
+        if (this.requestOptions) {
+          maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
         }
-        return releases;
-      });
-    }
-    exports2.getManifestFromRepo = getManifestFromRepo;
-    function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter);
-        return match;
-      });
-    }
-    exports2.findFromManifest = findFromManifest;
-    function _createExtractFolder(dest) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        if (!dest) {
-          dest = path2.join(_getTempDirectory(), crypto.randomUUID());
+        if (proxyUrl && proxyUrl.hostname) {
+          const agentOptions = {
+            maxSockets,
+            keepAlive: this._keepAlive,
+            proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && {
+              proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+            }), { host: proxyUrl.hostname, port: proxyUrl.port })
+          };
+          let tunnelAgent;
+          const overHttps = proxyUrl.protocol === "https:";
+          if (usingSsl) {
+            tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+          } else {
+            tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
+          }
+          agent = tunnelAgent(agentOptions);
+          this._proxyAgent = agent;
         }
-        yield io6.mkdirP(dest);
-        return dest;
-      });
-    }
-    function _createToolPath(tool, version, arch) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const folderPath = path2.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || "");
-        core14.debug(`destination ${folderPath}`);
-        const markerPath = `${folderPath}.complete`;
-        yield io6.rmRF(folderPath);
-        yield io6.rmRF(markerPath);
-        yield io6.mkdirP(folderPath);
-        return folderPath;
-      });
-    }
-    function _completeToolPath(tool, version, arch) {
-      const folderPath = path2.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch || "");
-      const markerPath = `${folderPath}.complete`;
-      fs2.writeFileSync(markerPath, "");
-      core14.debug("finished caching tool");
-    }
-    function isExplicitVersion(versionSpec) {
-      const c = semver8.clean(versionSpec) || "";
-      core14.debug(`isExplicit: ${c}`);
-      const valid3 = semver8.valid(c) != null;
-      core14.debug(`explicit? ${valid3}`);
-      return valid3;
-    }
-    exports2.isExplicitVersion = isExplicitVersion;
-    function evaluateVersions(versions, versionSpec) {
-      let version = "";
-      core14.debug(`evaluating ${versions.length} versions`);
-      versions = versions.sort((a, b) => {
-        if (semver8.gt(a, b)) {
-          return 1;
+        if (!agent) {
+          const options = { keepAlive: this._keepAlive, maxSockets };
+          agent = usingSsl ? new https2.Agent(options) : new http.Agent(options);
+          this._agent = agent;
         }
-        return -1;
-      });
-      for (let i = versions.length - 1; i >= 0; i--) {
-        const potential = versions[i];
-        const satisfied = semver8.satisfies(potential, versionSpec);
-        if (satisfied) {
-          version = potential;
-          break;
+        if (usingSsl && this._ignoreSslError) {
+          agent.options = Object.assign(agent.options || {}, {
+            rejectUnauthorized: false
+          });
         }
+        return agent;
       }
-      if (version) {
-        core14.debug(`matched: ${version}`);
-      } else {
-        core14.debug("match not found");
-      }
-      return version;
-    }
-    exports2.evaluateVersions = evaluateVersions;
-    function _getCacheDirectory() {
-      const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || "";
-      (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined");
-      return cacheDirectory;
-    }
-    function _getTempDirectory() {
-      const tempDirectory = process.env["RUNNER_TEMP"] || "";
-      (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined");
-      return tempDirectory;
-    }
-    function _getGlobal(key, defaultValue) {
-      const value = global[key];
-      return value !== void 0 ? value : defaultValue;
-    }
-    function _unique(values) {
-      return Array.from(new Set(values));
-    }
-  }
-});
-
-// node_modules/fast-deep-equal/index.js
-var require_fast_deep_equal = __commonJS({
-  "node_modules/fast-deep-equal/index.js"(exports2, module2) {
-    "use strict";
-    module2.exports = function equal(a, b) {
-      if (a === b) return true;
-      if (a && b && typeof a == "object" && typeof b == "object") {
-        if (a.constructor !== b.constructor) return false;
-        var length, i, keys;
-        if (Array.isArray(a)) {
-          length = a.length;
-          if (length != b.length) return false;
-          for (i = length; i-- !== 0; )
-            if (!equal(a[i], b[i])) return false;
-          return true;
+      _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+        let proxyAgent;
+        if (this._keepAlive) {
+          proxyAgent = this._proxyAgentDispatcher;
         }
-        if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
-        if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
-        if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
-        keys = Object.keys(a);
-        length = keys.length;
-        if (length !== Object.keys(b).length) return false;
-        for (i = length; i-- !== 0; )
-          if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
-        for (i = length; i-- !== 0; ) {
-          var key = keys[i];
-          if (!equal(a[key], b[key])) return false;
+        if (proxyAgent) {
+          return proxyAgent;
         }
-        return true;
+        const usingSsl = parsedUrl.protocol === "https:";
+        proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && {
+          token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}`
+        }));
+        this._proxyAgentDispatcher = proxyAgent;
+        if (usingSsl && this._ignoreSslError) {
+          proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return proxyAgent;
+      }
+      _performExponentialBackoff(retryNumber) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+          const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+          return new Promise((resolve2) => setTimeout(() => resolve2(), ms));
+        });
+      }
+      _processResponse(res, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve2, reject) => __awaiter4(this, void 0, void 0, function* () {
+            const statusCode = res.message.statusCode || 0;
+            const response = {
+              statusCode,
+              result: null,
+              headers: {}
+            };
+            if (statusCode === HttpCodes.NotFound) {
+              resolve2(response);
+            }
+            function dateTimeDeserializer(key, value) {
+              if (typeof value === "string") {
+                const a = new Date(value);
+                if (!isNaN(a.valueOf())) {
+                  return a;
+                }
+              }
+              return value;
+            }
+            let obj;
+            let contents;
+            try {
+              contents = yield res.readBody();
+              if (contents && contents.length > 0) {
+                if (options && options.deserializeDates) {
+                  obj = JSON.parse(contents, dateTimeDeserializer);
+                } else {
+                  obj = JSON.parse(contents);
+                }
+                response.result = obj;
+              }
+              response.headers = res.message.headers;
+            } catch (err) {
+            }
+            if (statusCode > 299) {
+              let msg;
+              if (obj && obj.message) {
+                msg = obj.message;
+              } else if (contents && contents.length > 0) {
+                msg = contents;
+              } else {
+                msg = `Failed request: (${statusCode})`;
+              }
+              const err = new HttpClientError(msg, statusCode);
+              err.result = response.result;
+              reject(err);
+            } else {
+              resolve2(response);
+            }
+          }));
+        });
       }
-      return a !== a && b !== b;
     };
+    exports2.HttpClient = HttpClient2;
+    var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
   }
 });
 
@@ -113542,7 +118122,7 @@ var cliErrorsConfig = {
 var core6 = __toESM(require_core());
 
 // src/config/db-config.ts
-var jsonschema = __toESM(require_lib3());
+var jsonschema = __toESM(require_lib6());
 var semver2 = __toESM(require_semver2());
 var PACK_IDENTIFIER_PATTERN = (function() {
   const alphaNumeric = "[a-z0-9]";
@@ -113829,7 +118409,7 @@ var semver5 = __toESM(require_semver2());
 
 // src/tools-download.ts
 var core9 = __toESM(require_core());
-var import_http_client = __toESM(require_lib());
+var import_http_client = __toESM(require_lib9());
 var toolcache2 = __toESM(require_tool_cache());
 var import_follow_redirects = __toESM(require_follow_redirects());
 var semver6 = __toESM(require_semver2());
diff --git a/lib/upload-sarif-action.js b/lib/upload-sarif-action.js
index 3caadc5fe8..a2dcea83a3 100644
--- a/lib/upload-sarif-action.js
+++ b/lib/upload-sarif-action.js
@@ -216,9 +216,9 @@ var require_file_command = __commonJS({
   }
 });
 
-// node_modules/@actions/http-client/lib/proxy.js
+// node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js
 var require_proxy = __commonJS({
-  "node_modules/@actions/http-client/lib/proxy.js"(exports2) {
+  "node_modules/@actions/core/node_modules/@actions/http-client/lib/proxy.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
     exports2.checkBypass = exports2.getProxyUrl = void 0;
@@ -17292,9 +17292,9 @@ var require_undici = __commonJS({
   }
 });
 
-// node_modules/@actions/http-client/lib/index.js
+// node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js
 var require_lib = __commonJS({
-  "node_modules/@actions/http-client/lib/index.js"(exports2) {
+  "node_modules/@actions/core/node_modules/@actions/http-client/lib/index.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -17911,9 +17911,9 @@ var require_lib = __commonJS({
   }
 });
 
-// node_modules/@actions/http-client/lib/auth.js
+// node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js
 var require_auth = __commonJS({
-  "node_modules/@actions/http-client/lib/auth.js"(exports2) {
+  "node_modules/@actions/core/node_modules/@actions/http-client/lib/auth.js"(exports2) {
     "use strict";
     var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
       function adopt(value) {
@@ -19875,9 +19875,91 @@ var require_context = __commonJS({
   }
 });
 
-// node_modules/@actions/github/lib/internal/utils.js
-var require_utils3 = __commonJS({
-  "node_modules/@actions/github/lib/internal/utils.js"(exports2) {
+// node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js
+var require_proxy2 = __commonJS({
+  "node_modules/@actions/github/node_modules/@actions/http-client/lib/proxy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.checkBypass = exports2.getProxyUrl = void 0;
+    function getProxyUrl(reqUrl) {
+      const usingSsl = reqUrl.protocol === "https:";
+      if (checkBypass(reqUrl)) {
+        return void 0;
+      }
+      const proxyVar = (() => {
+        if (usingSsl) {
+          return process.env["https_proxy"] || process.env["HTTPS_PROXY"];
+        } else {
+          return process.env["http_proxy"] || process.env["HTTP_PROXY"];
+        }
+      })();
+      if (proxyVar) {
+        try {
+          return new DecodedURL(proxyVar);
+        } catch (_a) {
+          if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://"))
+            return new DecodedURL(`http://${proxyVar}`);
+        }
+      } else {
+        return void 0;
+      }
+    }
+    exports2.getProxyUrl = getProxyUrl;
+    function checkBypass(reqUrl) {
+      if (!reqUrl.hostname) {
+        return false;
+      }
+      const reqHost = reqUrl.hostname;
+      if (isLoopbackAddress(reqHost)) {
+        return true;
+      }
+      const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || "";
+      if (!noProxy) {
+        return false;
+      }
+      let reqPort;
+      if (reqUrl.port) {
+        reqPort = Number(reqUrl.port);
+      } else if (reqUrl.protocol === "http:") {
+        reqPort = 80;
+      } else if (reqUrl.protocol === "https:") {
+        reqPort = 443;
+      }
+      const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+      if (typeof reqPort === "number") {
+        upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
+      }
+      for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) {
+        if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) {
+          return true;
+        }
+      }
+      return false;
+    }
+    exports2.checkBypass = checkBypass;
+    function isLoopbackAddress(host) {
+      const hostLower = host.toLowerCase();
+      return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]");
+    }
+    var DecodedURL = class extends URL {
+      constructor(url2, base) {
+        super(url2, base);
+        this._decodedUsername = decodeURIComponent(super.username);
+        this._decodedPassword = decodeURIComponent(super.password);
+      }
+      get username() {
+        return this._decodedUsername;
+      }
+      get password() {
+        return this._decodedPassword;
+      }
+    };
+  }
+});
+
+// node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js
+var require_lib2 = __commonJS({
+  "node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -19934,737 +20016,826 @@ var require_utils3 = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0;
-    var httpClient = __importStar4(require_lib());
+    exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0;
+    var http = __importStar4(require("http"));
+    var https2 = __importStar4(require("https"));
+    var pm = __importStar4(require_proxy2());
+    var tunnel = __importStar4(require_tunnel2());
     var undici_1 = require_undici();
-    function getAuthString(token, options) {
-      if (!token && !options.auth) {
-        throw new Error("Parameter token or opts.auth is required");
-      } else if (token && options.auth) {
-        throw new Error("Parameters token and opts.auth may not both be specified");
-      }
-      return typeof options.auth === "string" ? options.auth : `token ${token}`;
-    }
-    exports2.getAuthString = getAuthString;
-    function getProxyAgent(destinationUrl) {
-      const hc = new httpClient.HttpClient();
-      return hc.getAgent(destinationUrl);
-    }
-    exports2.getProxyAgent = getProxyAgent;
-    function getProxyAgentDispatcher(destinationUrl) {
-      const hc = new httpClient.HttpClient();
-      return hc.getAgentDispatcher(destinationUrl);
-    }
-    exports2.getProxyAgentDispatcher = getProxyAgentDispatcher;
-    function getProxyFetch(destinationUrl) {
-      const httpDispatcher = getProxyAgentDispatcher(destinationUrl);
-      const proxyFetch = (url2, opts) => __awaiter4(this, void 0, void 0, function* () {
-        return (0, undici_1.fetch)(url2, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher }));
-      });
-      return proxyFetch;
-    }
-    exports2.getProxyFetch = getProxyFetch;
-    function getApiBaseUrl() {
-      return process.env["GITHUB_API_URL"] || "https://api.github.com";
+    var HttpCodes;
+    (function(HttpCodes2) {
+      HttpCodes2[HttpCodes2["OK"] = 200] = "OK";
+      HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices";
+      HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently";
+      HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved";
+      HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther";
+      HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified";
+      HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy";
+      HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy";
+      HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+      HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect";
+      HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest";
+      HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized";
+      HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired";
+      HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden";
+      HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound";
+      HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+      HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable";
+      HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+      HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout";
+      HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict";
+      HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone";
+      HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests";
+      HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError";
+      HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented";
+      HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway";
+      HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+      HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout";
+    })(HttpCodes || (exports2.HttpCodes = HttpCodes = {}));
+    var Headers;
+    (function(Headers2) {
+      Headers2["Accept"] = "accept";
+      Headers2["ContentType"] = "content-type";
+    })(Headers || (exports2.Headers = Headers = {}));
+    var MediaTypes;
+    (function(MediaTypes2) {
+      MediaTypes2["ApplicationJson"] = "application/json";
+    })(MediaTypes || (exports2.MediaTypes = MediaTypes = {}));
+    function getProxyUrl(serverUrl) {
+      const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+      return proxyUrl ? proxyUrl.href : "";
     }
-    exports2.getApiBaseUrl = getApiBaseUrl;
-  }
-});
-
-// node_modules/universal-user-agent/dist-node/index.js
-var require_dist_node = __commonJS({
-  "node_modules/universal-user-agent/dist-node/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    function getUserAgent() {
-      if (typeof navigator === "object" && "userAgent" in navigator) {
-        return navigator.userAgent;
-      }
-      if (typeof process === "object" && "version" in process) {
-        return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
+    exports2.getProxyUrl = getProxyUrl;
+    var HttpRedirectCodes = [
+      HttpCodes.MovedPermanently,
+      HttpCodes.ResourceMoved,
+      HttpCodes.SeeOther,
+      HttpCodes.TemporaryRedirect,
+      HttpCodes.PermanentRedirect
+    ];
+    var HttpResponseRetryCodes = [
+      HttpCodes.BadGateway,
+      HttpCodes.ServiceUnavailable,
+      HttpCodes.GatewayTimeout
+    ];
+    var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"];
+    var ExponentialBackoffCeiling = 10;
+    var ExponentialBackoffTimeSlice = 5;
+    var HttpClientError = class _HttpClientError extends Error {
+      constructor(message, statusCode) {
+        super(message);
+        this.name = "HttpClientError";
+        this.statusCode = statusCode;
+        Object.setPrototypeOf(this, _HttpClientError.prototype);
       }
-      return "";
-    }
-    exports2.getUserAgent = getUserAgent;
-  }
-});
-
-// node_modules/before-after-hook/lib/register.js
-var require_register = __commonJS({
-  "node_modules/before-after-hook/lib/register.js"(exports2, module2) {
-    module2.exports = register;
-    function register(state, name, method, options) {
-      if (typeof method !== "function") {
-        throw new Error("method for before hook must be a function");
+    };
+    exports2.HttpClientError = HttpClientError;
+    var HttpClientResponse = class {
+      constructor(message) {
+        this.message = message;
       }
-      if (!options) {
-        options = {};
+      readBody() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () {
+            let output = Buffer.alloc(0);
+            this.message.on("data", (chunk) => {
+              output = Buffer.concat([output, chunk]);
+            });
+            this.message.on("end", () => {
+              resolve6(output.toString());
+            });
+          }));
+        });
       }
-      if (Array.isArray(name)) {
-        return name.reverse().reduce(function(callback, name2) {
-          return register.bind(null, state, name2, callback, options);
-        }, method)();
+      readBodyBuffer() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () {
+            const chunks = [];
+            this.message.on("data", (chunk) => {
+              chunks.push(chunk);
+            });
+            this.message.on("end", () => {
+              resolve6(Buffer.concat(chunks));
+            });
+          }));
+        });
       }
-      return Promise.resolve().then(function() {
-        if (!state.registry[name]) {
-          return method(options);
-        }
-        return state.registry[name].reduce(function(method2, registered) {
-          return registered.hook.bind(null, method2, options);
-        }, method)();
-      });
+    };
+    exports2.HttpClientResponse = HttpClientResponse;
+    function isHttps(requestUrl) {
+      const parsedUrl = new URL(requestUrl);
+      return parsedUrl.protocol === "https:";
     }
-  }
-});
-
-// node_modules/before-after-hook/lib/add.js
-var require_add = __commonJS({
-  "node_modules/before-after-hook/lib/add.js"(exports2, module2) {
-    module2.exports = addHook;
-    function addHook(state, kind, name, hook) {
-      var orig = hook;
-      if (!state.registry[name]) {
-        state.registry[name] = [];
+    exports2.isHttps = isHttps;
+    var HttpClient2 = class {
+      constructor(userAgent, handlers, requestOptions) {
+        this._ignoreSslError = false;
+        this._allowRedirects = true;
+        this._allowRedirectDowngrade = false;
+        this._maxRedirects = 50;
+        this._allowRetries = false;
+        this._maxRetries = 1;
+        this._keepAlive = false;
+        this._disposed = false;
+        this.userAgent = userAgent;
+        this.handlers = handlers || [];
+        this.requestOptions = requestOptions;
+        if (requestOptions) {
+          if (requestOptions.ignoreSslError != null) {
+            this._ignoreSslError = requestOptions.ignoreSslError;
+          }
+          this._socketTimeout = requestOptions.socketTimeout;
+          if (requestOptions.allowRedirects != null) {
+            this._allowRedirects = requestOptions.allowRedirects;
+          }
+          if (requestOptions.allowRedirectDowngrade != null) {
+            this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+          }
+          if (requestOptions.maxRedirects != null) {
+            this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+          }
+          if (requestOptions.keepAlive != null) {
+            this._keepAlive = requestOptions.keepAlive;
+          }
+          if (requestOptions.allowRetries != null) {
+            this._allowRetries = requestOptions.allowRetries;
+          }
+          if (requestOptions.maxRetries != null) {
+            this._maxRetries = requestOptions.maxRetries;
+          }
+        }
       }
-      if (kind === "before") {
-        hook = function(method, options) {
-          return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options));
-        };
+      options(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("OPTIONS", requestUrl, null, additionalHeaders || {});
+        });
       }
-      if (kind === "after") {
-        hook = function(method, options) {
-          var result;
-          return Promise.resolve().then(method.bind(null, options)).then(function(result_) {
-            result = result_;
-            return orig(result, options);
-          }).then(function() {
-            return result;
-          });
-        };
+      get(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("GET", requestUrl, null, additionalHeaders || {});
+        });
       }
-      if (kind === "error") {
-        hook = function(method, options) {
-          return Promise.resolve().then(method.bind(null, options)).catch(function(error4) {
-            return orig(error4, options);
-          });
-        };
+      del(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("DELETE", requestUrl, null, additionalHeaders || {});
+        });
       }
-      state.registry[name].push({
-        hook,
-        orig
-      });
-    }
-  }
-});
-
-// node_modules/before-after-hook/lib/remove.js
-var require_remove = __commonJS({
-  "node_modules/before-after-hook/lib/remove.js"(exports2, module2) {
-    module2.exports = removeHook;
-    function removeHook(state, name, method) {
-      if (!state.registry[name]) {
-        return;
+      post(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("POST", requestUrl, data, additionalHeaders || {});
+        });
       }
-      var index = state.registry[name].map(function(registered) {
-        return registered.orig;
-      }).indexOf(method);
-      if (index === -1) {
-        return;
+      patch(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PATCH", requestUrl, data, additionalHeaders || {});
+        });
       }
-      state.registry[name].splice(index, 1);
-    }
-  }
-});
-
-// node_modules/before-after-hook/index.js
-var require_before_after_hook = __commonJS({
-  "node_modules/before-after-hook/index.js"(exports2, module2) {
-    var register = require_register();
-    var addHook = require_add();
-    var removeHook = require_remove();
-    var bind = Function.bind;
-    var bindable = bind.bind(bind);
-    function bindApi(hook, state, name) {
-      var removeHookRef = bindable(removeHook, null).apply(
-        null,
-        name ? [state, name] : [state]
-      );
-      hook.api = { remove: removeHookRef };
-      hook.remove = removeHookRef;
-      ["before", "error", "after", "wrap"].forEach(function(kind) {
-        var args = name ? [state, kind, name] : [state, kind];
-        hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args);
-      });
-    }
-    function HookSingular() {
-      var singularHookName = "h";
-      var singularHookState = {
-        registry: {}
-      };
-      var singularHook = register.bind(null, singularHookState, singularHookName);
-      bindApi(singularHook, singularHookState, singularHookName);
-      return singularHook;
-    }
-    function HookCollection() {
-      var state = {
-        registry: {}
-      };
-      var hook = register.bind(null, state);
-      bindApi(hook, state);
-      return hook;
-    }
-    var collectionHookDeprecationMessageDisplayed = false;
-    function Hook() {
-      if (!collectionHookDeprecationMessageDisplayed) {
-        console.warn(
-          '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4'
-        );
-        collectionHookDeprecationMessageDisplayed = true;
+      put(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PUT", requestUrl, data, additionalHeaders || {});
+        });
       }
-      return HookCollection();
-    }
-    Hook.Singular = HookSingular.bind();
-    Hook.Collection = HookCollection.bind();
-    module2.exports = Hook;
-    module2.exports.Hook = Hook;
-    module2.exports.Singular = Hook.Singular;
-    module2.exports.Collection = Hook.Collection;
-  }
-});
-
-// node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js
-var require_dist_node2 = __commonJS({
-  "node_modules/@octokit/core/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) {
-    "use strict";
-    var __defProp2 = Object.defineProperty;
-    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
-    var __getOwnPropNames2 = Object.getOwnPropertyNames;
-    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
-    var __export2 = (target, all) => {
-      for (var name in all)
-        __defProp2(target, name, { get: all[name], enumerable: true });
-    };
-    var __copyProps2 = (to, from, except, desc) => {
-      if (from && typeof from === "object" || typeof from === "function") {
-        for (let key of __getOwnPropNames2(from))
-          if (!__hasOwnProp2.call(to, key) && key !== except)
-            __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
+      head(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("HEAD", requestUrl, null, additionalHeaders || {});
+        });
       }
-      return to;
-    };
-    var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
-    var dist_src_exports = {};
-    __export2(dist_src_exports, {
-      endpoint: () => endpoint
-    });
-    module2.exports = __toCommonJS2(dist_src_exports);
-    var import_universal_user_agent = require_dist_node();
-    var VERSION = "9.0.6";
-    var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;
-    var DEFAULTS = {
-      method: "GET",
-      baseUrl: "https://api.github.com",
-      headers: {
-        accept: "application/vnd.github.v3+json",
-        "user-agent": userAgent
-      },
-      mediaType: {
-        format: ""
+      sendStream(verb, requestUrl, stream2, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request(verb, requestUrl, stream2, additionalHeaders);
+        });
       }
-    };
-    function lowercaseKeys(object) {
-      if (!object) {
-        return {};
+      /**
+       * Gets a typed object from an endpoint
+       * Be aware that not found returns a null.  Other errors (4xx, 5xx) reject the promise
+       */
+      getJson(requestUrl, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          const res = yield this.get(requestUrl, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      return Object.keys(object).reduce((newObj, key) => {
-        newObj[key.toLowerCase()] = object[key];
-        return newObj;
-      }, {});
-    }
-    function isPlainObject(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 (isPlainObject(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, url2] = route.split(" ");
-        options = Object.assign(url2 ? { method, url: url2 } : { 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(url2, parameters) {
-      const separator = /\?/.test(url2) ? "&" : "?";
-      const names = Object.keys(parameters);
-      if (names.length === 0) {
-        return url2;
-      }
-      return url2 + 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+)|(?:(? a.concat(b), []);
-    }
-    function omit(object, keysToOmit) {
-      const result = { __proto__: null };
-      for (const key of Object.keys(object)) {
-        if (keysToOmit.indexOf(key) === -1) {
-          result[key] = object[key];
-        }
+      putJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.put(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      return result;
-    }
-    function encodeReserved(str2) {
-      return str2.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(str2) {
-      return encodeURIComponent(str2).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;
+      patchJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.patch(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-    }
-    function isDefined2(value) {
-      return value !== void 0 && value !== null;
-    }
-    function isKeyOperator(operator) {
-      return operator === ";" || operator === "&" || operator === "?";
-    }
-    function getValues(context2, operator, key, modifier) {
-      var value = context2[key], result = [];
-      if (isDefined2(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));
+      /**
+       * Makes a raw http request.
+       * All other methods such as get, post, patch, and request ultimately call this.
+       * Prefer get, del, post and patch
+       */
+      request(verb, requestUrl, data, headers) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          if (this._disposed) {
+            throw new Error("Client has already been disposed.");
           }
-          result.push(
-            encodeValue(operator, value, isKeyOperator(operator) ? key : "")
-          );
-        } else {
-          if (modifier === "*") {
-            if (Array.isArray(value)) {
-              value.filter(isDefined2).forEach(function(value2) {
-                result.push(
-                  encodeValue(operator, value2, isKeyOperator(operator) ? key : "")
-                );
-              });
-            } else {
-              Object.keys(value).forEach(function(k) {
-                if (isDefined2(value[k])) {
-                  result.push(encodeValue(operator, value[k], k));
+          const parsedUrl = new URL(requestUrl);
+          let info6 = this._prepareRequest(verb, parsedUrl, headers);
+          const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1;
+          let numTries = 0;
+          let response;
+          do {
+            response = yield this.requestRaw(info6, data);
+            if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
+              let authenticationHandler;
+              for (const handler of this.handlers) {
+                if (handler.canHandleAuthentication(response)) {
+                  authenticationHandler = handler;
+                  break;
                 }
-              });
+              }
+              if (authenticationHandler) {
+                return authenticationHandler.handleAuthentication(this, info6, data);
+              } else {
+                return response;
+              }
             }
-          } else {
-            const tmp = [];
-            if (Array.isArray(value)) {
-              value.filter(isDefined2).forEach(function(value2) {
-                tmp.push(encodeValue(operator, value2));
-              });
-            } else {
-              Object.keys(value).forEach(function(k) {
-                if (isDefined2(value[k])) {
-                  tmp.push(encodeUnreserved(k));
-                  tmp.push(encodeValue(operator, value[k].toString()));
+            let redirectsRemaining = this._maxRedirects;
+            while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) {
+              const redirectUrl = response.message.headers["location"];
+              if (!redirectUrl) {
+                break;
+              }
+              const parsedRedirectUrl = new URL(redirectUrl);
+              if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
+                throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
+              }
+              yield response.readBody();
+              if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+                for (const header in headers) {
+                  if (header.toLowerCase() === "authorization") {
+                    delete headers[header];
+                  }
                 }
-              });
+              }
+              info6 = this._prepareRequest(verb, parsedRedirectUrl, headers);
+              response = yield this.requestRaw(info6, data);
+              redirectsRemaining--;
             }
-            if (isKeyOperator(operator)) {
-              result.push(encodeUnreserved(key) + "=" + tmp.join(","));
-            } else if (tmp.length !== 0) {
-              result.push(tmp.join(","));
+            if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+              return response;
             }
-          }
-        }
-      } else {
-        if (operator === ";") {
-          if (isDefined2(value)) {
-            result.push(encodeUnreserved(key));
-          }
-        } else if (value === "" && (operator === "&" || operator === "?")) {
-          result.push(encodeUnreserved(key) + "=");
-        } else if (value === "") {
-          result.push("");
+            numTries += 1;
+            if (numTries < maxTries) {
+              yield response.readBody();
+              yield this._performExponentialBackoff(numTries);
+            }
+          } while (numTries < maxTries);
+          return response;
+        });
+      }
+      /**
+       * Needs to be called if keepAlive is set to true in request options.
+       */
+      dispose() {
+        if (this._agent) {
+          this._agent.destroy();
         }
+        this._disposed = true;
       }
-      return result;
-    }
-    function parseUrl(template) {
-      return {
-        expand: expand.bind(null, template)
-      };
-    }
-    function expand(template, context2) {
-      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(context2, operator, tmp[1], tmp[2] || tmp[3]));
-            });
-            if (operator && operator !== "+") {
-              var separator = ",";
-              if (operator === "?") {
-                separator = "&";
-              } else if (operator !== "#") {
-                separator = operator;
+      /**
+       * Raw request.
+       * @param info
+       * @param data
+       */
+      requestRaw(info6, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6, reject) => {
+            function callbackForResult(err, res) {
+              if (err) {
+                reject(err);
+              } else if (!res) {
+                reject(new Error("Unknown error"));
+              } else {
+                resolve6(res);
               }
-              return (values.length !== 0 ? operator : "") + values.join(separator);
-            } else {
-              return values.join(",");
             }
-          } else {
-            return encodeReserved(literal);
+            this.requestRawWithCallback(info6, data, callbackForResult);
+          });
+        });
+      }
+      /**
+       * Raw request with callback.
+       * @param info
+       * @param data
+       * @param onResult
+       */
+      requestRawWithCallback(info6, data, onResult) {
+        if (typeof data === "string") {
+          if (!info6.options.headers) {
+            info6.options.headers = {};
           }
+          info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8");
         }
-      );
-      if (template === "/") {
-        return template;
-      } else {
-        return template.replace(/\/$/, "");
-      }
-    }
-    function parse(options) {
-      let method = options.method.toUpperCase();
-      let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
-      let headers = Object.assign({}, options.headers);
-      let body;
-      let parameters = omit(options, [
-        "method",
-        "baseUrl",
-        "url",
-        "headers",
-        "request",
-        "mediaType"
-      ]);
-      const urlVariableNames = extractUrlVariableNames(url2);
-      url2 = parseUrl(url2).expand(parameters);
-      if (!/^http/.test(url2)) {
-        url2 = options.baseUrl + url2;
-      }
-      const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
-      const remainingParameters = omit(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(",");
+        let callbackCalled = false;
+        function handleResult(err, res) {
+          if (!callbackCalled) {
+            callbackCalled = true;
+            onResult(err, res);
+          }
         }
-        if (url2.endsWith("/graphql")) {
-          if (options.mediaType.previews?.length) {
-            const previewsFromAcceptHeader = headers.accept.match(/(? {
-              const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
-              return `application/vnd.github.${preview}-preview${format}`;
-            }).join(",");
+        const req = info6.httpModule.request(info6.options, (msg) => {
+          const res = new HttpClientResponse(msg);
+          handleResult(void 0, res);
+        });
+        let socket;
+        req.on("socket", (sock) => {
+          socket = sock;
+        });
+        req.setTimeout(this._socketTimeout || 3 * 6e4, () => {
+          if (socket) {
+            socket.end();
           }
+          handleResult(new Error(`Request timeout: ${info6.options.path}`));
+        });
+        req.on("error", function(err) {
+          handleResult(err);
+        });
+        if (data && typeof data === "string") {
+          req.write(data, "utf8");
         }
-      }
-      if (["GET", "HEAD"].includes(method)) {
-        url2 = addQueryParameters(url2, remainingParameters);
-      } else {
-        if ("data" in remainingParameters) {
-          body = remainingParameters.data;
+        if (data && typeof data !== "string") {
+          data.on("close", function() {
+            req.end();
+          });
+          data.pipe(req);
         } else {
-          if (Object.keys(remainingParameters).length) {
-            body = remainingParameters;
-          }
+          req.end();
         }
       }
-      if (!headers["content-type"] && typeof body !== "undefined") {
-        headers["content-type"] = "application/json; charset=utf-8";
+      /**
+       * Gets an http agent. This function is useful when you need an http agent that handles
+       * routing through a proxy server - depending upon the url and proxy environment variables.
+       * @param serverUrl  The server URL where the request will be sent. For example, https://api.github.com
+       */
+      getAgent(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        return this._getAgent(parsedUrl);
       }
-      if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
-        body = "";
+      getAgentDispatcher(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (!useProxy) {
+          return;
+        }
+        return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
       }
-      return Object.assign(
-        { method, url: url2, headers },
-        typeof body !== "undefined" ? { body } : null,
-        options.request ? { request: options.request } : null
-      );
-    }
-    function endpointWithDefaults(defaults, route, options) {
-      return parse(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
-      });
-    }
-    var endpoint = withDefaults(null, DEFAULTS);
-  }
-});
-
-// node_modules/deprecation/dist-node/index.js
-var require_dist_node3 = __commonJS({
-  "node_modules/deprecation/dist-node/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    var Deprecation = class extends Error {
-      constructor(message) {
-        super(message);
-        if (Error.captureStackTrace) {
-          Error.captureStackTrace(this, this.constructor);
+      _prepareRequest(method, requestUrl, headers) {
+        const info6 = {};
+        info6.parsedUrl = requestUrl;
+        const usingSsl = info6.parsedUrl.protocol === "https:";
+        info6.httpModule = usingSsl ? https2 : http;
+        const defaultPort = usingSsl ? 443 : 80;
+        info6.options = {};
+        info6.options.host = info6.parsedUrl.hostname;
+        info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort;
+        info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || "");
+        info6.options.method = method;
+        info6.options.headers = this._mergeHeaders(headers);
+        if (this.userAgent != null) {
+          info6.options.headers["user-agent"] = this.userAgent;
         }
-        this.name = "Deprecation";
+        info6.options.agent = this._getAgent(info6.parsedUrl);
+        if (this.handlers) {
+          for (const handler of this.handlers) {
+            handler.prepareRequest(info6.options);
+          }
+        }
+        return info6;
       }
-    };
-    exports2.Deprecation = Deprecation;
-  }
-});
-
-// node_modules/wrappy/wrappy.js
-var require_wrappy = __commonJS({
-  "node_modules/wrappy/wrappy.js"(exports2, module2) {
-    module2.exports = wrappy;
-    function wrappy(fn, cb) {
-      if (fn && cb) return wrappy(fn)(cb);
-      if (typeof fn !== "function")
-        throw new TypeError("need wrapper function");
-      Object.keys(fn).forEach(function(k) {
-        wrapper[k] = fn[k];
-      });
-      return wrapper;
-      function wrapper() {
-        var args = new Array(arguments.length);
-        for (var i = 0; i < args.length; i++) {
-          args[i] = arguments[i];
+      _mergeHeaders(headers) {
+        if (this.requestOptions && this.requestOptions.headers) {
+          return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
         }
-        var ret = fn.apply(this, args);
-        var cb2 = args[args.length - 1];
-        if (typeof ret === "function" && ret !== cb2) {
-          Object.keys(cb2).forEach(function(k) {
-            ret[k] = cb2[k];
-          });
+        return lowercaseKeys(headers || {});
+      }
+      _getExistingOrDefaultHeader(additionalHeaders, header, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
         }
-        return ret;
+        return additionalHeaders[header] || clientHeader || _default2;
       }
-    }
-  }
-});
-
-// node_modules/once/once.js
-var require_once = __commonJS({
-  "node_modules/once/once.js"(exports2, module2) {
-    var wrappy = require_wrappy();
-    module2.exports = wrappy(once);
-    module2.exports.strict = wrappy(onceStrict);
-    once.proto = once(function() {
-      Object.defineProperty(Function.prototype, "once", {
-        value: function() {
-          return once(this);
-        },
-        configurable: true
+      _getAgent(parsedUrl) {
+        let agent;
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (this._keepAlive && useProxy) {
+          agent = this._proxyAgent;
+        }
+        if (!useProxy) {
+          agent = this._agent;
+        }
+        if (agent) {
+          return agent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        let maxSockets = 100;
+        if (this.requestOptions) {
+          maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
+        }
+        if (proxyUrl && proxyUrl.hostname) {
+          const agentOptions = {
+            maxSockets,
+            keepAlive: this._keepAlive,
+            proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && {
+              proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+            }), { host: proxyUrl.hostname, port: proxyUrl.port })
+          };
+          let tunnelAgent;
+          const overHttps = proxyUrl.protocol === "https:";
+          if (usingSsl) {
+            tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+          } else {
+            tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
+          }
+          agent = tunnelAgent(agentOptions);
+          this._proxyAgent = agent;
+        }
+        if (!agent) {
+          const options = { keepAlive: this._keepAlive, maxSockets };
+          agent = usingSsl ? new https2.Agent(options) : new http.Agent(options);
+          this._agent = agent;
+        }
+        if (usingSsl && this._ignoreSslError) {
+          agent.options = Object.assign(agent.options || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return agent;
+      }
+      _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+        let proxyAgent;
+        if (this._keepAlive) {
+          proxyAgent = this._proxyAgentDispatcher;
+        }
+        if (proxyAgent) {
+          return proxyAgent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && {
+          token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}`
+        }));
+        this._proxyAgentDispatcher = proxyAgent;
+        if (usingSsl && this._ignoreSslError) {
+          proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return proxyAgent;
+      }
+      _performExponentialBackoff(retryNumber) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+          const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+          return new Promise((resolve6) => setTimeout(() => resolve6(), ms));
+        });
+      }
+      _processResponse(res, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6, reject) => __awaiter4(this, void 0, void 0, function* () {
+            const statusCode = res.message.statusCode || 0;
+            const response = {
+              statusCode,
+              result: null,
+              headers: {}
+            };
+            if (statusCode === HttpCodes.NotFound) {
+              resolve6(response);
+            }
+            function dateTimeDeserializer(key, value) {
+              if (typeof value === "string") {
+                const a = new Date(value);
+                if (!isNaN(a.valueOf())) {
+                  return a;
+                }
+              }
+              return value;
+            }
+            let obj;
+            let contents;
+            try {
+              contents = yield res.readBody();
+              if (contents && contents.length > 0) {
+                if (options && options.deserializeDates) {
+                  obj = JSON.parse(contents, dateTimeDeserializer);
+                } else {
+                  obj = JSON.parse(contents);
+                }
+                response.result = obj;
+              }
+              response.headers = res.message.headers;
+            } catch (err) {
+            }
+            if (statusCode > 299) {
+              let msg;
+              if (obj && obj.message) {
+                msg = obj.message;
+              } else if (contents && contents.length > 0) {
+                msg = contents;
+              } else {
+                msg = `Failed request: (${statusCode})`;
+              }
+              const err = new HttpClientError(msg, statusCode);
+              err.result = response.result;
+              reject(err);
+            } else {
+              resolve6(response);
+            }
+          }));
+        });
+      }
+    };
+    exports2.HttpClient = HttpClient2;
+    var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
+  }
+});
+
+// node_modules/@actions/github/lib/internal/utils.js
+var require_utils3 = __commonJS({
+  "node_modules/@actions/github/lib/internal/utils.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
       });
-      Object.defineProperty(Function.prototype, "onceStrict", {
-        value: function() {
-          return onceStrict(this);
-        },
-        configurable: true
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getApiBaseUrl = exports2.getProxyFetch = exports2.getProxyAgentDispatcher = exports2.getProxyAgent = exports2.getAuthString = void 0;
+    var httpClient = __importStar4(require_lib2());
+    var undici_1 = require_undici();
+    function getAuthString(token, options) {
+      if (!token && !options.auth) {
+        throw new Error("Parameter token or opts.auth is required");
+      } else if (token && options.auth) {
+        throw new Error("Parameters token and opts.auth may not both be specified");
+      }
+      return typeof options.auth === "string" ? options.auth : `token ${token}`;
+    }
+    exports2.getAuthString = getAuthString;
+    function getProxyAgent(destinationUrl) {
+      const hc = new httpClient.HttpClient();
+      return hc.getAgent(destinationUrl);
+    }
+    exports2.getProxyAgent = getProxyAgent;
+    function getProxyAgentDispatcher(destinationUrl) {
+      const hc = new httpClient.HttpClient();
+      return hc.getAgentDispatcher(destinationUrl);
+    }
+    exports2.getProxyAgentDispatcher = getProxyAgentDispatcher;
+    function getProxyFetch(destinationUrl) {
+      const httpDispatcher = getProxyAgentDispatcher(destinationUrl);
+      const proxyFetch = (url2, opts) => __awaiter4(this, void 0, void 0, function* () {
+        return (0, undici_1.fetch)(url2, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher }));
       });
-    });
-    function once(fn) {
-      var f = function() {
-        if (f.called) return f.value;
-        f.called = true;
-        return f.value = fn.apply(this, arguments);
-      };
-      f.called = false;
-      return f;
+      return proxyFetch;
     }
-    function onceStrict(fn) {
-      var f = function() {
-        if (f.called)
-          throw new Error(f.onceError);
-        f.called = true;
-        return f.value = fn.apply(this, arguments);
-      };
-      var name = fn.name || "Function wrapped with `once`";
-      f.onceError = name + " shouldn't be called more than once";
-      f.called = false;
-      return f;
+    exports2.getProxyFetch = getProxyFetch;
+    function getApiBaseUrl() {
+      return process.env["GITHUB_API_URL"] || "https://api.github.com";
     }
+    exports2.getApiBaseUrl = getApiBaseUrl;
   }
 });
 
-// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js
-var require_dist_node4 = __commonJS({
-  "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) {
+// node_modules/universal-user-agent/dist-node/index.js
+var require_dist_node = __commonJS({
+  "node_modules/universal-user-agent/dist-node/index.js"(exports2) {
     "use strict";
-    var __create2 = Object.create;
-    var __defProp2 = Object.defineProperty;
-    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
-    var __getOwnPropNames2 = Object.getOwnPropertyNames;
-    var __getProtoOf2 = Object.getPrototypeOf;
-    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
-    var __export2 = (target, all) => {
-      for (var name in all)
-        __defProp2(target, name, { get: all[name], enumerable: true });
-    };
-    var __copyProps2 = (to, from, except, desc) => {
-      if (from && typeof from === "object" || typeof from === "function") {
-        for (let key of __getOwnPropNames2(from))
-          if (!__hasOwnProp2.call(to, key) && key !== except)
-            __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    function getUserAgent() {
+      if (typeof navigator === "object" && "userAgent" in navigator) {
+        return navigator.userAgent;
       }
-      return to;
-    };
-    var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
-      // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
-      mod
-    ));
-    var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
-    var dist_src_exports = {};
-    __export2(dist_src_exports, {
-      RequestError: () => RequestError
-    });
-    module2.exports = __toCommonJS2(dist_src_exports);
-    var import_deprecation = require_dist_node3();
-    var import_once = __toESM2(require_once());
-    var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation));
-    var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation));
-    var RequestError = class extends Error {
-      constructor(message, statusCode, options) {
-        super(message);
-        if (Error.captureStackTrace) {
-          Error.captureStackTrace(this, this.constructor);
-        }
-        this.name = "HttpError";
-        this.status = statusCode;
-        let headers;
-        if ("headers" in options && typeof options.headers !== "undefined") {
-          headers = options.headers;
-        }
-        if ("response" in options) {
-          this.response = options.response;
-          headers = options.response.headers;
+      if (typeof process === "object" && "version" in process) {
+        return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
+      }
+      return "";
+    }
+    exports2.getUserAgent = getUserAgent;
+  }
+});
+
+// node_modules/before-after-hook/lib/register.js
+var require_register = __commonJS({
+  "node_modules/before-after-hook/lib/register.js"(exports2, module2) {
+    module2.exports = register;
+    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(function(callback, name2) {
+          return register.bind(null, state, name2, callback, options);
+        }, method)();
+      }
+      return Promise.resolve().then(function() {
+        if (!state.registry[name]) {
+          return method(options);
         }
-        const requestCopy = Object.assign({}, options.request);
-        if (options.request.headers.authorization) {
-          requestCopy.headers = Object.assign({}, options.request.headers, {
-            authorization: options.request.headers.authorization.replace(
-              /(? __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
     var dist_src_exports = {};
     __export2(dist_src_exports, {
-      request: () => request
-    });
-    module2.exports = __toCommonJS2(dist_src_exports);
-    var import_endpoint = require_dist_node2();
-    var import_universal_user_agent = require_dist_node();
-    var VERSION = "8.4.1";
-    function isPlainObject(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);
-    }
-    var import_request_error = require_dist_node4();
-    function getBufferResponse(response) {
-      return response.arrayBuffer();
-    }
-    function fetchWrapper(requestOptions) {
-      var _a, _b, _c, _d;
-      const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
-      const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false;
-      if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
-        requestOptions.body = JSON.stringify(requestOptions.body);
-      }
-      let headers = {};
-      let status;
-      let url2;
-      let { fetch } = globalThis;
-      if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) {
-        fetch = requestOptions.request.fetch;
-      }
-      if (!fetch) {
-        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"
-        );
-      }
-      return fetch(requestOptions.url, {
-        method: requestOptions.method,
-        body: requestOptions.body,
-        redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect,
-        headers: requestOptions.headers,
-        signal: (_d = requestOptions.request) == null ? void 0 : _d.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" }
-      }).then(async (response) => {
-        url2 = response.url;
-        status = response.status;
-        for (const keyAndValue of response.headers) {
-          headers[keyAndValue[0]] = keyAndValue[1];
-        }
-        if ("deprecation" in headers) {
-          const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`
-          );
-        }
-        if (status === 204 || status === 205) {
-          return;
-        }
-        if (requestOptions.method === "HEAD") {
-          if (status < 400) {
-            return;
-          }
-          throw new import_request_error.RequestError(response.statusText, status, {
-            response: {
-              url: url2,
-              status,
-              headers,
-              data: void 0
-            },
-            request: requestOptions
-          });
-        }
-        if (status === 304) {
-          throw new import_request_error.RequestError("Not modified", status, {
-            response: {
-              url: url2,
-              status,
-              headers,
-              data: await getResponseData(response)
-            },
-            request: requestOptions
-          });
-        }
-        if (status >= 400) {
-          const data = await getResponseData(response);
-          const error4 = new import_request_error.RequestError(toErrorMessage(data), status, {
-            response: {
-              url: url2,
-              status,
-              headers,
-              data
-            },
-            request: requestOptions
-          });
-          throw error4;
-        }
-        return parseSuccessResponseBody ? await getResponseData(response) : response.body;
-      }).then((data) => {
-        return {
-          status,
-          url: url2,
-          headers,
-          data
-        };
-      }).catch((error4) => {
-        if (error4 instanceof import_request_error.RequestError)
-          throw error4;
-        else if (error4.name === "AbortError")
-          throw error4;
-        let message = error4.message;
-        if (error4.name === "TypeError" && "cause" in error4) {
-          if (error4.cause instanceof Error) {
-            message = error4.cause.message;
-          } else if (typeof error4.cause === "string") {
-            message = error4.cause;
-          }
-        }
-        throw new import_request_error.RequestError(message, 500, {
-          request: requestOptions
-        });
-      });
-    }
-    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 getBufferResponse(response);
-    }
-    function toErrorMessage(data) {
-      if (typeof data === "string")
-        return data;
-      let suffix;
-      if ("documentation_url" in data) {
-        suffix = ` - ${data.documentation_url}`;
-      } else {
-        suffix = "";
-      }
-      if ("message" in data) {
-        if (Array.isArray(data.errors)) {
-          return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`;
-        }
-        return `${data.message}${suffix}`;
-      }
-      return `Unknown error: ${JSON.stringify(data)}`;
-    }
-    function withDefaults(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: withDefaults.bind(null, endpoint2)
-        });
-        return endpointOptions.request.hook(request2, endpointOptions);
-      };
-      return Object.assign(newApi, {
-        endpoint: endpoint2,
-        defaults: withDefaults.bind(null, endpoint2)
-      });
-    }
-    var request = withDefaults(import_endpoint.endpoint, {
-      headers: {
-        "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
-      }
-    });
-  }
-});
-
-// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js
-var require_dist_node6 = __commonJS({
-  "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) {
-    "use strict";
-    var __defProp2 = Object.defineProperty;
-    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
-    var __getOwnPropNames2 = Object.getOwnPropertyNames;
-    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
-    var __export2 = (target, all) => {
-      for (var name in all)
-        __defProp2(target, name, { get: all[name], enumerable: true });
-    };
-    var __copyProps2 = (to, from, except, desc) => {
-      if (from && typeof from === "object" || typeof from === "function") {
-        for (let key of __getOwnPropNames2(from))
-          if (!__hasOwnProp2.call(to, key) && key !== except)
-            __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
-      }
-      return to;
-    };
-    var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
-    var dist_src_exports = {};
-    __export2(dist_src_exports, {
-      endpoint: () => endpoint
+      endpoint: () => endpoint
     });
     module2.exports = __toCommonJS2(dist_src_exports);
     var import_universal_user_agent = require_dist_node();
@@ -21218,9 +21179,101 @@ var require_dist_node6 = __commonJS({
   }
 });
 
-// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js
-var require_dist_node7 = __commonJS({
-  "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) {
+// node_modules/deprecation/dist-node/index.js
+var require_dist_node3 = __commonJS({
+  "node_modules/deprecation/dist-node/index.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    var Deprecation = class extends Error {
+      constructor(message) {
+        super(message);
+        if (Error.captureStackTrace) {
+          Error.captureStackTrace(this, this.constructor);
+        }
+        this.name = "Deprecation";
+      }
+    };
+    exports2.Deprecation = Deprecation;
+  }
+});
+
+// node_modules/wrappy/wrappy.js
+var require_wrappy = __commonJS({
+  "node_modules/wrappy/wrappy.js"(exports2, module2) {
+    module2.exports = wrappy;
+    function wrappy(fn, cb) {
+      if (fn && cb) return wrappy(fn)(cb);
+      if (typeof fn !== "function")
+        throw new TypeError("need wrapper function");
+      Object.keys(fn).forEach(function(k) {
+        wrapper[k] = fn[k];
+      });
+      return wrapper;
+      function wrapper() {
+        var args = new Array(arguments.length);
+        for (var i = 0; i < args.length; i++) {
+          args[i] = arguments[i];
+        }
+        var ret = fn.apply(this, args);
+        var cb2 = args[args.length - 1];
+        if (typeof ret === "function" && ret !== cb2) {
+          Object.keys(cb2).forEach(function(k) {
+            ret[k] = cb2[k];
+          });
+        }
+        return ret;
+      }
+    }
+  }
+});
+
+// node_modules/once/once.js
+var require_once = __commonJS({
+  "node_modules/once/once.js"(exports2, module2) {
+    var wrappy = require_wrappy();
+    module2.exports = wrappy(once);
+    module2.exports.strict = wrappy(onceStrict);
+    once.proto = once(function() {
+      Object.defineProperty(Function.prototype, "once", {
+        value: function() {
+          return once(this);
+        },
+        configurable: true
+      });
+      Object.defineProperty(Function.prototype, "onceStrict", {
+        value: function() {
+          return onceStrict(this);
+        },
+        configurable: true
+      });
+    });
+    function once(fn) {
+      var f = function() {
+        if (f.called) return f.value;
+        f.called = true;
+        return f.value = fn.apply(this, arguments);
+      };
+      f.called = false;
+      return f;
+    }
+    function onceStrict(fn) {
+      var f = function() {
+        if (f.called)
+          throw new Error(f.onceError);
+        f.called = true;
+        return f.value = fn.apply(this, arguments);
+      };
+      var name = fn.name || "Function wrapped with `once`";
+      f.onceError = name + " shouldn't be called more than once";
+      f.called = false;
+      return f;
+    }
+  }
+});
+
+// node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js
+var require_dist_node4 = __commonJS({
+  "node_modules/@octokit/core/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) {
     "use strict";
     var __create2 = Object.create;
     var __defProp2 = Object.defineProperty;
@@ -21310,9 +21363,9 @@ var require_dist_node7 = __commonJS({
   }
 });
 
-// node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js
-var require_dist_node8 = __commonJS({
-  "node_modules/@octokit/graphql/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) {
+// node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js
+var require_dist_node5 = __commonJS({
+  "node_modules/@octokit/core/node_modules/@octokit/request/dist-node/index.js"(exports2, module2) {
     "use strict";
     var __defProp2 = Object.defineProperty;
     var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -21336,7 +21389,7 @@ var require_dist_node8 = __commonJS({
       request: () => request
     });
     module2.exports = __toCommonJS2(dist_src_exports);
-    var import_endpoint = require_dist_node6();
+    var import_endpoint = require_dist_node2();
     var import_universal_user_agent = require_dist_node();
     var VERSION = "8.4.1";
     function isPlainObject(value) {
@@ -21350,7 +21403,7 @@ var require_dist_node8 = __commonJS({
       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);
     }
-    var import_request_error = require_dist_node7();
+    var import_request_error = require_dist_node4();
     function getBufferResponse(response) {
       return response.arrayBuffer();
     }
@@ -21520,9 +21573,9 @@ var require_dist_node8 = __commonJS({
   }
 });
 
-// node_modules/@octokit/graphql/dist-node/index.js
-var require_dist_node9 = __commonJS({
-  "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) {
+// node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js
+var require_dist_node6 = __commonJS({
+  "node_modules/@octokit/graphql/node_modules/@octokit/endpoint/dist-node/index.js"(exports2, module2) {
     "use strict";
     var __defProp2 = Object.defineProperty;
     var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -21541,129 +21594,340 @@ var require_dist_node9 = __commonJS({
       return to;
     };
     var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
-    var index_exports = {};
-    __export2(index_exports, {
-      GraphqlResponseError: () => GraphqlResponseError,
-      graphql: () => graphql2,
-      withCustomRequest: () => withCustomRequest
+    var dist_src_exports = {};
+    __export2(dist_src_exports, {
+      endpoint: () => endpoint
     });
-    module2.exports = __toCommonJS2(index_exports);
-    var import_request3 = require_dist_node8();
+    module2.exports = __toCommonJS2(dist_src_exports);
     var import_universal_user_agent = require_dist_node();
-    var VERSION = "7.1.1";
-    var import_request2 = require_dist_node8();
-    var import_request = require_dist_node8();
-    function _buildMessageForResponseErrors(data) {
-      return `Request failed due to following response errors:
-` + data.errors.map((e) => ` - ${e.message}`).join("\n");
+    var VERSION = "9.0.6";
+    var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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;
+      }, {});
     }
-    var GraphqlResponseError = class extends Error {
-      constructor(request2, headers, response) {
-        super(_buildMessageForResponseErrors(response));
-        this.request = request2;
-        this.headers = headers;
-        this.response = response;
-        this.name = "GraphqlResponseError";
-        this.errors = response.errors;
-        this.data = response.data;
-        if (Error.captureStackTrace) {
-          Error.captureStackTrace(this, this.constructor);
+    function isPlainObject(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 (isPlainObject(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];
         }
       }
-    };
-    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`)
-          );
+      return obj;
+    }
+    function merge2(defaults, route, options) {
+      if (typeof route === "string") {
+        let [method, url2] = route.split(" ");
+        options = Object.assign(url2 ? { method, url: url2 } : { 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);
         }
-        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`
-            )
-          );
+        mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, ""));
+      }
+      return mergedOptions;
+    }
+    function addQueryParameters(url2, parameters) {
+      const separator = /\?/.test(url2) ? "&" : "?";
+      const names = Object.keys(parameters);
+      if (names.length === 0) {
+        return url2;
+      }
+      return url2 + 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+)|(?:(? {
-        if (NON_VARIABLE_OPTIONS.includes(key)) {
-          result[key] = parsedOptions[key];
-          return result;
+      return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
+    }
+    function omit(object, keysToOmit) {
+      const result = { __proto__: null };
+      for (const key of Object.keys(object)) {
+        if (keysToOmit.indexOf(key) === -1) {
+          result[key] = object[key];
         }
-        if (!result.variables) {
-          result.variables = {};
+      }
+      return result;
+    }
+    function encodeReserved(str2) {
+      return str2.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, "]");
         }
-        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 part;
+      }).join("");
+    }
+    function encodeUnreserved(str2) {
+      return encodeURIComponent(str2).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;
       }
-      return request2(requestOptions).then((response) => {
-        if (response.data.errors) {
-          const headers = {};
-          for (const key of Object.keys(response.headers)) {
-            headers[key] = response.headers[key];
+    }
+    function isDefined2(value) {
+      return value !== void 0 && value !== null;
+    }
+    function isKeyOperator(operator) {
+      return operator === ";" || operator === "&" || operator === "?";
+    }
+    function getValues(context2, operator, key, modifier) {
+      var value = context2[key], result = [];
+      if (isDefined2(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));
           }
-          throw new GraphqlResponseError(
-            requestOptions,
-            headers,
-            response.data
+          result.push(
+            encodeValue(operator, value, isKeyOperator(operator) ? key : "")
           );
+        } else {
+          if (modifier === "*") {
+            if (Array.isArray(value)) {
+              value.filter(isDefined2).forEach(function(value2) {
+                result.push(
+                  encodeValue(operator, value2, isKeyOperator(operator) ? key : "")
+                );
+              });
+            } else {
+              Object.keys(value).forEach(function(k) {
+                if (isDefined2(value[k])) {
+                  result.push(encodeValue(operator, value[k], k));
+                }
+              });
+            }
+          } else {
+            const tmp = [];
+            if (Array.isArray(value)) {
+              value.filter(isDefined2).forEach(function(value2) {
+                tmp.push(encodeValue(operator, value2));
+              });
+            } else {
+              Object.keys(value).forEach(function(k) {
+                if (isDefined2(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(","));
+            }
+          }
         }
-        return response.data.data;
-      });
+      } else {
+        if (operator === ";") {
+          if (isDefined2(value)) {
+            result.push(encodeUnreserved(key));
+          }
+        } else if (value === "" && (operator === "&" || operator === "?")) {
+          result.push(encodeUnreserved(key) + "=");
+        } else if (value === "") {
+          result.push("");
+        }
+      }
+      return result;
     }
-    function withDefaults(request2, newDefaults) {
-      const newRequest = request2.defaults(newDefaults);
-      const newApi = (query, options) => {
-        return graphql(newRequest, query, options);
+    function parseUrl(template) {
+      return {
+        expand: expand.bind(null, template)
       };
-      return Object.assign(newApi, {
-        defaults: withDefaults.bind(null, newRequest),
-        endpoint: newRequest.endpoint
-      });
     }
-    var graphql2 = withDefaults(import_request3.request, {
-      headers: {
-        "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
-      },
-      method: "POST",
-      url: "/graphql"
-    });
-    function withCustomRequest(customRequest) {
-      return withDefaults(customRequest, {
-        method: "POST",
-        url: "/graphql"
+    function expand(template, context2) {
+      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(context2, 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 parse(options) {
+      let method = options.method.toUpperCase();
+      let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
+      let headers = Object.assign({}, options.headers);
+      let body;
+      let parameters = omit(options, [
+        "method",
+        "baseUrl",
+        "url",
+        "headers",
+        "request",
+        "mediaType"
+      ]);
+      const urlVariableNames = extractUrlVariableNames(url2);
+      url2 = parseUrl(url2).expand(parameters);
+      if (!/^http/.test(url2)) {
+        url2 = options.baseUrl + url2;
+      }
+      const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
+      const remainingParameters = omit(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 (url2.endsWith("/graphql")) {
+          if (options.mediaType.previews?.length) {
+            const previewsFromAcceptHeader = headers.accept.match(/(? {
+              const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
+              return `application/vnd.github.${preview}-preview${format}`;
+            }).join(",");
+          }
+        }
+      }
+      if (["GET", "HEAD"].includes(method)) {
+        url2 = addQueryParameters(url2, 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: url2, headers },
+        typeof body !== "undefined" ? { body } : null,
+        options.request ? { request: options.request } : null
+      );
+    }
+    function endpointWithDefaults(defaults, route, options) {
+      return parse(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
       });
     }
+    var endpoint = withDefaults(null, DEFAULTS);
   }
 });
 
-// node_modules/@octokit/auth-token/dist-node/index.js
-var require_dist_node10 = __commonJS({
-  "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) {
+// node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js
+var require_dist_node7 = __commonJS({
+  "node_modules/@octokit/graphql/node_modules/@octokit/request-error/dist-node/index.js"(exports2, module2) {
     "use strict";
+    var __create2 = Object.create;
     var __defProp2 = Object.defineProperty;
     var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
     var __getOwnPropNames2 = Object.getOwnPropertyNames;
+    var __getProtoOf2 = Object.getPrototypeOf;
     var __hasOwnProp2 = Object.prototype.hasOwnProperty;
     var __export2 = (target, all) => {
       for (var name in all)
@@ -21677,53 +21941,490 @@ var require_dist_node10 = __commonJS({
       }
       return to;
     };
+    var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
+      // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
+      mod
+    ));
     var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
     var dist_src_exports = {};
     __export2(dist_src_exports, {
-      createTokenAuth: () => createTokenAuth
+      RequestError: () => RequestError
     });
     module2.exports = __toCommonJS2(dist_src_exports);
-    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, request, route, parameters) {
-      const endpoint = request.endpoint.merge(
-        route,
-        parameters
-      );
-      endpoint.headers.authorization = withAuthorizationPrefix(token);
-      return request(endpoint);
-    }
-    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"
-        );
+    var import_deprecation = require_dist_node3();
+    var import_once = __toESM2(require_once());
+    var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation));
+    var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation));
+    var RequestError = class extends Error {
+      constructor(message, statusCode, options) {
+        super(message);
+        if (Error.captureStackTrace) {
+          Error.captureStackTrace(this, this.constructor);
+        }
+        this.name = "HttpError";
+        this.status = statusCode;
+        let headers;
+        if ("headers" in options && typeof options.headers !== "undefined") {
+          headers = options.headers;
+        }
+        if ("response" in options) {
+          this.response = options.response;
+          headers = options.response.headers;
+        }
+        const requestCopy = Object.assign({}, options.request);
+        if (options.request.headers.authorization) {
+          requestCopy.headers = Object.assign({}, options.request.headers, {
+            authorization: options.request.headers.authorization.replace(
+              /(? {
+      for (var name in all)
+        __defProp2(target, name, { get: all[name], enumerable: true });
+    };
+    var __copyProps2 = (to, from, except, desc) => {
+      if (from && typeof from === "object" || typeof from === "function") {
+        for (let key of __getOwnPropNames2(from))
+          if (!__hasOwnProp2.call(to, key) && key !== except)
+            __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
+      }
+      return to;
+    };
+    var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
+    var dist_src_exports = {};
+    __export2(dist_src_exports, {
+      request: () => request
+    });
+    module2.exports = __toCommonJS2(dist_src_exports);
+    var import_endpoint = require_dist_node6();
+    var import_universal_user_agent = require_dist_node();
+    var VERSION = "8.4.1";
+    function isPlainObject(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);
+    }
+    var import_request_error = require_dist_node7();
+    function getBufferResponse(response) {
+      return response.arrayBuffer();
+    }
+    function fetchWrapper(requestOptions) {
+      var _a, _b, _c, _d;
+      const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
+      const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false;
+      if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
+        requestOptions.body = JSON.stringify(requestOptions.body);
+      }
+      let headers = {};
+      let status;
+      let url2;
+      let { fetch } = globalThis;
+      if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) {
+        fetch = requestOptions.request.fetch;
+      }
+      if (!fetch) {
+        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"
+        );
+      }
+      return fetch(requestOptions.url, {
+        method: requestOptions.method,
+        body: requestOptions.body,
+        redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect,
+        headers: requestOptions.headers,
+        signal: (_d = requestOptions.request) == null ? void 0 : _d.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" }
+      }).then(async (response) => {
+        url2 = response.url;
+        status = response.status;
+        for (const keyAndValue of response.headers) {
+          headers[keyAndValue[0]] = keyAndValue[1];
+        }
+        if ("deprecation" in headers) {
+          const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`
+          );
+        }
+        if (status === 204 || status === 205) {
+          return;
+        }
+        if (requestOptions.method === "HEAD") {
+          if (status < 400) {
+            return;
+          }
+          throw new import_request_error.RequestError(response.statusText, status, {
+            response: {
+              url: url2,
+              status,
+              headers,
+              data: void 0
+            },
+            request: requestOptions
+          });
+        }
+        if (status === 304) {
+          throw new import_request_error.RequestError("Not modified", status, {
+            response: {
+              url: url2,
+              status,
+              headers,
+              data: await getResponseData(response)
+            },
+            request: requestOptions
+          });
+        }
+        if (status >= 400) {
+          const data = await getResponseData(response);
+          const error4 = new import_request_error.RequestError(toErrorMessage(data), status, {
+            response: {
+              url: url2,
+              status,
+              headers,
+              data
+            },
+            request: requestOptions
+          });
+          throw error4;
+        }
+        return parseSuccessResponseBody ? await getResponseData(response) : response.body;
+      }).then((data) => {
+        return {
+          status,
+          url: url2,
+          headers,
+          data
+        };
+      }).catch((error4) => {
+        if (error4 instanceof import_request_error.RequestError)
+          throw error4;
+        else if (error4.name === "AbortError")
+          throw error4;
+        let message = error4.message;
+        if (error4.name === "TypeError" && "cause" in error4) {
+          if (error4.cause instanceof Error) {
+            message = error4.cause.message;
+          } else if (typeof error4.cause === "string") {
+            message = error4.cause;
+          }
+        }
+        throw new import_request_error.RequestError(message, 500, {
+          request: requestOptions
+        });
+      });
+    }
+    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 getBufferResponse(response);
+    }
+    function toErrorMessage(data) {
+      if (typeof data === "string")
+        return data;
+      let suffix;
+      if ("documentation_url" in data) {
+        suffix = ` - ${data.documentation_url}`;
+      } else {
+        suffix = "";
+      }
+      if ("message" in data) {
+        if (Array.isArray(data.errors)) {
+          return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`;
+        }
+        return `${data.message}${suffix}`;
+      }
+      return `Unknown error: ${JSON.stringify(data)}`;
+    }
+    function withDefaults(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: withDefaults.bind(null, endpoint2)
+        });
+        return endpointOptions.request.hook(request2, endpointOptions);
+      };
+      return Object.assign(newApi, {
+        endpoint: endpoint2,
+        defaults: withDefaults.bind(null, endpoint2)
+      });
+    }
+    var request = withDefaults(import_endpoint.endpoint, {
+      headers: {
+        "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
+      }
+    });
+  }
+});
+
+// node_modules/@octokit/graphql/dist-node/index.js
+var require_dist_node9 = __commonJS({
+  "node_modules/@octokit/graphql/dist-node/index.js"(exports2, module2) {
+    "use strict";
+    var __defProp2 = Object.defineProperty;
+    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
+    var __getOwnPropNames2 = Object.getOwnPropertyNames;
+    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
+    var __export2 = (target, all) => {
+      for (var name in all)
+        __defProp2(target, name, { get: all[name], enumerable: true });
+    };
+    var __copyProps2 = (to, from, except, desc) => {
+      if (from && typeof from === "object" || typeof from === "function") {
+        for (let key of __getOwnPropNames2(from))
+          if (!__hasOwnProp2.call(to, key) && key !== except)
+            __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
+      }
+      return to;
+    };
+    var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
+    var index_exports = {};
+    __export2(index_exports, {
+      GraphqlResponseError: () => GraphqlResponseError,
+      graphql: () => graphql2,
+      withCustomRequest: () => withCustomRequest
+    });
+    module2.exports = __toCommonJS2(index_exports);
+    var import_request3 = require_dist_node8();
+    var import_universal_user_agent = require_dist_node();
+    var VERSION = "7.1.1";
+    var import_request2 = require_dist_node8();
+    var import_request = require_dist_node8();
+    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.name = "GraphqlResponseError";
+        this.errors = response.errors;
+        this.data = response.data;
+        if (Error.captureStackTrace) {
+          Error.captureStackTrace(this, this.constructor);
+        }
+      }
+    };
+    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 withDefaults(request2, newDefaults) {
+      const newRequest = request2.defaults(newDefaults);
+      const newApi = (query, options) => {
+        return graphql(newRequest, query, options);
+      };
+      return Object.assign(newApi, {
+        defaults: withDefaults.bind(null, newRequest),
+        endpoint: newRequest.endpoint
+      });
+    }
+    var graphql2 = withDefaults(import_request3.request, {
+      headers: {
+        "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
+      },
+      method: "POST",
+      url: "/graphql"
+    });
+    function withCustomRequest(customRequest) {
+      return withDefaults(customRequest, {
+        method: "POST",
+        url: "/graphql"
+      });
+    }
+  }
+});
+
+// node_modules/@octokit/auth-token/dist-node/index.js
+var require_dist_node10 = __commonJS({
+  "node_modules/@octokit/auth-token/dist-node/index.js"(exports2, module2) {
+    "use strict";
+    var __defProp2 = Object.defineProperty;
+    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
+    var __getOwnPropNames2 = Object.getOwnPropertyNames;
+    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
+    var __export2 = (target, all) => {
+      for (var name in all)
+        __defProp2(target, name, { get: all[name], enumerable: true });
+    };
+    var __copyProps2 = (to, from, except, desc) => {
+      if (from && typeof from === "object" || typeof from === "function") {
+        for (let key of __getOwnPropNames2(from))
+          if (!__hasOwnProp2.call(to, key) && key !== except)
+            __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
+      }
+      return to;
+    };
+    var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
+    var dist_src_exports = {};
+    __export2(dist_src_exports, {
+      createTokenAuth: () => createTokenAuth
+    });
+    module2.exports = __toCommonJS2(dist_src_exports);
+    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, request, route, parameters) {
+      const endpoint = request.endpoint.merge(
+        route,
+        parameters
+      );
+      endpoint.headers.authorization = withAuthorizationPrefix(token);
+      return request(endpoint);
+    }
+    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)
+      });
     };
   }
 });
@@ -26499,7 +27200,7 @@ var require_package = __commonJS({
         "@actions/exec": "^1.1.1",
         "@actions/github": "^6.0.0",
         "@actions/glob": "^0.5.0",
-        "@actions/http-client": "^2.2.3",
+        "@actions/http-client": "^3.0.0",
         "@actions/io": "^1.1.3",
         "@actions/tool-cache": "^2.0.2",
         "@octokit/plugin-retry": "^6.0.0",
@@ -31214,5021 +31915,5826 @@ var require_cacheUtils = __commonJS({
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js
-var require_pipeline = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) {
+// node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js
+var require_proxy3 = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createEmptyPipeline = createEmptyPipeline;
-    var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
-    var HttpPipeline = class _HttpPipeline {
-      constructor(policies) {
-        var _a;
-        this._policies = [];
-        this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : [];
-        this._orderedPolicies = void 0;
+    exports2.checkBypass = exports2.getProxyUrl = void 0;
+    function getProxyUrl(reqUrl) {
+      const usingSsl = reqUrl.protocol === "https:";
+      if (checkBypass(reqUrl)) {
+        return void 0;
       }
-      addPolicy(policy, options = {}) {
-        if (options.phase && options.afterPhase) {
-          throw new Error("Policies inside a phase cannot specify afterPhase.");
-        }
-        if (options.phase && !ValidPhaseNames.has(options.phase)) {
-          throw new Error(`Invalid phase name: ${options.phase}`);
+      const proxyVar = (() => {
+        if (usingSsl) {
+          return process.env["https_proxy"] || process.env["HTTPS_PROXY"];
+        } else {
+          return process.env["http_proxy"] || process.env["HTTP_PROXY"];
         }
-        if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
-          throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
+      })();
+      if (proxyVar) {
+        try {
+          return new DecodedURL(proxyVar);
+        } catch (_a) {
+          if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://"))
+            return new DecodedURL(`http://${proxyVar}`);
         }
-        this._policies.push({
-          policy,
-          options
-        });
-        this._orderedPolicies = void 0;
+      } else {
+        return void 0;
       }
-      removePolicy(options) {
-        const removedPolicies = [];
-        this._policies = this._policies.filter((policyDescriptor) => {
-          if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) {
-            removedPolicies.push(policyDescriptor.policy);
-            return false;
-          } else {
-            return true;
-          }
-        });
-        this._orderedPolicies = void 0;
-        return removedPolicies;
+    }
+    exports2.getProxyUrl = getProxyUrl;
+    function checkBypass(reqUrl) {
+      if (!reqUrl.hostname) {
+        return false;
       }
-      sendRequest(httpClient, request) {
-        const policies = this.getOrderedPolicies();
-        const pipeline = policies.reduceRight((next, policy) => {
-          return (req) => {
-            return policy.sendRequest(req, next);
-          };
-        }, (req) => httpClient.sendRequest(req));
-        return pipeline(request);
+      const reqHost = reqUrl.hostname;
+      if (isLoopbackAddress(reqHost)) {
+        return true;
       }
-      getOrderedPolicies() {
-        if (!this._orderedPolicies) {
-          this._orderedPolicies = this.orderPolicies();
-        }
-        return this._orderedPolicies;
+      const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || "";
+      if (!noProxy) {
+        return false;
       }
-      clone() {
-        return new _HttpPipeline(this._policies);
+      let reqPort;
+      if (reqUrl.port) {
+        reqPort = Number(reqUrl.port);
+      } else if (reqUrl.protocol === "http:") {
+        reqPort = 80;
+      } else if (reqUrl.protocol === "https:") {
+        reqPort = 443;
       }
-      static create() {
-        return new _HttpPipeline();
+      const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+      if (typeof reqPort === "number") {
+        upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
       }
-      orderPolicies() {
-        const result = [];
-        const policyMap = /* @__PURE__ */ new Map();
-        function createPhase(name) {
-          return {
-            name,
-            policies: /* @__PURE__ */ new Set(),
-            hasRun: false,
-            hasAfterPolicies: false
-          };
-        }
-        const serializePhase = createPhase("Serialize");
-        const noPhase = createPhase("None");
-        const deserializePhase = createPhase("Deserialize");
-        const retryPhase = createPhase("Retry");
-        const signPhase = createPhase("Sign");
-        const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
-        function getPhase(phase) {
-          if (phase === "Retry") {
-            return retryPhase;
-          } else if (phase === "Serialize") {
-            return serializePhase;
-          } else if (phase === "Deserialize") {
-            return deserializePhase;
-          } else if (phase === "Sign") {
-            return signPhase;
-          } else {
-            return noPhase;
-          }
-        }
-        for (const descriptor of this._policies) {
-          const policy = descriptor.policy;
-          const options = descriptor.options;
-          const policyName = policy.name;
-          if (policyMap.has(policyName)) {
-            throw new Error("Duplicate policy names not allowed in pipeline");
-          }
-          const node = {
-            policy,
-            dependsOn: /* @__PURE__ */ new Set(),
-            dependants: /* @__PURE__ */ new Set()
-          };
-          if (options.afterPhase) {
-            node.afterPhase = getPhase(options.afterPhase);
-            node.afterPhase.hasAfterPolicies = true;
-          }
-          policyMap.set(policyName, node);
-          const phase = getPhase(options.phase);
-          phase.policies.add(node);
-        }
-        for (const descriptor of this._policies) {
-          const { policy, options } = descriptor;
-          const policyName = policy.name;
-          const node = policyMap.get(policyName);
-          if (!node) {
-            throw new Error(`Missing node for policy ${policyName}`);
-          }
-          if (options.afterPolicies) {
-            for (const afterPolicyName of options.afterPolicies) {
-              const afterNode = policyMap.get(afterPolicyName);
-              if (afterNode) {
-                node.dependsOn.add(afterNode);
-                afterNode.dependants.add(node);
-              }
-            }
-          }
-          if (options.beforePolicies) {
-            for (const beforePolicyName of options.beforePolicies) {
-              const beforeNode = policyMap.get(beforePolicyName);
-              if (beforeNode) {
-                beforeNode.dependsOn.add(node);
-                node.dependants.add(beforeNode);
-              }
-            }
-          }
-        }
-        function walkPhase(phase) {
-          phase.hasRun = true;
-          for (const node of phase.policies) {
-            if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
-              continue;
-            }
-            if (node.dependsOn.size === 0) {
-              result.push(node.policy);
-              for (const dependant of node.dependants) {
-                dependant.dependsOn.delete(node);
-              }
-              policyMap.delete(node.policy.name);
-              phase.policies.delete(node);
-            }
-          }
-        }
-        function walkPhases() {
-          for (const phase of orderedPhases) {
-            walkPhase(phase);
-            if (phase.policies.size > 0 && phase !== noPhase) {
-              if (!noPhase.hasRun) {
-                walkPhase(noPhase);
-              }
-              return;
-            }
-            if (phase.hasAfterPolicies) {
-              walkPhase(noPhase);
-            }
-          }
-        }
-        let iteration = 0;
-        while (policyMap.size > 0) {
-          iteration++;
-          const initialResultLength = result.length;
-          walkPhases();
-          if (result.length <= initialResultLength && iteration > 1) {
-            throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
-          }
+      for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) {
+        if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) {
+          return true;
         }
-        return result;
       }
-    };
-    function createEmptyPipeline() {
-      return HttpPipeline.create();
+      return false;
+    }
+    exports2.checkBypass = checkBypass;
+    function isLoopbackAddress(host) {
+      const hostLower = host.toLowerCase();
+      return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]");
     }
+    var DecodedURL = class extends URL {
+      constructor(url2, base) {
+        super(url2, base);
+        this._decodedUsername = decodeURIComponent(super.username);
+        this._decodedPassword = decodeURIComponent(super.password);
+      }
+      get username() {
+        return this._decodedUsername;
+      }
+      get password() {
+        return this._decodedPassword;
+      }
+    };
   }
 });
 
-// node_modules/@azure/logger/dist/index.js
-var require_dist = __commonJS({
-  "node_modules/@azure/logger/dist/index.js"(exports2) {
+// node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js
+var require_lib3 = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/http-client/lib/index.js"(exports2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    var os3 = require("os");
-    var util = require("util");
-    function _interopDefaultLegacy(e) {
-      return e && typeof e === "object" && "default" in e ? e : { "default": e };
-    }
-    var util__default = /* @__PURE__ */ _interopDefaultLegacy(util);
-    function log(message, ...args) {
-      process.stderr.write(`${util__default["default"].format(message, ...args)}${os3.EOL}`);
-    }
-    var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0;
-    var enabledString;
-    var enabledNamespaces = [];
-    var skippedNamespaces = [];
-    var debuggers = [];
-    if (debugEnvVariable) {
-      enable(debugEnvVariable);
-    }
-    var debugObj = Object.assign((namespace) => {
-      return createDebugger(namespace);
-    }, {
-      enable,
-      enabled,
-      disable,
-      log
-    });
-    function enable(namespaces) {
-      enabledString = namespaces;
-      enabledNamespaces = [];
-      skippedNamespaces = [];
-      const wildcard = /\*/g;
-      const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?"));
-      for (const ns of namespaceList) {
-        if (ns.startsWith("-")) {
-          skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`));
-        } else {
-          enabledNamespaces.push(new RegExp(`^${ns}$`));
-        }
-      }
-      for (const instance of debuggers) {
-        instance.enabled = enabled(instance.namespace);
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-    }
-    function enabled(namespace) {
-      if (namespace.endsWith("*")) {
-        return true;
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-      for (const skipped of skippedNamespaces) {
-        if (skipped.test(namespace)) {
-          return false;
-        }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
       }
-      for (const enabledNamespace of enabledNamespaces) {
-        if (enabledNamespace.test(namespace)) {
-          return true;
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-      }
-      return false;
-    }
-    function disable() {
-      const result = enabledString || "";
-      enable("");
-      return result;
-    }
-    function createDebugger(namespace) {
-      const newDebugger = Object.assign(debug7, {
-        enabled: enabled(namespace),
-        destroy,
-        log: debugObj.log,
-        namespace,
-        extend: extend3
-      });
-      function debug7(...args) {
-        if (!newDebugger.enabled) {
-          return;
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        if (args.length > 0) {
-          args[0] = `${namespace} ${args[0]}`;
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
         }
-        newDebugger.log(...args);
-      }
-      debuggers.push(newDebugger);
-      return newDebugger;
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0;
+    var http = __importStar4(require("http"));
+    var https2 = __importStar4(require("https"));
+    var pm = __importStar4(require_proxy3());
+    var tunnel = __importStar4(require_tunnel2());
+    var undici_1 = require_undici();
+    var HttpCodes;
+    (function(HttpCodes2) {
+      HttpCodes2[HttpCodes2["OK"] = 200] = "OK";
+      HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices";
+      HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently";
+      HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved";
+      HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther";
+      HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified";
+      HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy";
+      HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy";
+      HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+      HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect";
+      HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest";
+      HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized";
+      HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired";
+      HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden";
+      HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound";
+      HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+      HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable";
+      HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+      HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout";
+      HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict";
+      HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone";
+      HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests";
+      HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError";
+      HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented";
+      HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway";
+      HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+      HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout";
+    })(HttpCodes || (exports2.HttpCodes = HttpCodes = {}));
+    var Headers;
+    (function(Headers2) {
+      Headers2["Accept"] = "accept";
+      Headers2["ContentType"] = "content-type";
+    })(Headers || (exports2.Headers = Headers = {}));
+    var MediaTypes;
+    (function(MediaTypes2) {
+      MediaTypes2["ApplicationJson"] = "application/json";
+    })(MediaTypes || (exports2.MediaTypes = MediaTypes = {}));
+    function getProxyUrl(serverUrl) {
+      const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+      return proxyUrl ? proxyUrl.href : "";
     }
-    function destroy() {
-      const index = debuggers.indexOf(this);
-      if (index >= 0) {
-        debuggers.splice(index, 1);
-        return true;
+    exports2.getProxyUrl = getProxyUrl;
+    var HttpRedirectCodes = [
+      HttpCodes.MovedPermanently,
+      HttpCodes.ResourceMoved,
+      HttpCodes.SeeOther,
+      HttpCodes.TemporaryRedirect,
+      HttpCodes.PermanentRedirect
+    ];
+    var HttpResponseRetryCodes = [
+      HttpCodes.BadGateway,
+      HttpCodes.ServiceUnavailable,
+      HttpCodes.GatewayTimeout
+    ];
+    var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"];
+    var ExponentialBackoffCeiling = 10;
+    var ExponentialBackoffTimeSlice = 5;
+    var HttpClientError = class _HttpClientError extends Error {
+      constructor(message, statusCode) {
+        super(message);
+        this.name = "HttpClientError";
+        this.statusCode = statusCode;
+        Object.setPrototypeOf(this, _HttpClientError.prototype);
       }
-      return false;
-    }
-    function extend3(namespace) {
-      const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
-      newDebugger.log = this.log;
-      return newDebugger;
-    }
-    var debug6 = debugObj;
-    var registeredLoggers = /* @__PURE__ */ new Set();
-    var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0;
-    var azureLogLevel;
-    var AzureLogger = debug6("azure");
-    AzureLogger.log = (...args) => {
-      debug6.log(...args);
     };
-    var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"];
-    if (logLevelFromEnv) {
-      if (isAzureLogLevel(logLevelFromEnv)) {
-        setLogLevel(logLevelFromEnv);
-      } else {
-        console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`);
+    exports2.HttpClientError = HttpClientError;
+    var HttpClientResponse = class {
+      constructor(message) {
+        this.message = message;
       }
-    }
-    function setLogLevel(level) {
-      if (level && !isAzureLogLevel(level)) {
-        throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`);
+      readBody() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () {
+            let output = Buffer.alloc(0);
+            this.message.on("data", (chunk) => {
+              output = Buffer.concat([output, chunk]);
+            });
+            this.message.on("end", () => {
+              resolve6(output.toString());
+            });
+          }));
+        });
       }
-      azureLogLevel = level;
-      const enabledNamespaces2 = [];
-      for (const logger of registeredLoggers) {
-        if (shouldEnable(logger)) {
-          enabledNamespaces2.push(logger.namespace);
-        }
+      readBodyBuffer() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () {
+            const chunks = [];
+            this.message.on("data", (chunk) => {
+              chunks.push(chunk);
+            });
+            this.message.on("end", () => {
+              resolve6(Buffer.concat(chunks));
+            });
+          }));
+        });
       }
-      debug6.enable(enabledNamespaces2.join(","));
-    }
-    function getLogLevel() {
-      return azureLogLevel;
-    }
-    var levelMap = {
-      verbose: 400,
-      info: 300,
-      warning: 200,
-      error: 100
     };
-    function createClientLogger(namespace) {
-      const clientRootLogger = AzureLogger.extend(namespace);
-      patchLogMethod(AzureLogger, clientRootLogger);
-      return {
-        error: createLogger(clientRootLogger, "error"),
-        warning: createLogger(clientRootLogger, "warning"),
-        info: createLogger(clientRootLogger, "info"),
-        verbose: createLogger(clientRootLogger, "verbose")
-      };
-    }
-    function patchLogMethod(parent, child) {
-      child.log = (...args) => {
-        parent.log(...args);
-      };
+    exports2.HttpClientResponse = HttpClientResponse;
+    function isHttps(requestUrl) {
+      const parsedUrl = new URL(requestUrl);
+      return parsedUrl.protocol === "https:";
     }
-    function createLogger(parent, level) {
-      const logger = Object.assign(parent.extend(level), {
-        level
-      });
-      patchLogMethod(parent, logger);
-      if (shouldEnable(logger)) {
-        const enabledNamespaces2 = debug6.disable();
-        debug6.enable(enabledNamespaces2 + "," + logger.namespace);
+    exports2.isHttps = isHttps;
+    var HttpClient2 = class {
+      constructor(userAgent, handlers, requestOptions) {
+        this._ignoreSslError = false;
+        this._allowRedirects = true;
+        this._allowRedirectDowngrade = false;
+        this._maxRedirects = 50;
+        this._allowRetries = false;
+        this._maxRetries = 1;
+        this._keepAlive = false;
+        this._disposed = false;
+        this.userAgent = userAgent;
+        this.handlers = handlers || [];
+        this.requestOptions = requestOptions;
+        if (requestOptions) {
+          if (requestOptions.ignoreSslError != null) {
+            this._ignoreSslError = requestOptions.ignoreSslError;
+          }
+          this._socketTimeout = requestOptions.socketTimeout;
+          if (requestOptions.allowRedirects != null) {
+            this._allowRedirects = requestOptions.allowRedirects;
+          }
+          if (requestOptions.allowRedirectDowngrade != null) {
+            this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+          }
+          if (requestOptions.maxRedirects != null) {
+            this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+          }
+          if (requestOptions.keepAlive != null) {
+            this._keepAlive = requestOptions.keepAlive;
+          }
+          if (requestOptions.allowRetries != null) {
+            this._allowRetries = requestOptions.allowRetries;
+          }
+          if (requestOptions.maxRetries != null) {
+            this._maxRetries = requestOptions.maxRetries;
+          }
+        }
       }
-      registeredLoggers.add(logger);
-      return logger;
-    }
-    function shouldEnable(logger) {
-      return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]);
-    }
-    function isAzureLogLevel(logLevel) {
-      return AZURE_LOG_LEVELS.includes(logLevel);
-    }
-    exports2.AzureLogger = AzureLogger;
-    exports2.createClientLogger = createClientLogger;
-    exports2.getLogLevel = getLogLevel;
-    exports2.setLogLevel = setLogLevel;
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js
-var require_log = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.logger = void 0;
-    var logger_1 = require_dist();
-    exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline");
-  }
-});
-
-// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js
-var require_AbortError = __commonJS({
-  "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.AbortError = void 0;
-    var AbortError = class extends Error {
-      constructor(message) {
-        super(message);
-        this.name = "AbortError";
+      options(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("OPTIONS", requestUrl, null, additionalHeaders || {});
+        });
       }
-    };
-    exports2.AbortError = AbortError;
-  }
-});
-
-// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js
-var require_commonjs = __commonJS({
-  "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.AbortError = void 0;
-    var AbortError_js_1 = require_AbortError();
-    Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() {
-      return AbortError_js_1.AbortError;
-    } });
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js
-var require_createAbortablePromise = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createAbortablePromise = createAbortablePromise;
-    var abort_controller_1 = require_commonjs();
-    function createAbortablePromise(buildPromise, options) {
-      const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
-      return new Promise((resolve6, reject) => {
-        function rejectOnAbort() {
-          reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted."));
+      get(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("GET", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      del(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("DELETE", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      post(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("POST", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      patch(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PATCH", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      put(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PUT", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      head(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("HEAD", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      sendStream(verb, requestUrl, stream2, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request(verb, requestUrl, stream2, additionalHeaders);
+        });
+      }
+      /**
+       * Gets a typed object from an endpoint
+       * Be aware that not found returns a null.  Other errors (4xx, 5xx) reject the promise
+       */
+      getJson(requestUrl, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          const res = yield this.get(requestUrl, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      postJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.post(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      putJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.put(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      patchJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.patch(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      /**
+       * Makes a raw http request.
+       * All other methods such as get, post, patch, and request ultimately call this.
+       * Prefer get, del, post and patch
+       */
+      request(verb, requestUrl, data, headers) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          if (this._disposed) {
+            throw new Error("Client has already been disposed.");
+          }
+          const parsedUrl = new URL(requestUrl);
+          let info6 = this._prepareRequest(verb, parsedUrl, headers);
+          const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1;
+          let numTries = 0;
+          let response;
+          do {
+            response = yield this.requestRaw(info6, data);
+            if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
+              let authenticationHandler;
+              for (const handler of this.handlers) {
+                if (handler.canHandleAuthentication(response)) {
+                  authenticationHandler = handler;
+                  break;
+                }
+              }
+              if (authenticationHandler) {
+                return authenticationHandler.handleAuthentication(this, info6, data);
+              } else {
+                return response;
+              }
+            }
+            let redirectsRemaining = this._maxRedirects;
+            while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) {
+              const redirectUrl = response.message.headers["location"];
+              if (!redirectUrl) {
+                break;
+              }
+              const parsedRedirectUrl = new URL(redirectUrl);
+              if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
+                throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
+              }
+              yield response.readBody();
+              if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+                for (const header in headers) {
+                  if (header.toLowerCase() === "authorization") {
+                    delete headers[header];
+                  }
+                }
+              }
+              info6 = this._prepareRequest(verb, parsedRedirectUrl, headers);
+              response = yield this.requestRaw(info6, data);
+              redirectsRemaining--;
+            }
+            if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+              return response;
+            }
+            numTries += 1;
+            if (numTries < maxTries) {
+              yield response.readBody();
+              yield this._performExponentialBackoff(numTries);
+            }
+          } while (numTries < maxTries);
+          return response;
+        });
+      }
+      /**
+       * Needs to be called if keepAlive is set to true in request options.
+       */
+      dispose() {
+        if (this._agent) {
+          this._agent.destroy();
         }
-        function removeListeners() {
-          abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort);
+        this._disposed = true;
+      }
+      /**
+       * Raw request.
+       * @param info
+       * @param data
+       */
+      requestRaw(info6, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6, reject) => {
+            function callbackForResult(err, res) {
+              if (err) {
+                reject(err);
+              } else if (!res) {
+                reject(new Error("Unknown error"));
+              } else {
+                resolve6(res);
+              }
+            }
+            this.requestRawWithCallback(info6, data, callbackForResult);
+          });
+        });
+      }
+      /**
+       * Raw request with callback.
+       * @param info
+       * @param data
+       * @param onResult
+       */
+      requestRawWithCallback(info6, data, onResult) {
+        if (typeof data === "string") {
+          if (!info6.options.headers) {
+            info6.options.headers = {};
+          }
+          info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8");
         }
-        function onAbort() {
-          cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort();
-          removeListeners();
-          rejectOnAbort();
+        let callbackCalled = false;
+        function handleResult(err, res) {
+          if (!callbackCalled) {
+            callbackCalled = true;
+            onResult(err, res);
+          }
         }
-        if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) {
-          return rejectOnAbort();
+        const req = info6.httpModule.request(info6.options, (msg) => {
+          const res = new HttpClientResponse(msg);
+          handleResult(void 0, res);
+        });
+        let socket;
+        req.on("socket", (sock) => {
+          socket = sock;
+        });
+        req.setTimeout(this._socketTimeout || 3 * 6e4, () => {
+          if (socket) {
+            socket.end();
+          }
+          handleResult(new Error(`Request timeout: ${info6.options.path}`));
+        });
+        req.on("error", function(err) {
+          handleResult(err);
+        });
+        if (data && typeof data === "string") {
+          req.write(data, "utf8");
         }
-        try {
-          buildPromise((x) => {
-            removeListeners();
-            resolve6(x);
-          }, (x) => {
-            removeListeners();
-            reject(x);
+        if (data && typeof data !== "string") {
+          data.on("close", function() {
+            req.end();
           });
-        } catch (err) {
-          reject(err);
+          data.pipe(req);
+        } else {
+          req.end();
         }
-        abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort);
-      });
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/random.js
-var require_random = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getRandomIntegerInclusive = getRandomIntegerInclusive;
-    function getRandomIntegerInclusive(min, max) {
-      min = Math.ceil(min);
-      max = Math.floor(max);
-      const offset = Math.floor(Math.random() * (max - min + 1));
-      return offset + min;
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/delay.js
-var require_delay = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.delay = delay2;
-    exports2.calculateRetryDelay = calculateRetryDelay;
-    var createAbortablePromise_js_1 = require_createAbortablePromise();
-    var random_js_1 = require_random();
-    var StandardAbortMessage = "The delay was aborted.";
-    function delay2(timeInMs, options) {
-      let token;
-      const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
-      return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve6) => {
-        token = setTimeout(resolve6, timeInMs);
-      }, {
-        cleanupBeforeAbort: () => clearTimeout(token),
-        abortSignal,
-        abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage
-      });
-    }
-    function calculateRetryDelay(retryAttempt, config) {
-      const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
-      const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
-      const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2);
-      return { retryAfterInMs };
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js
-var require_aborterUtils = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.cancelablePromiseRace = cancelablePromiseRace;
-    async function cancelablePromiseRace(abortablePromiseBuilders, options) {
-      var _a, _b;
-      const aborter = new AbortController();
-      function abortHandler() {
-        aborter.abort();
       }
-      (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler);
-      try {
-        return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
-      } finally {
-        aborter.abort();
-        (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler);
+      /**
+       * Gets an http agent. This function is useful when you need an http agent that handles
+       * routing through a proxy server - depending upon the url and proxy environment variables.
+       * @param serverUrl  The server URL where the request will be sent. For example, https://api.github.com
+       */
+      getAgent(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        return this._getAgent(parsedUrl);
       }
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/object.js
-var require_object = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.isObject = isObject2;
-    function isObject2(input) {
-      return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date);
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/error.js
-var require_error = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.isError = isError;
-    exports2.getErrorMessage = getErrorMessage2;
-    var object_js_1 = require_object();
-    function isError(e) {
-      if ((0, object_js_1.isObject)(e)) {
-        const hasName = typeof e.name === "string";
-        const hasMessage = typeof e.message === "string";
-        return hasName && hasMessage;
+      getAgentDispatcher(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (!useProxy) {
+          return;
+        }
+        return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
       }
-      return false;
-    }
-    function getErrorMessage2(e) {
-      if (isError(e)) {
-        return e.message;
-      } else {
-        let stringified;
-        try {
-          if (typeof e === "object" && e) {
-            stringified = JSON.stringify(e);
-          } else {
-            stringified = String(e);
+      _prepareRequest(method, requestUrl, headers) {
+        const info6 = {};
+        info6.parsedUrl = requestUrl;
+        const usingSsl = info6.parsedUrl.protocol === "https:";
+        info6.httpModule = usingSsl ? https2 : http;
+        const defaultPort = usingSsl ? 443 : 80;
+        info6.options = {};
+        info6.options.host = info6.parsedUrl.hostname;
+        info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort;
+        info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || "");
+        info6.options.method = method;
+        info6.options.headers = this._mergeHeaders(headers);
+        if (this.userAgent != null) {
+          info6.options.headers["user-agent"] = this.userAgent;
+        }
+        info6.options.agent = this._getAgent(info6.parsedUrl);
+        if (this.handlers) {
+          for (const handler of this.handlers) {
+            handler.prepareRequest(info6.options);
           }
-        } catch (err) {
-          stringified = "[unable to stringify input]";
         }
-        return `Unknown error ${stringified}`;
+        return info6;
       }
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/sha256.js
-var require_sha256 = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.computeSha256Hmac = computeSha256Hmac;
-    exports2.computeSha256Hash = computeSha256Hash;
-    var crypto_1 = require("crypto");
-    async function computeSha256Hmac(key, stringToSign, encoding) {
-      const decodedKey = Buffer.from(key, "base64");
-      return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding);
-    }
-    async function computeSha256Hash(content, encoding) {
-      return (0, crypto_1.createHash)("sha256").update(content).digest(encoding);
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/typeGuards.js
-var require_typeGuards = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.isDefined = isDefined2;
-    exports2.isObjectWithProperties = isObjectWithProperties;
-    exports2.objectHasProperty = objectHasProperty;
-    function isDefined2(thing) {
-      return typeof thing !== "undefined" && thing !== null;
-    }
-    function isObjectWithProperties(thing, properties) {
-      if (!isDefined2(thing) || typeof thing !== "object") {
-        return false;
-      }
-      for (const property of properties) {
-        if (!objectHasProperty(thing, property)) {
-          return false;
+      _mergeHeaders(headers) {
+        if (this.requestOptions && this.requestOptions.headers) {
+          return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
         }
+        return lowercaseKeys(headers || {});
       }
-      return true;
-    }
-    function objectHasProperty(thing, property) {
-      return isDefined2(thing) && typeof thing === "object" && property in thing;
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js
-var require_uuidUtils = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) {
-    "use strict";
-    var _a;
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.randomUUID = randomUUID2;
-    var crypto_1 = require("crypto");
-    var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID;
-    function randomUUID2() {
-      return uuidFunction();
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js
-var require_checkEnvironment = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) {
-    "use strict";
-    var _a;
-    var _b;
-    var _c;
-    var _d;
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0;
-    exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
-    exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope");
-    exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined";
-    exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
-    exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node);
-    exports2.isNode = exports2.isNodeLike;
-    exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno;
-    exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative";
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js
-var require_bytesEncoding = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.uint8ArrayToString = uint8ArrayToString;
-    exports2.stringToUint8Array = stringToUint8Array;
-    function uint8ArrayToString(bytes, format) {
-      return Buffer.from(bytes).toString(format);
-    }
-    function stringToUint8Array(value, format) {
-      return Buffer.from(value, format);
-    }
-  }
-});
-
-// node_modules/@azure/core-util/dist/commonjs/index.js
-var require_commonjs2 = __commonJS({
-  "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0;
-    var delay_js_1 = require_delay();
-    Object.defineProperty(exports2, "delay", { enumerable: true, get: function() {
-      return delay_js_1.delay;
-    } });
-    Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() {
-      return delay_js_1.calculateRetryDelay;
-    } });
-    var aborterUtils_js_1 = require_aborterUtils();
-    Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() {
-      return aborterUtils_js_1.cancelablePromiseRace;
-    } });
-    var createAbortablePromise_js_1 = require_createAbortablePromise();
-    Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() {
-      return createAbortablePromise_js_1.createAbortablePromise;
-    } });
-    var random_js_1 = require_random();
-    Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() {
-      return random_js_1.getRandomIntegerInclusive;
-    } });
-    var object_js_1 = require_object();
-    Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() {
-      return object_js_1.isObject;
-    } });
-    var error_js_1 = require_error();
-    Object.defineProperty(exports2, "isError", { enumerable: true, get: function() {
-      return error_js_1.isError;
-    } });
-    Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() {
-      return error_js_1.getErrorMessage;
-    } });
-    var sha256_js_1 = require_sha256();
-    Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() {
-      return sha256_js_1.computeSha256Hash;
-    } });
-    Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() {
-      return sha256_js_1.computeSha256Hmac;
-    } });
-    var typeGuards_js_1 = require_typeGuards();
-    Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() {
-      return typeGuards_js_1.isDefined;
-    } });
-    Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() {
-      return typeGuards_js_1.isObjectWithProperties;
-    } });
-    Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() {
-      return typeGuards_js_1.objectHasProperty;
-    } });
-    var uuidUtils_js_1 = require_uuidUtils();
-    Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() {
-      return uuidUtils_js_1.randomUUID;
-    } });
-    var checkEnvironment_js_1 = require_checkEnvironment();
-    Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() {
-      return checkEnvironment_js_1.isBrowser;
-    } });
-    Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() {
-      return checkEnvironment_js_1.isBun;
-    } });
-    Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() {
-      return checkEnvironment_js_1.isNode;
-    } });
-    Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() {
-      return checkEnvironment_js_1.isNodeLike;
-    } });
-    Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() {
-      return checkEnvironment_js_1.isNodeRuntime;
-    } });
-    Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() {
-      return checkEnvironment_js_1.isDeno;
-    } });
-    Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() {
-      return checkEnvironment_js_1.isReactNative;
-    } });
-    Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() {
-      return checkEnvironment_js_1.isWebWorker;
-    } });
-    var bytesEncoding_js_1 = require_bytesEncoding();
-    Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() {
-      return bytesEncoding_js_1.uint8ArrayToString;
-    } });
-    Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() {
-      return bytesEncoding_js_1.stringToUint8Array;
-    } });
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js
-var require_sanitizer = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Sanitizer = void 0;
-    var core_util_1 = require_commonjs2();
-    var RedactedString = "REDACTED";
-    var defaultAllowedHeaderNames = [
-      "x-ms-client-request-id",
-      "x-ms-return-client-request-id",
-      "x-ms-useragent",
-      "x-ms-correlation-request-id",
-      "x-ms-request-id",
-      "client-request-id",
-      "ms-cv",
-      "return-client-request-id",
-      "traceparent",
-      "Access-Control-Allow-Credentials",
-      "Access-Control-Allow-Headers",
-      "Access-Control-Allow-Methods",
-      "Access-Control-Allow-Origin",
-      "Access-Control-Expose-Headers",
-      "Access-Control-Max-Age",
-      "Access-Control-Request-Headers",
-      "Access-Control-Request-Method",
-      "Origin",
-      "Accept",
-      "Accept-Encoding",
-      "Cache-Control",
-      "Connection",
-      "Content-Length",
-      "Content-Type",
-      "Date",
-      "ETag",
-      "Expires",
-      "If-Match",
-      "If-Modified-Since",
-      "If-None-Match",
-      "If-Unmodified-Since",
-      "Last-Modified",
-      "Pragma",
-      "Request-Id",
-      "Retry-After",
-      "Server",
-      "Transfer-Encoding",
-      "User-Agent",
-      "WWW-Authenticate"
-    ];
-    var defaultAllowedQueryParameters = ["api-version"];
-    var Sanitizer = class {
-      constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) {
-        allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
-        allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
-        this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
-        this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
-      }
-      sanitize(obj) {
-        const seen = /* @__PURE__ */ new Set();
-        return JSON.stringify(obj, (key, value) => {
-          if (value instanceof Error) {
-            return Object.assign(Object.assign({}, value), { name: value.name, message: value.message });
-          }
-          if (key === "headers") {
-            return this.sanitizeHeaders(value);
-          } else if (key === "url") {
-            return this.sanitizeUrl(value);
-          } else if (key === "query") {
-            return this.sanitizeQuery(value);
-          } else if (key === "body") {
-            return void 0;
-          } else if (key === "response") {
-            return void 0;
-          } else if (key === "operationSpec") {
-            return void 0;
-          } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) {
-            if (seen.has(value)) {
-              return "[Circular]";
-            }
-            seen.add(value);
-          }
-          return value;
-        }, 2);
+      _getExistingOrDefaultHeader(additionalHeaders, header, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
+        }
+        return additionalHeaders[header] || clientHeader || _default2;
       }
-      sanitizeUrl(value) {
-        if (typeof value !== "string" || value === null || value === "") {
-          return value;
+      _getAgent(parsedUrl) {
+        let agent;
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (this._keepAlive && useProxy) {
+          agent = this._proxyAgent;
         }
-        const url2 = new URL(value);
-        if (!url2.search) {
-          return value;
+        if (!useProxy) {
+          agent = this._agent;
         }
-        for (const [key] of url2.searchParams) {
-          if (!this.allowedQueryParameters.has(key.toLowerCase())) {
-            url2.searchParams.set(key, RedactedString);
-          }
+        if (agent) {
+          return agent;
         }
-        return url2.toString();
-      }
-      sanitizeHeaders(obj) {
-        const sanitized = {};
-        for (const key of Object.keys(obj)) {
-          if (this.allowedHeaderNames.has(key.toLowerCase())) {
-            sanitized[key] = obj[key];
+        const usingSsl = parsedUrl.protocol === "https:";
+        let maxSockets = 100;
+        if (this.requestOptions) {
+          maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
+        }
+        if (proxyUrl && proxyUrl.hostname) {
+          const agentOptions = {
+            maxSockets,
+            keepAlive: this._keepAlive,
+            proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && {
+              proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+            }), { host: proxyUrl.hostname, port: proxyUrl.port })
+          };
+          let tunnelAgent;
+          const overHttps = proxyUrl.protocol === "https:";
+          if (usingSsl) {
+            tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
           } else {
-            sanitized[key] = RedactedString;
+            tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
           }
+          agent = tunnelAgent(agentOptions);
+          this._proxyAgent = agent;
         }
-        return sanitized;
+        if (!agent) {
+          const options = { keepAlive: this._keepAlive, maxSockets };
+          agent = usingSsl ? new https2.Agent(options) : new http.Agent(options);
+          this._agent = agent;
+        }
+        if (usingSsl && this._ignoreSslError) {
+          agent.options = Object.assign(agent.options || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return agent;
       }
-      sanitizeQuery(value) {
-        if (typeof value !== "object" || value === null) {
-          return value;
+      _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+        let proxyAgent;
+        if (this._keepAlive) {
+          proxyAgent = this._proxyAgentDispatcher;
         }
-        const sanitized = {};
-        for (const k of Object.keys(value)) {
-          if (this.allowedQueryParameters.has(k.toLowerCase())) {
-            sanitized[k] = value[k];
-          } else {
-            sanitized[k] = RedactedString;
-          }
+        if (proxyAgent) {
+          return proxyAgent;
         }
-        return sanitized;
+        const usingSsl = parsedUrl.protocol === "https:";
+        proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && {
+          token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}`
+        }));
+        this._proxyAgentDispatcher = proxyAgent;
+        if (usingSsl && this._ignoreSslError) {
+          proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return proxyAgent;
+      }
+      _performExponentialBackoff(retryNumber) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+          const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+          return new Promise((resolve6) => setTimeout(() => resolve6(), ms));
+        });
+      }
+      _processResponse(res, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6, reject) => __awaiter4(this, void 0, void 0, function* () {
+            const statusCode = res.message.statusCode || 0;
+            const response = {
+              statusCode,
+              result: null,
+              headers: {}
+            };
+            if (statusCode === HttpCodes.NotFound) {
+              resolve6(response);
+            }
+            function dateTimeDeserializer(key, value) {
+              if (typeof value === "string") {
+                const a = new Date(value);
+                if (!isNaN(a.valueOf())) {
+                  return a;
+                }
+              }
+              return value;
+            }
+            let obj;
+            let contents;
+            try {
+              contents = yield res.readBody();
+              if (contents && contents.length > 0) {
+                if (options && options.deserializeDates) {
+                  obj = JSON.parse(contents, dateTimeDeserializer);
+                } else {
+                  obj = JSON.parse(contents);
+                }
+                response.result = obj;
+              }
+              response.headers = res.message.headers;
+            } catch (err) {
+            }
+            if (statusCode > 299) {
+              let msg;
+              if (obj && obj.message) {
+                msg = obj.message;
+              } else if (contents && contents.length > 0) {
+                msg = contents;
+              } else {
+                msg = `Failed request: (${statusCode})`;
+              }
+              const err = new HttpClientError(msg, statusCode);
+              err.result = response.result;
+              reject(err);
+            } else {
+              resolve6(response);
+            }
+          }));
+        });
       }
     };
-    exports2.Sanitizer = Sanitizer;
+    exports2.HttpClient = HttpClient2;
+    var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js
-var require_logPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) {
+// node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js
+var require_auth2 = __commonJS({
+  "node_modules/@actions/cache/node_modules/@actions/http-client/lib/auth.js"(exports2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.logPolicyName = void 0;
-    exports2.logPolicy = logPolicy;
-    var log_js_1 = require_log();
-    var sanitizer_js_1 = require_sanitizer();
-    exports2.logPolicyName = "logPolicy";
-    function logPolicy(options = {}) {
-      var _a;
-      const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info;
-      const sanitizer = new sanitizer_js_1.Sanitizer({
-        additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
-        additionalAllowedQueryParameters: options.additionalAllowedQueryParameters
-      });
-      return {
-        name: exports2.logPolicyName,
-        async sendRequest(request, next) {
-          if (!logger.enabled) {
-            return next(request);
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
           }
-          logger(`Request: ${sanitizer.sanitize(request)}`);
-          const response = await next(request);
-          logger(`Response status code: ${response.status}`);
-          logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
-          return response;
         }
-      };
-    }
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js
-var require_redirectPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.redirectPolicyName = void 0;
-    exports2.redirectPolicy = redirectPolicy;
-    exports2.redirectPolicyName = "redirectPolicy";
-    var allowedRedirect = ["GET", "HEAD"];
-    function redirectPolicy(options = {}) {
-      const { maxRetries = 20 } = options;
-      return {
-        name: exports2.redirectPolicyName,
-        async sendRequest(request, next) {
-          const response = await next(request);
-          return handleRedirect(next, response, maxRetries);
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
         }
-      };
-    }
-    async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
-      const { request, status, headers } = response;
-      const locationHeader = headers.get("location");
-      if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) {
-        const url2 = new URL(locationHeader, request.url);
-        request.url = url2.toString();
-        if (status === 303) {
-          request.method = "GET";
-          request.headers.delete("Content-Length");
-          delete request.body;
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
         }
-        request.headers.delete("Authorization");
-        const res = await next(request);
-        return handleRedirect(next, res, maxRetries, currentRetries + 1);
-      }
-      return response;
-    }
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs
-var tslib_es6_exports = {};
-__export(tslib_es6_exports, {
-  __addDisposableResource: () => __addDisposableResource,
-  __assign: () => __assign,
-  __asyncDelegator: () => __asyncDelegator,
-  __asyncGenerator: () => __asyncGenerator,
-  __asyncValues: () => __asyncValues,
-  __await: () => __await,
-  __awaiter: () => __awaiter,
-  __classPrivateFieldGet: () => __classPrivateFieldGet,
-  __classPrivateFieldIn: () => __classPrivateFieldIn,
-  __classPrivateFieldSet: () => __classPrivateFieldSet,
-  __createBinding: () => __createBinding,
-  __decorate: () => __decorate,
-  __disposeResources: () => __disposeResources,
-  __esDecorate: () => __esDecorate,
-  __exportStar: () => __exportStar,
-  __extends: () => __extends,
-  __generator: () => __generator,
-  __importDefault: () => __importDefault,
-  __importStar: () => __importStar,
-  __makeTemplateObject: () => __makeTemplateObject,
-  __metadata: () => __metadata,
-  __param: () => __param,
-  __propKey: () => __propKey,
-  __read: () => __read,
-  __rest: () => __rest,
-  __runInitializers: () => __runInitializers,
-  __setFunctionName: () => __setFunctionName,
-  __spread: () => __spread,
-  __spreadArray: () => __spreadArray,
-  __spreadArrays: () => __spreadArrays,
-  __values: () => __values2,
-  default: () => tslib_es6_default
-});
-function __extends(d, b) {
-  if (typeof b !== "function" && b !== null)
-    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
-  extendStatics(d, b);
-  function __() {
-    this.constructor = d;
-  }
-  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-}
-function __rest(s, e) {
-  var t = {};
-  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
-    t[p] = s[p];
-  if (s != null && typeof Object.getOwnPropertySymbols === "function")
-    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
-      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
-        t[p[i]] = s[p[i]];
-    }
-  return t;
-}
-function __decorate(decorators, target, key, desc) {
-  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
-  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
-  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
-  return c > 3 && r && Object.defineProperty(target, key, r), r;
-}
-function __param(paramIndex, decorator) {
-  return function(target, key) {
-    decorator(target, key, paramIndex);
-  };
-}
-function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
-  function accept(f) {
-    if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
-    return f;
-  }
-  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
-  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
-  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
-  var _, done = false;
-  for (var i = decorators.length - 1; i >= 0; i--) {
-    var context2 = {};
-    for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p];
-    for (var p in contextIn.access) context2.access[p] = contextIn.access[p];
-    context2.addInitializer = function(f) {
-      if (done) throw new TypeError("Cannot add initializers after decoration has completed");
-      extraInitializers.push(accept(f || null));
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2);
-    if (kind === "accessor") {
-      if (result === void 0) continue;
-      if (result === null || typeof result !== "object") throw new TypeError("Object expected");
-      if (_ = accept(result.get)) descriptor.get = _;
-      if (_ = accept(result.set)) descriptor.set = _;
-      if (_ = accept(result.init)) initializers.unshift(_);
-    } else if (_ = accept(result)) {
-      if (kind === "field") initializers.unshift(_);
-      else descriptor[key] = _;
-    }
-  }
-  if (target) Object.defineProperty(target, contextIn.name, descriptor);
-  done = true;
-}
-function __runInitializers(thisArg, initializers, value) {
-  var useValue = arguments.length > 2;
-  for (var i = 0; i < initializers.length; i++) {
-    value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
-  }
-  return useValue ? value : void 0;
-}
-function __propKey(x) {
-  return typeof x === "symbol" ? x : "".concat(x);
-}
-function __setFunctionName(f, name, prefix) {
-  if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
-  return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
-}
-function __metadata(metadataKey, metadataValue) {
-  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
-}
-function __awaiter(thisArg, _arguments, P, generator) {
-  function adopt(value) {
-    return value instanceof P ? value : new P(function(resolve6) {
-      resolve6(value);
-    });
-  }
-  return new (P || (P = Promise))(function(resolve6, reject) {
-    function fulfilled(value) {
-      try {
-        step(generator.next(value));
-      } catch (e) {
-        reject(e);
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.PersonalAccessTokenCredentialHandler = exports2.BearerCredentialHandler = exports2.BasicCredentialHandler = void 0;
+    var BasicCredentialHandler = class {
+      constructor(username, password) {
+        this.username = username;
+        this.password = password;
       }
-    }
-    function rejected(value) {
-      try {
-        step(generator["throw"](value));
-      } catch (e) {
-        reject(e);
+      prepareRequest(options) {
+        if (!options.headers) {
+          throw Error("The request has no headers");
+        }
+        options.headers["Authorization"] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`;
+      }
+      // This handler cannot handle 401
+      canHandleAuthentication() {
+        return false;
+      }
+      handleAuthentication() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          throw new Error("not implemented");
+        });
+      }
+    };
+    exports2.BasicCredentialHandler = BasicCredentialHandler;
+    var BearerCredentialHandler = class {
+      constructor(token) {
+        this.token = token;
+      }
+      // currently implements pre-authorization
+      // TODO: support preAuth = false where it hooks on 401
+      prepareRequest(options) {
+        if (!options.headers) {
+          throw Error("The request has no headers");
+        }
+        options.headers["Authorization"] = `Bearer ${this.token}`;
+      }
+      // This handler cannot handle 401
+      canHandleAuthentication() {
+        return false;
+      }
+      handleAuthentication() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          throw new Error("not implemented");
+        });
+      }
+    };
+    exports2.BearerCredentialHandler = BearerCredentialHandler;
+    var PersonalAccessTokenCredentialHandler = class {
+      constructor(token) {
+        this.token = token;
+      }
+      // currently implements pre-authorization
+      // TODO: support preAuth = false where it hooks on 401
+      prepareRequest(options) {
+        if (!options.headers) {
+          throw Error("The request has no headers");
+        }
+        options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`;
+      }
+      // This handler cannot handle 401
+      canHandleAuthentication() {
+        return false;
+      }
+      handleAuthentication() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          throw new Error("not implemented");
+        });
       }
-    }
-    function step(result) {
-      result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
-    }
-    step((generator = generator.apply(thisArg, _arguments || [])).next());
-  });
-}
-function __generator(thisArg, body) {
-  var _ = { label: 0, sent: function() {
-    if (t[0] & 1) throw t[1];
-    return t[1];
-  }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
-  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
-    return this;
-  }), g;
-  function verb(n) {
-    return function(v) {
-      return step([n, v]);
     };
+    exports2.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
   }
-  function step(op) {
-    if (f) throw new TypeError("Generator is already executing.");
-    while (g && (g = 0, op[0] && (_ = 0)), _) try {
-      if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
-      if (y = 0, t) op = [op[0] & 2, t.value];
-      switch (op[0]) {
-        case 0:
-        case 1:
-          t = op;
-          break;
-        case 4:
-          _.label++;
-          return { value: op[1], done: false };
-        case 5:
-          _.label++;
-          y = op[1];
-          op = [0];
-          continue;
-        case 7:
-          op = _.ops.pop();
-          _.trys.pop();
-          continue;
-        default:
-          if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
-            _ = 0;
-            continue;
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js
+var require_pipeline = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipeline.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.createEmptyPipeline = createEmptyPipeline;
+    var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
+    var HttpPipeline = class _HttpPipeline {
+      constructor(policies) {
+        var _a;
+        this._policies = [];
+        this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : [];
+        this._orderedPolicies = void 0;
+      }
+      addPolicy(policy, options = {}) {
+        if (options.phase && options.afterPhase) {
+          throw new Error("Policies inside a phase cannot specify afterPhase.");
+        }
+        if (options.phase && !ValidPhaseNames.has(options.phase)) {
+          throw new Error(`Invalid phase name: ${options.phase}`);
+        }
+        if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
+          throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
+        }
+        this._policies.push({
+          policy,
+          options
+        });
+        this._orderedPolicies = void 0;
+      }
+      removePolicy(options) {
+        const removedPolicies = [];
+        this._policies = this._policies.filter((policyDescriptor) => {
+          if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) {
+            removedPolicies.push(policyDescriptor.policy);
+            return false;
+          } else {
+            return true;
           }
-          if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
-            _.label = op[1];
-            break;
+        });
+        this._orderedPolicies = void 0;
+        return removedPolicies;
+      }
+      sendRequest(httpClient, request) {
+        const policies = this.getOrderedPolicies();
+        const pipeline = policies.reduceRight((next, policy) => {
+          return (req) => {
+            return policy.sendRequest(req, next);
+          };
+        }, (req) => httpClient.sendRequest(req));
+        return pipeline(request);
+      }
+      getOrderedPolicies() {
+        if (!this._orderedPolicies) {
+          this._orderedPolicies = this.orderPolicies();
+        }
+        return this._orderedPolicies;
+      }
+      clone() {
+        return new _HttpPipeline(this._policies);
+      }
+      static create() {
+        return new _HttpPipeline();
+      }
+      orderPolicies() {
+        const result = [];
+        const policyMap = /* @__PURE__ */ new Map();
+        function createPhase(name) {
+          return {
+            name,
+            policies: /* @__PURE__ */ new Set(),
+            hasRun: false,
+            hasAfterPolicies: false
+          };
+        }
+        const serializePhase = createPhase("Serialize");
+        const noPhase = createPhase("None");
+        const deserializePhase = createPhase("Deserialize");
+        const retryPhase = createPhase("Retry");
+        const signPhase = createPhase("Sign");
+        const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
+        function getPhase(phase) {
+          if (phase === "Retry") {
+            return retryPhase;
+          } else if (phase === "Serialize") {
+            return serializePhase;
+          } else if (phase === "Deserialize") {
+            return deserializePhase;
+          } else if (phase === "Sign") {
+            return signPhase;
+          } else {
+            return noPhase;
           }
-          if (op[0] === 6 && _.label < t[1]) {
-            _.label = t[1];
-            t = op;
-            break;
+        }
+        for (const descriptor of this._policies) {
+          const policy = descriptor.policy;
+          const options = descriptor.options;
+          const policyName = policy.name;
+          if (policyMap.has(policyName)) {
+            throw new Error("Duplicate policy names not allowed in pipeline");
           }
-          if (t && _.label < t[2]) {
-            _.label = t[2];
-            _.ops.push(op);
-            break;
+          const node = {
+            policy,
+            dependsOn: /* @__PURE__ */ new Set(),
+            dependants: /* @__PURE__ */ new Set()
+          };
+          if (options.afterPhase) {
+            node.afterPhase = getPhase(options.afterPhase);
+            node.afterPhase.hasAfterPolicies = true;
           }
-          if (t[2]) _.ops.pop();
-          _.trys.pop();
-          continue;
+          policyMap.set(policyName, node);
+          const phase = getPhase(options.phase);
+          phase.policies.add(node);
+        }
+        for (const descriptor of this._policies) {
+          const { policy, options } = descriptor;
+          const policyName = policy.name;
+          const node = policyMap.get(policyName);
+          if (!node) {
+            throw new Error(`Missing node for policy ${policyName}`);
+          }
+          if (options.afterPolicies) {
+            for (const afterPolicyName of options.afterPolicies) {
+              const afterNode = policyMap.get(afterPolicyName);
+              if (afterNode) {
+                node.dependsOn.add(afterNode);
+                afterNode.dependants.add(node);
+              }
+            }
+          }
+          if (options.beforePolicies) {
+            for (const beforePolicyName of options.beforePolicies) {
+              const beforeNode = policyMap.get(beforePolicyName);
+              if (beforeNode) {
+                beforeNode.dependsOn.add(node);
+                node.dependants.add(beforeNode);
+              }
+            }
+          }
+        }
+        function walkPhase(phase) {
+          phase.hasRun = true;
+          for (const node of phase.policies) {
+            if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
+              continue;
+            }
+            if (node.dependsOn.size === 0) {
+              result.push(node.policy);
+              for (const dependant of node.dependants) {
+                dependant.dependsOn.delete(node);
+              }
+              policyMap.delete(node.policy.name);
+              phase.policies.delete(node);
+            }
+          }
+        }
+        function walkPhases() {
+          for (const phase of orderedPhases) {
+            walkPhase(phase);
+            if (phase.policies.size > 0 && phase !== noPhase) {
+              if (!noPhase.hasRun) {
+                walkPhase(noPhase);
+              }
+              return;
+            }
+            if (phase.hasAfterPolicies) {
+              walkPhase(noPhase);
+            }
+          }
+        }
+        let iteration = 0;
+        while (policyMap.size > 0) {
+          iteration++;
+          const initialResultLength = result.length;
+          walkPhases();
+          if (result.length <= initialResultLength && iteration > 1) {
+            throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
+          }
+        }
+        return result;
       }
-      op = body.call(thisArg, _);
-    } catch (e) {
-      op = [6, e];
-      y = 0;
-    } finally {
-      f = t = 0;
+    };
+    function createEmptyPipeline() {
+      return HttpPipeline.create();
     }
-    if (op[0] & 5) throw op[1];
-    return { value: op[0] ? op[1] : void 0, done: true };
   }
-}
-function __exportStar(m, o) {
-  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
-}
-function __values2(o) {
-  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
-  if (m) return m.call(o);
-  if (o && typeof o.length === "number") return {
-    next: function() {
-      if (o && i >= o.length) o = void 0;
-      return { value: o && o[i++], done: !o };
+});
+
+// node_modules/@azure/logger/dist/index.js
+var require_dist = __commonJS({
+  "node_modules/@azure/logger/dist/index.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    var os3 = require("os");
+    var util = require("util");
+    function _interopDefaultLegacy(e) {
+      return e && typeof e === "object" && "default" in e ? e : { "default": e };
     }
-  };
-  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
-}
-function __read(o, n) {
-  var m = typeof Symbol === "function" && o[Symbol.iterator];
-  if (!m) return o;
-  var i = m.call(o), r, ar = [], e;
-  try {
-    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
-  } catch (error4) {
-    e = { error: error4 };
-  } finally {
-    try {
-      if (r && !r.done && (m = i["return"])) m.call(i);
-    } finally {
-      if (e) throw e.error;
+    var util__default = /* @__PURE__ */ _interopDefaultLegacy(util);
+    function log(message, ...args) {
+      process.stderr.write(`${util__default["default"].format(message, ...args)}${os3.EOL}`);
     }
-  }
-  return ar;
-}
-function __spread() {
-  for (var ar = [], i = 0; i < arguments.length; i++)
-    ar = ar.concat(__read(arguments[i]));
-  return ar;
-}
-function __spreadArrays() {
-  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
-  for (var r = Array(s), k = 0, i = 0; i < il; i++)
-    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
-      r[k] = a[j];
-  return r;
-}
-function __spreadArray(to, from, pack) {
-  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
-    if (ar || !(i in from)) {
-      if (!ar) ar = Array.prototype.slice.call(from, 0, i);
-      ar[i] = from[i];
+    var debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0;
+    var enabledString;
+    var enabledNamespaces = [];
+    var skippedNamespaces = [];
+    var debuggers = [];
+    if (debugEnvVariable) {
+      enable(debugEnvVariable);
     }
-  }
-  return to.concat(ar || Array.prototype.slice.call(from));
-}
-function __await(v) {
-  return this instanceof __await ? (this.v = v, this) : new __await(v);
-}
-function __asyncGenerator(thisArg, _arguments, generator) {
-  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
-  var g = generator.apply(thisArg, _arguments || []), i, q = [];
-  return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
-    return this;
-  }, i;
-  function awaitReturn(f) {
-    return function(v) {
-      return Promise.resolve(v).then(f, reject);
-    };
-  }
-  function verb(n, f) {
-    if (g[n]) {
-      i[n] = function(v) {
-        return new Promise(function(a, b) {
-          q.push([n, v, a, b]) > 1 || resume(n, v);
-        });
-      };
-      if (f) i[n] = f(i[n]);
+    var debugObj = Object.assign((namespace) => {
+      return createDebugger(namespace);
+    }, {
+      enable,
+      enabled,
+      disable,
+      log
+    });
+    function enable(namespaces) {
+      enabledString = namespaces;
+      enabledNamespaces = [];
+      skippedNamespaces = [];
+      const wildcard = /\*/g;
+      const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?"));
+      for (const ns of namespaceList) {
+        if (ns.startsWith("-")) {
+          skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`));
+        } else {
+          enabledNamespaces.push(new RegExp(`^${ns}$`));
+        }
+      }
+      for (const instance of debuggers) {
+        instance.enabled = enabled(instance.namespace);
+      }
     }
-  }
-  function resume(n, v) {
-    try {
-      step(g[n](v));
-    } catch (e) {
-      settle(q[0][3], e);
+    function enabled(namespace) {
+      if (namespace.endsWith("*")) {
+        return true;
+      }
+      for (const skipped of skippedNamespaces) {
+        if (skipped.test(namespace)) {
+          return false;
+        }
+      }
+      for (const enabledNamespace of enabledNamespaces) {
+        if (enabledNamespace.test(namespace)) {
+          return true;
+        }
+      }
+      return false;
     }
-  }
-  function step(r) {
-    r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
-  }
-  function fulfill(value) {
-    resume("next", value);
-  }
-  function reject(value) {
-    resume("throw", value);
-  }
-  function settle(f, v) {
-    if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
-  }
-}
-function __asyncDelegator(o) {
-  var i, p;
-  return i = {}, verb("next"), verb("throw", function(e) {
-    throw e;
-  }), verb("return"), i[Symbol.iterator] = function() {
-    return this;
-  }, i;
-  function verb(n, f) {
-    i[n] = o[n] ? function(v) {
-      return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
-    } : f;
-  }
-}
-function __asyncValues(o) {
-  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
-  var m = o[Symbol.asyncIterator], i;
-  return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
-    return this;
-  }, i);
-  function verb(n) {
-    i[n] = o[n] && function(v) {
-      return new Promise(function(resolve6, reject) {
-        v = o[n](v), settle(resolve6, reject, v.done, v.value);
-      });
-    };
-  }
-  function settle(resolve6, reject, d, v) {
-    Promise.resolve(v).then(function(v2) {
-      resolve6({ value: v2, done: d });
-    }, reject);
-  }
-}
-function __makeTemplateObject(cooked, raw) {
-  if (Object.defineProperty) {
-    Object.defineProperty(cooked, "raw", { value: raw });
-  } else {
-    cooked.raw = raw;
-  }
-  return cooked;
-}
-function __importStar(mod) {
-  if (mod && mod.__esModule) return mod;
-  var result = {};
-  if (mod != null) {
-    for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-  }
-  __setModuleDefault(result, mod);
-  return result;
-}
-function __importDefault(mod) {
-  return mod && mod.__esModule ? mod : { default: mod };
-}
-function __classPrivateFieldGet(receiver, state, kind, f) {
-  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
-  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
-  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-}
-function __classPrivateFieldSet(receiver, state, value, kind, f) {
-  if (kind === "m") throw new TypeError("Private method is not writable");
-  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
-  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
-  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
-}
-function __classPrivateFieldIn(state, receiver) {
-  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
-  return typeof state === "function" ? receiver === state : state.has(receiver);
-}
-function __addDisposableResource(env, value, async) {
-  if (value !== null && value !== void 0) {
-    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
-    var dispose, inner;
-    if (async) {
-      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
-      dispose = value[Symbol.asyncDispose];
+    function disable() {
+      const result = enabledString || "";
+      enable("");
+      return result;
     }
-    if (dispose === void 0) {
-      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
-      dispose = value[Symbol.dispose];
-      if (async) inner = dispose;
+    function createDebugger(namespace) {
+      const newDebugger = Object.assign(debug7, {
+        enabled: enabled(namespace),
+        destroy,
+        log: debugObj.log,
+        namespace,
+        extend: extend3
+      });
+      function debug7(...args) {
+        if (!newDebugger.enabled) {
+          return;
+        }
+        if (args.length > 0) {
+          args[0] = `${namespace} ${args[0]}`;
+        }
+        newDebugger.log(...args);
+      }
+      debuggers.push(newDebugger);
+      return newDebugger;
     }
-    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
-    if (inner) dispose = function() {
-      try {
-        inner.call(this);
-      } catch (e) {
-        return Promise.reject(e);
+    function destroy() {
+      const index = debuggers.indexOf(this);
+      if (index >= 0) {
+        debuggers.splice(index, 1);
+        return true;
       }
+      return false;
+    }
+    function extend3(namespace) {
+      const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
+      newDebugger.log = this.log;
+      return newDebugger;
+    }
+    var debug6 = debugObj;
+    var registeredLoggers = /* @__PURE__ */ new Set();
+    var logLevelFromEnv = typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL || void 0;
+    var azureLogLevel;
+    var AzureLogger = debug6("azure");
+    AzureLogger.log = (...args) => {
+      debug6.log(...args);
     };
-    env.stack.push({ value, dispose, async });
-  } else if (async) {
-    env.stack.push({ async: true });
-  }
-  return value;
-}
-function __disposeResources(env) {
-  function fail(e) {
-    env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
-    env.hasError = true;
-  }
-  var r, s = 0;
-  function next() {
-    while (r = env.stack.pop()) {
-      try {
-        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
-        if (r.dispose) {
-          var result = r.dispose.call(r.value);
-          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
-            fail(e);
-            return next();
-          });
-        } else s |= 1;
-      } catch (e) {
-        fail(e);
+    var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"];
+    if (logLevelFromEnv) {
+      if (isAzureLogLevel(logLevelFromEnv)) {
+        setLogLevel(logLevelFromEnv);
+      } else {
+        console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`);
       }
     }
-    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
-    if (env.hasError) throw env.error;
-  }
-  return next();
-}
-var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default;
-var init_tslib_es6 = __esm({
-  "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() {
-    extendStatics = function(d, b) {
-      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
-        d2.__proto__ = b2;
-      } || function(d2, b2) {
-        for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
-      };
-      return extendStatics(d, b);
-    };
-    __assign = function() {
-      __assign = Object.assign || function __assign4(t) {
-        for (var s, i = 1, n = arguments.length; i < n; i++) {
-          s = arguments[i];
-          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+    function setLogLevel(level) {
+      if (level && !isAzureLogLevel(level)) {
+        throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`);
+      }
+      azureLogLevel = level;
+      const enabledNamespaces2 = [];
+      for (const logger of registeredLoggers) {
+        if (shouldEnable(logger)) {
+          enabledNamespaces2.push(logger.namespace);
         }
-        return t;
-      };
-      return __assign.apply(this, arguments);
-    };
-    __createBinding = Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    });
-    __setModuleDefault = Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    };
-    _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) {
-      var e = new Error(message);
-      return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e;
-    };
-    tslib_es6_default = {
-      __extends,
-      __assign,
-      __rest,
-      __decorate,
-      __param,
-      __metadata,
-      __awaiter,
-      __generator,
-      __createBinding,
-      __exportStar,
-      __values: __values2,
-      __read,
-      __spread,
-      __spreadArrays,
-      __spreadArray,
-      __await,
-      __asyncGenerator,
-      __asyncDelegator,
-      __asyncValues,
-      __makeTemplateObject,
-      __importStar,
-      __importDefault,
-      __classPrivateFieldGet,
-      __classPrivateFieldSet,
-      __classPrivateFieldIn,
-      __addDisposableResource,
-      __disposeResources
+      debug6.enable(enabledNamespaces2.join(","));
+    }
+    function getLogLevel() {
+      return azureLogLevel;
+    }
+    var levelMap = {
+      verbose: 400,
+      info: 300,
+      warning: 200,
+      error: 100
     };
+    function createClientLogger(namespace) {
+      const clientRootLogger = AzureLogger.extend(namespace);
+      patchLogMethod(AzureLogger, clientRootLogger);
+      return {
+        error: createLogger(clientRootLogger, "error"),
+        warning: createLogger(clientRootLogger, "warning"),
+        info: createLogger(clientRootLogger, "info"),
+        verbose: createLogger(clientRootLogger, "verbose")
+      };
+    }
+    function patchLogMethod(parent, child) {
+      child.log = (...args) => {
+        parent.log(...args);
+      };
+    }
+    function createLogger(parent, level) {
+      const logger = Object.assign(parent.extend(level), {
+        level
+      });
+      patchLogMethod(parent, logger);
+      if (shouldEnable(logger)) {
+        const enabledNamespaces2 = debug6.disable();
+        debug6.enable(enabledNamespaces2 + "," + logger.namespace);
+      }
+      registeredLoggers.add(logger);
+      return logger;
+    }
+    function shouldEnable(logger) {
+      return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]);
+    }
+    function isAzureLogLevel(logLevel) {
+      return AZURE_LOG_LEVELS.includes(logLevel);
+    }
+    exports2.AzureLogger = AzureLogger;
+    exports2.createClientLogger = createClientLogger;
+    exports2.getLogLevel = getLogLevel;
+    exports2.setLogLevel = setLogLevel;
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js
-var require_userAgentPlatform = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js
+var require_log = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/log.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getHeaderName = getHeaderName;
-    exports2.setPlatformSpecificData = setPlatformSpecificData;
-    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
-    var os3 = tslib_1.__importStar(require("node:os"));
-    var process2 = tslib_1.__importStar(require("node:process"));
-    function getHeaderName() {
-      return "User-Agent";
-    }
-    async function setPlatformSpecificData(map2) {
-      if (process2 && process2.versions) {
-        const versions = process2.versions;
-        if (versions.bun) {
-          map2.set("Bun", versions.bun);
-        } else if (versions.deno) {
-          map2.set("Deno", versions.deno);
-        } else if (versions.node) {
-          map2.set("Node", versions.node);
-        }
-      }
-      map2.set("OS", `(${os3.arch()}-${os3.type()}-${os3.release()})`);
-    }
+    exports2.logger = void 0;
+    var logger_1 = require_dist();
+    exports2.logger = (0, logger_1.createClientLogger)("core-rest-pipeline");
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js
-var require_constants8 = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) {
+// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js
+var require_AbortError = __commonJS({
+  "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0;
-    exports2.SDK_VERSION = "1.17.0";
-    exports2.DEFAULT_RETRY_POLICY_COUNT = 3;
+    exports2.AbortError = void 0;
+    var AbortError = class extends Error {
+      constructor(message) {
+        super(message);
+        this.name = "AbortError";
+      }
+    };
+    exports2.AbortError = AbortError;
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js
-var require_userAgent = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) {
+// node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js
+var require_commonjs = __commonJS({
+  "node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getUserAgentHeaderName = getUserAgentHeaderName;
-    exports2.getUserAgentValue = getUserAgentValue;
-    var userAgentPlatform_js_1 = require_userAgentPlatform();
-    var constants_js_1 = require_constants8();
-    function getUserAgentString(telemetryInfo) {
-      const parts = [];
-      for (const [key, value] of telemetryInfo) {
-        const token = value ? `${key}/${value}` : key;
-        parts.push(token);
-      }
-      return parts.join(" ");
-    }
-    function getUserAgentHeaderName() {
-      return (0, userAgentPlatform_js_1.getHeaderName)();
-    }
-    async function getUserAgentValue(prefix) {
-      const runtimeInfo = /* @__PURE__ */ new Map();
-      runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION);
-      await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo);
-      const defaultAgent = getUserAgentString(runtimeInfo);
-      const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
-      return userAgentValue;
-    }
+    exports2.AbortError = void 0;
+    var AbortError_js_1 = require_AbortError();
+    Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() {
+      return AbortError_js_1.AbortError;
+    } });
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js
-var require_userAgentPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js
+var require_createAbortablePromise = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/createAbortablePromise.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.userAgentPolicyName = void 0;
-    exports2.userAgentPolicy = userAgentPolicy;
-    var userAgent_js_1 = require_userAgent();
-    var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)();
-    exports2.userAgentPolicyName = "userAgentPolicy";
-    function userAgentPolicy(options = {}) {
-      const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
-      return {
-        name: exports2.userAgentPolicyName,
-        async sendRequest(request, next) {
-          if (!request.headers.has(UserAgentHeaderName)) {
-            request.headers.set(UserAgentHeaderName, await userAgentValue);
-          }
-          return next(request);
+    exports2.createAbortablePromise = createAbortablePromise;
+    var abort_controller_1 = require_commonjs();
+    function createAbortablePromise(buildPromise, options) {
+      const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+      return new Promise((resolve6, reject) => {
+        function rejectOnAbort() {
+          reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted."));
         }
-      };
+        function removeListeners() {
+          abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort);
+        }
+        function onAbort() {
+          cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort();
+          removeListeners();
+          rejectOnAbort();
+        }
+        if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) {
+          return rejectOnAbort();
+        }
+        try {
+          buildPromise((x) => {
+            removeListeners();
+            resolve6(x);
+          }, (x) => {
+            removeListeners();
+            reject(x);
+          });
+        } catch (err) {
+          reject(err);
+        }
+        abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort);
+      });
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js
-var require_typeGuards2 = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/random.js
+var require_random = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/random.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.isNodeReadableStream = isNodeReadableStream;
-    exports2.isWebReadableStream = isWebReadableStream;
-    exports2.isReadableStream = isReadableStream;
-    exports2.isBlob = isBlob;
-    function isNodeReadableStream(x) {
-      return Boolean(x && typeof x["pipe"] === "function");
-    }
-    function isWebReadableStream(x) {
-      return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function");
-    }
-    function isReadableStream(x) {
-      return isNodeReadableStream(x) || isWebReadableStream(x);
-    }
-    function isBlob(x) {
-      return typeof x.stream === "function";
+    exports2.getRandomIntegerInclusive = getRandomIntegerInclusive;
+    function getRandomIntegerInclusive(min, max) {
+      min = Math.ceil(min);
+      max = Math.floor(max);
+      const offset = Math.floor(Math.random() * (max - min + 1));
+      return offset + min;
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js
-var require_file2 = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/delay.js
+var require_delay = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/delay.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getRawContent = getRawContent;
-    exports2.createFileFromStream = createFileFromStream;
-    exports2.createFile = createFile;
-    var core_util_1 = require_commonjs2();
-    var typeGuards_js_1 = require_typeGuards2();
-    var unimplementedMethods = {
-      arrayBuffer: () => {
-        throw new Error("Not implemented");
-      },
-      slice: () => {
-        throw new Error("Not implemented");
-      },
-      text: () => {
-        throw new Error("Not implemented");
-      }
-    };
-    var rawContent = Symbol("rawContent");
-    function hasRawContent(x) {
-      return typeof x[rawContent] === "function";
-    }
-    function getRawContent(blob) {
-      if (hasRawContent(blob)) {
-        return blob[rawContent]();
-      } else {
-        return blob.stream();
-      }
-    }
-    function createFileFromStream(stream2, name, options = {}) {
-      var _a, _b, _c, _d;
-      return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => {
-        const s = stream2();
-        if ((0, typeGuards_js_1.isNodeReadableStream)(s)) {
-          throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
-        }
-        return s;
-      }, [rawContent]: stream2 });
+    exports2.delay = delay2;
+    exports2.calculateRetryDelay = calculateRetryDelay;
+    var createAbortablePromise_js_1 = require_createAbortablePromise();
+    var random_js_1 = require_random();
+    var StandardAbortMessage = "The delay was aborted.";
+    function delay2(timeInMs, options) {
+      let token;
+      const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+      return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve6) => {
+        token = setTimeout(resolve6, timeInMs);
+      }, {
+        cleanupBeforeAbort: () => clearTimeout(token),
+        abortSignal,
+        abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage
+      });
     }
-    function createFile(content, name, options = {}) {
-      var _a, _b, _c;
-      if (core_util_1.isNodeLike) {
-        return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content });
-      } else {
-        return new File([content], name, options);
-      }
+    function calculateRetryDelay(retryAttempt, config) {
+      const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
+      const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
+      const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2);
+      return { retryAfterInMs };
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js
-var require_concat = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/aborterUtils.js
+var require_aborterUtils = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/aborterUtils.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.concat = concat;
-    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
-    var node_stream_1 = require("node:stream");
-    var typeGuards_js_1 = require_typeGuards2();
-    var file_js_1 = require_file2();
-    function streamAsyncIterator() {
-      return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() {
-        const reader = this.getReader();
-        try {
-          while (true) {
-            const { done, value } = yield tslib_1.__await(reader.read());
-            if (done) {
-              return yield tslib_1.__await(void 0);
-            }
-            yield yield tslib_1.__await(value);
-          }
-        } finally {
-          reader.releaseLock();
-        }
-      });
-    }
-    function makeAsyncIterable(webStream) {
-      if (!webStream[Symbol.asyncIterator]) {
-        webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
-      }
-      if (!webStream.values) {
-        webStream.values = streamAsyncIterator.bind(webStream);
-      }
-    }
-    function ensureNodeStream(stream2) {
-      if (stream2 instanceof ReadableStream) {
-        makeAsyncIterable(stream2);
-        return node_stream_1.Readable.fromWeb(stream2);
-      } else {
-        return stream2;
+    exports2.cancelablePromiseRace = cancelablePromiseRace;
+    async function cancelablePromiseRace(abortablePromiseBuilders, options) {
+      var _a, _b;
+      const aborter = new AbortController();
+      function abortHandler() {
+        aborter.abort();
       }
-    }
-    function toStream(source) {
-      if (source instanceof Uint8Array) {
-        return node_stream_1.Readable.from(Buffer.from(source));
-      } else if ((0, typeGuards_js_1.isBlob)(source)) {
-        return toStream((0, file_js_1.getRawContent)(source));
-      } else {
-        return ensureNodeStream(source);
+      (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler);
+      try {
+        return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
+      } finally {
+        aborter.abort();
+        (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler);
       }
     }
-    async function concat(sources) {
-      return function() {
-        const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream);
-        return node_stream_1.Readable.from((function() {
-          return tslib_1.__asyncGenerator(this, arguments, function* () {
-            var _a, e_1, _b, _c;
-            for (const stream2 of streams) {
-              try {
-                for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream2)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) {
-                  _c = stream_1_1.value;
-                  _d = false;
-                  const chunk = _c;
-                  yield yield tslib_1.__await(chunk);
-                }
-              } catch (e_1_1) {
-                e_1 = { error: e_1_1 };
-              } finally {
-                try {
-                  if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1));
-                } finally {
-                  if (e_1) throw e_1.error;
-                }
-              }
-            }
-          });
-        })());
-      };
-    }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js
-var require_multipartPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/object.js
+var require_object = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/object.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.multipartPolicyName = void 0;
-    exports2.multipartPolicy = multipartPolicy;
-    var core_util_1 = require_commonjs2();
-    var concat_js_1 = require_concat();
-    var typeGuards_js_1 = require_typeGuards2();
-    function generateBoundary() {
-      return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`;
+    exports2.isObject = isObject2;
+    function isObject2(input) {
+      return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date);
     }
-    function encodeHeaders(headers) {
-      let result = "";
-      for (const [key, value] of headers) {
-        result += `${key}: ${value}\r
-`;
+  }
+});
+
+// node_modules/@azure/core-util/dist/commonjs/error.js
+var require_error = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/error.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.isError = isError;
+    exports2.getErrorMessage = getErrorMessage2;
+    var object_js_1 = require_object();
+    function isError(e) {
+      if ((0, object_js_1.isObject)(e)) {
+        const hasName = typeof e.name === "string";
+        const hasMessage = typeof e.message === "string";
+        return hasName && hasMessage;
       }
-      return result;
+      return false;
     }
-    function getLength(source) {
-      if (source instanceof Uint8Array) {
-        return source.byteLength;
-      } else if ((0, typeGuards_js_1.isBlob)(source)) {
-        return source.size === -1 ? void 0 : source.size;
+    function getErrorMessage2(e) {
+      if (isError(e)) {
+        return e.message;
       } else {
-        return void 0;
-      }
-    }
-    function getTotalLength(sources) {
-      let total = 0;
-      for (const source of sources) {
-        const partLength = getLength(source);
-        if (partLength === void 0) {
-          return void 0;
-        } else {
-          total += partLength;
-        }
-      }
-      return total;
-    }
-    async function buildRequestBody(request, parts, boundary) {
-      const sources = [
-        (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"),
-        ...parts.flatMap((part) => [
-          (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
-          (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"),
-          (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
-          part.body,
-          (0, core_util_1.stringToUint8Array)(`\r
---${boundary}`, "utf-8")
-        ]),
-        (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8")
-      ];
-      const contentLength = getTotalLength(sources);
-      if (contentLength) {
-        request.headers.set("Content-Length", contentLength);
-      }
-      request.body = await (0, concat_js_1.concat)(sources);
-    }
-    exports2.multipartPolicyName = "multipartPolicy";
-    var maxBoundaryLength = 70;
-    var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
-    function assertValidBoundary(boundary) {
-      if (boundary.length > maxBoundaryLength) {
-        throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
-      }
-      if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
-        throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
-      }
-    }
-    function multipartPolicy() {
-      return {
-        name: exports2.multipartPolicyName,
-        async sendRequest(request, next) {
-          var _a;
-          if (!request.multipartBody) {
-            return next(request);
-          }
-          if (request.body) {
-            throw new Error("multipartBody and regular body cannot be set at the same time");
-          }
-          let boundary = request.multipartBody.boundary;
-          const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed";
-          const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
-          if (!parsedHeader) {
-            throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
-          }
-          const [, contentType, parsedBoundary] = parsedHeader;
-          if (parsedBoundary && boundary && parsedBoundary !== boundary) {
-            throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
-          }
-          boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary;
-          if (boundary) {
-            assertValidBoundary(boundary);
+        let stringified;
+        try {
+          if (typeof e === "object" && e) {
+            stringified = JSON.stringify(e);
           } else {
-            boundary = generateBoundary();
+            stringified = String(e);
           }
-          request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
-          await buildRequestBody(request, request.multipartBody.parts, boundary);
-          request.multipartBody = void 0;
-          return next(request);
+        } catch (err) {
+          stringified = "[unable to stringify input]";
         }
-      };
+        return `Unknown error ${stringified}`;
+      }
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js
-var require_decompressResponsePolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/sha256.js
+var require_sha256 = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/sha256.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.decompressResponsePolicyName = void 0;
-    exports2.decompressResponsePolicy = decompressResponsePolicy;
-    exports2.decompressResponsePolicyName = "decompressResponsePolicy";
-    function decompressResponsePolicy() {
-      return {
-        name: exports2.decompressResponsePolicyName,
-        async sendRequest(request, next) {
-          if (request.method !== "HEAD") {
-            request.headers.set("Accept-Encoding", "gzip,deflate");
-          }
-          return next(request);
-        }
-      };
+    exports2.computeSha256Hmac = computeSha256Hmac;
+    exports2.computeSha256Hash = computeSha256Hash;
+    var crypto_1 = require("crypto");
+    async function computeSha256Hmac(key, stringToSign, encoding) {
+      const decodedKey = Buffer.from(key, "base64");
+      return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding);
+    }
+    async function computeSha256Hash(content, encoding) {
+      return (0, crypto_1.createHash)("sha256").update(content).digest(encoding);
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js
-var require_AbortError2 = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/typeGuards.js
+var require_typeGuards = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/typeGuards.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.AbortError = void 0;
-    var AbortError = class extends Error {
-      constructor(message) {
-        super(message);
-        this.name = "AbortError";
+    exports2.isDefined = isDefined2;
+    exports2.isObjectWithProperties = isObjectWithProperties;
+    exports2.objectHasProperty = objectHasProperty;
+    function isDefined2(thing) {
+      return typeof thing !== "undefined" && thing !== null;
+    }
+    function isObjectWithProperties(thing, properties) {
+      if (!isDefined2(thing) || typeof thing !== "object") {
+        return false;
       }
-    };
-    exports2.AbortError = AbortError;
+      for (const property of properties) {
+        if (!objectHasProperty(thing, property)) {
+          return false;
+        }
+      }
+      return true;
+    }
+    function objectHasProperty(thing, property) {
+      return isDefined2(thing) && typeof thing === "object" && property in thing;
+    }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js
-var require_commonjs3 = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/uuidUtils.js
+var require_uuidUtils = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/uuidUtils.js"(exports2) {
     "use strict";
+    var _a;
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.AbortError = void 0;
-    var AbortError_js_1 = require_AbortError2();
-    Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() {
-      return AbortError_js_1.AbortError;
-    } });
+    exports2.randomUUID = randomUUID2;
+    var crypto_1 = require("crypto");
+    var uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : crypto_1.randomUUID;
+    function randomUUID2() {
+      return uuidFunction();
+    }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js
-var require_helpers = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js
+var require_checkEnvironment = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/checkEnvironment.js"(exports2) {
     "use strict";
+    var _a;
+    var _b;
+    var _c;
+    var _d;
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.delay = delay2;
-    exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber;
-    var abort_controller_1 = require_commonjs3();
-    var StandardAbortMessage = "The operation was aborted.";
-    function delay2(delayInMs, value, options) {
-      return new Promise((resolve6, reject) => {
-        let timer = void 0;
-        let onAborted = void 0;
-        const rejectOnAbort = () => {
-          return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage));
-        };
-        const removeListeners = () => {
-          if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) {
-            options.abortSignal.removeEventListener("abort", onAborted);
-          }
-        };
-        onAborted = () => {
-          if (timer) {
-            clearTimeout(timer);
-          }
-          removeListeners();
-          return rejectOnAbort();
-        };
-        if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) {
-          return rejectOnAbort();
-        }
-        timer = setTimeout(() => {
-          removeListeners();
-          resolve6(value);
-        }, delayInMs);
-        if (options === null || options === void 0 ? void 0 : options.abortSignal) {
-          options.abortSignal.addEventListener("abort", onAborted);
-        }
-      });
-    }
-    function parseHeaderValueAsNumber(response, headerName) {
-      const value = response.headers.get(headerName);
-      if (!value)
-        return;
-      const valueAsNum = Number(value);
-      if (Number.isNaN(valueAsNum))
-        return;
-      return valueAsNum;
-    }
+    exports2.isReactNative = exports2.isNodeRuntime = exports2.isNode = exports2.isNodeLike = exports2.isBun = exports2.isDeno = exports2.isWebWorker = exports2.isBrowser = void 0;
+    exports2.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
+    exports2.isWebWorker = typeof self === "object" && typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope");
+    exports2.isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined";
+    exports2.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
+    exports2.isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node);
+    exports2.isNode = exports2.isNodeLike;
+    exports2.isNodeRuntime = exports2.isNodeLike && !exports2.isBun && !exports2.isDeno;
+    exports2.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative";
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js
-var require_throttlingRetryStrategy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js
+var require_bytesEncoding = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/bytesEncoding.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.isThrottlingRetryResponse = isThrottlingRetryResponse;
-    exports2.throttlingRetryStrategy = throttlingRetryStrategy;
-    var helpers_js_1 = require_helpers();
-    var RetryAfterHeader = "Retry-After";
-    var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
-    function getRetryAfterInMs(response) {
-      if (!(response && [429, 503].includes(response.status)))
-        return void 0;
-      try {
-        for (const header of AllRetryAfterHeaders) {
-          const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header);
-          if (retryAfterValue === 0 || retryAfterValue) {
-            const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1;
-            return retryAfterValue * multiplyingFactor;
-          }
-        }
-        const retryAfterHeader = response.headers.get(RetryAfterHeader);
-        if (!retryAfterHeader)
-          return;
-        const date = Date.parse(retryAfterHeader);
-        const diff = date - Date.now();
-        return Number.isFinite(diff) ? Math.max(0, diff) : void 0;
-      } catch (_a) {
-        return void 0;
-      }
-    }
-    function isThrottlingRetryResponse(response) {
-      return Number.isFinite(getRetryAfterInMs(response));
+    exports2.uint8ArrayToString = uint8ArrayToString;
+    exports2.stringToUint8Array = stringToUint8Array;
+    function uint8ArrayToString(bytes, format) {
+      return Buffer.from(bytes).toString(format);
     }
-    function throttlingRetryStrategy() {
-      return {
-        name: "throttlingRetryStrategy",
-        retry({ response }) {
-          const retryAfterInMs = getRetryAfterInMs(response);
-          if (!Number.isFinite(retryAfterInMs)) {
-            return { skipStrategy: true };
-          }
-          return {
-            retryAfterInMs
-          };
-        }
-      };
+    function stringToUint8Array(value, format) {
+      return Buffer.from(value, format);
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js
-var require_exponentialRetryStrategy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) {
+// node_modules/@azure/core-util/dist/commonjs/index.js
+var require_commonjs2 = __commonJS({
+  "node_modules/@azure/core-util/dist/commonjs/index.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.exponentialRetryStrategy = exponentialRetryStrategy;
-    exports2.isExponentialRetryResponse = isExponentialRetryResponse;
-    exports2.isSystemError = isSystemError;
+    exports2.stringToUint8Array = exports2.uint8ArrayToString = exports2.isWebWorker = exports2.isReactNative = exports2.isDeno = exports2.isNodeRuntime = exports2.isNodeLike = exports2.isNode = exports2.isBun = exports2.isBrowser = exports2.randomUUID = exports2.objectHasProperty = exports2.isObjectWithProperties = exports2.isDefined = exports2.computeSha256Hmac = exports2.computeSha256Hash = exports2.getErrorMessage = exports2.isError = exports2.isObject = exports2.getRandomIntegerInclusive = exports2.createAbortablePromise = exports2.cancelablePromiseRace = exports2.calculateRetryDelay = exports2.delay = void 0;
+    var delay_js_1 = require_delay();
+    Object.defineProperty(exports2, "delay", { enumerable: true, get: function() {
+      return delay_js_1.delay;
+    } });
+    Object.defineProperty(exports2, "calculateRetryDelay", { enumerable: true, get: function() {
+      return delay_js_1.calculateRetryDelay;
+    } });
+    var aborterUtils_js_1 = require_aborterUtils();
+    Object.defineProperty(exports2, "cancelablePromiseRace", { enumerable: true, get: function() {
+      return aborterUtils_js_1.cancelablePromiseRace;
+    } });
+    var createAbortablePromise_js_1 = require_createAbortablePromise();
+    Object.defineProperty(exports2, "createAbortablePromise", { enumerable: true, get: function() {
+      return createAbortablePromise_js_1.createAbortablePromise;
+    } });
+    var random_js_1 = require_random();
+    Object.defineProperty(exports2, "getRandomIntegerInclusive", { enumerable: true, get: function() {
+      return random_js_1.getRandomIntegerInclusive;
+    } });
+    var object_js_1 = require_object();
+    Object.defineProperty(exports2, "isObject", { enumerable: true, get: function() {
+      return object_js_1.isObject;
+    } });
+    var error_js_1 = require_error();
+    Object.defineProperty(exports2, "isError", { enumerable: true, get: function() {
+      return error_js_1.isError;
+    } });
+    Object.defineProperty(exports2, "getErrorMessage", { enumerable: true, get: function() {
+      return error_js_1.getErrorMessage;
+    } });
+    var sha256_js_1 = require_sha256();
+    Object.defineProperty(exports2, "computeSha256Hash", { enumerable: true, get: function() {
+      return sha256_js_1.computeSha256Hash;
+    } });
+    Object.defineProperty(exports2, "computeSha256Hmac", { enumerable: true, get: function() {
+      return sha256_js_1.computeSha256Hmac;
+    } });
+    var typeGuards_js_1 = require_typeGuards();
+    Object.defineProperty(exports2, "isDefined", { enumerable: true, get: function() {
+      return typeGuards_js_1.isDefined;
+    } });
+    Object.defineProperty(exports2, "isObjectWithProperties", { enumerable: true, get: function() {
+      return typeGuards_js_1.isObjectWithProperties;
+    } });
+    Object.defineProperty(exports2, "objectHasProperty", { enumerable: true, get: function() {
+      return typeGuards_js_1.objectHasProperty;
+    } });
+    var uuidUtils_js_1 = require_uuidUtils();
+    Object.defineProperty(exports2, "randomUUID", { enumerable: true, get: function() {
+      return uuidUtils_js_1.randomUUID;
+    } });
+    var checkEnvironment_js_1 = require_checkEnvironment();
+    Object.defineProperty(exports2, "isBrowser", { enumerable: true, get: function() {
+      return checkEnvironment_js_1.isBrowser;
+    } });
+    Object.defineProperty(exports2, "isBun", { enumerable: true, get: function() {
+      return checkEnvironment_js_1.isBun;
+    } });
+    Object.defineProperty(exports2, "isNode", { enumerable: true, get: function() {
+      return checkEnvironment_js_1.isNode;
+    } });
+    Object.defineProperty(exports2, "isNodeLike", { enumerable: true, get: function() {
+      return checkEnvironment_js_1.isNodeLike;
+    } });
+    Object.defineProperty(exports2, "isNodeRuntime", { enumerable: true, get: function() {
+      return checkEnvironment_js_1.isNodeRuntime;
+    } });
+    Object.defineProperty(exports2, "isDeno", { enumerable: true, get: function() {
+      return checkEnvironment_js_1.isDeno;
+    } });
+    Object.defineProperty(exports2, "isReactNative", { enumerable: true, get: function() {
+      return checkEnvironment_js_1.isReactNative;
+    } });
+    Object.defineProperty(exports2, "isWebWorker", { enumerable: true, get: function() {
+      return checkEnvironment_js_1.isWebWorker;
+    } });
+    var bytesEncoding_js_1 = require_bytesEncoding();
+    Object.defineProperty(exports2, "uint8ArrayToString", { enumerable: true, get: function() {
+      return bytesEncoding_js_1.uint8ArrayToString;
+    } });
+    Object.defineProperty(exports2, "stringToUint8Array", { enumerable: true, get: function() {
+      return bytesEncoding_js_1.stringToUint8Array;
+    } });
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js
+var require_sanitizer = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/sanitizer.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.Sanitizer = void 0;
     var core_util_1 = require_commonjs2();
-    var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy();
-    var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3;
-    var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64;
-    function exponentialRetryStrategy(options = {}) {
-      var _a, _b;
-      const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL;
-      const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
-      let retryAfterInMs = retryInterval;
-      return {
-        name: "exponentialRetryStrategy",
-        retry({ retryCount, response, responseError }) {
-          const matchedSystemError = isSystemError(responseError);
-          const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;
-          const isExponential = isExponentialRetryResponse(response);
-          const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;
-          const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential);
-          if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
-            return { skipStrategy: true };
+    var RedactedString = "REDACTED";
+    var defaultAllowedHeaderNames = [
+      "x-ms-client-request-id",
+      "x-ms-return-client-request-id",
+      "x-ms-useragent",
+      "x-ms-correlation-request-id",
+      "x-ms-request-id",
+      "client-request-id",
+      "ms-cv",
+      "return-client-request-id",
+      "traceparent",
+      "Access-Control-Allow-Credentials",
+      "Access-Control-Allow-Headers",
+      "Access-Control-Allow-Methods",
+      "Access-Control-Allow-Origin",
+      "Access-Control-Expose-Headers",
+      "Access-Control-Max-Age",
+      "Access-Control-Request-Headers",
+      "Access-Control-Request-Method",
+      "Origin",
+      "Accept",
+      "Accept-Encoding",
+      "Cache-Control",
+      "Connection",
+      "Content-Length",
+      "Content-Type",
+      "Date",
+      "ETag",
+      "Expires",
+      "If-Match",
+      "If-Modified-Since",
+      "If-None-Match",
+      "If-Unmodified-Since",
+      "Last-Modified",
+      "Pragma",
+      "Request-Id",
+      "Retry-After",
+      "Server",
+      "Transfer-Encoding",
+      "User-Agent",
+      "WWW-Authenticate"
+    ];
+    var defaultAllowedQueryParameters = ["api-version"];
+    var Sanitizer = class {
+      constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) {
+        allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
+        allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
+        this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
+        this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
+      }
+      sanitize(obj) {
+        const seen = /* @__PURE__ */ new Set();
+        return JSON.stringify(obj, (key, value) => {
+          if (value instanceof Error) {
+            return Object.assign(Object.assign({}, value), { name: value.name, message: value.message });
           }
-          if (responseError && !matchedSystemError && !isExponential) {
-            return { errorToThrow: responseError };
+          if (key === "headers") {
+            return this.sanitizeHeaders(value);
+          } else if (key === "url") {
+            return this.sanitizeUrl(value);
+          } else if (key === "query") {
+            return this.sanitizeQuery(value);
+          } else if (key === "body") {
+            return void 0;
+          } else if (key === "response") {
+            return void 0;
+          } else if (key === "operationSpec") {
+            return void 0;
+          } else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) {
+            if (seen.has(value)) {
+              return "[Circular]";
+            }
+            seen.add(value);
           }
-          const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount);
-          const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay);
-          retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2);
-          return { retryAfterInMs };
+          return value;
+        }, 2);
+      }
+      sanitizeUrl(value) {
+        if (typeof value !== "string" || value === null || value === "") {
+          return value;
         }
-      };
-    }
-    function isExponentialRetryResponse(response) {
-      return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505);
-    }
-    function isSystemError(err) {
-      if (!err) {
-        return false;
+        const url2 = new URL(value);
+        if (!url2.search) {
+          return value;
+        }
+        for (const [key] of url2.searchParams) {
+          if (!this.allowedQueryParameters.has(key.toLowerCase())) {
+            url2.searchParams.set(key, RedactedString);
+          }
+        }
+        return url2.toString();
       }
-      return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND";
-    }
+      sanitizeHeaders(obj) {
+        const sanitized = {};
+        for (const key of Object.keys(obj)) {
+          if (this.allowedHeaderNames.has(key.toLowerCase())) {
+            sanitized[key] = obj[key];
+          } else {
+            sanitized[key] = RedactedString;
+          }
+        }
+        return sanitized;
+      }
+      sanitizeQuery(value) {
+        if (typeof value !== "object" || value === null) {
+          return value;
+        }
+        const sanitized = {};
+        for (const k of Object.keys(value)) {
+          if (this.allowedQueryParameters.has(k.toLowerCase())) {
+            sanitized[k] = value[k];
+          } else {
+            sanitized[k] = RedactedString;
+          }
+        }
+        return sanitized;
+      }
+    };
+    exports2.Sanitizer = Sanitizer;
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js
-var require_retryPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js
+var require_logPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/logPolicy.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.retryPolicy = retryPolicy;
-    var helpers_js_1 = require_helpers();
-    var logger_1 = require_dist();
-    var abort_controller_1 = require_commonjs3();
-    var constants_js_1 = require_constants8();
-    var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy");
-    var retryPolicyName = "retryPolicy";
-    function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) {
-      const logger = options.logger || retryPolicyLogger;
+    exports2.logPolicyName = void 0;
+    exports2.logPolicy = logPolicy;
+    var log_js_1 = require_log();
+    var sanitizer_js_1 = require_sanitizer();
+    exports2.logPolicyName = "logPolicy";
+    function logPolicy(options = {}) {
+      var _a;
+      const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info;
+      const sanitizer = new sanitizer_js_1.Sanitizer({
+        additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
+        additionalAllowedQueryParameters: options.additionalAllowedQueryParameters
+      });
       return {
-        name: retryPolicyName,
+        name: exports2.logPolicyName,
         async sendRequest(request, next) {
-          var _a, _b;
-          let response;
-          let responseError;
-          let retryCount = -1;
-          retryRequest: while (true) {
-            retryCount += 1;
-            response = void 0;
-            responseError = void 0;
-            try {
-              logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
-              response = await next(request);
-              logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
-            } catch (e) {
-              logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
-              responseError = e;
-              if (!e || responseError.name !== "RestError") {
-                throw e;
-              }
-              response = responseError.response;
-            }
-            if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
-              logger.error(`Retry ${retryCount}: Request aborted.`);
-              const abortError = new abort_controller_1.AbortError();
-              throw abortError;
-            }
-            if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) {
-              logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
-              if (responseError) {
-                throw responseError;
-              } else if (response) {
-                return response;
-              } else {
-                throw new Error("Maximum retries reached with no response or error to throw");
-              }
-            }
-            logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
-            strategiesLoop: for (const strategy of strategies) {
-              const strategyLogger = strategy.logger || retryPolicyLogger;
-              strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
-              const modifiers = strategy.retry({
-                retryCount,
-                response,
-                responseError
-              });
-              if (modifiers.skipStrategy) {
-                strategyLogger.info(`Retry ${retryCount}: Skipped.`);
-                continue strategiesLoop;
-              }
-              const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
-              if (errorToThrow) {
-                strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
-                throw errorToThrow;
-              }
-              if (retryAfterInMs || retryAfterInMs === 0) {
-                strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
-                await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal });
-                continue retryRequest;
-              }
-              if (redirectTo) {
-                strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
-                request.url = redirectTo;
-                continue retryRequest;
-              }
-            }
-            if (responseError) {
-              logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
-              throw responseError;
-            }
-            if (response) {
-              logger.info(`None of the retry strategies could work with the received response. Returning it.`);
-              return response;
-            }
+          if (!logger.enabled) {
+            return next(request);
           }
+          logger(`Request: ${sanitizer.sanitize(request)}`);
+          const response = await next(request);
+          logger(`Response status code: ${response.status}`);
+          logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
+          return response;
         }
       };
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js
-var require_defaultRetryPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js
+var require_redirectPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/redirectPolicy.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.defaultRetryPolicyName = void 0;
-    exports2.defaultRetryPolicy = defaultRetryPolicy;
-    var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy();
-    var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy();
-    var retryPolicy_js_1 = require_retryPolicy();
-    var constants_js_1 = require_constants8();
-    exports2.defaultRetryPolicyName = "defaultRetryPolicy";
-    function defaultRetryPolicy(options = {}) {
-      var _a;
+    exports2.redirectPolicyName = void 0;
+    exports2.redirectPolicy = redirectPolicy;
+    exports2.redirectPolicyName = "redirectPolicy";
+    var allowedRedirect = ["GET", "HEAD"];
+    function redirectPolicy(options = {}) {
+      const { maxRetries = 20 } = options;
       return {
-        name: exports2.defaultRetryPolicyName,
-        sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], {
-          maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT
-        }).sendRequest
+        name: exports2.redirectPolicyName,
+        async sendRequest(request, next) {
+          const response = await next(request);
+          return handleRedirect(next, response, maxRetries);
+        }
       };
     }
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js
-var require_httpHeaders = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createHttpHeaders = createHttpHeaders;
-    function normalizeName(name) {
-      return name.toLowerCase();
-    }
-    function* headerIterator(map2) {
-      for (const entry of map2.values()) {
-        yield [entry.name, entry.value];
-      }
-    }
-    var HttpHeadersImpl = class {
-      constructor(rawHeaders) {
-        this._headersMap = /* @__PURE__ */ new Map();
-        if (rawHeaders) {
-          for (const headerName of Object.keys(rawHeaders)) {
-            this.set(headerName, rawHeaders[headerName]);
-          }
-        }
-      }
-      /**
-       * Set a header in this collection with the provided name and value. The name is
-       * case-insensitive.
-       * @param name - The name of the header to set. This value is case-insensitive.
-       * @param value - The value of the header to set.
-       */
-      set(name, value) {
-        this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
-      }
-      /**
-       * Get the header value for the provided header name, or undefined if no header exists in this
-       * collection with the provided name.
-       * @param name - The name of the header. This value is case-insensitive.
-       */
-      get(name) {
-        var _a;
-        return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value;
-      }
-      /**
-       * Get whether or not this header collection contains a header entry for the provided header name.
-       * @param name - The name of the header to set. This value is case-insensitive.
-       */
-      has(name) {
-        return this._headersMap.has(normalizeName(name));
-      }
-      /**
-       * Remove the header with the provided headerName.
-       * @param name - The name of the header to remove.
-       */
-      delete(name) {
-        this._headersMap.delete(normalizeName(name));
-      }
-      /**
-       * Get the JSON object representation of this HTTP header collection.
-       */
-      toJSON(options = {}) {
-        const result = {};
-        if (options.preserveCase) {
-          for (const entry of this._headersMap.values()) {
-            result[entry.name] = entry.value;
-          }
-        } else {
-          for (const [normalizedName, entry] of this._headersMap) {
-            result[normalizedName] = entry.value;
-          }
+    async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
+      const { request, status, headers } = response;
+      const locationHeader = headers.get("location");
+      if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) {
+        const url2 = new URL(locationHeader, request.url);
+        request.url = url2.toString();
+        if (status === 303) {
+          request.method = "GET";
+          request.headers.delete("Content-Length");
+          delete request.body;
         }
-        return result;
-      }
-      /**
-       * Get the string representation of this HTTP header collection.
-       */
-      toString() {
-        return JSON.stringify(this.toJSON({ preserveCase: true }));
-      }
-      /**
-       * Iterate over tuples of header [name, value] pairs.
-       */
-      [Symbol.iterator]() {
-        return headerIterator(this._headersMap);
+        request.headers.delete("Authorization");
+        const res = await next(request);
+        return handleRedirect(next, res, maxRetries, currentRetries + 1);
       }
-    };
-    function createHttpHeaders(rawHeaders) {
-      return new HttpHeadersImpl(rawHeaders);
+      return response;
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js
-var require_formDataPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.formDataPolicyName = void 0;
-    exports2.formDataPolicy = formDataPolicy;
-    var core_util_1 = require_commonjs2();
-    var httpHeaders_js_1 = require_httpHeaders();
-    exports2.formDataPolicyName = "formDataPolicy";
-    function formDataToFormDataMap(formData) {
-      var _a;
-      const formDataMap = {};
-      for (const [key, value] of formData.entries()) {
-        (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = [];
-        formDataMap[key].push(value);
-      }
-      return formDataMap;
-    }
-    function formDataPolicy() {
-      return {
-        name: exports2.formDataPolicyName,
-        async sendRequest(request, next) {
-          if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
-            request.formData = formDataToFormDataMap(request.body);
-            request.body = void 0;
-          }
-          if (request.formData) {
-            const contentType = request.headers.get("Content-Type");
-            if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
-              request.body = wwwFormUrlEncode(request.formData);
-            } else {
-              await prepareFormData(request.formData, request);
-            }
-            request.formData = void 0;
-          }
-          return next(request);
-        }
-      };
-    }
-    function wwwFormUrlEncode(formData) {
-      const urlSearchParams = new URLSearchParams();
-      for (const [key, value] of Object.entries(formData)) {
-        if (Array.isArray(value)) {
-          for (const subValue of value) {
-            urlSearchParams.append(key, subValue.toString());
-          }
-        } else {
-          urlSearchParams.append(key, value.toString());
-        }
-      }
-      return urlSearchParams.toString();
-    }
-    async function prepareFormData(formData, request) {
-      const contentType = request.headers.get("Content-Type");
-      if (contentType && !contentType.startsWith("multipart/form-data")) {
-        return;
-      }
-      request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data");
-      const parts = [];
-      for (const [fieldName, values] of Object.entries(formData)) {
-        for (const value of Array.isArray(values) ? values : [values]) {
-          if (typeof value === "string") {
-            parts.push({
-              headers: (0, httpHeaders_js_1.createHttpHeaders)({
-                "Content-Disposition": `form-data; name="${fieldName}"`
-              }),
-              body: (0, core_util_1.stringToUint8Array)(value, "utf-8")
-            });
-          } else if (value === void 0 || value === null || typeof value !== "object") {
-            throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
-          } else {
-            const fileName = value.name || "blob";
-            const headers = (0, httpHeaders_js_1.createHttpHeaders)();
-            headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
-            headers.set("Content-Type", value.type || "application/octet-stream");
-            parts.push({
-              headers,
-              body: value
-            });
-          }
-        }
-      }
-      request.multipartBody = { parts };
+// node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs
+var tslib_es6_exports = {};
+__export(tslib_es6_exports, {
+  __addDisposableResource: () => __addDisposableResource,
+  __assign: () => __assign,
+  __asyncDelegator: () => __asyncDelegator,
+  __asyncGenerator: () => __asyncGenerator,
+  __asyncValues: () => __asyncValues,
+  __await: () => __await,
+  __awaiter: () => __awaiter,
+  __classPrivateFieldGet: () => __classPrivateFieldGet,
+  __classPrivateFieldIn: () => __classPrivateFieldIn,
+  __classPrivateFieldSet: () => __classPrivateFieldSet,
+  __createBinding: () => __createBinding,
+  __decorate: () => __decorate,
+  __disposeResources: () => __disposeResources,
+  __esDecorate: () => __esDecorate,
+  __exportStar: () => __exportStar,
+  __extends: () => __extends,
+  __generator: () => __generator,
+  __importDefault: () => __importDefault,
+  __importStar: () => __importStar,
+  __makeTemplateObject: () => __makeTemplateObject,
+  __metadata: () => __metadata,
+  __param: () => __param,
+  __propKey: () => __propKey,
+  __read: () => __read,
+  __rest: () => __rest,
+  __runInitializers: () => __runInitializers,
+  __setFunctionName: () => __setFunctionName,
+  __spread: () => __spread,
+  __spreadArray: () => __spreadArray,
+  __spreadArrays: () => __spreadArrays,
+  __values: () => __values2,
+  default: () => tslib_es6_default
+});
+function __extends(d, b) {
+  if (typeof b !== "function" && b !== null)
+    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+  extendStatics(d, b);
+  function __() {
+    this.constructor = d;
+  }
+  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+}
+function __rest(s, e) {
+  var t = {};
+  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+    t[p] = s[p];
+  if (s != null && typeof Object.getOwnPropertySymbols === "function")
+    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+        t[p[i]] = s[p[i]];
     }
+  return t;
+}
+function __decorate(decorators, target, key, desc) {
+  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+  return c > 3 && r && Object.defineProperty(target, key, r), r;
+}
+function __param(paramIndex, decorator) {
+  return function(target, key) {
+    decorator(target, key, paramIndex);
+  };
+}
+function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
+  function accept(f) {
+    if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
+    return f;
   }
-});
-
-// node_modules/ms/index.js
-var require_ms = __commonJS({
-  "node_modules/ms/index.js"(exports2, module2) {
-    var s = 1e3;
-    var m = s * 60;
-    var h = m * 60;
-    var d = h * 24;
-    var w = d * 7;
-    var y = d * 365.25;
-    module2.exports = function(val2, options) {
-      options = options || {};
-      var type2 = typeof val2;
-      if (type2 === "string" && val2.length > 0) {
-        return parse(val2);
-      } else if (type2 === "number" && isFinite(val2)) {
-        return options.long ? fmtLong(val2) : fmtShort(val2);
-      }
-      throw new Error(
-        "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2)
-      );
+  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
+  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
+  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
+  var _, done = false;
+  for (var i = decorators.length - 1; i >= 0; i--) {
+    var context2 = {};
+    for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p];
+    for (var p in contextIn.access) context2.access[p] = contextIn.access[p];
+    context2.addInitializer = function(f) {
+      if (done) throw new TypeError("Cannot add initializers after decoration has completed");
+      extraInitializers.push(accept(f || null));
     };
-    function parse(str2) {
-      str2 = String(str2);
-      if (str2.length > 100) {
-        return;
-      }
-      var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
-        str2
-      );
-      if (!match) {
-        return;
-      }
-      var n = parseFloat(match[1]);
-      var type2 = (match[2] || "ms").toLowerCase();
-      switch (type2) {
-        case "years":
-        case "year":
-        case "yrs":
-        case "yr":
-        case "y":
-          return n * y;
-        case "weeks":
-        case "week":
-        case "w":
-          return n * w;
-        case "days":
-        case "day":
-        case "d":
-          return n * d;
-        case "hours":
-        case "hour":
-        case "hrs":
-        case "hr":
-        case "h":
-          return n * h;
-        case "minutes":
-        case "minute":
-        case "mins":
-        case "min":
-        case "m":
-          return n * m;
-        case "seconds":
-        case "second":
-        case "secs":
-        case "sec":
-        case "s":
-          return n * s;
-        case "milliseconds":
-        case "millisecond":
-        case "msecs":
-        case "msec":
-        case "ms":
-          return n;
-        default:
-          return void 0;
-      }
+    var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2);
+    if (kind === "accessor") {
+      if (result === void 0) continue;
+      if (result === null || typeof result !== "object") throw new TypeError("Object expected");
+      if (_ = accept(result.get)) descriptor.get = _;
+      if (_ = accept(result.set)) descriptor.set = _;
+      if (_ = accept(result.init)) initializers.unshift(_);
+    } else if (_ = accept(result)) {
+      if (kind === "field") initializers.unshift(_);
+      else descriptor[key] = _;
     }
-    function fmtShort(ms) {
-      var msAbs = Math.abs(ms);
-      if (msAbs >= d) {
-        return Math.round(ms / d) + "d";
-      }
-      if (msAbs >= h) {
-        return Math.round(ms / h) + "h";
-      }
-      if (msAbs >= m) {
-        return Math.round(ms / m) + "m";
-      }
-      if (msAbs >= s) {
-        return Math.round(ms / s) + "s";
+  }
+  if (target) Object.defineProperty(target, contextIn.name, descriptor);
+  done = true;
+}
+function __runInitializers(thisArg, initializers, value) {
+  var useValue = arguments.length > 2;
+  for (var i = 0; i < initializers.length; i++) {
+    value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
+  }
+  return useValue ? value : void 0;
+}
+function __propKey(x) {
+  return typeof x === "symbol" ? x : "".concat(x);
+}
+function __setFunctionName(f, name, prefix) {
+  if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
+  return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
+}
+function __metadata(metadataKey, metadataValue) {
+  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+}
+function __awaiter(thisArg, _arguments, P, generator) {
+  function adopt(value) {
+    return value instanceof P ? value : new P(function(resolve6) {
+      resolve6(value);
+    });
+  }
+  return new (P || (P = Promise))(function(resolve6, reject) {
+    function fulfilled(value) {
+      try {
+        step(generator.next(value));
+      } catch (e) {
+        reject(e);
       }
-      return ms + "ms";
     }
-    function fmtLong(ms) {
-      var msAbs = Math.abs(ms);
-      if (msAbs >= d) {
-        return plural(ms, msAbs, d, "day");
-      }
-      if (msAbs >= h) {
-        return plural(ms, msAbs, h, "hour");
-      }
-      if (msAbs >= m) {
-        return plural(ms, msAbs, m, "minute");
-      }
-      if (msAbs >= s) {
-        return plural(ms, msAbs, s, "second");
+    function rejected(value) {
+      try {
+        step(generator["throw"](value));
+      } catch (e) {
+        reject(e);
       }
-      return ms + " ms";
     }
-    function plural(ms, msAbs, n, name) {
-      var isPlural = msAbs >= n * 1.5;
-      return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
+    function step(result) {
+      result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
     }
+    step((generator = generator.apply(thisArg, _arguments || [])).next());
+  });
+}
+function __generator(thisArg, body) {
+  var _ = { label: 0, sent: function() {
+    if (t[0] & 1) throw t[1];
+    return t[1];
+  }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
+  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
+    return this;
+  }), g;
+  function verb(n) {
+    return function(v) {
+      return step([n, v]);
+    };
   }
-});
-
-// node_modules/debug/src/common.js
-var require_common = __commonJS({
-  "node_modules/debug/src/common.js"(exports2, module2) {
-    function setup(env) {
-      createDebug.debug = createDebug;
-      createDebug.default = createDebug;
-      createDebug.coerce = coerce3;
-      createDebug.disable = disable;
-      createDebug.enable = enable;
-      createDebug.enabled = enabled;
-      createDebug.humanize = require_ms();
-      createDebug.destroy = destroy;
-      Object.keys(env).forEach((key) => {
-        createDebug[key] = env[key];
-      });
-      createDebug.names = [];
-      createDebug.skips = [];
-      createDebug.formatters = {};
-      function selectColor(namespace) {
-        let hash2 = 0;
-        for (let i = 0; i < namespace.length; i++) {
-          hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
-          hash2 |= 0;
-        }
-        return createDebug.colors[Math.abs(hash2) % createDebug.colors.length];
-      }
-      createDebug.selectColor = selectColor;
-      function createDebug(namespace) {
-        let prevTime;
-        let enableOverride = null;
-        let namespacesCache;
-        let enabledCache;
-        function debug6(...args) {
-          if (!debug6.enabled) {
-            return;
-          }
-          const self2 = debug6;
-          const curr = Number(/* @__PURE__ */ new Date());
-          const ms = curr - (prevTime || curr);
-          self2.diff = ms;
-          self2.prev = prevTime;
-          self2.curr = curr;
-          prevTime = curr;
-          args[0] = createDebug.coerce(args[0]);
-          if (typeof args[0] !== "string") {
-            args.unshift("%O");
-          }
-          let index = 0;
-          args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
-            if (match === "%%") {
-              return "%";
-            }
-            index++;
-            const formatter = createDebug.formatters[format];
-            if (typeof formatter === "function") {
-              const val2 = args[index];
-              match = formatter.call(self2, val2);
-              args.splice(index, 1);
-              index--;
-            }
-            return match;
-          });
-          createDebug.formatArgs.call(self2, args);
-          const logFn = self2.log || createDebug.log;
-          logFn.apply(self2, args);
-        }
-        debug6.namespace = namespace;
-        debug6.useColors = createDebug.useColors();
-        debug6.color = createDebug.selectColor(namespace);
-        debug6.extend = extend3;
-        debug6.destroy = createDebug.destroy;
-        Object.defineProperty(debug6, "enabled", {
-          enumerable: true,
-          configurable: false,
-          get: () => {
-            if (enableOverride !== null) {
-              return enableOverride;
-            }
-            if (namespacesCache !== createDebug.namespaces) {
-              namespacesCache = createDebug.namespaces;
-              enabledCache = createDebug.enabled(namespace);
-            }
-            return enabledCache;
-          },
-          set: (v) => {
-            enableOverride = v;
-          }
-        });
-        if (typeof createDebug.init === "function") {
-          createDebug.init(debug6);
-        }
-        return debug6;
-      }
-      function extend3(namespace, delimiter) {
-        const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
-        newDebug.log = this.log;
-        return newDebug;
-      }
-      function enable(namespaces) {
-        createDebug.save(namespaces);
-        createDebug.namespaces = namespaces;
-        createDebug.names = [];
-        createDebug.skips = [];
-        const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
-        for (const ns of split) {
-          if (ns[0] === "-") {
-            createDebug.skips.push(ns.slice(1));
-          } else {
-            createDebug.names.push(ns);
+  function step(op) {
+    if (f) throw new TypeError("Generator is already executing.");
+    while (g && (g = 0, op[0] && (_ = 0)), _) try {
+      if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+      if (y = 0, t) op = [op[0] & 2, t.value];
+      switch (op[0]) {
+        case 0:
+        case 1:
+          t = op;
+          break;
+        case 4:
+          _.label++;
+          return { value: op[1], done: false };
+        case 5:
+          _.label++;
+          y = op[1];
+          op = [0];
+          continue;
+        case 7:
+          op = _.ops.pop();
+          _.trys.pop();
+          continue;
+        default:
+          if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
+            _ = 0;
+            continue;
           }
-        }
-      }
-      function matchesTemplate(search, template) {
-        let searchIndex = 0;
-        let templateIndex = 0;
-        let starIndex = -1;
-        let matchIndex = 0;
-        while (searchIndex < search.length) {
-          if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
-            if (template[templateIndex] === "*") {
-              starIndex = templateIndex;
-              matchIndex = searchIndex;
-              templateIndex++;
-            } else {
-              searchIndex++;
-              templateIndex++;
-            }
-          } else if (starIndex !== -1) {
-            templateIndex = starIndex + 1;
-            matchIndex++;
-            searchIndex = matchIndex;
-          } else {
-            return false;
+          if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
+            _.label = op[1];
+            break;
           }
-        }
-        while (templateIndex < template.length && template[templateIndex] === "*") {
-          templateIndex++;
-        }
-        return templateIndex === template.length;
-      }
-      function disable() {
-        const namespaces = [
-          ...createDebug.names,
-          ...createDebug.skips.map((namespace) => "-" + namespace)
-        ].join(",");
-        createDebug.enable("");
-        return namespaces;
-      }
-      function enabled(name) {
-        for (const skip of createDebug.skips) {
-          if (matchesTemplate(name, skip)) {
-            return false;
+          if (op[0] === 6 && _.label < t[1]) {
+            _.label = t[1];
+            t = op;
+            break;
           }
-        }
-        for (const ns of createDebug.names) {
-          if (matchesTemplate(name, ns)) {
-            return true;
+          if (t && _.label < t[2]) {
+            _.label = t[2];
+            _.ops.push(op);
+            break;
           }
-        }
-        return false;
+          if (t[2]) _.ops.pop();
+          _.trys.pop();
+          continue;
       }
-      function coerce3(val2) {
-        if (val2 instanceof Error) {
-          return val2.stack || val2.message;
-        }
-        return val2;
-      }
-      function destroy() {
-        console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
-      }
-      createDebug.enable(createDebug.load());
-      return createDebug;
+      op = body.call(thisArg, _);
+    } catch (e) {
+      op = [6, e];
+      y = 0;
+    } finally {
+      f = t = 0;
     }
-    module2.exports = setup;
+    if (op[0] & 5) throw op[1];
+    return { value: op[0] ? op[1] : void 0, done: true };
   }
-});
-
-// node_modules/debug/src/browser.js
-var require_browser = __commonJS({
-  "node_modules/debug/src/browser.js"(exports2, module2) {
-    exports2.formatArgs = formatArgs;
-    exports2.save = save;
-    exports2.load = load2;
-    exports2.useColors = useColors;
-    exports2.storage = localstorage();
-    exports2.destroy = /* @__PURE__ */ (() => {
-      let warned = false;
-      return () => {
-        if (!warned) {
-          warned = true;
-          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
-        }
+}
+function __exportStar(m, o) {
+  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
+}
+function __values2(o) {
+  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+  if (m) return m.call(o);
+  if (o && typeof o.length === "number") return {
+    next: function() {
+      if (o && i >= o.length) o = void 0;
+      return { value: o && o[i++], done: !o };
+    }
+  };
+  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+}
+function __read(o, n) {
+  var m = typeof Symbol === "function" && o[Symbol.iterator];
+  if (!m) return o;
+  var i = m.call(o), r, ar = [], e;
+  try {
+    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+  } catch (error4) {
+    e = { error: error4 };
+  } finally {
+    try {
+      if (r && !r.done && (m = i["return"])) m.call(i);
+    } finally {
+      if (e) throw e.error;
+    }
+  }
+  return ar;
+}
+function __spread() {
+  for (var ar = [], i = 0; i < arguments.length; i++)
+    ar = ar.concat(__read(arguments[i]));
+  return ar;
+}
+function __spreadArrays() {
+  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+  for (var r = Array(s), k = 0, i = 0; i < il; i++)
+    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+      r[k] = a[j];
+  return r;
+}
+function __spreadArray(to, from, pack) {
+  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+    if (ar || !(i in from)) {
+      if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+      ar[i] = from[i];
+    }
+  }
+  return to.concat(ar || Array.prototype.slice.call(from));
+}
+function __await(v) {
+  return this instanceof __await ? (this.v = v, this) : new __await(v);
+}
+function __asyncGenerator(thisArg, _arguments, generator) {
+  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+  var g = generator.apply(thisArg, _arguments || []), i, q = [];
+  return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
+    return this;
+  }, i;
+  function awaitReturn(f) {
+    return function(v) {
+      return Promise.resolve(v).then(f, reject);
+    };
+  }
+  function verb(n, f) {
+    if (g[n]) {
+      i[n] = function(v) {
+        return new Promise(function(a, b) {
+          q.push([n, v, a, b]) > 1 || resume(n, v);
+        });
       };
-    })();
-    exports2.colors = [
-      "#0000CC",
-      "#0000FF",
-      "#0033CC",
-      "#0033FF",
-      "#0066CC",
-      "#0066FF",
-      "#0099CC",
-      "#0099FF",
-      "#00CC00",
-      "#00CC33",
-      "#00CC66",
-      "#00CC99",
-      "#00CCCC",
-      "#00CCFF",
-      "#3300CC",
-      "#3300FF",
-      "#3333CC",
-      "#3333FF",
-      "#3366CC",
-      "#3366FF",
-      "#3399CC",
-      "#3399FF",
-      "#33CC00",
-      "#33CC33",
-      "#33CC66",
-      "#33CC99",
-      "#33CCCC",
-      "#33CCFF",
-      "#6600CC",
-      "#6600FF",
-      "#6633CC",
-      "#6633FF",
-      "#66CC00",
-      "#66CC33",
-      "#9900CC",
-      "#9900FF",
-      "#9933CC",
-      "#9933FF",
-      "#99CC00",
-      "#99CC33",
-      "#CC0000",
-      "#CC0033",
-      "#CC0066",
-      "#CC0099",
-      "#CC00CC",
-      "#CC00FF",
-      "#CC3300",
-      "#CC3333",
-      "#CC3366",
-      "#CC3399",
-      "#CC33CC",
-      "#CC33FF",
-      "#CC6600",
-      "#CC6633",
-      "#CC9900",
-      "#CC9933",
-      "#CCCC00",
-      "#CCCC33",
-      "#FF0000",
-      "#FF0033",
-      "#FF0066",
-      "#FF0099",
-      "#FF00CC",
-      "#FF00FF",
-      "#FF3300",
-      "#FF3333",
-      "#FF3366",
-      "#FF3399",
-      "#FF33CC",
-      "#FF33FF",
-      "#FF6600",
-      "#FF6633",
-      "#FF9900",
-      "#FF9933",
-      "#FFCC00",
-      "#FFCC33"
-    ];
-    function useColors() {
-      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
-        return true;
-      }
-      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
-        return false;
-      }
-      let m;
-      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
-      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
-      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
-      typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
-      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
+      if (f) i[n] = f(i[n]);
     }
-    function formatArgs(args) {
-      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
-      if (!this.useColors) {
-        return;
-      }
-      const c = "color: " + this.color;
-      args.splice(1, 0, c, "color: inherit");
-      let index = 0;
-      let lastC = 0;
-      args[0].replace(/%[a-zA-Z%]/g, (match) => {
-        if (match === "%%") {
-          return;
-        }
-        index++;
-        if (match === "%c") {
-          lastC = index;
-        }
+  }
+  function resume(n, v) {
+    try {
+      step(g[n](v));
+    } catch (e) {
+      settle(q[0][3], e);
+    }
+  }
+  function step(r) {
+    r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
+  }
+  function fulfill(value) {
+    resume("next", value);
+  }
+  function reject(value) {
+    resume("throw", value);
+  }
+  function settle(f, v) {
+    if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
+  }
+}
+function __asyncDelegator(o) {
+  var i, p;
+  return i = {}, verb("next"), verb("throw", function(e) {
+    throw e;
+  }), verb("return"), i[Symbol.iterator] = function() {
+    return this;
+  }, i;
+  function verb(n, f) {
+    i[n] = o[n] ? function(v) {
+      return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
+    } : f;
+  }
+}
+function __asyncValues(o) {
+  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+  var m = o[Symbol.asyncIterator], i;
+  return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
+    return this;
+  }, i);
+  function verb(n) {
+    i[n] = o[n] && function(v) {
+      return new Promise(function(resolve6, reject) {
+        v = o[n](v), settle(resolve6, reject, v.done, v.value);
       });
-      args.splice(lastC, 0, c);
+    };
+  }
+  function settle(resolve6, reject, d, v) {
+    Promise.resolve(v).then(function(v2) {
+      resolve6({ value: v2, done: d });
+    }, reject);
+  }
+}
+function __makeTemplateObject(cooked, raw) {
+  if (Object.defineProperty) {
+    Object.defineProperty(cooked, "raw", { value: raw });
+  } else {
+    cooked.raw = raw;
+  }
+  return cooked;
+}
+function __importStar(mod) {
+  if (mod && mod.__esModule) return mod;
+  var result = {};
+  if (mod != null) {
+    for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+  }
+  __setModuleDefault(result, mod);
+  return result;
+}
+function __importDefault(mod) {
+  return mod && mod.__esModule ? mod : { default: mod };
+}
+function __classPrivateFieldGet(receiver, state, kind, f) {
+  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+}
+function __classPrivateFieldSet(receiver, state, value, kind, f) {
+  if (kind === "m") throw new TypeError("Private method is not writable");
+  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
+}
+function __classPrivateFieldIn(state, receiver) {
+  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
+  return typeof state === "function" ? receiver === state : state.has(receiver);
+}
+function __addDisposableResource(env, value, async) {
+  if (value !== null && value !== void 0) {
+    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
+    var dispose, inner;
+    if (async) {
+      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
+      dispose = value[Symbol.asyncDispose];
     }
-    exports2.log = console.debug || console.log || (() => {
-    });
-    function save(namespaces) {
-      try {
-        if (namespaces) {
-          exports2.storage.setItem("debug", namespaces);
-        } else {
-          exports2.storage.removeItem("debug");
-        }
-      } catch (error4) {
-      }
+    if (dispose === void 0) {
+      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
+      dispose = value[Symbol.dispose];
+      if (async) inner = dispose;
     }
-    function load2() {
-      let r;
+    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
+    if (inner) dispose = function() {
       try {
-        r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
-      } catch (error4) {
-      }
-      if (!r && typeof process !== "undefined" && "env" in process) {
-        r = process.env.DEBUG;
+        inner.call(this);
+      } catch (e) {
+        return Promise.reject(e);
       }
-      return r;
-    }
-    function localstorage() {
+    };
+    env.stack.push({ value, dispose, async });
+  } else if (async) {
+    env.stack.push({ async: true });
+  }
+  return value;
+}
+function __disposeResources(env) {
+  function fail(e) {
+    env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
+    env.hasError = true;
+  }
+  var r, s = 0;
+  function next() {
+    while (r = env.stack.pop()) {
       try {
-        return localStorage;
-      } catch (error4) {
+        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
+        if (r.dispose) {
+          var result = r.dispose.call(r.value);
+          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
+            fail(e);
+            return next();
+          });
+        } else s |= 1;
+      } catch (e) {
+        fail(e);
       }
     }
-    module2.exports = require_common()(exports2);
-    var { formatters } = module2.exports;
-    formatters.j = function(v) {
-      try {
-        return JSON.stringify(v);
-      } catch (error4) {
-        return "[UnexpectedJSONParseError]: " + error4.message;
+    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
+    if (env.hasError) throw env.error;
+  }
+  return next();
+}
+var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default;
+var init_tslib_es6 = __esm({
+  "node_modules/@azure/core-rest-pipeline/node_modules/tslib/tslib.es6.mjs"() {
+    extendStatics = function(d, b) {
+      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
+        d2.__proto__ = b2;
+      } || function(d2, b2) {
+        for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
+      };
+      return extendStatics(d, b);
+    };
+    __assign = function() {
+      __assign = Object.assign || function __assign4(t) {
+        for (var s, i = 1, n = arguments.length; i < n; i++) {
+          s = arguments[i];
+          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+        }
+        return t;
+      };
+      return __assign.apply(this, arguments);
+    };
+    __createBinding = Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    });
+    __setModuleDefault = Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
     };
-  }
-});
-
-// node_modules/has-flag/index.js
-var require_has_flag = __commonJS({
-  "node_modules/has-flag/index.js"(exports2, module2) {
-    "use strict";
-    module2.exports = (flag, argv = process.argv) => {
-      const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
-      const position = argv.indexOf(prefix + flag);
-      const terminatorPosition = argv.indexOf("--");
-      return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
+    _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error4, suppressed, message) {
+      var e = new Error(message);
+      return e.name = "SuppressedError", e.error = error4, e.suppressed = suppressed, e;
+    };
+    tslib_es6_default = {
+      __extends,
+      __assign,
+      __rest,
+      __decorate,
+      __param,
+      __metadata,
+      __awaiter,
+      __generator,
+      __createBinding,
+      __exportStar,
+      __values: __values2,
+      __read,
+      __spread,
+      __spreadArrays,
+      __spreadArray,
+      __await,
+      __asyncGenerator,
+      __asyncDelegator,
+      __asyncValues,
+      __makeTemplateObject,
+      __importStar,
+      __importDefault,
+      __classPrivateFieldGet,
+      __classPrivateFieldSet,
+      __classPrivateFieldIn,
+      __addDisposableResource,
+      __disposeResources
     };
   }
 });
 
-// node_modules/supports-color/index.js
-var require_supports_color = __commonJS({
-  "node_modules/supports-color/index.js"(exports2, module2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js
+var require_userAgentPlatform = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgentPlatform.js"(exports2) {
     "use strict";
-    var os3 = require("os");
-    var tty = require("tty");
-    var hasFlag = require_has_flag();
-    var { env } = process;
-    var forceColor;
-    if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
-      forceColor = 0;
-    } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
-      forceColor = 1;
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getHeaderName = getHeaderName;
+    exports2.setPlatformSpecificData = setPlatformSpecificData;
+    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
+    var os3 = tslib_1.__importStar(require("node:os"));
+    var process2 = tslib_1.__importStar(require("node:process"));
+    function getHeaderName() {
+      return "User-Agent";
     }
-    if ("FORCE_COLOR" in env) {
-      if (env.FORCE_COLOR === "true") {
-        forceColor = 1;
-      } else if (env.FORCE_COLOR === "false") {
-        forceColor = 0;
-      } else {
-        forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
+    async function setPlatformSpecificData(map2) {
+      if (process2 && process2.versions) {
+        const versions = process2.versions;
+        if (versions.bun) {
+          map2.set("Bun", versions.bun);
+        } else if (versions.deno) {
+          map2.set("Deno", versions.deno);
+        } else if (versions.node) {
+          map2.set("Node", versions.node);
+        }
       }
+      map2.set("OS", `(${os3.arch()}-${os3.type()}-${os3.release()})`);
     }
-    function translateLevel(level) {
-      if (level === 0) {
-        return false;
-      }
-      return {
-        level,
-        hasBasic: true,
-        has256: level >= 2,
-        has16m: level >= 3
-      };
-    }
-    function supportsColor(haveStream, streamIsTTY) {
-      if (forceColor === 0) {
-        return 0;
-      }
-      if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
-        return 3;
-      }
-      if (hasFlag("color=256")) {
-        return 2;
-      }
-      if (haveStream && !streamIsTTY && forceColor === void 0) {
-        return 0;
-      }
-      const min = forceColor || 0;
-      if (env.TERM === "dumb") {
-        return min;
-      }
-      if (process.platform === "win32") {
-        const osRelease = os3.release().split(".");
-        if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
-          return Number(osRelease[2]) >= 14931 ? 3 : 2;
-        }
-        return 1;
-      }
-      if ("CI" in env) {
-        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
-          return 1;
-        }
-        return min;
-      }
-      if ("TEAMCITY_VERSION" in env) {
-        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
-      }
-      if (env.COLORTERM === "truecolor") {
-        return 3;
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js
+var require_constants8 = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/constants.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.DEFAULT_RETRY_POLICY_COUNT = exports2.SDK_VERSION = void 0;
+    exports2.SDK_VERSION = "1.17.0";
+    exports2.DEFAULT_RETRY_POLICY_COUNT = 3;
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js
+var require_userAgent = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/userAgent.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getUserAgentHeaderName = getUserAgentHeaderName;
+    exports2.getUserAgentValue = getUserAgentValue;
+    var userAgentPlatform_js_1 = require_userAgentPlatform();
+    var constants_js_1 = require_constants8();
+    function getUserAgentString(telemetryInfo) {
+      const parts = [];
+      for (const [key, value] of telemetryInfo) {
+        const token = value ? `${key}/${value}` : key;
+        parts.push(token);
       }
-      if ("TERM_PROGRAM" in env) {
-        const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
-        switch (env.TERM_PROGRAM) {
-          case "iTerm.app":
-            return version >= 3 ? 3 : 2;
-          case "Apple_Terminal":
-            return 2;
+      return parts.join(" ");
+    }
+    function getUserAgentHeaderName() {
+      return (0, userAgentPlatform_js_1.getHeaderName)();
+    }
+    async function getUserAgentValue(prefix) {
+      const runtimeInfo = /* @__PURE__ */ new Map();
+      runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION);
+      await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo);
+      const defaultAgent = getUserAgentString(runtimeInfo);
+      const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
+      return userAgentValue;
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js
+var require_userAgentPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/userAgentPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.userAgentPolicyName = void 0;
+    exports2.userAgentPolicy = userAgentPolicy;
+    var userAgent_js_1 = require_userAgent();
+    var UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)();
+    exports2.userAgentPolicyName = "userAgentPolicy";
+    function userAgentPolicy(options = {}) {
+      const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
+      return {
+        name: exports2.userAgentPolicyName,
+        async sendRequest(request, next) {
+          if (!request.headers.has(UserAgentHeaderName)) {
+            request.headers.set(UserAgentHeaderName, await userAgentValue);
+          }
+          return next(request);
         }
-      }
-      if (/-256(color)?$/i.test(env.TERM)) {
-        return 2;
-      }
-      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
-        return 1;
-      }
-      if ("COLORTERM" in env) {
-        return 1;
-      }
-      return min;
+      };
     }
-    function getSupportLevel(stream2) {
-      const level = supportsColor(stream2, stream2 && stream2.isTTY);
-      return translateLevel(level);
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js
+var require_typeGuards2 = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/typeGuards.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.isNodeReadableStream = isNodeReadableStream;
+    exports2.isWebReadableStream = isWebReadableStream;
+    exports2.isReadableStream = isReadableStream;
+    exports2.isBlob = isBlob;
+    function isNodeReadableStream(x) {
+      return Boolean(x && typeof x["pipe"] === "function");
+    }
+    function isWebReadableStream(x) {
+      return Boolean(x && typeof x.getReader === "function" && typeof x.tee === "function");
+    }
+    function isReadableStream(x) {
+      return isNodeReadableStream(x) || isWebReadableStream(x);
+    }
+    function isBlob(x) {
+      return typeof x.stream === "function";
     }
-    module2.exports = {
-      supportsColor: getSupportLevel,
-      stdout: translateLevel(supportsColor(true, tty.isatty(1))),
-      stderr: translateLevel(supportsColor(true, tty.isatty(2)))
-    };
   }
 });
 
-// node_modules/debug/src/node.js
-var require_node = __commonJS({
-  "node_modules/debug/src/node.js"(exports2, module2) {
-    var tty = require("tty");
-    var util = require("util");
-    exports2.init = init;
-    exports2.log = log;
-    exports2.formatArgs = formatArgs;
-    exports2.save = save;
-    exports2.load = load2;
-    exports2.useColors = useColors;
-    exports2.destroy = util.deprecate(
-      () => {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js
+var require_file2 = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/file.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getRawContent = getRawContent;
+    exports2.createFileFromStream = createFileFromStream;
+    exports2.createFile = createFile;
+    var core_util_1 = require_commonjs2();
+    var typeGuards_js_1 = require_typeGuards2();
+    var unimplementedMethods = {
+      arrayBuffer: () => {
+        throw new Error("Not implemented");
       },
-      "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
-    );
-    exports2.colors = [6, 2, 3, 4, 5, 1];
-    try {
-      const supportsColor = require_supports_color();
-      if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
-        exports2.colors = [
-          20,
-          21,
-          26,
-          27,
-          32,
-          33,
-          38,
-          39,
-          40,
-          41,
-          42,
-          43,
-          44,
-          45,
-          56,
-          57,
-          62,
-          63,
-          68,
-          69,
-          74,
-          75,
-          76,
-          77,
-          78,
-          79,
-          80,
-          81,
-          92,
-          93,
-          98,
-          99,
-          112,
-          113,
-          128,
-          129,
-          134,
-          135,
-          148,
-          149,
-          160,
-          161,
-          162,
-          163,
-          164,
-          165,
-          166,
-          167,
-          168,
-          169,
-          170,
-          171,
-          172,
-          173,
-          178,
-          179,
-          184,
-          185,
-          196,
-          197,
-          198,
-          199,
-          200,
-          201,
-          202,
-          203,
-          204,
-          205,
-          206,
-          207,
-          208,
-          209,
-          214,
-          215,
-          220,
-          221
-        ];
+      slice: () => {
+        throw new Error("Not implemented");
+      },
+      text: () => {
+        throw new Error("Not implemented");
       }
-    } catch (error4) {
+    };
+    var rawContent = Symbol("rawContent");
+    function hasRawContent(x) {
+      return typeof x[rawContent] === "function";
     }
-    exports2.inspectOpts = Object.keys(process.env).filter((key) => {
-      return /^debug_/i.test(key);
-    }).reduce((obj, key) => {
-      const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
-        return k.toUpperCase();
-      });
-      let val2 = process.env[key];
-      if (/^(yes|on|true|enabled)$/i.test(val2)) {
-        val2 = true;
-      } else if (/^(no|off|false|disabled)$/i.test(val2)) {
-        val2 = false;
-      } else if (val2 === "null") {
-        val2 = null;
+    function getRawContent(blob) {
+      if (hasRawContent(blob)) {
+        return blob[rawContent]();
       } else {
-        val2 = Number(val2);
+        return blob.stream();
       }
-      obj[prop] = val2;
-      return obj;
-    }, {});
-    function useColors() {
-      return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd);
     }
-    function formatArgs(args) {
-      const { namespace: name, useColors: useColors2 } = this;
-      if (useColors2) {
-        const c = this.color;
-        const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
-        const prefix = `  ${colorCode};1m${name} \x1B[0m`;
-        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
-        args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
+    function createFileFromStream(stream2, name, options = {}) {
+      var _a, _b, _c, _d;
+      return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => {
+        const s = stream2();
+        if ((0, typeGuards_js_1.isNodeReadableStream)(s)) {
+          throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
+        }
+        return s;
+      }, [rawContent]: stream2 });
+    }
+    function createFile(content, name, options = {}) {
+      var _a, _b, _c;
+      if (core_util_1.isNodeLike) {
+        return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : (/* @__PURE__ */ new Date()).getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content });
       } else {
-        args[0] = getDate() + name + " " + args[0];
+        return new File([content], name, options);
       }
     }
-    function getDate() {
-      if (exports2.inspectOpts.hideDate) {
-        return "";
-      }
-      return (/* @__PURE__ */ new Date()).toISOString() + " ";
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js
+var require_concat = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/concat.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.concat = concat;
+    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
+    var node_stream_1 = require("node:stream");
+    var typeGuards_js_1 = require_typeGuards2();
+    var file_js_1 = require_file2();
+    function streamAsyncIterator() {
+      return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() {
+        const reader = this.getReader();
+        try {
+          while (true) {
+            const { done, value } = yield tslib_1.__await(reader.read());
+            if (done) {
+              return yield tslib_1.__await(void 0);
+            }
+            yield yield tslib_1.__await(value);
+          }
+        } finally {
+          reader.releaseLock();
+        }
+      });
     }
-    function log(...args) {
-      return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
+    function makeAsyncIterable(webStream) {
+      if (!webStream[Symbol.asyncIterator]) {
+        webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
+      }
+      if (!webStream.values) {
+        webStream.values = streamAsyncIterator.bind(webStream);
+      }
     }
-    function save(namespaces) {
-      if (namespaces) {
-        process.env.DEBUG = namespaces;
+    function ensureNodeStream(stream2) {
+      if (stream2 instanceof ReadableStream) {
+        makeAsyncIterable(stream2);
+        return node_stream_1.Readable.fromWeb(stream2);
       } else {
-        delete process.env.DEBUG;
+        return stream2;
       }
     }
-    function load2() {
-      return process.env.DEBUG;
-    }
-    function init(debug6) {
-      debug6.inspectOpts = {};
-      const keys = Object.keys(exports2.inspectOpts);
-      for (let i = 0; i < keys.length; i++) {
-        debug6.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
+    function toStream(source) {
+      if (source instanceof Uint8Array) {
+        return node_stream_1.Readable.from(Buffer.from(source));
+      } else if ((0, typeGuards_js_1.isBlob)(source)) {
+        return toStream((0, file_js_1.getRawContent)(source));
+      } else {
+        return ensureNodeStream(source);
       }
     }
-    module2.exports = require_common()(exports2);
-    var { formatters } = module2.exports;
-    formatters.o = function(v) {
-      this.inspectOpts.colors = this.useColors;
-      return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" ");
-    };
-    formatters.O = function(v) {
-      this.inspectOpts.colors = this.useColors;
-      return util.inspect(v, this.inspectOpts);
-    };
-  }
-});
-
-// node_modules/debug/src/index.js
-var require_src = __commonJS({
-  "node_modules/debug/src/index.js"(exports2, module2) {
-    if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
-      module2.exports = require_browser();
-    } else {
-      module2.exports = require_node();
+    async function concat(sources) {
+      return function() {
+        const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream);
+        return node_stream_1.Readable.from((function() {
+          return tslib_1.__asyncGenerator(this, arguments, function* () {
+            var _a, e_1, _b, _c;
+            for (const stream2 of streams) {
+              try {
+                for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream2)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) {
+                  _c = stream_1_1.value;
+                  _d = false;
+                  const chunk = _c;
+                  yield yield tslib_1.__await(chunk);
+                }
+              } catch (e_1_1) {
+                e_1 = { error: e_1_1 };
+              } finally {
+                try {
+                  if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1));
+                } finally {
+                  if (e_1) throw e_1.error;
+                }
+              }
+            }
+          });
+        })());
+      };
     }
   }
 });
 
-// node_modules/agent-base/dist/helpers.js
-var require_helpers2 = __commonJS({
-  "node_modules/agent-base/dist/helpers.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js
+var require_multipartPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/multipartPolicy.js"(exports2) {
     "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.req = exports2.json = exports2.toBuffer = void 0;
-    var http = __importStar4(require("http"));
-    var https2 = __importStar4(require("https"));
-    async function toBuffer(stream2) {
-      let length = 0;
-      const chunks = [];
-      for await (const chunk of stream2) {
-        length += chunk.length;
-        chunks.push(chunk);
+    exports2.multipartPolicyName = void 0;
+    exports2.multipartPolicy = multipartPolicy;
+    var core_util_1 = require_commonjs2();
+    var concat_js_1 = require_concat();
+    var typeGuards_js_1 = require_typeGuards2();
+    function generateBoundary() {
+      return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`;
+    }
+    function encodeHeaders(headers) {
+      let result = "";
+      for (const [key, value] of headers) {
+        result += `${key}: ${value}\r
+`;
       }
-      return Buffer.concat(chunks, length);
+      return result;
     }
-    exports2.toBuffer = toBuffer;
-    async function json2(stream2) {
-      const buf = await toBuffer(stream2);
-      const str2 = buf.toString("utf8");
-      try {
-        return JSON.parse(str2);
-      } catch (_err) {
-        const err = _err;
-        err.message += ` (input: ${str2})`;
-        throw err;
+    function getLength(source) {
+      if (source instanceof Uint8Array) {
+        return source.byteLength;
+      } else if ((0, typeGuards_js_1.isBlob)(source)) {
+        return source.size === -1 ? void 0 : source.size;
+      } else {
+        return void 0;
       }
     }
-    exports2.json = json2;
-    function req(url2, opts = {}) {
-      const href = typeof url2 === "string" ? url2 : url2.href;
-      const req2 = (href.startsWith("https:") ? https2 : http).request(url2, opts);
-      const promise = new Promise((resolve6, reject) => {
-        req2.once("response", resolve6).once("error", reject).end();
-      });
-      req2.then = promise.then.bind(promise);
-      return req2;
+    function getTotalLength(sources) {
+      let total = 0;
+      for (const source of sources) {
+        const partLength = getLength(source);
+        if (partLength === void 0) {
+          return void 0;
+        } else {
+          total += partLength;
+        }
+      }
+      return total;
     }
-    exports2.req = req;
-  }
-});
-
-// node_modules/agent-base/dist/index.js
-var require_dist2 = __commonJS({
-  "node_modules/agent-base/dist/index.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+    async function buildRequestBody(request, parts, boundary) {
+      const sources = [
+        (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"),
+        ...parts.flatMap((part) => [
+          (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
+          (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"),
+          (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
+          part.body,
+          (0, core_util_1.stringToUint8Array)(`\r
+--${boundary}`, "utf-8")
+        ]),
+        (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8")
+      ];
+      const contentLength = getTotalLength(sources);
+      if (contentLength) {
+        request.headers.set("Content-Length", contentLength);
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      request.body = await (0, concat_js_1.concat)(sources);
+    }
+    exports2.multipartPolicyName = "multipartPolicy";
+    var maxBoundaryLength = 70;
+    var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
+    function assertValidBoundary(boundary) {
+      if (boundary.length > maxBoundaryLength) {
+        throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
       }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) {
-      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p);
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Agent = void 0;
-    var net = __importStar4(require("net"));
-    var http = __importStar4(require("http"));
-    var https_1 = require("https");
-    __exportStar4(require_helpers2(), exports2);
-    var INTERNAL = Symbol("AgentBaseInternalState");
-    var Agent = class extends http.Agent {
-      constructor(opts) {
-        super(opts);
-        this[INTERNAL] = {};
+      if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
+        throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
       }
-      /**
-       * Determine whether this is an `http` or `https` request.
-       */
-      isSecureEndpoint(options) {
-        if (options) {
-          if (typeof options.secureEndpoint === "boolean") {
-            return options.secureEndpoint;
+    }
+    function multipartPolicy() {
+      return {
+        name: exports2.multipartPolicyName,
+        async sendRequest(request, next) {
+          var _a;
+          if (!request.multipartBody) {
+            return next(request);
           }
-          if (typeof options.protocol === "string") {
-            return options.protocol === "https:";
+          if (request.body) {
+            throw new Error("multipartBody and regular body cannot be set at the same time");
           }
-        }
-        const { stack } = new Error();
-        if (typeof stack !== "string")
-          return false;
-        return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1);
-      }
-      // In order to support async signatures in `connect()` and Node's native
-      // connection pooling in `http.Agent`, the array of sockets for each origin
-      // has to be updated synchronously. This is so the length of the array is
-      // accurate when `addRequest()` is next called. We achieve this by creating a
-      // fake socket and adding it to `sockets[origin]` and incrementing
-      // `totalSocketCount`.
-      incrementSockets(name) {
-        if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
-          return null;
-        }
-        if (!this.sockets[name]) {
-          this.sockets[name] = [];
-        }
-        const fakeSocket = new net.Socket({ writable: false });
-        this.sockets[name].push(fakeSocket);
-        this.totalSocketCount++;
-        return fakeSocket;
-      }
-      decrementSockets(name, socket) {
-        if (!this.sockets[name] || socket === null) {
-          return;
-        }
-        const sockets = this.sockets[name];
-        const index = sockets.indexOf(socket);
-        if (index !== -1) {
-          sockets.splice(index, 1);
-          this.totalSocketCount--;
-          if (sockets.length === 0) {
-            delete this.sockets[name];
+          let boundary = request.multipartBody.boundary;
+          const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed";
+          const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
+          if (!parsedHeader) {
+            throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
           }
-        }
-      }
-      // In order to properly update the socket pool, we need to call `getName()` on
-      // the core `https.Agent` if it is a secureEndpoint.
-      getName(options) {
-        const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options);
-        if (secureEndpoint) {
-          return https_1.Agent.prototype.getName.call(this, options);
-        }
-        return super.getName(options);
-      }
-      createSocket(req, options, cb) {
-        const connectOpts = {
-          ...options,
-          secureEndpoint: this.isSecureEndpoint(options)
-        };
-        const name = this.getName(connectOpts);
-        const fakeSocket = this.incrementSockets(name);
-        Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
-          this.decrementSockets(name, fakeSocket);
-          if (socket instanceof http.Agent) {
-            try {
-              return socket.addRequest(req, connectOpts);
-            } catch (err) {
-              return cb(err);
-            }
+          const [, contentType, parsedBoundary] = parsedHeader;
+          if (parsedBoundary && boundary && parsedBoundary !== boundary) {
+            throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
           }
-          this[INTERNAL].currentSocket = socket;
-          super.createSocket(req, options, cb);
-        }, (err) => {
-          this.decrementSockets(name, fakeSocket);
-          cb(err);
-        });
-      }
-      createConnection() {
-        const socket = this[INTERNAL].currentSocket;
-        this[INTERNAL].currentSocket = void 0;
-        if (!socket) {
-          throw new Error("No socket was returned in the `connect()` function");
-        }
-        return socket;
-      }
-      get defaultPort() {
-        return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
-      }
-      set defaultPort(v) {
-        if (this[INTERNAL]) {
-          this[INTERNAL].defaultPort = v;
+          boundary !== null && boundary !== void 0 ? boundary : boundary = parsedBoundary;
+          if (boundary) {
+            assertValidBoundary(boundary);
+          } else {
+            boundary = generateBoundary();
+          }
+          request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
+          await buildRequestBody(request, request.multipartBody.parts, boundary);
+          request.multipartBody = void 0;
+          return next(request);
         }
-      }
-      get protocol() {
-        return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
-      }
-      set protocol(v) {
-        if (this[INTERNAL]) {
-          this[INTERNAL].protocol = v;
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js
+var require_decompressResponsePolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/decompressResponsePolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.decompressResponsePolicyName = void 0;
+    exports2.decompressResponsePolicy = decompressResponsePolicy;
+    exports2.decompressResponsePolicyName = "decompressResponsePolicy";
+    function decompressResponsePolicy() {
+      return {
+        name: exports2.decompressResponsePolicyName,
+        async sendRequest(request, next) {
+          if (request.method !== "HEAD") {
+            request.headers.set("Accept-Encoding", "gzip,deflate");
+          }
+          return next(request);
         }
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js
+var require_AbortError2 = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/AbortError.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.AbortError = void 0;
+    var AbortError = class extends Error {
+      constructor(message) {
+        super(message);
+        this.name = "AbortError";
       }
     };
-    exports2.Agent = Agent;
+    exports2.AbortError = AbortError;
   }
 });
 
-// node_modules/https-proxy-agent/dist/parse-proxy-response.js
-var require_parse_proxy_response = __commonJS({
-  "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js
+var require_commonjs3 = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/node_modules/@azure/abort-controller/dist/commonjs/index.js"(exports2) {
     "use strict";
-    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
-      return mod && mod.__esModule ? mod : { "default": mod };
-    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.parseProxyResponse = void 0;
-    var debug_1 = __importDefault4(require_src());
-    var debug6 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
-    function parseProxyResponse(socket) {
+    exports2.AbortError = void 0;
+    var AbortError_js_1 = require_AbortError2();
+    Object.defineProperty(exports2, "AbortError", { enumerable: true, get: function() {
+      return AbortError_js_1.AbortError;
+    } });
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js
+var require_helpers = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/helpers.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.delay = delay2;
+    exports2.parseHeaderValueAsNumber = parseHeaderValueAsNumber;
+    var abort_controller_1 = require_commonjs3();
+    var StandardAbortMessage = "The operation was aborted.";
+    function delay2(delayInMs, value, options) {
       return new Promise((resolve6, reject) => {
-        let buffersLength = 0;
-        const buffers = [];
-        function read() {
-          const b = socket.read();
-          if (b)
-            ondata(b);
-          else
-            socket.once("readable", read);
-        }
-        function cleanup() {
-          socket.removeListener("end", onend);
-          socket.removeListener("error", onerror);
-          socket.removeListener("readable", read);
-        }
-        function onend() {
-          cleanup();
-          debug6("onend");
-          reject(new Error("Proxy connection ended before receiving CONNECT response"));
-        }
-        function onerror(err) {
-          cleanup();
-          debug6("onerror %o", err);
-          reject(err);
-        }
-        function ondata(b) {
-          buffers.push(b);
-          buffersLength += b.length;
-          const buffered = Buffer.concat(buffers, buffersLength);
-          const endOfHeaders = buffered.indexOf("\r\n\r\n");
-          if (endOfHeaders === -1) {
-            debug6("have not received end of HTTP headers yet...");
-            read();
-            return;
-          }
-          const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n");
-          const firstLine = headerParts.shift();
-          if (!firstLine) {
-            socket.destroy();
-            return reject(new Error("No header received from proxy CONNECT response"));
+        let timer = void 0;
+        let onAborted = void 0;
+        const rejectOnAbort = () => {
+          return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage));
+        };
+        const removeListeners = () => {
+          if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) {
+            options.abortSignal.removeEventListener("abort", onAborted);
           }
-          const firstLineParts = firstLine.split(" ");
-          const statusCode = +firstLineParts[1];
-          const statusText = firstLineParts.slice(2).join(" ");
-          const headers = {};
-          for (const header of headerParts) {
-            if (!header)
-              continue;
-            const firstColon = header.indexOf(":");
-            if (firstColon === -1) {
-              socket.destroy();
-              return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
-            }
-            const key = header.slice(0, firstColon).toLowerCase();
-            const value = header.slice(firstColon + 1).trimStart();
-            const current = headers[key];
-            if (typeof current === "string") {
-              headers[key] = [current, value];
-            } else if (Array.isArray(current)) {
-              current.push(value);
-            } else {
-              headers[key] = value;
-            }
+        };
+        onAborted = () => {
+          if (timer) {
+            clearTimeout(timer);
           }
-          debug6("got proxy server response: %o %o", firstLine, headers);
-          cleanup();
-          resolve6({
-            connect: {
-              statusCode,
-              statusText,
-              headers
-            },
-            buffered
-          });
+          removeListeners();
+          return rejectOnAbort();
+        };
+        if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) {
+          return rejectOnAbort();
+        }
+        timer = setTimeout(() => {
+          removeListeners();
+          resolve6(value);
+        }, delayInMs);
+        if (options === null || options === void 0 ? void 0 : options.abortSignal) {
+          options.abortSignal.addEventListener("abort", onAborted);
         }
-        socket.on("error", onerror);
-        socket.on("end", onend);
-        read();
       });
     }
-    exports2.parseProxyResponse = parseProxyResponse;
+    function parseHeaderValueAsNumber(response, headerName) {
+      const value = response.headers.get(headerName);
+      if (!value)
+        return;
+      const valueAsNum = Number(value);
+      if (Number.isNaN(valueAsNum))
+        return;
+      return valueAsNum;
+    }
   }
 });
 
-// node_modules/https-proxy-agent/dist/index.js
-var require_dist3 = __commonJS({
-  "node_modules/https-proxy-agent/dist/index.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js
+var require_throttlingRetryStrategy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/throttlingRetryStrategy.js"(exports2) {
     "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
-      return mod && mod.__esModule ? mod : { "default": mod };
-    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.HttpsProxyAgent = void 0;
-    var net = __importStar4(require("net"));
-    var tls = __importStar4(require("tls"));
-    var assert_1 = __importDefault4(require("assert"));
-    var debug_1 = __importDefault4(require_src());
-    var agent_base_1 = require_dist2();
-    var url_1 = require("url");
-    var parse_proxy_response_1 = require_parse_proxy_response();
-    var debug6 = (0, debug_1.default)("https-proxy-agent");
-    var setServernameFromNonIpHost = (options) => {
-      if (options.servername === void 0 && options.host && !net.isIP(options.host)) {
-        return {
-          ...options,
-          servername: options.host
-        };
-      }
-      return options;
-    };
-    var HttpsProxyAgent = class extends agent_base_1.Agent {
-      constructor(proxy, opts) {
-        super(opts);
-        this.options = { path: void 0 };
-        this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy;
-        this.proxyHeaders = opts?.headers ?? {};
-        debug6("Creating new HttpsProxyAgent instance: %o", this.proxy.href);
-        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
-        const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80;
-        this.connectOpts = {
-          // Attempt to negotiate http/1.1 for proxy servers that support http/2
-          ALPNProtocols: ["http/1.1"],
-          ...opts ? omit(opts, "headers") : null,
-          host,
-          port
-        };
+    exports2.isThrottlingRetryResponse = isThrottlingRetryResponse;
+    exports2.throttlingRetryStrategy = throttlingRetryStrategy;
+    var helpers_js_1 = require_helpers();
+    var RetryAfterHeader = "Retry-After";
+    var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
+    function getRetryAfterInMs(response) {
+      if (!(response && [429, 503].includes(response.status)))
+        return void 0;
+      try {
+        for (const header of AllRetryAfterHeaders) {
+          const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header);
+          if (retryAfterValue === 0 || retryAfterValue) {
+            const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1;
+            return retryAfterValue * multiplyingFactor;
+          }
+        }
+        const retryAfterHeader = response.headers.get(RetryAfterHeader);
+        if (!retryAfterHeader)
+          return;
+        const date = Date.parse(retryAfterHeader);
+        const diff = date - Date.now();
+        return Number.isFinite(diff) ? Math.max(0, diff) : void 0;
+      } catch (_a) {
+        return void 0;
       }
-      /**
-       * Called when the node-core HTTP client library is creating a
-       * new HTTP request.
-       */
-      async connect(req, opts) {
-        const { proxy } = this;
-        if (!opts.host) {
-          throw new TypeError('No "host" provided');
+    }
+    function isThrottlingRetryResponse(response) {
+      return Number.isFinite(getRetryAfterInMs(response));
+    }
+    function throttlingRetryStrategy() {
+      return {
+        name: "throttlingRetryStrategy",
+        retry({ response }) {
+          const retryAfterInMs = getRetryAfterInMs(response);
+          if (!Number.isFinite(retryAfterInMs)) {
+            return { skipStrategy: true };
+          }
+          return {
+            retryAfterInMs
+          };
         }
-        let socket;
-        if (proxy.protocol === "https:") {
-          debug6("Creating `tls.Socket`: %o", this.connectOpts);
-          socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
-        } else {
-          debug6("Creating `net.Socket`: %o", this.connectOpts);
-          socket = net.connect(this.connectOpts);
-        }
-        const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
-        const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
-        let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r
-`;
-        if (proxy.username || proxy.password) {
-          const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
-          headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
-        }
-        headers.Host = `${host}:${opts.port}`;
-        if (!headers["Proxy-Connection"]) {
-          headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
-        }
-        for (const name of Object.keys(headers)) {
-          payload += `${name}: ${headers[name]}\r
-`;
-        }
-        const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
-        socket.write(`${payload}\r
-`);
-        const { connect, buffered } = await proxyResponsePromise;
-        req.emit("proxyConnect", connect);
-        this.emit("proxyConnect", connect, req);
-        if (connect.statusCode === 200) {
-          req.once("socket", resume);
-          if (opts.secureEndpoint) {
-            debug6("Upgrading socket connection to TLS");
-            return tls.connect({
-              ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"),
-              socket
-            });
-          }
-          return socket;
-        }
-        socket.destroy();
-        const fakeSocket = new net.Socket({ writable: false });
-        fakeSocket.readable = true;
-        req.once("socket", (s) => {
-          debug6("Replaying proxy buffer for failed request");
-          (0, assert_1.default)(s.listenerCount("data") > 0);
-          s.push(buffered);
-          s.push(null);
-        });
-        return fakeSocket;
-      }
-    };
-    HttpsProxyAgent.protocols = ["http", "https"];
-    exports2.HttpsProxyAgent = HttpsProxyAgent;
-    function resume(socket) {
-      socket.resume();
-    }
-    function omit(obj, ...keys) {
-      const ret = {};
-      let key;
-      for (key in obj) {
-        if (!keys.includes(key)) {
-          ret[key] = obj[key];
-        }
-      }
-      return ret;
-    }
-  }
-});
-
-// node_modules/http-proxy-agent/dist/index.js
-var require_dist4 = __commonJS({
-  "node_modules/http-proxy-agent/dist/index.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
-      return mod && mod.__esModule ? mod : { "default": mod };
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.HttpProxyAgent = void 0;
-    var net = __importStar4(require("net"));
-    var tls = __importStar4(require("tls"));
-    var debug_1 = __importDefault4(require_src());
-    var events_1 = require("events");
-    var agent_base_1 = require_dist2();
-    var url_1 = require("url");
-    var debug6 = (0, debug_1.default)("http-proxy-agent");
-    var HttpProxyAgent = class extends agent_base_1.Agent {
-      constructor(proxy, opts) {
-        super(opts);
-        this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy;
-        this.proxyHeaders = opts?.headers ?? {};
-        debug6("Creating new HttpProxyAgent instance: %o", this.proxy.href);
-        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
-        const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80;
-        this.connectOpts = {
-          ...opts ? omit(opts, "headers") : null,
-          host,
-          port
-        };
-      }
-      addRequest(req, opts) {
-        req._header = null;
-        this.setRequestProps(req, opts);
-        super.addRequest(req, opts);
-      }
-      setRequestProps(req, opts) {
-        const { proxy } = this;
-        const protocol = opts.secureEndpoint ? "https:" : "http:";
-        const hostname = req.getHeader("host") || "localhost";
-        const base = `${protocol}//${hostname}`;
-        const url2 = new url_1.URL(req.path, base);
-        if (opts.port !== 80) {
-          url2.port = String(opts.port);
-        }
-        req.path = String(url2);
-        const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
-        if (proxy.username || proxy.password) {
-          const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
-          headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
-        }
-        if (!headers["Proxy-Connection"]) {
-          headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
-        }
-        for (const name of Object.keys(headers)) {
-          const value = headers[name];
-          if (value) {
-            req.setHeader(name, value);
-          }
-        }
-      }
-      async connect(req, opts) {
-        req._header = null;
-        if (!req.path.includes("://")) {
-          this.setRequestProps(req, opts);
-        }
-        let first;
-        let endOfHeaders;
-        debug6("Regenerating stored HTTP header string for request");
-        req._implicitHeader();
-        if (req.outputData && req.outputData.length > 0) {
-          debug6("Patching connection write() output buffer with updated header");
-          first = req.outputData[0].data;
-          endOfHeaders = first.indexOf("\r\n\r\n") + 4;
-          req.outputData[0].data = req._header + first.substring(endOfHeaders);
-          debug6("Output buffer: %o", req.outputData[0].data);
-        }
-        let socket;
-        if (this.proxy.protocol === "https:") {
-          debug6("Creating `tls.Socket`: %o", this.connectOpts);
-          socket = tls.connect(this.connectOpts);
-        } else {
-          debug6("Creating `net.Socket`: %o", this.connectOpts);
-          socket = net.connect(this.connectOpts);
-        }
-        await (0, events_1.once)(socket, "connect");
-        return socket;
-      }
-    };
-    HttpProxyAgent.protocols = ["http", "https"];
-    exports2.HttpProxyAgent = HttpProxyAgent;
-    function omit(obj, ...keys) {
-      const ret = {};
-      let key;
-      for (key in obj) {
-        if (!keys.includes(key)) {
-          ret[key] = obj[key];
-        }
-      }
-      return ret;
+      };
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js
-var require_proxyPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js
+var require_exponentialRetryStrategy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/retryStrategies/exponentialRetryStrategy.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.globalNoProxyList = exports2.proxyPolicyName = void 0;
-    exports2.loadNoProxy = loadNoProxy;
-    exports2.getDefaultProxySettings = getDefaultProxySettings;
-    exports2.proxyPolicy = proxyPolicy;
-    var https_proxy_agent_1 = require_dist3();
-    var http_proxy_agent_1 = require_dist4();
-    var log_js_1 = require_log();
-    var HTTPS_PROXY = "HTTPS_PROXY";
-    var HTTP_PROXY = "HTTP_PROXY";
-    var ALL_PROXY = "ALL_PROXY";
-    var NO_PROXY = "NO_PROXY";
-    exports2.proxyPolicyName = "proxyPolicy";
-    exports2.globalNoProxyList = [];
-    var noProxyListLoaded = false;
-    var globalBypassedMap = /* @__PURE__ */ new Map();
-    function getEnvironmentValue(name) {
-      if (process.env[name]) {
-        return process.env[name];
-      } else if (process.env[name.toLowerCase()]) {
-        return process.env[name.toLowerCase()];
-      }
-      return void 0;
-    }
-    function loadEnvironmentProxyValue() {
-      if (!process) {
-        return void 0;
-      }
-      const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
-      const allProxy = getEnvironmentValue(ALL_PROXY);
-      const httpProxy = getEnvironmentValue(HTTP_PROXY);
-      return httpsProxy || allProxy || httpProxy;
-    }
-    function isBypassed(uri, noProxyList, bypassedMap) {
-      if (noProxyList.length === 0) {
-        return false;
-      }
-      const host = new URL(uri).hostname;
-      if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) {
-        return bypassedMap.get(host);
-      }
-      let isBypassedFlag = false;
-      for (const pattern of noProxyList) {
-        if (pattern[0] === ".") {
-          if (host.endsWith(pattern)) {
-            isBypassedFlag = true;
-          } else {
-            if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
-              isBypassedFlag = true;
-            }
+    exports2.exponentialRetryStrategy = exponentialRetryStrategy;
+    exports2.isExponentialRetryResponse = isExponentialRetryResponse;
+    exports2.isSystemError = isSystemError;
+    var core_util_1 = require_commonjs2();
+    var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy();
+    var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3;
+    var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64;
+    function exponentialRetryStrategy(options = {}) {
+      var _a, _b;
+      const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL;
+      const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
+      let retryAfterInMs = retryInterval;
+      return {
+        name: "exponentialRetryStrategy",
+        retry({ retryCount, response, responseError }) {
+          const matchedSystemError = isSystemError(responseError);
+          const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;
+          const isExponential = isExponentialRetryResponse(response);
+          const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;
+          const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential);
+          if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
+            return { skipStrategy: true };
           }
-        } else {
-          if (host === pattern) {
-            isBypassedFlag = true;
+          if (responseError && !matchedSystemError && !isExponential) {
+            return { errorToThrow: responseError };
           }
+          const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount);
+          const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay);
+          retryAfterInMs = clampedExponentialDelay / 2 + (0, core_util_1.getRandomIntegerInclusive)(0, clampedExponentialDelay / 2);
+          return { retryAfterInMs };
         }
-      }
-      bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag);
-      return isBypassedFlag;
-    }
-    function loadNoProxy() {
-      const noProxy = getEnvironmentValue(NO_PROXY);
-      noProxyListLoaded = true;
-      if (noProxy) {
-        return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length);
-      }
-      return [];
-    }
-    function getDefaultProxySettings(proxyUrl) {
-      if (!proxyUrl) {
-        proxyUrl = loadEnvironmentProxyValue();
-        if (!proxyUrl) {
-          return void 0;
-        }
-      }
-      const parsedUrl = new URL(proxyUrl);
-      const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
-      return {
-        host: schema2 + parsedUrl.hostname,
-        port: Number.parseInt(parsedUrl.port || "80"),
-        username: parsedUrl.username,
-        password: parsedUrl.password
       };
     }
-    function getDefaultProxySettingsInternal() {
-      const envProxy = loadEnvironmentProxyValue();
-      return envProxy ? new URL(envProxy) : void 0;
-    }
-    function getUrlFromProxySettings(settings) {
-      let parsedProxyUrl;
-      try {
-        parsedProxyUrl = new URL(settings.host);
-      } catch (_a) {
-        throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
-      }
-      parsedProxyUrl.port = String(settings.port);
-      if (settings.username) {
-        parsedProxyUrl.username = settings.username;
-      }
-      if (settings.password) {
-        parsedProxyUrl.password = settings.password;
-      }
-      return parsedProxyUrl;
-    }
-    function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
-      if (request.agent) {
-        return;
-      }
-      const url2 = new URL(request.url);
-      const isInsecure = url2.protocol !== "https:";
-      if (request.tlsSettings) {
-        log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
-      }
-      const headers = request.headers.toJSON();
-      if (isInsecure) {
-        if (!cachedAgents.httpProxyAgent) {
-          cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers });
-        }
-        request.agent = cachedAgents.httpProxyAgent;
-      } else {
-        if (!cachedAgents.httpsProxyAgent) {
-          cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers });
-        }
-        request.agent = cachedAgents.httpsProxyAgent;
-      }
+    function isExponentialRetryResponse(response) {
+      return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505);
     }
-    function proxyPolicy(proxySettings, options) {
-      if (!noProxyListLoaded) {
-        exports2.globalNoProxyList.push(...loadNoProxy());
+    function isSystemError(err) {
+      if (!err) {
+        return false;
       }
-      const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal();
-      const cachedAgents = {};
-      return {
-        name: exports2.proxyPolicyName,
-        async sendRequest(request, next) {
-          var _a;
-          if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) {
-            setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
-          } else if (request.proxySettings) {
-            setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
-          }
-          return next(request);
-        }
-      };
+      return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND";
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js
-var require_setClientRequestIdPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js
+var require_retryPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/retryPolicy.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.setClientRequestIdPolicyName = void 0;
-    exports2.setClientRequestIdPolicy = setClientRequestIdPolicy;
-    exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy";
-    function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
+    exports2.retryPolicy = retryPolicy;
+    var helpers_js_1 = require_helpers();
+    var logger_1 = require_dist();
+    var abort_controller_1 = require_commonjs3();
+    var constants_js_1 = require_constants8();
+    var retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy");
+    var retryPolicyName = "retryPolicy";
+    function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) {
+      const logger = options.logger || retryPolicyLogger;
       return {
-        name: exports2.setClientRequestIdPolicyName,
+        name: retryPolicyName,
         async sendRequest(request, next) {
-          if (!request.headers.has(requestIdHeaderName)) {
-            request.headers.set(requestIdHeaderName, request.requestId);
+          var _a, _b;
+          let response;
+          let responseError;
+          let retryCount = -1;
+          retryRequest: while (true) {
+            retryCount += 1;
+            response = void 0;
+            responseError = void 0;
+            try {
+              logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
+              response = await next(request);
+              logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
+            } catch (e) {
+              logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
+              responseError = e;
+              if (!e || responseError.name !== "RestError") {
+                throw e;
+              }
+              response = responseError.response;
+            }
+            if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
+              logger.error(`Retry ${retryCount}: Request aborted.`);
+              const abortError = new abort_controller_1.AbortError();
+              throw abortError;
+            }
+            if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) {
+              logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
+              if (responseError) {
+                throw responseError;
+              } else if (response) {
+                return response;
+              } else {
+                throw new Error("Maximum retries reached with no response or error to throw");
+              }
+            }
+            logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
+            strategiesLoop: for (const strategy of strategies) {
+              const strategyLogger = strategy.logger || retryPolicyLogger;
+              strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
+              const modifiers = strategy.retry({
+                retryCount,
+                response,
+                responseError
+              });
+              if (modifiers.skipStrategy) {
+                strategyLogger.info(`Retry ${retryCount}: Skipped.`);
+                continue strategiesLoop;
+              }
+              const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
+              if (errorToThrow) {
+                strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
+                throw errorToThrow;
+              }
+              if (retryAfterInMs || retryAfterInMs === 0) {
+                strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
+                await (0, helpers_js_1.delay)(retryAfterInMs, void 0, { abortSignal: request.abortSignal });
+                continue retryRequest;
+              }
+              if (redirectTo) {
+                strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
+                request.url = redirectTo;
+                continue retryRequest;
+              }
+            }
+            if (responseError) {
+              logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
+              throw responseError;
+            }
+            if (response) {
+              logger.info(`None of the retry strategies could work with the received response. Returning it.`);
+              return response;
+            }
           }
-          return next(request);
         }
       };
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js
-var require_tlsPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js
+var require_defaultRetryPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/defaultRetryPolicy.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.tlsPolicyName = void 0;
-    exports2.tlsPolicy = tlsPolicy;
-    exports2.tlsPolicyName = "tlsPolicy";
-    function tlsPolicy(tlsSettings) {
+    exports2.defaultRetryPolicyName = void 0;
+    exports2.defaultRetryPolicy = defaultRetryPolicy;
+    var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy();
+    var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy();
+    var retryPolicy_js_1 = require_retryPolicy();
+    var constants_js_1 = require_constants8();
+    exports2.defaultRetryPolicyName = "defaultRetryPolicy";
+    function defaultRetryPolicy(options = {}) {
+      var _a;
       return {
-        name: exports2.tlsPolicyName,
-        sendRequest: async (req, next) => {
-          if (!req.tlsSettings) {
-            req.tlsSettings = tlsSettings;
-          }
-          return next(req);
-        }
+        name: exports2.defaultRetryPolicyName,
+        sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], {
+          maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT
+        }).sendRequest
       };
     }
   }
 });
 
-// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js
-var require_tracingContext = __commonJS({
-  "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js
+var require_httpHeaders = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/httpHeaders.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0;
-    exports2.knownContextKeys = {
-      span: Symbol.for("@azure/core-tracing span"),
-      namespace: Symbol.for("@azure/core-tracing namespace")
-    };
-    function createTracingContext(options = {}) {
-      let context2 = new TracingContextImpl(options.parentContext);
-      if (options.span) {
-        context2 = context2.setValue(exports2.knownContextKeys.span, options.span);
-      }
-      if (options.namespace) {
-        context2 = context2.setValue(exports2.knownContextKeys.namespace, options.namespace);
-      }
-      return context2;
+    exports2.createHttpHeaders = createHttpHeaders;
+    function normalizeName(name) {
+      return name.toLowerCase();
     }
-    exports2.createTracingContext = createTracingContext;
-    var TracingContextImpl = class _TracingContextImpl {
-      constructor(initialContext) {
-        this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map();
-      }
-      setValue(key, value) {
-        const newContext = new _TracingContextImpl(this);
-        newContext._contextMap.set(key, value);
-        return newContext;
-      }
-      getValue(key) {
-        return this._contextMap.get(key);
-      }
-      deleteValue(key) {
-        const newContext = new _TracingContextImpl(this);
-        newContext._contextMap.delete(key);
-        return newContext;
+    function* headerIterator(map2) {
+      for (const entry of map2.values()) {
+        yield [entry.name, entry.value];
       }
-    };
-    exports2.TracingContextImpl = TracingContextImpl;
-  }
-});
-
-// node_modules/@azure/core-tracing/dist/commonjs/state.js
-var require_state = __commonJS({
-  "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.state = void 0;
-    exports2.state = {
-      instrumenterImplementation: void 0
-    };
-  }
-});
-
-// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js
-var require_instrumenter = __commonJS({
-  "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0;
-    var tracingContext_js_1 = require_tracingContext();
-    var state_js_1 = require_state();
-    function createDefaultTracingSpan() {
-      return {
-        end: () => {
-        },
-        isRecording: () => false,
-        recordException: () => {
-        },
-        setAttribute: () => {
-        },
-        setStatus: () => {
-        }
-      };
     }
-    exports2.createDefaultTracingSpan = createDefaultTracingSpan;
-    function createDefaultInstrumenter() {
-      return {
-        createRequestHeaders: () => {
-          return {};
-        },
-        parseTraceparentHeader: () => {
-          return void 0;
-        },
-        startSpan: (_name, spanOptions) => {
-          return {
-            span: createDefaultTracingSpan(),
-            tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext })
-          };
-        },
-        withContext(_context, callback, ...callbackArgs) {
-          return callback(...callbackArgs);
+    var HttpHeadersImpl = class {
+      constructor(rawHeaders) {
+        this._headersMap = /* @__PURE__ */ new Map();
+        if (rawHeaders) {
+          for (const headerName of Object.keys(rawHeaders)) {
+            this.set(headerName, rawHeaders[headerName]);
+          }
         }
-      };
-    }
-    exports2.createDefaultInstrumenter = createDefaultInstrumenter;
-    function useInstrumenter(instrumenter) {
-      state_js_1.state.instrumenterImplementation = instrumenter;
-    }
-    exports2.useInstrumenter = useInstrumenter;
-    function getInstrumenter() {
-      if (!state_js_1.state.instrumenterImplementation) {
-        state_js_1.state.instrumenterImplementation = createDefaultInstrumenter();
       }
-      return state_js_1.state.instrumenterImplementation;
-    }
-    exports2.getInstrumenter = getInstrumenter;
-  }
-});
-
-// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js
-var require_tracingClient = __commonJS({
-  "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createTracingClient = void 0;
-    var instrumenter_js_1 = require_instrumenter();
-    var tracingContext_js_1 = require_tracingContext();
-    function createTracingClient(options) {
-      const { namespace, packageName, packageVersion } = options;
-      function startSpan(name, operationOptions, spanOptions) {
-        var _a;
-        const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext }));
-        let tracingContext = startSpanResult.tracingContext;
-        const span = startSpanResult.span;
-        if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) {
-          tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace);
-        }
-        span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace));
-        const updatedOptions = Object.assign({}, operationOptions, {
-          tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext })
-        });
-        return {
-          span,
-          updatedOptions
-        };
+      /**
+       * Set a header in this collection with the provided name and value. The name is
+       * case-insensitive.
+       * @param name - The name of the header to set. This value is case-insensitive.
+       * @param value - The value of the header to set.
+       */
+      set(name, value) {
+        this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
       }
-      async function withSpan(name, operationOptions, callback, spanOptions) {
-        const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);
-        try {
-          const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span)));
-          span.setStatus({ status: "success" });
-          return result;
-        } catch (err) {
-          span.setStatus({ status: "error", error: err });
-          throw err;
-        } finally {
-          span.end();
-        }
+      /**
+       * Get the header value for the provided header name, or undefined if no header exists in this
+       * collection with the provided name.
+       * @param name - The name of the header. This value is case-insensitive.
+       */
+      get(name) {
+        var _a;
+        return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value;
       }
-      function withContext(context2, callback, ...callbackArgs) {
-        return (0, instrumenter_js_1.getInstrumenter)().withContext(context2, callback, ...callbackArgs);
+      /**
+       * Get whether or not this header collection contains a header entry for the provided header name.
+       * @param name - The name of the header to set. This value is case-insensitive.
+       */
+      has(name) {
+        return this._headersMap.has(normalizeName(name));
       }
-      function parseTraceparentHeader(traceparentHeader) {
-        return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader);
+      /**
+       * Remove the header with the provided headerName.
+       * @param name - The name of the header to remove.
+       */
+      delete(name) {
+        this._headersMap.delete(normalizeName(name));
       }
-      function createRequestHeaders(tracingContext) {
-        return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext);
+      /**
+       * Get the JSON object representation of this HTTP header collection.
+       */
+      toJSON(options = {}) {
+        const result = {};
+        if (options.preserveCase) {
+          for (const entry of this._headersMap.values()) {
+            result[entry.name] = entry.value;
+          }
+        } else {
+          for (const [normalizedName, entry] of this._headersMap) {
+            result[normalizedName] = entry.value;
+          }
+        }
+        return result;
       }
-      return {
-        startSpan,
-        withSpan,
-        withContext,
-        parseTraceparentHeader,
-        createRequestHeaders
-      };
-    }
-    exports2.createTracingClient = createTracingClient;
-  }
-});
-
-// node_modules/@azure/core-tracing/dist/commonjs/index.js
-var require_commonjs4 = __commonJS({
-  "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createTracingClient = exports2.useInstrumenter = void 0;
-    var instrumenter_js_1 = require_instrumenter();
-    Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() {
-      return instrumenter_js_1.useInstrumenter;
-    } });
-    var tracingClient_js_1 = require_tracingClient();
-    Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() {
-      return tracingClient_js_1.createTracingClient;
-    } });
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js
-var require_inspect = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.custom = void 0;
-    var node_util_1 = require("node:util");
-    exports2.custom = node_util_1.inspect.custom;
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js
-var require_restError = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.RestError = void 0;
-    exports2.isRestError = isRestError;
-    var core_util_1 = require_commonjs2();
-    var inspect_js_1 = require_inspect();
-    var sanitizer_js_1 = require_sanitizer();
-    var errorSanitizer = new sanitizer_js_1.Sanitizer();
-    var RestError = class _RestError extends Error {
-      constructor(message, options = {}) {
-        super(message);
-        this.name = "RestError";
-        this.code = options.code;
-        this.statusCode = options.statusCode;
-        Object.defineProperty(this, "request", { value: options.request, enumerable: false });
-        Object.defineProperty(this, "response", { value: options.response, enumerable: false });
-        Object.setPrototypeOf(this, _RestError.prototype);
+      /**
+       * Get the string representation of this HTTP header collection.
+       */
+      toString() {
+        return JSON.stringify(this.toJSON({ preserveCase: true }));
       }
       /**
-       * Logging method for util.inspect in Node
+       * Iterate over tuples of header [name, value] pairs.
        */
-      [inspect_js_1.custom]() {
-        return `RestError: ${this.message} 
- ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`;
+      [Symbol.iterator]() {
+        return headerIterator(this._headersMap);
       }
     };
-    exports2.RestError = RestError;
-    RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
-    RestError.PARSE_ERROR = "PARSE_ERROR";
-    function isRestError(e) {
-      if (e instanceof RestError) {
-        return true;
-      }
-      return (0, core_util_1.isError)(e) && e.name === "RestError";
+    function createHttpHeaders(rawHeaders) {
+      return new HttpHeadersImpl(rawHeaders);
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js
-var require_tracingPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) {
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js
+var require_formDataPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/formDataPolicy.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.tracingPolicyName = void 0;
-    exports2.tracingPolicy = tracingPolicy;
-    var core_tracing_1 = require_commonjs4();
-    var constants_js_1 = require_constants8();
-    var userAgent_js_1 = require_userAgent();
-    var log_js_1 = require_log();
+    exports2.formDataPolicyName = void 0;
+    exports2.formDataPolicy = formDataPolicy;
     var core_util_1 = require_commonjs2();
-    var restError_js_1 = require_restError();
-    var sanitizer_js_1 = require_sanitizer();
-    exports2.tracingPolicyName = "tracingPolicy";
-    function tracingPolicy(options = {}) {
-      const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
-      const sanitizer = new sanitizer_js_1.Sanitizer({
-        additionalAllowedQueryParameters: options.additionalAllowedQueryParameters
-      });
-      const tracingClient = tryCreateTracingClient();
+    var httpHeaders_js_1 = require_httpHeaders();
+    exports2.formDataPolicyName = "formDataPolicy";
+    function formDataToFormDataMap(formData) {
+      var _a;
+      const formDataMap = {};
+      for (const [key, value] of formData.entries()) {
+        (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : formDataMap[key] = [];
+        formDataMap[key].push(value);
+      }
+      return formDataMap;
+    }
+    function formDataPolicy() {
       return {
-        name: exports2.tracingPolicyName,
+        name: exports2.formDataPolicyName,
         async sendRequest(request, next) {
-          var _a;
-          if (!tracingClient) {
-            return next(request);
-          }
-          const userAgent = await userAgentPromise;
-          const spanAttributes = {
-            "http.url": sanitizer.sanitizeUrl(request.url),
-            "http.method": request.method,
-            "http.user_agent": userAgent,
-            requestId: request.requestId
-          };
-          if (userAgent) {
-            spanAttributes["http.user_agent"] = userAgent;
-          }
-          const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {};
-          if (!span || !tracingContext) {
-            return next(request);
+          if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
+            request.formData = formDataToFormDataMap(request.body);
+            request.body = void 0;
           }
-          try {
-            const response = await tracingClient.withContext(tracingContext, next, request);
-            tryProcessResponse(span, response);
-            return response;
-          } catch (err) {
-            tryProcessError(span, err);
-            throw err;
+          if (request.formData) {
+            const contentType = request.headers.get("Content-Type");
+            if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
+              request.body = wwwFormUrlEncode(request.formData);
+            } else {
+              await prepareFormData(request.formData, request);
+            }
+            request.formData = void 0;
           }
+          return next(request);
         }
       };
     }
-    function tryCreateTracingClient() {
-      try {
-        return (0, core_tracing_1.createTracingClient)({
-          namespace: "",
-          packageName: "@azure/core-rest-pipeline",
-          packageVersion: constants_js_1.SDK_VERSION
-        });
-      } catch (e) {
-        log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`);
-        return void 0;
-      }
-    }
-    function tryCreateSpan(tracingClient, request, spanAttributes) {
-      try {
-        const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
-          spanKind: "client",
-          spanAttributes
-        });
-        if (!span.isRecording()) {
-          span.end();
-          return void 0;
-        }
-        const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
-        for (const [key, value] of Object.entries(headers)) {
-          request.headers.set(key, value);
+    function wwwFormUrlEncode(formData) {
+      const urlSearchParams = new URLSearchParams();
+      for (const [key, value] of Object.entries(formData)) {
+        if (Array.isArray(value)) {
+          for (const subValue of value) {
+            urlSearchParams.append(key, subValue.toString());
+          }
+        } else {
+          urlSearchParams.append(key, value.toString());
         }
-        return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
-      } catch (e) {
-        log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
-        return void 0;
       }
+      return urlSearchParams.toString();
     }
-    function tryProcessError(span, error4) {
-      try {
-        span.setStatus({
-          status: "error",
-          error: (0, core_util_1.isError)(error4) ? error4 : void 0
-        });
-        if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) {
-          span.setAttribute("http.status_code", error4.statusCode);
-        }
-        span.end();
-      } catch (e) {
-        log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+    async function prepareFormData(formData, request) {
+      const contentType = request.headers.get("Content-Type");
+      if (contentType && !contentType.startsWith("multipart/form-data")) {
+        return;
       }
-    }
-    function tryProcessResponse(span, response) {
-      try {
-        span.setAttribute("http.status_code", response.status);
-        const serviceRequestId = response.headers.get("x-ms-request-id");
-        if (serviceRequestId) {
-          span.setAttribute("serviceRequestId", serviceRequestId);
+      request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data");
+      const parts = [];
+      for (const [fieldName, values] of Object.entries(formData)) {
+        for (const value of Array.isArray(values) ? values : [values]) {
+          if (typeof value === "string") {
+            parts.push({
+              headers: (0, httpHeaders_js_1.createHttpHeaders)({
+                "Content-Disposition": `form-data; name="${fieldName}"`
+              }),
+              body: (0, core_util_1.stringToUint8Array)(value, "utf-8")
+            });
+          } else if (value === void 0 || value === null || typeof value !== "object") {
+            throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
+          } else {
+            const fileName = value.name || "blob";
+            const headers = (0, httpHeaders_js_1.createHttpHeaders)();
+            headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
+            headers.set("Content-Type", value.type || "application/octet-stream");
+            parts.push({
+              headers,
+              body: value
+            });
+          }
         }
-        span.setStatus({
-          status: "success"
-        });
-        span.end();
-      } catch (e) {
-        log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
       }
+      request.multipartBody = { parts };
     }
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js
-var require_createPipelineFromOptions = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createPipelineFromOptions = createPipelineFromOptions;
-    var logPolicy_js_1 = require_logPolicy();
-    var pipeline_js_1 = require_pipeline();
-    var redirectPolicy_js_1 = require_redirectPolicy();
-    var userAgentPolicy_js_1 = require_userAgentPolicy();
-    var multipartPolicy_js_1 = require_multipartPolicy();
-    var decompressResponsePolicy_js_1 = require_decompressResponsePolicy();
-    var defaultRetryPolicy_js_1 = require_defaultRetryPolicy();
-    var formDataPolicy_js_1 = require_formDataPolicy();
-    var core_util_1 = require_commonjs2();
-    var proxyPolicy_js_1 = require_proxyPolicy();
-    var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy();
-    var tlsPolicy_js_1 = require_tlsPolicy();
-    var tracingPolicy_js_1 = require_tracingPolicy();
-    function createPipelineFromOptions(options) {
-      var _a;
-      const pipeline = (0, pipeline_js_1.createEmptyPipeline)();
-      if (core_util_1.isNodeLike) {
-        if (options.tlsOptions) {
-          pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions));
-        }
-        pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions));
-        pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)());
+// node_modules/ms/index.js
+var require_ms = __commonJS({
+  "node_modules/ms/index.js"(exports2, module2) {
+    var s = 1e3;
+    var m = s * 60;
+    var h = m * 60;
+    var d = h * 24;
+    var w = d * 7;
+    var y = d * 365.25;
+    module2.exports = function(val2, options) {
+      options = options || {};
+      var type2 = typeof val2;
+      if (type2 === "string" && val2.length > 0) {
+        return parse(val2);
+      } else if (type2 === "number" && isFinite(val2)) {
+        return options.long ? fmtLong(val2) : fmtShort(val2);
       }
-      pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] });
-      pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions));
-      pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName));
-      pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" });
-      pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" });
-      pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), {
-        afterPhase: "Retry"
-      });
-      if (core_util_1.isNodeLike) {
-        pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" });
+      throw new Error(
+        "val is not a non-empty string or a valid number. val=" + JSON.stringify(val2)
+      );
+    };
+    function parse(str2) {
+      str2 = String(str2);
+      if (str2.length > 100) {
+        return;
+      }
+      var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
+        str2
+      );
+      if (!match) {
+        return;
+      }
+      var n = parseFloat(match[1]);
+      var type2 = (match[2] || "ms").toLowerCase();
+      switch (type2) {
+        case "years":
+        case "year":
+        case "yrs":
+        case "yr":
+        case "y":
+          return n * y;
+        case "weeks":
+        case "week":
+        case "w":
+          return n * w;
+        case "days":
+        case "day":
+        case "d":
+          return n * d;
+        case "hours":
+        case "hour":
+        case "hrs":
+        case "hr":
+        case "h":
+          return n * h;
+        case "minutes":
+        case "minute":
+        case "mins":
+        case "min":
+        case "m":
+          return n * m;
+        case "seconds":
+        case "second":
+        case "secs":
+        case "sec":
+        case "s":
+          return n * s;
+        case "milliseconds":
+        case "millisecond":
+        case "msecs":
+        case "msec":
+        case "ms":
+          return n;
+        default:
+          return void 0;
       }
-      pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" });
-      return pipeline;
-    }
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js
-var require_nodeHttpClient = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getBodyLength = getBodyLength;
-    exports2.createNodeHttpClient = createNodeHttpClient;
-    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
-    var http = tslib_1.__importStar(require("node:http"));
-    var https2 = tslib_1.__importStar(require("node:https"));
-    var zlib2 = tslib_1.__importStar(require("node:zlib"));
-    var node_stream_1 = require("node:stream");
-    var abort_controller_1 = require_commonjs3();
-    var httpHeaders_js_1 = require_httpHeaders();
-    var restError_js_1 = require_restError();
-    var log_js_1 = require_log();
-    var DEFAULT_TLS_SETTINGS = {};
-    function isReadableStream(body) {
-      return body && typeof body.pipe === "function";
-    }
-    function isStreamComplete(stream2) {
-      return new Promise((resolve6) => {
-        const handler = () => {
-          resolve6();
-          stream2.removeListener("close", handler);
-          stream2.removeListener("end", handler);
-          stream2.removeListener("error", handler);
-        };
-        stream2.on("close", handler);
-        stream2.on("end", handler);
-        stream2.on("error", handler);
-      });
     }
-    function isArrayBuffer(body) {
-      return body && typeof body.byteLength === "number";
+    function fmtShort(ms) {
+      var msAbs = Math.abs(ms);
+      if (msAbs >= d) {
+        return Math.round(ms / d) + "d";
+      }
+      if (msAbs >= h) {
+        return Math.round(ms / h) + "h";
+      }
+      if (msAbs >= m) {
+        return Math.round(ms / m) + "m";
+      }
+      if (msAbs >= s) {
+        return Math.round(ms / s) + "s";
+      }
+      return ms + "ms";
     }
-    var ReportTransform = class extends node_stream_1.Transform {
-      // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
-      _transform(chunk, _encoding, callback) {
-        this.push(chunk);
-        this.loadedBytes += chunk.length;
-        try {
-          this.progressCallback({ loadedBytes: this.loadedBytes });
-          callback();
-        } catch (e) {
-          callback(e);
-        }
+    function fmtLong(ms) {
+      var msAbs = Math.abs(ms);
+      if (msAbs >= d) {
+        return plural(ms, msAbs, d, "day");
       }
-      constructor(progressCallback) {
-        super();
-        this.loadedBytes = 0;
-        this.progressCallback = progressCallback;
+      if (msAbs >= h) {
+        return plural(ms, msAbs, h, "hour");
       }
-    };
-    var NodeHttpClient = class {
-      constructor() {
-        this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap();
+      if (msAbs >= m) {
+        return plural(ms, msAbs, m, "minute");
       }
-      /**
-       * Makes a request over an underlying transport layer and returns the response.
-       * @param request - The request to be made.
-       */
-      async sendRequest(request) {
-        var _a, _b, _c;
-        const abortController = new AbortController();
-        let abortListener;
-        if (request.abortSignal) {
-          if (request.abortSignal.aborted) {
-            throw new abort_controller_1.AbortError("The operation was aborted.");
-          }
-          abortListener = (event) => {
-            if (event.type === "abort") {
-              abortController.abort();
-            }
-          };
-          request.abortSignal.addEventListener("abort", abortListener);
-        }
-        if (request.timeout > 0) {
-          setTimeout(() => {
-            abortController.abort();
-          }, request.timeout);
-        }
-        const acceptEncoding = request.headers.get("Accept-Encoding");
-        const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
-        let body = typeof request.body === "function" ? request.body() : request.body;
-        if (body && !request.headers.has("Content-Length")) {
-          const bodyLength = getBodyLength(body);
-          if (bodyLength !== null) {
-            request.headers.set("Content-Length", bodyLength);
-          }
+      if (msAbs >= s) {
+        return plural(ms, msAbs, s, "second");
+      }
+      return ms + " ms";
+    }
+    function plural(ms, msAbs, n, name) {
+      var isPlural = msAbs >= n * 1.5;
+      return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
+    }
+  }
+});
+
+// node_modules/debug/src/common.js
+var require_common = __commonJS({
+  "node_modules/debug/src/common.js"(exports2, module2) {
+    function setup(env) {
+      createDebug.debug = createDebug;
+      createDebug.default = createDebug;
+      createDebug.coerce = coerce3;
+      createDebug.disable = disable;
+      createDebug.enable = enable;
+      createDebug.enabled = enabled;
+      createDebug.humanize = require_ms();
+      createDebug.destroy = destroy;
+      Object.keys(env).forEach((key) => {
+        createDebug[key] = env[key];
+      });
+      createDebug.names = [];
+      createDebug.skips = [];
+      createDebug.formatters = {};
+      function selectColor(namespace) {
+        let hash2 = 0;
+        for (let i = 0; i < namespace.length; i++) {
+          hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
+          hash2 |= 0;
         }
-        let responseStream;
-        try {
-          if (body && request.onUploadProgress) {
-            const onUploadProgress = request.onUploadProgress;
-            const uploadReportStream = new ReportTransform(onUploadProgress);
-            uploadReportStream.on("error", (e) => {
-              log_js_1.logger.error("Error in upload progress", e);
-            });
-            if (isReadableStream(body)) {
-              body.pipe(uploadReportStream);
-            } else {
-              uploadReportStream.end(body);
-            }
-            body = uploadReportStream;
-          }
-          const res = await this.makeRequest(request, abortController, body);
-          const headers = getResponseHeaders(res);
-          const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
-          const response = {
-            status,
-            headers,
-            request
-          };
-          if (request.method === "HEAD") {
-            res.resume();
-            return response;
-          }
-          responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
-          const onDownloadProgress = request.onDownloadProgress;
-          if (onDownloadProgress) {
-            const downloadReportStream = new ReportTransform(onDownloadProgress);
-            downloadReportStream.on("error", (e) => {
-              log_js_1.logger.error("Error in download progress", e);
-            });
-            responseStream.pipe(downloadReportStream);
-            responseStream = downloadReportStream;
+        return createDebug.colors[Math.abs(hash2) % createDebug.colors.length];
+      }
+      createDebug.selectColor = selectColor;
+      function createDebug(namespace) {
+        let prevTime;
+        let enableOverride = null;
+        let namespacesCache;
+        let enabledCache;
+        function debug6(...args) {
+          if (!debug6.enabled) {
+            return;
           }
-          if (
-            // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
-            ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))
-          ) {
-            response.readableStreamBody = responseStream;
-          } else {
-            response.bodyAsText = await streamToText(responseStream);
+          const self2 = debug6;
+          const curr = Number(/* @__PURE__ */ new Date());
+          const ms = curr - (prevTime || curr);
+          self2.diff = ms;
+          self2.prev = prevTime;
+          self2.curr = curr;
+          prevTime = curr;
+          args[0] = createDebug.coerce(args[0]);
+          if (typeof args[0] !== "string") {
+            args.unshift("%O");
           }
-          return response;
-        } finally {
-          if (request.abortSignal && abortListener) {
-            let uploadStreamDone = Promise.resolve();
-            if (isReadableStream(body)) {
-              uploadStreamDone = isStreamComplete(body);
+          let index = 0;
+          args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
+            if (match === "%%") {
+              return "%";
             }
-            let downloadStreamDone = Promise.resolve();
-            if (isReadableStream(responseStream)) {
-              downloadStreamDone = isStreamComplete(responseStream);
+            index++;
+            const formatter = createDebug.formatters[format];
+            if (typeof formatter === "function") {
+              const val2 = args[index];
+              match = formatter.call(self2, val2);
+              args.splice(index, 1);
+              index--;
             }
-            Promise.all([uploadStreamDone, downloadStreamDone]).then(() => {
-              var _a2;
-              if (abortListener) {
-                (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener);
-              }
-            }).catch((e) => {
-              log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e);
-            });
+            return match;
+          });
+          createDebug.formatArgs.call(self2, args);
+          const logFn = self2.log || createDebug.log;
+          logFn.apply(self2, args);
+        }
+        debug6.namespace = namespace;
+        debug6.useColors = createDebug.useColors();
+        debug6.color = createDebug.selectColor(namespace);
+        debug6.extend = extend3;
+        debug6.destroy = createDebug.destroy;
+        Object.defineProperty(debug6, "enabled", {
+          enumerable: true,
+          configurable: false,
+          get: () => {
+            if (enableOverride !== null) {
+              return enableOverride;
+            }
+            if (namespacesCache !== createDebug.namespaces) {
+              namespacesCache = createDebug.namespaces;
+              enabledCache = createDebug.enabled(namespace);
+            }
+            return enabledCache;
+          },
+          set: (v) => {
+            enableOverride = v;
           }
+        });
+        if (typeof createDebug.init === "function") {
+          createDebug.init(debug6);
         }
+        return debug6;
       }
-      makeRequest(request, abortController, body) {
-        var _a;
-        const url2 = new URL(request.url);
-        const isInsecure = url2.protocol !== "https:";
-        if (isInsecure && !request.allowInsecureConnection) {
-          throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
+      function extend3(namespace, delimiter) {
+        const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
+        newDebug.log = this.log;
+        return newDebug;
+      }
+      function enable(namespaces) {
+        createDebug.save(namespaces);
+        createDebug.namespaces = namespaces;
+        createDebug.names = [];
+        createDebug.skips = [];
+        const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
+        for (const ns of split) {
+          if (ns[0] === "-") {
+            createDebug.skips.push(ns.slice(1));
+          } else {
+            createDebug.names.push(ns);
+          }
         }
-        const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure);
-        const options = {
-          agent,
-          hostname: url2.hostname,
-          path: `${url2.pathname}${url2.search}`,
-          port: url2.port,
-          method: request.method,
-          headers: request.headers.toJSON({ preserveCase: true })
-        };
-        return new Promise((resolve6, reject) => {
-          const req = isInsecure ? http.request(options, resolve6) : https2.request(options, resolve6);
-          req.once("error", (err) => {
-            var _a2;
-            reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request }));
-          });
-          abortController.signal.addEventListener("abort", () => {
-            const abortError = new abort_controller_1.AbortError("The operation was aborted.");
-            req.destroy(abortError);
-            reject(abortError);
-          });
-          if (body && isReadableStream(body)) {
-            body.pipe(req);
-          } else if (body) {
-            if (typeof body === "string" || Buffer.isBuffer(body)) {
-              req.end(body);
-            } else if (isArrayBuffer(body)) {
-              req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
+      }
+      function matchesTemplate(search, template) {
+        let searchIndex = 0;
+        let templateIndex = 0;
+        let starIndex = -1;
+        let matchIndex = 0;
+        while (searchIndex < search.length) {
+          if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
+            if (template[templateIndex] === "*") {
+              starIndex = templateIndex;
+              matchIndex = searchIndex;
+              templateIndex++;
             } else {
-              log_js_1.logger.error("Unrecognized body type", body);
-              reject(new restError_js_1.RestError("Unrecognized body type"));
+              searchIndex++;
+              templateIndex++;
             }
+          } else if (starIndex !== -1) {
+            templateIndex = starIndex + 1;
+            matchIndex++;
+            searchIndex = matchIndex;
           } else {
-            req.end();
+            return false;
           }
-        });
+        }
+        while (templateIndex < template.length && template[templateIndex] === "*") {
+          templateIndex++;
+        }
+        return templateIndex === template.length;
       }
-      getOrCreateAgent(request, isInsecure) {
-        var _a;
-        const disableKeepAlive = request.disableKeepAlive;
-        if (isInsecure) {
-          if (disableKeepAlive) {
-            return http.globalAgent;
-          }
-          if (!this.cachedHttpAgent) {
-            this.cachedHttpAgent = new http.Agent({ keepAlive: true });
-          }
-          return this.cachedHttpAgent;
-        } else {
-          if (disableKeepAlive && !request.tlsSettings) {
-            return https2.globalAgent;
-          }
-          const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS;
-          let agent = this.cachedHttpsAgents.get(tlsSettings);
-          if (agent && agent.options.keepAlive === !disableKeepAlive) {
-            return agent;
+      function disable() {
+        const namespaces = [
+          ...createDebug.names,
+          ...createDebug.skips.map((namespace) => "-" + namespace)
+        ].join(",");
+        createDebug.enable("");
+        return namespaces;
+      }
+      function enabled(name) {
+        for (const skip of createDebug.skips) {
+          if (matchesTemplate(name, skip)) {
+            return false;
           }
-          log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent");
-          agent = new https2.Agent(Object.assign({
-            // keepAlive is true if disableKeepAlive is false.
-            keepAlive: !disableKeepAlive
-          }, tlsSettings));
-          this.cachedHttpsAgents.set(tlsSettings, agent);
-          return agent;
         }
-      }
-    };
-    function getResponseHeaders(res) {
-      const headers = (0, httpHeaders_js_1.createHttpHeaders)();
-      for (const header of Object.keys(res.headers)) {
-        const value = res.headers[header];
-        if (Array.isArray(value)) {
-          if (value.length > 0) {
-            headers.set(header, value[0]);
+        for (const ns of createDebug.names) {
+          if (matchesTemplate(name, ns)) {
+            return true;
           }
-        } else if (value) {
-          headers.set(header, value);
         }
+        return false;
       }
-      return headers;
-    }
-    function getDecodedResponseStream(stream2, headers) {
-      const contentEncoding = headers.get("Content-Encoding");
-      if (contentEncoding === "gzip") {
-        const unzip = zlib2.createGunzip();
-        stream2.pipe(unzip);
-        return unzip;
-      } else if (contentEncoding === "deflate") {
-        const inflate = zlib2.createInflate();
-        stream2.pipe(inflate);
-        return inflate;
+      function coerce3(val2) {
+        if (val2 instanceof Error) {
+          return val2.stack || val2.message;
+        }
+        return val2;
       }
-      return stream2;
-    }
-    function streamToText(stream2) {
-      return new Promise((resolve6, reject) => {
-        const buffer = [];
-        stream2.on("data", (chunk) => {
-          if (Buffer.isBuffer(chunk)) {
-            buffer.push(chunk);
-          } else {
-            buffer.push(Buffer.from(chunk));
-          }
-        });
-        stream2.on("end", () => {
-          resolve6(Buffer.concat(buffer).toString("utf8"));
-        });
-        stream2.on("error", (e) => {
-          if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") {
-            reject(e);
-          } else {
-            reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, {
-              code: restError_js_1.RestError.PARSE_ERROR
-            }));
-          }
-        });
-      });
-    }
-    function getBodyLength(body) {
-      if (!body) {
-        return 0;
-      } else if (Buffer.isBuffer(body)) {
-        return body.length;
-      } else if (isReadableStream(body)) {
-        return null;
-      } else if (isArrayBuffer(body)) {
-        return body.byteLength;
-      } else if (typeof body === "string") {
-        return Buffer.from(body).length;
-      } else {
-        return null;
+      function destroy() {
+        console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
       }
+      createDebug.enable(createDebug.load());
+      return createDebug;
     }
-    function createNodeHttpClient() {
-      return new NodeHttpClient();
-    }
+    module2.exports = setup;
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js
-var require_defaultHttpClient = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createDefaultHttpClient = createDefaultHttpClient;
-    var nodeHttpClient_js_1 = require_nodeHttpClient();
-    function createDefaultHttpClient() {
-      return (0, nodeHttpClient_js_1.createNodeHttpClient)();
-    }
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js
-var require_pipelineRequest = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createPipelineRequest = createPipelineRequest;
-    var httpHeaders_js_1 = require_httpHeaders();
-    var core_util_1 = require_commonjs2();
-    var PipelineRequestImpl = class {
-      constructor(options) {
-        var _a, _b, _c, _d, _e, _f, _g;
-        this.url = options.url;
-        this.body = options.body;
-        this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)();
-        this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET";
-        this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0;
-        this.multipartBody = options.multipartBody;
-        this.formData = options.formData;
-        this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false;
-        this.proxySettings = options.proxySettings;
-        this.streamResponseStatusCodes = options.streamResponseStatusCodes;
-        this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false;
-        this.abortSignal = options.abortSignal;
-        this.tracingOptions = options.tracingOptions;
-        this.onUploadProgress = options.onUploadProgress;
-        this.onDownloadProgress = options.onDownloadProgress;
-        this.requestId = options.requestId || (0, core_util_1.randomUUID)();
-        this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false;
-        this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false;
+// node_modules/debug/src/browser.js
+var require_browser = __commonJS({
+  "node_modules/debug/src/browser.js"(exports2, module2) {
+    exports2.formatArgs = formatArgs;
+    exports2.save = save;
+    exports2.load = load2;
+    exports2.useColors = useColors;
+    exports2.storage = localstorage();
+    exports2.destroy = /* @__PURE__ */ (() => {
+      let warned = false;
+      return () => {
+        if (!warned) {
+          warned = true;
+          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
+        }
+      };
+    })();
+    exports2.colors = [
+      "#0000CC",
+      "#0000FF",
+      "#0033CC",
+      "#0033FF",
+      "#0066CC",
+      "#0066FF",
+      "#0099CC",
+      "#0099FF",
+      "#00CC00",
+      "#00CC33",
+      "#00CC66",
+      "#00CC99",
+      "#00CCCC",
+      "#00CCFF",
+      "#3300CC",
+      "#3300FF",
+      "#3333CC",
+      "#3333FF",
+      "#3366CC",
+      "#3366FF",
+      "#3399CC",
+      "#3399FF",
+      "#33CC00",
+      "#33CC33",
+      "#33CC66",
+      "#33CC99",
+      "#33CCCC",
+      "#33CCFF",
+      "#6600CC",
+      "#6600FF",
+      "#6633CC",
+      "#6633FF",
+      "#66CC00",
+      "#66CC33",
+      "#9900CC",
+      "#9900FF",
+      "#9933CC",
+      "#9933FF",
+      "#99CC00",
+      "#99CC33",
+      "#CC0000",
+      "#CC0033",
+      "#CC0066",
+      "#CC0099",
+      "#CC00CC",
+      "#CC00FF",
+      "#CC3300",
+      "#CC3333",
+      "#CC3366",
+      "#CC3399",
+      "#CC33CC",
+      "#CC33FF",
+      "#CC6600",
+      "#CC6633",
+      "#CC9900",
+      "#CC9933",
+      "#CCCC00",
+      "#CCCC33",
+      "#FF0000",
+      "#FF0033",
+      "#FF0066",
+      "#FF0099",
+      "#FF00CC",
+      "#FF00FF",
+      "#FF3300",
+      "#FF3333",
+      "#FF3366",
+      "#FF3399",
+      "#FF33CC",
+      "#FF33FF",
+      "#FF6600",
+      "#FF6633",
+      "#FF9900",
+      "#FF9933",
+      "#FFCC00",
+      "#FFCC33"
+    ];
+    function useColors() {
+      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
+        return true;
       }
-    };
-    function createPipelineRequest(options) {
-      return new PipelineRequestImpl(options);
+      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
+        return false;
+      }
+      let m;
+      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
+      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
+      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+      typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
+      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
     }
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js
-var require_exponentialRetryPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.exponentialRetryPolicyName = void 0;
-    exports2.exponentialRetryPolicy = exponentialRetryPolicy;
-    var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy();
-    var retryPolicy_js_1 = require_retryPolicy();
-    var constants_js_1 = require_constants8();
-    exports2.exponentialRetryPolicyName = "exponentialRetryPolicy";
-    function exponentialRetryPolicy(options = {}) {
-      var _a;
-      return (0, retryPolicy_js_1.retryPolicy)([
-        (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true }))
-      ], {
-        maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT
+    function formatArgs(args) {
+      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
+      if (!this.useColors) {
+        return;
+      }
+      const c = "color: " + this.color;
+      args.splice(1, 0, c, "color: inherit");
+      let index = 0;
+      let lastC = 0;
+      args[0].replace(/%[a-zA-Z%]/g, (match) => {
+        if (match === "%%") {
+          return;
+        }
+        index++;
+        if (match === "%c") {
+          lastC = index;
+        }
       });
+      args.splice(lastC, 0, c);
+    }
+    exports2.log = console.debug || console.log || (() => {
+    });
+    function save(namespaces) {
+      try {
+        if (namespaces) {
+          exports2.storage.setItem("debug", namespaces);
+        } else {
+          exports2.storage.removeItem("debug");
+        }
+      } catch (error4) {
+      }
+    }
+    function load2() {
+      let r;
+      try {
+        r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
+      } catch (error4) {
+      }
+      if (!r && typeof process !== "undefined" && "env" in process) {
+        r = process.env.DEBUG;
+      }
+      return r;
+    }
+    function localstorage() {
+      try {
+        return localStorage;
+      } catch (error4) {
+      }
     }
+    module2.exports = require_common()(exports2);
+    var { formatters } = module2.exports;
+    formatters.j = function(v) {
+      try {
+        return JSON.stringify(v);
+      } catch (error4) {
+        return "[UnexpectedJSONParseError]: " + error4.message;
+      }
+    };
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js
-var require_systemErrorRetryPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) {
+// node_modules/has-flag/index.js
+var require_has_flag = __commonJS({
+  "node_modules/has-flag/index.js"(exports2, module2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.systemErrorRetryPolicyName = void 0;
-    exports2.systemErrorRetryPolicy = systemErrorRetryPolicy;
-    var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy();
-    var retryPolicy_js_1 = require_retryPolicy();
-    var constants_js_1 = require_constants8();
-    exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy";
-    function systemErrorRetryPolicy(options = {}) {
-      var _a;
-      return {
-        name: exports2.systemErrorRetryPolicyName,
-        sendRequest: (0, retryPolicy_js_1.retryPolicy)([
-          (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true }))
-        ], {
-          maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT
-        }).sendRequest
-      };
-    }
+    module2.exports = (flag, argv = process.argv) => {
+      const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
+      const position = argv.indexOf(prefix + flag);
+      const terminatorPosition = argv.indexOf("--");
+      return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
+    };
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js
-var require_throttlingRetryPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) {
+// node_modules/supports-color/index.js
+var require_supports_color = __commonJS({
+  "node_modules/supports-color/index.js"(exports2, module2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.throttlingRetryPolicyName = void 0;
-    exports2.throttlingRetryPolicy = throttlingRetryPolicy;
-    var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy();
-    var retryPolicy_js_1 = require_retryPolicy();
-    var constants_js_1 = require_constants8();
-    exports2.throttlingRetryPolicyName = "throttlingRetryPolicy";
-    function throttlingRetryPolicy(options = {}) {
-      var _a;
+    var os3 = require("os");
+    var tty = require("tty");
+    var hasFlag = require_has_flag();
+    var { env } = process;
+    var forceColor;
+    if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
+      forceColor = 0;
+    } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
+      forceColor = 1;
+    }
+    if ("FORCE_COLOR" in env) {
+      if (env.FORCE_COLOR === "true") {
+        forceColor = 1;
+      } else if (env.FORCE_COLOR === "false") {
+        forceColor = 0;
+      } else {
+        forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
+      }
+    }
+    function translateLevel(level) {
+      if (level === 0) {
+        return false;
+      }
       return {
-        name: exports2.throttlingRetryPolicyName,
-        sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], {
-          maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT
-        }).sendRequest
+        level,
+        hasBasic: true,
+        has256: level >= 2,
+        has16m: level >= 3
       };
     }
-  }
-});
-
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js
-var require_tokenCycler = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.DEFAULT_CYCLER_OPTIONS = void 0;
-    exports2.createTokenCycler = createTokenCycler;
-    var helpers_js_1 = require_helpers();
-    exports2.DEFAULT_CYCLER_OPTIONS = {
-      forcedRefreshWindowInMs: 1e3,
-      // Force waiting for a refresh 1s before the token expires
-      retryIntervalInMs: 3e3,
-      // Allow refresh attempts every 3s
-      refreshWindowInMs: 1e3 * 60 * 2
-      // Start refreshing 2m before expiry
-    };
-    async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
-      async function tryGetAccessToken() {
-        if (Date.now() < refreshTimeout) {
-          try {
-            return await getAccessToken();
-          } catch (_a) {
-            return null;
-          }
-        } else {
-          const finalToken = await getAccessToken();
-          if (finalToken === null) {
-            throw new Error("Failed to refresh access token.");
-          }
-          return finalToken;
-        }
+    function supportsColor(haveStream, streamIsTTY) {
+      if (forceColor === 0) {
+        return 0;
       }
-      let token = await tryGetAccessToken();
-      while (token === null) {
-        await (0, helpers_js_1.delay)(retryIntervalInMs);
-        token = await tryGetAccessToken();
+      if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
+        return 3;
       }
-      return token;
-    }
-    function createTokenCycler(credential, tokenCyclerOptions) {
-      let refreshWorker = null;
-      let token = null;
-      let tenantId;
-      const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions);
-      const cycler = {
-        /**
-         * Produces true if a refresh job is currently in progress.
-         */
-        get isRefreshing() {
-          return refreshWorker !== null;
-        },
-        /**
-         * Produces true if the cycler SHOULD refresh (we are within the refresh
-         * window and not already refreshing)
-         */
-        get shouldRefresh() {
-          var _a;
-          if (cycler.isRefreshing) {
-            return false;
-          }
-          if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) {
-            return true;
-          }
-          return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now();
-        },
-        /**
-         * Produces true if the cycler MUST refresh (null or nearly-expired
-         * token).
-         */
-        get mustRefresh() {
-          return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now();
-        }
-      };
-      function refresh(scopes, getTokenOptions) {
-        var _a;
-        if (!cycler.isRefreshing) {
-          const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
-          refreshWorker = beginRefresh(
-            tryGetAccessToken,
-            options.retryIntervalInMs,
-            // If we don't have a token, then we should timeout immediately
-            (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()
-          ).then((_token) => {
-            refreshWorker = null;
-            token = _token;
-            tenantId = getTokenOptions.tenantId;
-            return token;
-          }).catch((reason) => {
-            refreshWorker = null;
-            token = null;
-            tenantId = void 0;
-            throw reason;
-          });
-        }
-        return refreshWorker;
+      if (hasFlag("color=256")) {
+        return 2;
       }
-      return async (scopes, tokenOptions) => {
-        const hasClaimChallenge = Boolean(tokenOptions.claims);
-        const tenantIdChanged = tenantId !== tokenOptions.tenantId;
-        if (hasClaimChallenge) {
-          token = null;
+      if (haveStream && !streamIsTTY && forceColor === void 0) {
+        return 0;
+      }
+      const min = forceColor || 0;
+      if (env.TERM === "dumb") {
+        return min;
+      }
+      if (process.platform === "win32") {
+        const osRelease = os3.release().split(".");
+        if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
+          return Number(osRelease[2]) >= 14931 ? 3 : 2;
         }
-        const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
-        if (mustRefresh) {
-          return refresh(scopes, tokenOptions);
+        return 1;
+      }
+      if ("CI" in env) {
+        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
+          return 1;
         }
-        if (cycler.shouldRefresh) {
-          refresh(scopes, tokenOptions);
+        return min;
+      }
+      if ("TEAMCITY_VERSION" in env) {
+        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
+      }
+      if (env.COLORTERM === "truecolor") {
+        return 3;
+      }
+      if ("TERM_PROGRAM" in env) {
+        const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
+        switch (env.TERM_PROGRAM) {
+          case "iTerm.app":
+            return version >= 3 ? 3 : 2;
+          case "Apple_Terminal":
+            return 2;
         }
-        return token;
-      };
+      }
+      if (/-256(color)?$/i.test(env.TERM)) {
+        return 2;
+      }
+      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
+        return 1;
+      }
+      if ("COLORTERM" in env) {
+        return 1;
+      }
+      return min;
+    }
+    function getSupportLevel(stream2) {
+      const level = supportsColor(stream2, stream2 && stream2.isTTY);
+      return translateLevel(level);
     }
+    module2.exports = {
+      supportsColor: getSupportLevel,
+      stdout: translateLevel(supportsColor(true, tty.isatty(1))),
+      stderr: translateLevel(supportsColor(true, tty.isatty(2)))
+    };
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js
-var require_bearerTokenAuthenticationPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.bearerTokenAuthenticationPolicyName = void 0;
-    exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy;
-    var tokenCycler_js_1 = require_tokenCycler();
-    var log_js_1 = require_log();
-    exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
-    async function defaultAuthorizeRequest(options) {
-      const { scopes, getAccessToken, request } = options;
-      const getTokenOptions = {
-        abortSignal: request.abortSignal,
-        tracingOptions: request.tracingOptions
-      };
-      const accessToken = await getAccessToken(scopes, getTokenOptions);
-      if (accessToken) {
-        options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
-      }
-    }
-    function getChallenge(response) {
-      const challenge = response.headers.get("WWW-Authenticate");
-      if (response.status === 401 && challenge) {
-        return challenge;
-      }
-      return;
-    }
-    function bearerTokenAuthenticationPolicy(options) {
-      var _a;
-      const { credential, scopes, challengeCallbacks } = options;
-      const logger = options.logger || log_js_1.logger;
-      const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks);
-      const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)(
-        credential
-        /* , options */
-      ) : () => Promise.resolve(null);
-      return {
-        name: exports2.bearerTokenAuthenticationPolicyName,
-        /**
-         * If there's no challenge parameter:
-         * - It will try to retrieve the token using the cache, or the credential's getToken.
-         * - Then it will try the next policy with or without the retrieved token.
-         *
-         * It uses the challenge parameters to:
-         * - Skip a first attempt to get the token from the credential if there's no cached token,
-         *   since it expects the token to be retrievable only after the challenge.
-         * - Prepare the outgoing request if the `prepareRequest` method has been provided.
-         * - Send an initial request to receive the challenge if it fails.
-         * - Process a challenge if the response contains it.
-         * - Retrieve a token with the challenge information, then re-send the request.
-         */
-        async sendRequest(request, next) {
-          if (!request.url.toLowerCase().startsWith("https://")) {
-            throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
-          }
-          await callbacks.authorizeRequest({
-            scopes: Array.isArray(scopes) ? scopes : [scopes],
-            request,
-            getAccessToken,
-            logger
-          });
-          let response;
-          let error4;
-          try {
-            response = await next(request);
-          } catch (err) {
-            error4 = err;
-            response = err.response;
-          }
-          if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) {
-            const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
-              scopes: Array.isArray(scopes) ? scopes : [scopes],
-              request,
-              response,
-              getAccessToken,
-              logger
-            });
-            if (shouldSendRequest) {
-              return next(request);
-            }
-          }
-          if (error4) {
-            throw error4;
-          } else {
-            return response;
-          }
-        }
-      };
+// node_modules/debug/src/node.js
+var require_node = __commonJS({
+  "node_modules/debug/src/node.js"(exports2, module2) {
+    var tty = require("tty");
+    var util = require("util");
+    exports2.init = init;
+    exports2.log = log;
+    exports2.formatArgs = formatArgs;
+    exports2.save = save;
+    exports2.load = load2;
+    exports2.useColors = useColors;
+    exports2.destroy = util.deprecate(
+      () => {
+      },
+      "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
+    );
+    exports2.colors = [6, 2, 3, 4, 5, 1];
+    try {
+      const supportsColor = require_supports_color();
+      if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
+        exports2.colors = [
+          20,
+          21,
+          26,
+          27,
+          32,
+          33,
+          38,
+          39,
+          40,
+          41,
+          42,
+          43,
+          44,
+          45,
+          56,
+          57,
+          62,
+          63,
+          68,
+          69,
+          74,
+          75,
+          76,
+          77,
+          78,
+          79,
+          80,
+          81,
+          92,
+          93,
+          98,
+          99,
+          112,
+          113,
+          128,
+          129,
+          134,
+          135,
+          148,
+          149,
+          160,
+          161,
+          162,
+          163,
+          164,
+          165,
+          166,
+          167,
+          168,
+          169,
+          170,
+          171,
+          172,
+          173,
+          178,
+          179,
+          184,
+          185,
+          196,
+          197,
+          198,
+          199,
+          200,
+          201,
+          202,
+          203,
+          204,
+          205,
+          206,
+          207,
+          208,
+          209,
+          214,
+          215,
+          220,
+          221
+        ];
+      }
+    } catch (error4) {
+    }
+    exports2.inspectOpts = Object.keys(process.env).filter((key) => {
+      return /^debug_/i.test(key);
+    }).reduce((obj, key) => {
+      const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
+        return k.toUpperCase();
+      });
+      let val2 = process.env[key];
+      if (/^(yes|on|true|enabled)$/i.test(val2)) {
+        val2 = true;
+      } else if (/^(no|off|false|disabled)$/i.test(val2)) {
+        val2 = false;
+      } else if (val2 === "null") {
+        val2 = null;
+      } else {
+        val2 = Number(val2);
+      }
+      obj[prop] = val2;
+      return obj;
+    }, {});
+    function useColors() {
+      return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd);
+    }
+    function formatArgs(args) {
+      const { namespace: name, useColors: useColors2 } = this;
+      if (useColors2) {
+        const c = this.color;
+        const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
+        const prefix = `  ${colorCode};1m${name} \x1B[0m`;
+        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
+        args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
+      } else {
+        args[0] = getDate() + name + " " + args[0];
+      }
+    }
+    function getDate() {
+      if (exports2.inspectOpts.hideDate) {
+        return "";
+      }
+      return (/* @__PURE__ */ new Date()).toISOString() + " ";
+    }
+    function log(...args) {
+      return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
+    }
+    function save(namespaces) {
+      if (namespaces) {
+        process.env.DEBUG = namespaces;
+      } else {
+        delete process.env.DEBUG;
+      }
+    }
+    function load2() {
+      return process.env.DEBUG;
     }
+    function init(debug6) {
+      debug6.inspectOpts = {};
+      const keys = Object.keys(exports2.inspectOpts);
+      for (let i = 0; i < keys.length; i++) {
+        debug6.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
+      }
+    }
+    module2.exports = require_common()(exports2);
+    var { formatters } = module2.exports;
+    formatters.o = function(v) {
+      this.inspectOpts.colors = this.useColors;
+      return util.inspect(v, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" ");
+    };
+    formatters.O = function(v) {
+      this.inspectOpts.colors = this.useColors;
+      return util.inspect(v, this.inspectOpts);
+    };
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js
-var require_ndJsonPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) {
+// node_modules/debug/src/index.js
+var require_src = __commonJS({
+  "node_modules/debug/src/index.js"(exports2, module2) {
+    if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
+      module2.exports = require_browser();
+    } else {
+      module2.exports = require_node();
+    }
+  }
+});
+
+// node_modules/agent-base/dist/helpers.js
+var require_helpers2 = __commonJS({
+  "node_modules/agent-base/dist/helpers.js"(exports2) {
     "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ndJsonPolicyName = void 0;
-    exports2.ndJsonPolicy = ndJsonPolicy;
-    exports2.ndJsonPolicyName = "ndJsonPolicy";
-    function ndJsonPolicy() {
-      return {
-        name: exports2.ndJsonPolicyName,
-        async sendRequest(request, next) {
-          if (typeof request.body === "string" && request.body.startsWith("[")) {
-            const body = JSON.parse(request.body);
-            if (Array.isArray(body)) {
-              request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
-            }
-          }
-          return next(request);
-        }
-      };
+    exports2.req = exports2.json = exports2.toBuffer = void 0;
+    var http = __importStar4(require("http"));
+    var https2 = __importStar4(require("https"));
+    async function toBuffer(stream2) {
+      let length = 0;
+      const chunks = [];
+      for await (const chunk of stream2) {
+        length += chunk.length;
+        chunks.push(chunk);
+      }
+      return Buffer.concat(chunks, length);
+    }
+    exports2.toBuffer = toBuffer;
+    async function json2(stream2) {
+      const buf = await toBuffer(stream2);
+      const str2 = buf.toString("utf8");
+      try {
+        return JSON.parse(str2);
+      } catch (_err) {
+        const err = _err;
+        err.message += ` (input: ${str2})`;
+        throw err;
+      }
+    }
+    exports2.json = json2;
+    function req(url2, opts = {}) {
+      const href = typeof url2 === "string" ? url2 : url2.href;
+      const req2 = (href.startsWith("https:") ? https2 : http).request(url2, opts);
+      const promise = new Promise((resolve6, reject) => {
+        req2.once("response", resolve6).once("error", reject).end();
+      });
+      req2.then = promise.then.bind(promise);
+      return req2;
     }
+    exports2.req = req;
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js
-var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) {
+// node_modules/agent-base/dist/index.js
+var require_dist2 = __commonJS({
+  "node_modules/agent-base/dist/index.js"(exports2) {
     "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __exportStar4 = exports2 && exports2.__exportStar || function(m, exports3) {
+      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding4(exports3, m, p);
+    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.auxiliaryAuthenticationHeaderPolicyName = void 0;
-    exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy;
-    var tokenCycler_js_1 = require_tokenCycler();
-    var log_js_1 = require_log();
-    exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
-    var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
-    async function sendAuthorizeRequest(options) {
-      var _a, _b;
-      const { scopes, getAccessToken, request } = options;
-      const getTokenOptions = {
-        abortSignal: request.abortSignal,
-        tracingOptions: request.tracingOptions
-      };
-      return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : "";
-    }
-    function auxiliaryAuthenticationHeaderPolicy(options) {
-      const { credentials, scopes } = options;
-      const logger = options.logger || log_js_1.logger;
-      const tokenCyclerMap = /* @__PURE__ */ new WeakMap();
-      return {
-        name: exports2.auxiliaryAuthenticationHeaderPolicyName,
-        async sendRequest(request, next) {
-          if (!request.url.toLowerCase().startsWith("https://")) {
-            throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
+    exports2.Agent = void 0;
+    var net = __importStar4(require("net"));
+    var http = __importStar4(require("http"));
+    var https_1 = require("https");
+    __exportStar4(require_helpers2(), exports2);
+    var INTERNAL = Symbol("AgentBaseInternalState");
+    var Agent = class extends http.Agent {
+      constructor(opts) {
+        super(opts);
+        this[INTERNAL] = {};
+      }
+      /**
+       * Determine whether this is an `http` or `https` request.
+       */
+      isSecureEndpoint(options) {
+        if (options) {
+          if (typeof options.secureEndpoint === "boolean") {
+            return options.secureEndpoint;
           }
-          if (!credentials || credentials.length === 0) {
-            logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
-            return next(request);
+          if (typeof options.protocol === "string") {
+            return options.protocol === "https:";
           }
-          const tokenPromises = [];
-          for (const credential of credentials) {
-            let getAccessToken = tokenCyclerMap.get(credential);
-            if (!getAccessToken) {
-              getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential);
-              tokenCyclerMap.set(credential, getAccessToken);
-            }
-            tokenPromises.push(sendAuthorizeRequest({
-              scopes: Array.isArray(scopes) ? scopes : [scopes],
-              request,
-              getAccessToken,
-              logger
-            }));
+        }
+        const { stack } = new Error();
+        if (typeof stack !== "string")
+          return false;
+        return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1);
+      }
+      // In order to support async signatures in `connect()` and Node's native
+      // connection pooling in `http.Agent`, the array of sockets for each origin
+      // has to be updated synchronously. This is so the length of the array is
+      // accurate when `addRequest()` is next called. We achieve this by creating a
+      // fake socket and adding it to `sockets[origin]` and incrementing
+      // `totalSocketCount`.
+      incrementSockets(name) {
+        if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
+          return null;
+        }
+        if (!this.sockets[name]) {
+          this.sockets[name] = [];
+        }
+        const fakeSocket = new net.Socket({ writable: false });
+        this.sockets[name].push(fakeSocket);
+        this.totalSocketCount++;
+        return fakeSocket;
+      }
+      decrementSockets(name, socket) {
+        if (!this.sockets[name] || socket === null) {
+          return;
+        }
+        const sockets = this.sockets[name];
+        const index = sockets.indexOf(socket);
+        if (index !== -1) {
+          sockets.splice(index, 1);
+          this.totalSocketCount--;
+          if (sockets.length === 0) {
+            delete this.sockets[name];
           }
-          const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
-          if (auxiliaryTokens.length === 0) {
-            logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
-            return next(request);
+        }
+      }
+      // In order to properly update the socket pool, we need to call `getName()` on
+      // the core `https.Agent` if it is a secureEndpoint.
+      getName(options) {
+        const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options);
+        if (secureEndpoint) {
+          return https_1.Agent.prototype.getName.call(this, options);
+        }
+        return super.getName(options);
+      }
+      createSocket(req, options, cb) {
+        const connectOpts = {
+          ...options,
+          secureEndpoint: this.isSecureEndpoint(options)
+        };
+        const name = this.getName(connectOpts);
+        const fakeSocket = this.incrementSockets(name);
+        Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
+          this.decrementSockets(name, fakeSocket);
+          if (socket instanceof http.Agent) {
+            try {
+              return socket.addRequest(req, connectOpts);
+            } catch (err) {
+              return cb(err);
+            }
           }
-          request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
-          return next(request);
+          this[INTERNAL].currentSocket = socket;
+          super.createSocket(req, options, cb);
+        }, (err) => {
+          this.decrementSockets(name, fakeSocket);
+          cb(err);
+        });
+      }
+      createConnection() {
+        const socket = this[INTERNAL].currentSocket;
+        this[INTERNAL].currentSocket = void 0;
+        if (!socket) {
+          throw new Error("No socket was returned in the `connect()` function");
         }
-      };
-    }
+        return socket;
+      }
+      get defaultPort() {
+        return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
+      }
+      set defaultPort(v) {
+        if (this[INTERNAL]) {
+          this[INTERNAL].defaultPort = v;
+        }
+      }
+      get protocol() {
+        return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
+      }
+      set protocol(v) {
+        if (this[INTERNAL]) {
+          this[INTERNAL].protocol = v;
+        }
+      }
+    };
+    exports2.Agent = Agent;
   }
 });
 
-// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js
-var require_commonjs5 = __commonJS({
-  "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) {
+// node_modules/https-proxy-agent/dist/parse-proxy-response.js
+var require_parse_proxy_response = __commonJS({
+  "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) {
     "use strict";
+    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
+      return mod && mod.__esModule ? mod : { "default": mod };
+    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0;
-    var pipeline_js_1 = require_pipeline();
-    Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() {
+    exports2.parseProxyResponse = void 0;
+    var debug_1 = __importDefault4(require_src());
+    var debug6 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
+    function parseProxyResponse(socket) {
+      return new Promise((resolve6, reject) => {
+        let buffersLength = 0;
+        const buffers = [];
+        function read() {
+          const b = socket.read();
+          if (b)
+            ondata(b);
+          else
+            socket.once("readable", read);
+        }
+        function cleanup() {
+          socket.removeListener("end", onend);
+          socket.removeListener("error", onerror);
+          socket.removeListener("readable", read);
+        }
+        function onend() {
+          cleanup();
+          debug6("onend");
+          reject(new Error("Proxy connection ended before receiving CONNECT response"));
+        }
+        function onerror(err) {
+          cleanup();
+          debug6("onerror %o", err);
+          reject(err);
+        }
+        function ondata(b) {
+          buffers.push(b);
+          buffersLength += b.length;
+          const buffered = Buffer.concat(buffers, buffersLength);
+          const endOfHeaders = buffered.indexOf("\r\n\r\n");
+          if (endOfHeaders === -1) {
+            debug6("have not received end of HTTP headers yet...");
+            read();
+            return;
+          }
+          const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n");
+          const firstLine = headerParts.shift();
+          if (!firstLine) {
+            socket.destroy();
+            return reject(new Error("No header received from proxy CONNECT response"));
+          }
+          const firstLineParts = firstLine.split(" ");
+          const statusCode = +firstLineParts[1];
+          const statusText = firstLineParts.slice(2).join(" ");
+          const headers = {};
+          for (const header of headerParts) {
+            if (!header)
+              continue;
+            const firstColon = header.indexOf(":");
+            if (firstColon === -1) {
+              socket.destroy();
+              return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
+            }
+            const key = header.slice(0, firstColon).toLowerCase();
+            const value = header.slice(firstColon + 1).trimStart();
+            const current = headers[key];
+            if (typeof current === "string") {
+              headers[key] = [current, value];
+            } else if (Array.isArray(current)) {
+              current.push(value);
+            } else {
+              headers[key] = value;
+            }
+          }
+          debug6("got proxy server response: %o %o", firstLine, headers);
+          cleanup();
+          resolve6({
+            connect: {
+              statusCode,
+              statusText,
+              headers
+            },
+            buffered
+          });
+        }
+        socket.on("error", onerror);
+        socket.on("end", onend);
+        read();
+      });
+    }
+    exports2.parseProxyResponse = parseProxyResponse;
+  }
+});
+
+// node_modules/https-proxy-agent/dist/index.js
+var require_dist3 = __commonJS({
+  "node_modules/https-proxy-agent/dist/index.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
+      return mod && mod.__esModule ? mod : { "default": mod };
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.HttpsProxyAgent = void 0;
+    var net = __importStar4(require("net"));
+    var tls = __importStar4(require("tls"));
+    var assert_1 = __importDefault4(require("assert"));
+    var debug_1 = __importDefault4(require_src());
+    var agent_base_1 = require_dist2();
+    var url_1 = require("url");
+    var parse_proxy_response_1 = require_parse_proxy_response();
+    var debug6 = (0, debug_1.default)("https-proxy-agent");
+    var setServernameFromNonIpHost = (options) => {
+      if (options.servername === void 0 && options.host && !net.isIP(options.host)) {
+        return {
+          ...options,
+          servername: options.host
+        };
+      }
+      return options;
+    };
+    var HttpsProxyAgent = class extends agent_base_1.Agent {
+      constructor(proxy, opts) {
+        super(opts);
+        this.options = { path: void 0 };
+        this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy;
+        this.proxyHeaders = opts?.headers ?? {};
+        debug6("Creating new HttpsProxyAgent instance: %o", this.proxy.href);
+        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
+        const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80;
+        this.connectOpts = {
+          // Attempt to negotiate http/1.1 for proxy servers that support http/2
+          ALPNProtocols: ["http/1.1"],
+          ...opts ? omit(opts, "headers") : null,
+          host,
+          port
+        };
+      }
+      /**
+       * Called when the node-core HTTP client library is creating a
+       * new HTTP request.
+       */
+      async connect(req, opts) {
+        const { proxy } = this;
+        if (!opts.host) {
+          throw new TypeError('No "host" provided');
+        }
+        let socket;
+        if (proxy.protocol === "https:") {
+          debug6("Creating `tls.Socket`: %o", this.connectOpts);
+          socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
+        } else {
+          debug6("Creating `net.Socket`: %o", this.connectOpts);
+          socket = net.connect(this.connectOpts);
+        }
+        const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
+        const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
+        let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r
+`;
+        if (proxy.username || proxy.password) {
+          const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
+          headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
+        }
+        headers.Host = `${host}:${opts.port}`;
+        if (!headers["Proxy-Connection"]) {
+          headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
+        }
+        for (const name of Object.keys(headers)) {
+          payload += `${name}: ${headers[name]}\r
+`;
+        }
+        const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
+        socket.write(`${payload}\r
+`);
+        const { connect, buffered } = await proxyResponsePromise;
+        req.emit("proxyConnect", connect);
+        this.emit("proxyConnect", connect, req);
+        if (connect.statusCode === 200) {
+          req.once("socket", resume);
+          if (opts.secureEndpoint) {
+            debug6("Upgrading socket connection to TLS");
+            return tls.connect({
+              ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"),
+              socket
+            });
+          }
+          return socket;
+        }
+        socket.destroy();
+        const fakeSocket = new net.Socket({ writable: false });
+        fakeSocket.readable = true;
+        req.once("socket", (s) => {
+          debug6("Replaying proxy buffer for failed request");
+          (0, assert_1.default)(s.listenerCount("data") > 0);
+          s.push(buffered);
+          s.push(null);
+        });
+        return fakeSocket;
+      }
+    };
+    HttpsProxyAgent.protocols = ["http", "https"];
+    exports2.HttpsProxyAgent = HttpsProxyAgent;
+    function resume(socket) {
+      socket.resume();
+    }
+    function omit(obj, ...keys) {
+      const ret = {};
+      let key;
+      for (key in obj) {
+        if (!keys.includes(key)) {
+          ret[key] = obj[key];
+        }
+      }
+      return ret;
+    }
+  }
+});
+
+// node_modules/http-proxy-agent/dist/index.js
+var require_dist4 = __commonJS({
+  "node_modules/http-proxy-agent/dist/index.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __importDefault4 = exports2 && exports2.__importDefault || function(mod) {
+      return mod && mod.__esModule ? mod : { "default": mod };
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.HttpProxyAgent = void 0;
+    var net = __importStar4(require("net"));
+    var tls = __importStar4(require("tls"));
+    var debug_1 = __importDefault4(require_src());
+    var events_1 = require("events");
+    var agent_base_1 = require_dist2();
+    var url_1 = require("url");
+    var debug6 = (0, debug_1.default)("http-proxy-agent");
+    var HttpProxyAgent = class extends agent_base_1.Agent {
+      constructor(proxy, opts) {
+        super(opts);
+        this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy;
+        this.proxyHeaders = opts?.headers ?? {};
+        debug6("Creating new HttpProxyAgent instance: %o", this.proxy.href);
+        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
+        const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80;
+        this.connectOpts = {
+          ...opts ? omit(opts, "headers") : null,
+          host,
+          port
+        };
+      }
+      addRequest(req, opts) {
+        req._header = null;
+        this.setRequestProps(req, opts);
+        super.addRequest(req, opts);
+      }
+      setRequestProps(req, opts) {
+        const { proxy } = this;
+        const protocol = opts.secureEndpoint ? "https:" : "http:";
+        const hostname = req.getHeader("host") || "localhost";
+        const base = `${protocol}//${hostname}`;
+        const url2 = new url_1.URL(req.path, base);
+        if (opts.port !== 80) {
+          url2.port = String(opts.port);
+        }
+        req.path = String(url2);
+        const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
+        if (proxy.username || proxy.password) {
+          const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
+          headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
+        }
+        if (!headers["Proxy-Connection"]) {
+          headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
+        }
+        for (const name of Object.keys(headers)) {
+          const value = headers[name];
+          if (value) {
+            req.setHeader(name, value);
+          }
+        }
+      }
+      async connect(req, opts) {
+        req._header = null;
+        if (!req.path.includes("://")) {
+          this.setRequestProps(req, opts);
+        }
+        let first;
+        let endOfHeaders;
+        debug6("Regenerating stored HTTP header string for request");
+        req._implicitHeader();
+        if (req.outputData && req.outputData.length > 0) {
+          debug6("Patching connection write() output buffer with updated header");
+          first = req.outputData[0].data;
+          endOfHeaders = first.indexOf("\r\n\r\n") + 4;
+          req.outputData[0].data = req._header + first.substring(endOfHeaders);
+          debug6("Output buffer: %o", req.outputData[0].data);
+        }
+        let socket;
+        if (this.proxy.protocol === "https:") {
+          debug6("Creating `tls.Socket`: %o", this.connectOpts);
+          socket = tls.connect(this.connectOpts);
+        } else {
+          debug6("Creating `net.Socket`: %o", this.connectOpts);
+          socket = net.connect(this.connectOpts);
+        }
+        await (0, events_1.once)(socket, "connect");
+        return socket;
+      }
+    };
+    HttpProxyAgent.protocols = ["http", "https"];
+    exports2.HttpProxyAgent = HttpProxyAgent;
+    function omit(obj, ...keys) {
+      const ret = {};
+      let key;
+      for (key in obj) {
+        if (!keys.includes(key)) {
+          ret[key] = obj[key];
+        }
+      }
+      return ret;
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js
+var require_proxyPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/proxyPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.globalNoProxyList = exports2.proxyPolicyName = void 0;
+    exports2.loadNoProxy = loadNoProxy;
+    exports2.getDefaultProxySettings = getDefaultProxySettings;
+    exports2.proxyPolicy = proxyPolicy;
+    var https_proxy_agent_1 = require_dist3();
+    var http_proxy_agent_1 = require_dist4();
+    var log_js_1 = require_log();
+    var HTTPS_PROXY = "HTTPS_PROXY";
+    var HTTP_PROXY = "HTTP_PROXY";
+    var ALL_PROXY = "ALL_PROXY";
+    var NO_PROXY = "NO_PROXY";
+    exports2.proxyPolicyName = "proxyPolicy";
+    exports2.globalNoProxyList = [];
+    var noProxyListLoaded = false;
+    var globalBypassedMap = /* @__PURE__ */ new Map();
+    function getEnvironmentValue(name) {
+      if (process.env[name]) {
+        return process.env[name];
+      } else if (process.env[name.toLowerCase()]) {
+        return process.env[name.toLowerCase()];
+      }
+      return void 0;
+    }
+    function loadEnvironmentProxyValue() {
+      if (!process) {
+        return void 0;
+      }
+      const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
+      const allProxy = getEnvironmentValue(ALL_PROXY);
+      const httpProxy = getEnvironmentValue(HTTP_PROXY);
+      return httpsProxy || allProxy || httpProxy;
+    }
+    function isBypassed(uri, noProxyList, bypassedMap) {
+      if (noProxyList.length === 0) {
+        return false;
+      }
+      const host = new URL(uri).hostname;
+      if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) {
+        return bypassedMap.get(host);
+      }
+      let isBypassedFlag = false;
+      for (const pattern of noProxyList) {
+        if (pattern[0] === ".") {
+          if (host.endsWith(pattern)) {
+            isBypassedFlag = true;
+          } else {
+            if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
+              isBypassedFlag = true;
+            }
+          }
+        } else {
+          if (host === pattern) {
+            isBypassedFlag = true;
+          }
+        }
+      }
+      bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag);
+      return isBypassedFlag;
+    }
+    function loadNoProxy() {
+      const noProxy = getEnvironmentValue(NO_PROXY);
+      noProxyListLoaded = true;
+      if (noProxy) {
+        return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length);
+      }
+      return [];
+    }
+    function getDefaultProxySettings(proxyUrl) {
+      if (!proxyUrl) {
+        proxyUrl = loadEnvironmentProxyValue();
+        if (!proxyUrl) {
+          return void 0;
+        }
+      }
+      const parsedUrl = new URL(proxyUrl);
+      const schema2 = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
+      return {
+        host: schema2 + parsedUrl.hostname,
+        port: Number.parseInt(parsedUrl.port || "80"),
+        username: parsedUrl.username,
+        password: parsedUrl.password
+      };
+    }
+    function getDefaultProxySettingsInternal() {
+      const envProxy = loadEnvironmentProxyValue();
+      return envProxy ? new URL(envProxy) : void 0;
+    }
+    function getUrlFromProxySettings(settings) {
+      let parsedProxyUrl;
+      try {
+        parsedProxyUrl = new URL(settings.host);
+      } catch (_a) {
+        throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
+      }
+      parsedProxyUrl.port = String(settings.port);
+      if (settings.username) {
+        parsedProxyUrl.username = settings.username;
+      }
+      if (settings.password) {
+        parsedProxyUrl.password = settings.password;
+      }
+      return parsedProxyUrl;
+    }
+    function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
+      if (request.agent) {
+        return;
+      }
+      const url2 = new URL(request.url);
+      const isInsecure = url2.protocol !== "https:";
+      if (request.tlsSettings) {
+        log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
+      }
+      const headers = request.headers.toJSON();
+      if (isInsecure) {
+        if (!cachedAgents.httpProxyAgent) {
+          cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers });
+        }
+        request.agent = cachedAgents.httpProxyAgent;
+      } else {
+        if (!cachedAgents.httpsProxyAgent) {
+          cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers });
+        }
+        request.agent = cachedAgents.httpsProxyAgent;
+      }
+    }
+    function proxyPolicy(proxySettings, options) {
+      if (!noProxyListLoaded) {
+        exports2.globalNoProxyList.push(...loadNoProxy());
+      }
+      const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal();
+      const cachedAgents = {};
+      return {
+        name: exports2.proxyPolicyName,
+        async sendRequest(request, next) {
+          var _a;
+          if (!request.proxySettings && defaultProxy && !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports2.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? void 0 : globalBypassedMap)) {
+            setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
+          } else if (request.proxySettings) {
+            setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
+          }
+          return next(request);
+        }
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js
+var require_setClientRequestIdPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/setClientRequestIdPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.setClientRequestIdPolicyName = void 0;
+    exports2.setClientRequestIdPolicy = setClientRequestIdPolicy;
+    exports2.setClientRequestIdPolicyName = "setClientRequestIdPolicy";
+    function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
+      return {
+        name: exports2.setClientRequestIdPolicyName,
+        async sendRequest(request, next) {
+          if (!request.headers.has(requestIdHeaderName)) {
+            request.headers.set(requestIdHeaderName, request.requestId);
+          }
+          return next(request);
+        }
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js
+var require_tlsPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tlsPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.tlsPolicyName = void 0;
+    exports2.tlsPolicy = tlsPolicy;
+    exports2.tlsPolicyName = "tlsPolicy";
+    function tlsPolicy(tlsSettings) {
+      return {
+        name: exports2.tlsPolicyName,
+        sendRequest: async (req, next) => {
+          if (!req.tlsSettings) {
+            req.tlsSettings = tlsSettings;
+          }
+          return next(req);
+        }
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js
+var require_tracingContext = __commonJS({
+  "node_modules/@azure/core-tracing/dist/commonjs/tracingContext.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.TracingContextImpl = exports2.createTracingContext = exports2.knownContextKeys = void 0;
+    exports2.knownContextKeys = {
+      span: Symbol.for("@azure/core-tracing span"),
+      namespace: Symbol.for("@azure/core-tracing namespace")
+    };
+    function createTracingContext(options = {}) {
+      let context2 = new TracingContextImpl(options.parentContext);
+      if (options.span) {
+        context2 = context2.setValue(exports2.knownContextKeys.span, options.span);
+      }
+      if (options.namespace) {
+        context2 = context2.setValue(exports2.knownContextKeys.namespace, options.namespace);
+      }
+      return context2;
+    }
+    exports2.createTracingContext = createTracingContext;
+    var TracingContextImpl = class _TracingContextImpl {
+      constructor(initialContext) {
+        this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map();
+      }
+      setValue(key, value) {
+        const newContext = new _TracingContextImpl(this);
+        newContext._contextMap.set(key, value);
+        return newContext;
+      }
+      getValue(key) {
+        return this._contextMap.get(key);
+      }
+      deleteValue(key) {
+        const newContext = new _TracingContextImpl(this);
+        newContext._contextMap.delete(key);
+        return newContext;
+      }
+    };
+    exports2.TracingContextImpl = TracingContextImpl;
+  }
+});
+
+// node_modules/@azure/core-tracing/dist/commonjs/state.js
+var require_state = __commonJS({
+  "node_modules/@azure/core-tracing/dist/commonjs/state.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.state = void 0;
+    exports2.state = {
+      instrumenterImplementation: void 0
+    };
+  }
+});
+
+// node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js
+var require_instrumenter = __commonJS({
+  "node_modules/@azure/core-tracing/dist/commonjs/instrumenter.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getInstrumenter = exports2.useInstrumenter = exports2.createDefaultInstrumenter = exports2.createDefaultTracingSpan = void 0;
+    var tracingContext_js_1 = require_tracingContext();
+    var state_js_1 = require_state();
+    function createDefaultTracingSpan() {
+      return {
+        end: () => {
+        },
+        isRecording: () => false,
+        recordException: () => {
+        },
+        setAttribute: () => {
+        },
+        setStatus: () => {
+        }
+      };
+    }
+    exports2.createDefaultTracingSpan = createDefaultTracingSpan;
+    function createDefaultInstrumenter() {
+      return {
+        createRequestHeaders: () => {
+          return {};
+        },
+        parseTraceparentHeader: () => {
+          return void 0;
+        },
+        startSpan: (_name, spanOptions) => {
+          return {
+            span: createDefaultTracingSpan(),
+            tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext })
+          };
+        },
+        withContext(_context, callback, ...callbackArgs) {
+          return callback(...callbackArgs);
+        }
+      };
+    }
+    exports2.createDefaultInstrumenter = createDefaultInstrumenter;
+    function useInstrumenter(instrumenter) {
+      state_js_1.state.instrumenterImplementation = instrumenter;
+    }
+    exports2.useInstrumenter = useInstrumenter;
+    function getInstrumenter() {
+      if (!state_js_1.state.instrumenterImplementation) {
+        state_js_1.state.instrumenterImplementation = createDefaultInstrumenter();
+      }
+      return state_js_1.state.instrumenterImplementation;
+    }
+    exports2.getInstrumenter = getInstrumenter;
+  }
+});
+
+// node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js
+var require_tracingClient = __commonJS({
+  "node_modules/@azure/core-tracing/dist/commonjs/tracingClient.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.createTracingClient = void 0;
+    var instrumenter_js_1 = require_instrumenter();
+    var tracingContext_js_1 = require_tracingContext();
+    function createTracingClient(options) {
+      const { namespace, packageName, packageVersion } = options;
+      function startSpan(name, operationOptions, spanOptions) {
+        var _a;
+        const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName, packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext }));
+        let tracingContext = startSpanResult.tracingContext;
+        const span = startSpanResult.span;
+        if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) {
+          tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace);
+        }
+        span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace));
+        const updatedOptions = Object.assign({}, operationOptions, {
+          tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext })
+        });
+        return {
+          span,
+          updatedOptions
+        };
+      }
+      async function withSpan(name, operationOptions, callback, spanOptions) {
+        const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);
+        try {
+          const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span)));
+          span.setStatus({ status: "success" });
+          return result;
+        } catch (err) {
+          span.setStatus({ status: "error", error: err });
+          throw err;
+        } finally {
+          span.end();
+        }
+      }
+      function withContext(context2, callback, ...callbackArgs) {
+        return (0, instrumenter_js_1.getInstrumenter)().withContext(context2, callback, ...callbackArgs);
+      }
+      function parseTraceparentHeader(traceparentHeader) {
+        return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader);
+      }
+      function createRequestHeaders(tracingContext) {
+        return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext);
+      }
+      return {
+        startSpan,
+        withSpan,
+        withContext,
+        parseTraceparentHeader,
+        createRequestHeaders
+      };
+    }
+    exports2.createTracingClient = createTracingClient;
+  }
+});
+
+// node_modules/@azure/core-tracing/dist/commonjs/index.js
+var require_commonjs4 = __commonJS({
+  "node_modules/@azure/core-tracing/dist/commonjs/index.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.createTracingClient = exports2.useInstrumenter = void 0;
+    var instrumenter_js_1 = require_instrumenter();
+    Object.defineProperty(exports2, "useInstrumenter", { enumerable: true, get: function() {
+      return instrumenter_js_1.useInstrumenter;
+    } });
+    var tracingClient_js_1 = require_tracingClient();
+    Object.defineProperty(exports2, "createTracingClient", { enumerable: true, get: function() {
+      return tracingClient_js_1.createTracingClient;
+    } });
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js
+var require_inspect = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/inspect.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.custom = void 0;
+    var node_util_1 = require("node:util");
+    exports2.custom = node_util_1.inspect.custom;
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js
+var require_restError = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/restError.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.RestError = void 0;
+    exports2.isRestError = isRestError;
+    var core_util_1 = require_commonjs2();
+    var inspect_js_1 = require_inspect();
+    var sanitizer_js_1 = require_sanitizer();
+    var errorSanitizer = new sanitizer_js_1.Sanitizer();
+    var RestError = class _RestError extends Error {
+      constructor(message, options = {}) {
+        super(message);
+        this.name = "RestError";
+        this.code = options.code;
+        this.statusCode = options.statusCode;
+        Object.defineProperty(this, "request", { value: options.request, enumerable: false });
+        Object.defineProperty(this, "response", { value: options.response, enumerable: false });
+        Object.setPrototypeOf(this, _RestError.prototype);
+      }
+      /**
+       * Logging method for util.inspect in Node
+       */
+      [inspect_js_1.custom]() {
+        return `RestError: ${this.message} 
+ ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`;
+      }
+    };
+    exports2.RestError = RestError;
+    RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
+    RestError.PARSE_ERROR = "PARSE_ERROR";
+    function isRestError(e) {
+      if (e instanceof RestError) {
+        return true;
+      }
+      return (0, core_util_1.isError)(e) && e.name === "RestError";
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js
+var require_tracingPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/tracingPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.tracingPolicyName = void 0;
+    exports2.tracingPolicy = tracingPolicy;
+    var core_tracing_1 = require_commonjs4();
+    var constants_js_1 = require_constants8();
+    var userAgent_js_1 = require_userAgent();
+    var log_js_1 = require_log();
+    var core_util_1 = require_commonjs2();
+    var restError_js_1 = require_restError();
+    var sanitizer_js_1 = require_sanitizer();
+    exports2.tracingPolicyName = "tracingPolicy";
+    function tracingPolicy(options = {}) {
+      const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
+      const sanitizer = new sanitizer_js_1.Sanitizer({
+        additionalAllowedQueryParameters: options.additionalAllowedQueryParameters
+      });
+      const tracingClient = tryCreateTracingClient();
+      return {
+        name: exports2.tracingPolicyName,
+        async sendRequest(request, next) {
+          var _a;
+          if (!tracingClient) {
+            return next(request);
+          }
+          const userAgent = await userAgentPromise;
+          const spanAttributes = {
+            "http.url": sanitizer.sanitizeUrl(request.url),
+            "http.method": request.method,
+            "http.user_agent": userAgent,
+            requestId: request.requestId
+          };
+          if (userAgent) {
+            spanAttributes["http.user_agent"] = userAgent;
+          }
+          const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {};
+          if (!span || !tracingContext) {
+            return next(request);
+          }
+          try {
+            const response = await tracingClient.withContext(tracingContext, next, request);
+            tryProcessResponse(span, response);
+            return response;
+          } catch (err) {
+            tryProcessError(span, err);
+            throw err;
+          }
+        }
+      };
+    }
+    function tryCreateTracingClient() {
+      try {
+        return (0, core_tracing_1.createTracingClient)({
+          namespace: "",
+          packageName: "@azure/core-rest-pipeline",
+          packageVersion: constants_js_1.SDK_VERSION
+        });
+      } catch (e) {
+        log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`);
+        return void 0;
+      }
+    }
+    function tryCreateSpan(tracingClient, request, spanAttributes) {
+      try {
+        const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
+          spanKind: "client",
+          spanAttributes
+        });
+        if (!span.isRecording()) {
+          span.end();
+          return void 0;
+        }
+        const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
+        for (const [key, value] of Object.entries(headers)) {
+          request.headers.set(key, value);
+        }
+        return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
+      } catch (e) {
+        log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+        return void 0;
+      }
+    }
+    function tryProcessError(span, error4) {
+      try {
+        span.setStatus({
+          status: "error",
+          error: (0, core_util_1.isError)(error4) ? error4 : void 0
+        });
+        if ((0, restError_js_1.isRestError)(error4) && error4.statusCode) {
+          span.setAttribute("http.status_code", error4.statusCode);
+        }
+        span.end();
+      } catch (e) {
+        log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+      }
+    }
+    function tryProcessResponse(span, response) {
+      try {
+        span.setAttribute("http.status_code", response.status);
+        const serviceRequestId = response.headers.get("x-ms-request-id");
+        if (serviceRequestId) {
+          span.setAttribute("serviceRequestId", serviceRequestId);
+        }
+        span.setStatus({
+          status: "success"
+        });
+        span.end();
+      } catch (e) {
+        log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+      }
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js
+var require_createPipelineFromOptions = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/createPipelineFromOptions.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.createPipelineFromOptions = createPipelineFromOptions;
+    var logPolicy_js_1 = require_logPolicy();
+    var pipeline_js_1 = require_pipeline();
+    var redirectPolicy_js_1 = require_redirectPolicy();
+    var userAgentPolicy_js_1 = require_userAgentPolicy();
+    var multipartPolicy_js_1 = require_multipartPolicy();
+    var decompressResponsePolicy_js_1 = require_decompressResponsePolicy();
+    var defaultRetryPolicy_js_1 = require_defaultRetryPolicy();
+    var formDataPolicy_js_1 = require_formDataPolicy();
+    var core_util_1 = require_commonjs2();
+    var proxyPolicy_js_1 = require_proxyPolicy();
+    var setClientRequestIdPolicy_js_1 = require_setClientRequestIdPolicy();
+    var tlsPolicy_js_1 = require_tlsPolicy();
+    var tracingPolicy_js_1 = require_tracingPolicy();
+    function createPipelineFromOptions(options) {
+      var _a;
+      const pipeline = (0, pipeline_js_1.createEmptyPipeline)();
+      if (core_util_1.isNodeLike) {
+        if (options.tlsOptions) {
+          pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions));
+        }
+        pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions));
+        pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)());
+      }
+      pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] });
+      pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions));
+      pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName));
+      pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" });
+      pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" });
+      pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), {
+        afterPhase: "Retry"
+      });
+      if (core_util_1.isNodeLike) {
+        pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" });
+      }
+      pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" });
+      return pipeline;
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js
+var require_nodeHttpClient = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/nodeHttpClient.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getBodyLength = getBodyLength;
+    exports2.createNodeHttpClient = createNodeHttpClient;
+    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
+    var http = tslib_1.__importStar(require("node:http"));
+    var https2 = tslib_1.__importStar(require("node:https"));
+    var zlib2 = tslib_1.__importStar(require("node:zlib"));
+    var node_stream_1 = require("node:stream");
+    var abort_controller_1 = require_commonjs3();
+    var httpHeaders_js_1 = require_httpHeaders();
+    var restError_js_1 = require_restError();
+    var log_js_1 = require_log();
+    var DEFAULT_TLS_SETTINGS = {};
+    function isReadableStream(body) {
+      return body && typeof body.pipe === "function";
+    }
+    function isStreamComplete(stream2) {
+      return new Promise((resolve6) => {
+        const handler = () => {
+          resolve6();
+          stream2.removeListener("close", handler);
+          stream2.removeListener("end", handler);
+          stream2.removeListener("error", handler);
+        };
+        stream2.on("close", handler);
+        stream2.on("end", handler);
+        stream2.on("error", handler);
+      });
+    }
+    function isArrayBuffer(body) {
+      return body && typeof body.byteLength === "number";
+    }
+    var ReportTransform = class extends node_stream_1.Transform {
+      // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
+      _transform(chunk, _encoding, callback) {
+        this.push(chunk);
+        this.loadedBytes += chunk.length;
+        try {
+          this.progressCallback({ loadedBytes: this.loadedBytes });
+          callback();
+        } catch (e) {
+          callback(e);
+        }
+      }
+      constructor(progressCallback) {
+        super();
+        this.loadedBytes = 0;
+        this.progressCallback = progressCallback;
+      }
+    };
+    var NodeHttpClient = class {
+      constructor() {
+        this.cachedHttpsAgents = /* @__PURE__ */ new WeakMap();
+      }
+      /**
+       * Makes a request over an underlying transport layer and returns the response.
+       * @param request - The request to be made.
+       */
+      async sendRequest(request) {
+        var _a, _b, _c;
+        const abortController = new AbortController();
+        let abortListener;
+        if (request.abortSignal) {
+          if (request.abortSignal.aborted) {
+            throw new abort_controller_1.AbortError("The operation was aborted.");
+          }
+          abortListener = (event) => {
+            if (event.type === "abort") {
+              abortController.abort();
+            }
+          };
+          request.abortSignal.addEventListener("abort", abortListener);
+        }
+        if (request.timeout > 0) {
+          setTimeout(() => {
+            abortController.abort();
+          }, request.timeout);
+        }
+        const acceptEncoding = request.headers.get("Accept-Encoding");
+        const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
+        let body = typeof request.body === "function" ? request.body() : request.body;
+        if (body && !request.headers.has("Content-Length")) {
+          const bodyLength = getBodyLength(body);
+          if (bodyLength !== null) {
+            request.headers.set("Content-Length", bodyLength);
+          }
+        }
+        let responseStream;
+        try {
+          if (body && request.onUploadProgress) {
+            const onUploadProgress = request.onUploadProgress;
+            const uploadReportStream = new ReportTransform(onUploadProgress);
+            uploadReportStream.on("error", (e) => {
+              log_js_1.logger.error("Error in upload progress", e);
+            });
+            if (isReadableStream(body)) {
+              body.pipe(uploadReportStream);
+            } else {
+              uploadReportStream.end(body);
+            }
+            body = uploadReportStream;
+          }
+          const res = await this.makeRequest(request, abortController, body);
+          const headers = getResponseHeaders(res);
+          const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
+          const response = {
+            status,
+            headers,
+            request
+          };
+          if (request.method === "HEAD") {
+            res.resume();
+            return response;
+          }
+          responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
+          const onDownloadProgress = request.onDownloadProgress;
+          if (onDownloadProgress) {
+            const downloadReportStream = new ReportTransform(onDownloadProgress);
+            downloadReportStream.on("error", (e) => {
+              log_js_1.logger.error("Error in download progress", e);
+            });
+            responseStream.pipe(downloadReportStream);
+            responseStream = downloadReportStream;
+          }
+          if (
+            // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
+            ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))
+          ) {
+            response.readableStreamBody = responseStream;
+          } else {
+            response.bodyAsText = await streamToText(responseStream);
+          }
+          return response;
+        } finally {
+          if (request.abortSignal && abortListener) {
+            let uploadStreamDone = Promise.resolve();
+            if (isReadableStream(body)) {
+              uploadStreamDone = isStreamComplete(body);
+            }
+            let downloadStreamDone = Promise.resolve();
+            if (isReadableStream(responseStream)) {
+              downloadStreamDone = isStreamComplete(responseStream);
+            }
+            Promise.all([uploadStreamDone, downloadStreamDone]).then(() => {
+              var _a2;
+              if (abortListener) {
+                (_a2 = request.abortSignal) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("abort", abortListener);
+              }
+            }).catch((e) => {
+              log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e);
+            });
+          }
+        }
+      }
+      makeRequest(request, abortController, body) {
+        var _a;
+        const url2 = new URL(request.url);
+        const isInsecure = url2.protocol !== "https:";
+        if (isInsecure && !request.allowInsecureConnection) {
+          throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
+        }
+        const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure);
+        const options = {
+          agent,
+          hostname: url2.hostname,
+          path: `${url2.pathname}${url2.search}`,
+          port: url2.port,
+          method: request.method,
+          headers: request.headers.toJSON({ preserveCase: true })
+        };
+        return new Promise((resolve6, reject) => {
+          const req = isInsecure ? http.request(options, resolve6) : https2.request(options, resolve6);
+          req.once("error", (err) => {
+            var _a2;
+            reject(new restError_js_1.RestError(err.message, { code: (_a2 = err.code) !== null && _a2 !== void 0 ? _a2 : restError_js_1.RestError.REQUEST_SEND_ERROR, request }));
+          });
+          abortController.signal.addEventListener("abort", () => {
+            const abortError = new abort_controller_1.AbortError("The operation was aborted.");
+            req.destroy(abortError);
+            reject(abortError);
+          });
+          if (body && isReadableStream(body)) {
+            body.pipe(req);
+          } else if (body) {
+            if (typeof body === "string" || Buffer.isBuffer(body)) {
+              req.end(body);
+            } else if (isArrayBuffer(body)) {
+              req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
+            } else {
+              log_js_1.logger.error("Unrecognized body type", body);
+              reject(new restError_js_1.RestError("Unrecognized body type"));
+            }
+          } else {
+            req.end();
+          }
+        });
+      }
+      getOrCreateAgent(request, isInsecure) {
+        var _a;
+        const disableKeepAlive = request.disableKeepAlive;
+        if (isInsecure) {
+          if (disableKeepAlive) {
+            return http.globalAgent;
+          }
+          if (!this.cachedHttpAgent) {
+            this.cachedHttpAgent = new http.Agent({ keepAlive: true });
+          }
+          return this.cachedHttpAgent;
+        } else {
+          if (disableKeepAlive && !request.tlsSettings) {
+            return https2.globalAgent;
+          }
+          const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS;
+          let agent = this.cachedHttpsAgents.get(tlsSettings);
+          if (agent && agent.options.keepAlive === !disableKeepAlive) {
+            return agent;
+          }
+          log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent");
+          agent = new https2.Agent(Object.assign({
+            // keepAlive is true if disableKeepAlive is false.
+            keepAlive: !disableKeepAlive
+          }, tlsSettings));
+          this.cachedHttpsAgents.set(tlsSettings, agent);
+          return agent;
+        }
+      }
+    };
+    function getResponseHeaders(res) {
+      const headers = (0, httpHeaders_js_1.createHttpHeaders)();
+      for (const header of Object.keys(res.headers)) {
+        const value = res.headers[header];
+        if (Array.isArray(value)) {
+          if (value.length > 0) {
+            headers.set(header, value[0]);
+          }
+        } else if (value) {
+          headers.set(header, value);
+        }
+      }
+      return headers;
+    }
+    function getDecodedResponseStream(stream2, headers) {
+      const contentEncoding = headers.get("Content-Encoding");
+      if (contentEncoding === "gzip") {
+        const unzip = zlib2.createGunzip();
+        stream2.pipe(unzip);
+        return unzip;
+      } else if (contentEncoding === "deflate") {
+        const inflate = zlib2.createInflate();
+        stream2.pipe(inflate);
+        return inflate;
+      }
+      return stream2;
+    }
+    function streamToText(stream2) {
+      return new Promise((resolve6, reject) => {
+        const buffer = [];
+        stream2.on("data", (chunk) => {
+          if (Buffer.isBuffer(chunk)) {
+            buffer.push(chunk);
+          } else {
+            buffer.push(Buffer.from(chunk));
+          }
+        });
+        stream2.on("end", () => {
+          resolve6(Buffer.concat(buffer).toString("utf8"));
+        });
+        stream2.on("error", (e) => {
+          if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") {
+            reject(e);
+          } else {
+            reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, {
+              code: restError_js_1.RestError.PARSE_ERROR
+            }));
+          }
+        });
+      });
+    }
+    function getBodyLength(body) {
+      if (!body) {
+        return 0;
+      } else if (Buffer.isBuffer(body)) {
+        return body.length;
+      } else if (isReadableStream(body)) {
+        return null;
+      } else if (isArrayBuffer(body)) {
+        return body.byteLength;
+      } else if (typeof body === "string") {
+        return Buffer.from(body).length;
+      } else {
+        return null;
+      }
+    }
+    function createNodeHttpClient() {
+      return new NodeHttpClient();
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js
+var require_defaultHttpClient = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/defaultHttpClient.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.createDefaultHttpClient = createDefaultHttpClient;
+    var nodeHttpClient_js_1 = require_nodeHttpClient();
+    function createDefaultHttpClient() {
+      return (0, nodeHttpClient_js_1.createNodeHttpClient)();
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js
+var require_pipelineRequest = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/pipelineRequest.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.createPipelineRequest = createPipelineRequest;
+    var httpHeaders_js_1 = require_httpHeaders();
+    var core_util_1 = require_commonjs2();
+    var PipelineRequestImpl = class {
+      constructor(options) {
+        var _a, _b, _c, _d, _e, _f, _g;
+        this.url = options.url;
+        this.body = options.body;
+        this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)();
+        this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET";
+        this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0;
+        this.multipartBody = options.multipartBody;
+        this.formData = options.formData;
+        this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false;
+        this.proxySettings = options.proxySettings;
+        this.streamResponseStatusCodes = options.streamResponseStatusCodes;
+        this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false;
+        this.abortSignal = options.abortSignal;
+        this.tracingOptions = options.tracingOptions;
+        this.onUploadProgress = options.onUploadProgress;
+        this.onDownloadProgress = options.onDownloadProgress;
+        this.requestId = options.requestId || (0, core_util_1.randomUUID)();
+        this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false;
+        this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false;
+      }
+    };
+    function createPipelineRequest(options) {
+      return new PipelineRequestImpl(options);
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js
+var require_exponentialRetryPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/exponentialRetryPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.exponentialRetryPolicyName = void 0;
+    exports2.exponentialRetryPolicy = exponentialRetryPolicy;
+    var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy();
+    var retryPolicy_js_1 = require_retryPolicy();
+    var constants_js_1 = require_constants8();
+    exports2.exponentialRetryPolicyName = "exponentialRetryPolicy";
+    function exponentialRetryPolicy(options = {}) {
+      var _a;
+      return (0, retryPolicy_js_1.retryPolicy)([
+        (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true }))
+      ], {
+        maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT
+      });
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js
+var require_systemErrorRetryPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/systemErrorRetryPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.systemErrorRetryPolicyName = void 0;
+    exports2.systemErrorRetryPolicy = systemErrorRetryPolicy;
+    var exponentialRetryStrategy_js_1 = require_exponentialRetryStrategy();
+    var retryPolicy_js_1 = require_retryPolicy();
+    var constants_js_1 = require_constants8();
+    exports2.systemErrorRetryPolicyName = "systemErrorRetryPolicy";
+    function systemErrorRetryPolicy(options = {}) {
+      var _a;
+      return {
+        name: exports2.systemErrorRetryPolicyName,
+        sendRequest: (0, retryPolicy_js_1.retryPolicy)([
+          (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true }))
+        ], {
+          maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT
+        }).sendRequest
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js
+var require_throttlingRetryPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/throttlingRetryPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.throttlingRetryPolicyName = void 0;
+    exports2.throttlingRetryPolicy = throttlingRetryPolicy;
+    var throttlingRetryStrategy_js_1 = require_throttlingRetryStrategy();
+    var retryPolicy_js_1 = require_retryPolicy();
+    var constants_js_1 = require_constants8();
+    exports2.throttlingRetryPolicyName = "throttlingRetryPolicy";
+    function throttlingRetryPolicy(options = {}) {
+      var _a;
+      return {
+        name: exports2.throttlingRetryPolicyName,
+        sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], {
+          maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT
+        }).sendRequest
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js
+var require_tokenCycler = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/util/tokenCycler.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.DEFAULT_CYCLER_OPTIONS = void 0;
+    exports2.createTokenCycler = createTokenCycler;
+    var helpers_js_1 = require_helpers();
+    exports2.DEFAULT_CYCLER_OPTIONS = {
+      forcedRefreshWindowInMs: 1e3,
+      // Force waiting for a refresh 1s before the token expires
+      retryIntervalInMs: 3e3,
+      // Allow refresh attempts every 3s
+      refreshWindowInMs: 1e3 * 60 * 2
+      // Start refreshing 2m before expiry
+    };
+    async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
+      async function tryGetAccessToken() {
+        if (Date.now() < refreshTimeout) {
+          try {
+            return await getAccessToken();
+          } catch (_a) {
+            return null;
+          }
+        } else {
+          const finalToken = await getAccessToken();
+          if (finalToken === null) {
+            throw new Error("Failed to refresh access token.");
+          }
+          return finalToken;
+        }
+      }
+      let token = await tryGetAccessToken();
+      while (token === null) {
+        await (0, helpers_js_1.delay)(retryIntervalInMs);
+        token = await tryGetAccessToken();
+      }
+      return token;
+    }
+    function createTokenCycler(credential, tokenCyclerOptions) {
+      let refreshWorker = null;
+      let token = null;
+      let tenantId;
+      const options = Object.assign(Object.assign({}, exports2.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions);
+      const cycler = {
+        /**
+         * Produces true if a refresh job is currently in progress.
+         */
+        get isRefreshing() {
+          return refreshWorker !== null;
+        },
+        /**
+         * Produces true if the cycler SHOULD refresh (we are within the refresh
+         * window and not already refreshing)
+         */
+        get shouldRefresh() {
+          var _a;
+          if (cycler.isRefreshing) {
+            return false;
+          }
+          if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) {
+            return true;
+          }
+          return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now();
+        },
+        /**
+         * Produces true if the cycler MUST refresh (null or nearly-expired
+         * token).
+         */
+        get mustRefresh() {
+          return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now();
+        }
+      };
+      function refresh(scopes, getTokenOptions) {
+        var _a;
+        if (!cycler.isRefreshing) {
+          const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
+          refreshWorker = beginRefresh(
+            tryGetAccessToken,
+            options.retryIntervalInMs,
+            // If we don't have a token, then we should timeout immediately
+            (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()
+          ).then((_token) => {
+            refreshWorker = null;
+            token = _token;
+            tenantId = getTokenOptions.tenantId;
+            return token;
+          }).catch((reason) => {
+            refreshWorker = null;
+            token = null;
+            tenantId = void 0;
+            throw reason;
+          });
+        }
+        return refreshWorker;
+      }
+      return async (scopes, tokenOptions) => {
+        const hasClaimChallenge = Boolean(tokenOptions.claims);
+        const tenantIdChanged = tenantId !== tokenOptions.tenantId;
+        if (hasClaimChallenge) {
+          token = null;
+        }
+        const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
+        if (mustRefresh) {
+          return refresh(scopes, tokenOptions);
+        }
+        if (cycler.shouldRefresh) {
+          refresh(scopes, tokenOptions);
+        }
+        return token;
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js
+var require_bearerTokenAuthenticationPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/bearerTokenAuthenticationPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.bearerTokenAuthenticationPolicyName = void 0;
+    exports2.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy;
+    var tokenCycler_js_1 = require_tokenCycler();
+    var log_js_1 = require_log();
+    exports2.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
+    async function defaultAuthorizeRequest(options) {
+      const { scopes, getAccessToken, request } = options;
+      const getTokenOptions = {
+        abortSignal: request.abortSignal,
+        tracingOptions: request.tracingOptions
+      };
+      const accessToken = await getAccessToken(scopes, getTokenOptions);
+      if (accessToken) {
+        options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
+      }
+    }
+    function getChallenge(response) {
+      const challenge = response.headers.get("WWW-Authenticate");
+      if (response.status === 401 && challenge) {
+        return challenge;
+      }
+      return;
+    }
+    function bearerTokenAuthenticationPolicy(options) {
+      var _a;
+      const { credential, scopes, challengeCallbacks } = options;
+      const logger = options.logger || log_js_1.logger;
+      const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks);
+      const getAccessToken = credential ? (0, tokenCycler_js_1.createTokenCycler)(
+        credential
+        /* , options */
+      ) : () => Promise.resolve(null);
+      return {
+        name: exports2.bearerTokenAuthenticationPolicyName,
+        /**
+         * If there's no challenge parameter:
+         * - It will try to retrieve the token using the cache, or the credential's getToken.
+         * - Then it will try the next policy with or without the retrieved token.
+         *
+         * It uses the challenge parameters to:
+         * - Skip a first attempt to get the token from the credential if there's no cached token,
+         *   since it expects the token to be retrievable only after the challenge.
+         * - Prepare the outgoing request if the `prepareRequest` method has been provided.
+         * - Send an initial request to receive the challenge if it fails.
+         * - Process a challenge if the response contains it.
+         * - Retrieve a token with the challenge information, then re-send the request.
+         */
+        async sendRequest(request, next) {
+          if (!request.url.toLowerCase().startsWith("https://")) {
+            throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
+          }
+          await callbacks.authorizeRequest({
+            scopes: Array.isArray(scopes) ? scopes : [scopes],
+            request,
+            getAccessToken,
+            logger
+          });
+          let response;
+          let error4;
+          try {
+            response = await next(request);
+          } catch (err) {
+            error4 = err;
+            response = err.response;
+          }
+          if (callbacks.authorizeRequestOnChallenge && (response === null || response === void 0 ? void 0 : response.status) === 401 && getChallenge(response)) {
+            const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
+              scopes: Array.isArray(scopes) ? scopes : [scopes],
+              request,
+              response,
+              getAccessToken,
+              logger
+            });
+            if (shouldSendRequest) {
+              return next(request);
+            }
+          }
+          if (error4) {
+            throw error4;
+          } else {
+            return response;
+          }
+        }
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js
+var require_ndJsonPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/ndJsonPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.ndJsonPolicyName = void 0;
+    exports2.ndJsonPolicy = ndJsonPolicy;
+    exports2.ndJsonPolicyName = "ndJsonPolicy";
+    function ndJsonPolicy() {
+      return {
+        name: exports2.ndJsonPolicyName,
+        async sendRequest(request, next) {
+          if (typeof request.body === "string" && request.body.startsWith("[")) {
+            const body = JSON.parse(request.body);
+            if (Array.isArray(body)) {
+              request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
+            }
+          }
+          return next(request);
+        }
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js
+var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/policies/auxiliaryAuthenticationHeaderPolicy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.auxiliaryAuthenticationHeaderPolicyName = void 0;
+    exports2.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy;
+    var tokenCycler_js_1 = require_tokenCycler();
+    var log_js_1 = require_log();
+    exports2.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
+    var AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
+    async function sendAuthorizeRequest(options) {
+      var _a, _b;
+      const { scopes, getAccessToken, request } = options;
+      const getTokenOptions = {
+        abortSignal: request.abortSignal,
+        tracingOptions: request.tracingOptions
+      };
+      return (_b = (_a = await getAccessToken(scopes, getTokenOptions)) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : "";
+    }
+    function auxiliaryAuthenticationHeaderPolicy(options) {
+      const { credentials, scopes } = options;
+      const logger = options.logger || log_js_1.logger;
+      const tokenCyclerMap = /* @__PURE__ */ new WeakMap();
+      return {
+        name: exports2.auxiliaryAuthenticationHeaderPolicyName,
+        async sendRequest(request, next) {
+          if (!request.url.toLowerCase().startsWith("https://")) {
+            throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
+          }
+          if (!credentials || credentials.length === 0) {
+            logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
+            return next(request);
+          }
+          const tokenPromises = [];
+          for (const credential of credentials) {
+            let getAccessToken = tokenCyclerMap.get(credential);
+            if (!getAccessToken) {
+              getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential);
+              tokenCyclerMap.set(credential, getAccessToken);
+            }
+            tokenPromises.push(sendAuthorizeRequest({
+              scopes: Array.isArray(scopes) ? scopes : [scopes],
+              request,
+              getAccessToken,
+              logger
+            }));
+          }
+          const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
+          if (auxiliaryTokens.length === 0) {
+            logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
+            return next(request);
+          }
+          request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
+          return next(request);
+        }
+      };
+    }
+  }
+});
+
+// node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js
+var require_commonjs5 = __commonJS({
+  "node_modules/@azure/core-rest-pipeline/dist/commonjs/index.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.createFileFromStream = exports2.createFile = exports2.auxiliaryAuthenticationHeaderPolicyName = exports2.auxiliaryAuthenticationHeaderPolicy = exports2.ndJsonPolicyName = exports2.ndJsonPolicy = exports2.bearerTokenAuthenticationPolicyName = exports2.bearerTokenAuthenticationPolicy = exports2.formDataPolicyName = exports2.formDataPolicy = exports2.tlsPolicyName = exports2.tlsPolicy = exports2.userAgentPolicyName = exports2.userAgentPolicy = exports2.defaultRetryPolicy = exports2.tracingPolicyName = exports2.tracingPolicy = exports2.retryPolicy = exports2.throttlingRetryPolicyName = exports2.throttlingRetryPolicy = exports2.systemErrorRetryPolicyName = exports2.systemErrorRetryPolicy = exports2.redirectPolicyName = exports2.redirectPolicy = exports2.getDefaultProxySettings = exports2.proxyPolicyName = exports2.proxyPolicy = exports2.multipartPolicyName = exports2.multipartPolicy = exports2.logPolicyName = exports2.logPolicy = exports2.setClientRequestIdPolicyName = exports2.setClientRequestIdPolicy = exports2.exponentialRetryPolicyName = exports2.exponentialRetryPolicy = exports2.decompressResponsePolicyName = exports2.decompressResponsePolicy = exports2.isRestError = exports2.RestError = exports2.createPipelineRequest = exports2.createHttpHeaders = exports2.createDefaultHttpClient = exports2.createPipelineFromOptions = exports2.createEmptyPipeline = void 0;
+    var pipeline_js_1 = require_pipeline();
+    Object.defineProperty(exports2, "createEmptyPipeline", { enumerable: true, get: function() {
       return pipeline_js_1.createEmptyPipeline;
     } });
     var createPipelineFromOptions_js_1 = require_createPipelineFromOptions();
@@ -66649,7 +68155,7 @@ var require_requestUtils = __commonJS({
     Object.defineProperty(exports2, "__esModule", { value: true });
     exports2.retryHttpClientResponse = exports2.retryTypedResponse = exports2.retry = exports2.isRetryableStatusCode = exports2.isServerErrorStatusCode = exports2.isSuccessStatusCode = void 0;
     var core14 = __importStar4(require_core());
-    var http_client_1 = require_lib();
+    var http_client_1 = require_lib3();
     var constants_1 = require_constants7();
     function isSuccessStatusCode(statusCode) {
       if (!statusCode) {
@@ -66817,7 +68323,7 @@ var require_downloadUtils = __commonJS({
     Object.defineProperty(exports2, "__esModule", { value: true });
     exports2.downloadCacheStorageSDK = exports2.downloadCacheHttpClientConcurrent = exports2.downloadCacheHttpClient = exports2.DownloadProgress = void 0;
     var core14 = __importStar4(require_core());
-    var http_client_1 = require_lib();
+    var http_client_1 = require_lib3();
     var storage_blob_1 = require_dist7();
     var buffer = __importStar4(require("buffer"));
     var fs13 = __importStar4(require("fs"));
@@ -67394,8 +68900,8 @@ var require_cacheHttpClient = __commonJS({
     Object.defineProperty(exports2, "__esModule", { value: true });
     exports2.saveCache = exports2.reserveCache = exports2.downloadCache = exports2.getCacheEntry = void 0;
     var core14 = __importStar4(require_core());
-    var http_client_1 = require_lib();
-    var auth_1 = require_auth();
+    var http_client_1 = require_lib3();
+    var auth_1 = require_auth2();
     var fs13 = __importStar4(require("fs"));
     var url_1 = require("url");
     var utils = __importStar4(require_cacheUtils());
@@ -67707,7255 +69213,8616 @@ var require_base642 = __commonJS({
             break;
         }
       }
-      if (groupPos) {
-        base64 += encTable[p];
-        base64 += "=";
-        if (groupPos == 1)
-          base64 += "=";
+      if (groupPos) {
+        base64 += encTable[p];
+        base64 += "=";
+        if (groupPos == 1)
+          base64 += "=";
+      }
+      return base64;
+    }
+    exports2.base64encode = base64encode;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js
+var require_protobufjs_utf8 = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.utf8read = void 0;
+    var fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk);
+    function utf8read(bytes) {
+      if (bytes.length < 1)
+        return "";
+      let pos = 0, parts = [], chunk = [], i = 0, t;
+      let len = bytes.length;
+      while (pos < len) {
+        t = bytes[pos++];
+        if (t < 128)
+          chunk[i++] = t;
+        else if (t > 191 && t < 224)
+          chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63;
+        else if (t > 239 && t < 365) {
+          t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 65536;
+          chunk[i++] = 55296 + (t >> 10);
+          chunk[i++] = 56320 + (t & 1023);
+        } else
+          chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63;
+        if (i > 8191) {
+          parts.push(fromCharCodes(chunk));
+          i = 0;
+        }
+      }
+      if (parts.length) {
+        if (i)
+          parts.push(fromCharCodes(chunk.slice(0, i)));
+        return parts.join("");
+      }
+      return fromCharCodes(chunk.slice(0, i));
+    }
+    exports2.utf8read = utf8read;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js
+var require_binary_format_contract = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.WireType = exports2.mergeBinaryOptions = exports2.UnknownFieldHandler = void 0;
+    var UnknownFieldHandler;
+    (function(UnknownFieldHandler2) {
+      UnknownFieldHandler2.symbol = Symbol.for("protobuf-ts/unknown");
+      UnknownFieldHandler2.onRead = (typeName, message, fieldNo, wireType, data) => {
+        let container = is(message) ? message[UnknownFieldHandler2.symbol] : message[UnknownFieldHandler2.symbol] = [];
+        container.push({ no: fieldNo, wireType, data });
+      };
+      UnknownFieldHandler2.onWrite = (typeName, message, writer) => {
+        for (let { no, wireType, data } of UnknownFieldHandler2.list(message))
+          writer.tag(no, wireType).raw(data);
+      };
+      UnknownFieldHandler2.list = (message, fieldNo) => {
+        if (is(message)) {
+          let all = message[UnknownFieldHandler2.symbol];
+          return fieldNo ? all.filter((uf) => uf.no == fieldNo) : all;
+        }
+        return [];
+      };
+      UnknownFieldHandler2.last = (message, fieldNo) => UnknownFieldHandler2.list(message, fieldNo).slice(-1)[0];
+      const is = (message) => message && Array.isArray(message[UnknownFieldHandler2.symbol]);
+    })(UnknownFieldHandler = exports2.UnknownFieldHandler || (exports2.UnknownFieldHandler = {}));
+    function mergeBinaryOptions(a, b) {
+      return Object.assign(Object.assign({}, a), b);
+    }
+    exports2.mergeBinaryOptions = mergeBinaryOptions;
+    var WireType;
+    (function(WireType2) {
+      WireType2[WireType2["Varint"] = 0] = "Varint";
+      WireType2[WireType2["Bit64"] = 1] = "Bit64";
+      WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited";
+      WireType2[WireType2["StartGroup"] = 3] = "StartGroup";
+      WireType2[WireType2["EndGroup"] = 4] = "EndGroup";
+      WireType2[WireType2["Bit32"] = 5] = "Bit32";
+    })(WireType = exports2.WireType || (exports2.WireType = {}));
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js
+var require_goog_varint = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.varint32read = exports2.varint32write = exports2.int64toString = exports2.int64fromString = exports2.varint64write = exports2.varint64read = void 0;
+    function varint64read() {
+      let lowBits = 0;
+      let highBits = 0;
+      for (let shift = 0; shift < 28; shift += 7) {
+        let b = this.buf[this.pos++];
+        lowBits |= (b & 127) << shift;
+        if ((b & 128) == 0) {
+          this.assertBounds();
+          return [lowBits, highBits];
+        }
+      }
+      let middleByte = this.buf[this.pos++];
+      lowBits |= (middleByte & 15) << 28;
+      highBits = (middleByte & 112) >> 4;
+      if ((middleByte & 128) == 0) {
+        this.assertBounds();
+        return [lowBits, highBits];
+      }
+      for (let shift = 3; shift <= 31; shift += 7) {
+        let b = this.buf[this.pos++];
+        highBits |= (b & 127) << shift;
+        if ((b & 128) == 0) {
+          this.assertBounds();
+          return [lowBits, highBits];
+        }
+      }
+      throw new Error("invalid varint");
+    }
+    exports2.varint64read = varint64read;
+    function varint64write(lo, hi, bytes) {
+      for (let i = 0; i < 28; i = i + 7) {
+        const shift = lo >>> i;
+        const hasNext = !(shift >>> 7 == 0 && hi == 0);
+        const byte = (hasNext ? shift | 128 : shift) & 255;
+        bytes.push(byte);
+        if (!hasNext) {
+          return;
+        }
+      }
+      const splitBits = lo >>> 28 & 15 | (hi & 7) << 4;
+      const hasMoreBits = !(hi >> 3 == 0);
+      bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255);
+      if (!hasMoreBits) {
+        return;
+      }
+      for (let i = 3; i < 31; i = i + 7) {
+        const shift = hi >>> i;
+        const hasNext = !(shift >>> 7 == 0);
+        const byte = (hasNext ? shift | 128 : shift) & 255;
+        bytes.push(byte);
+        if (!hasNext) {
+          return;
+        }
+      }
+      bytes.push(hi >>> 31 & 1);
+    }
+    exports2.varint64write = varint64write;
+    var TWO_PWR_32_DBL2 = (1 << 16) * (1 << 16);
+    function int64fromString(dec) {
+      let minus = dec[0] == "-";
+      if (minus)
+        dec = dec.slice(1);
+      const base = 1e6;
+      let lowBits = 0;
+      let highBits = 0;
+      function add1e6digit(begin, end) {
+        const digit1e6 = Number(dec.slice(begin, end));
+        highBits *= base;
+        lowBits = lowBits * base + digit1e6;
+        if (lowBits >= TWO_PWR_32_DBL2) {
+          highBits = highBits + (lowBits / TWO_PWR_32_DBL2 | 0);
+          lowBits = lowBits % TWO_PWR_32_DBL2;
+        }
+      }
+      add1e6digit(-24, -18);
+      add1e6digit(-18, -12);
+      add1e6digit(-12, -6);
+      add1e6digit(-6);
+      return [minus, lowBits, highBits];
+    }
+    exports2.int64fromString = int64fromString;
+    function int64toString(bitsLow, bitsHigh) {
+      if (bitsHigh >>> 0 <= 2097151) {
+        return "" + (TWO_PWR_32_DBL2 * bitsHigh + (bitsLow >>> 0));
+      }
+      let low = bitsLow & 16777215;
+      let mid = (bitsLow >>> 24 | bitsHigh << 8) >>> 0 & 16777215;
+      let high = bitsHigh >> 16 & 65535;
+      let digitA = low + mid * 6777216 + high * 6710656;
+      let digitB = mid + high * 8147497;
+      let digitC = high * 2;
+      let base = 1e7;
+      if (digitA >= base) {
+        digitB += Math.floor(digitA / base);
+        digitA %= base;
+      }
+      if (digitB >= base) {
+        digitC += Math.floor(digitB / base);
+        digitB %= base;
+      }
+      function decimalFrom1e7(digit1e7, needLeadingZeros) {
+        let partial = digit1e7 ? String(digit1e7) : "";
+        if (needLeadingZeros) {
+          return "0000000".slice(partial.length) + partial;
+        }
+        return partial;
+      }
+      return decimalFrom1e7(
+        digitC,
+        /*needLeadingZeros=*/
+        0
+      ) + decimalFrom1e7(
+        digitB,
+        /*needLeadingZeros=*/
+        digitC
+      ) + // If the final 1e7 digit didn't need leading zeros, we would have
+      // returned via the trivial code path at the top.
+      decimalFrom1e7(
+        digitA,
+        /*needLeadingZeros=*/
+        1
+      );
+    }
+    exports2.int64toString = int64toString;
+    function varint32write(value, bytes) {
+      if (value >= 0) {
+        while (value > 127) {
+          bytes.push(value & 127 | 128);
+          value = value >>> 7;
+        }
+        bytes.push(value);
+      } else {
+        for (let i = 0; i < 9; i++) {
+          bytes.push(value & 127 | 128);
+          value = value >> 7;
+        }
+        bytes.push(1);
+      }
+    }
+    exports2.varint32write = varint32write;
+    function varint32read() {
+      let b = this.buf[this.pos++];
+      let result = b & 127;
+      if ((b & 128) == 0) {
+        this.assertBounds();
+        return result;
+      }
+      b = this.buf[this.pos++];
+      result |= (b & 127) << 7;
+      if ((b & 128) == 0) {
+        this.assertBounds();
+        return result;
+      }
+      b = this.buf[this.pos++];
+      result |= (b & 127) << 14;
+      if ((b & 128) == 0) {
+        this.assertBounds();
+        return result;
+      }
+      b = this.buf[this.pos++];
+      result |= (b & 127) << 21;
+      if ((b & 128) == 0) {
+        this.assertBounds();
+        return result;
+      }
+      b = this.buf[this.pos++];
+      result |= (b & 15) << 28;
+      for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++)
+        b = this.buf[this.pos++];
+      if ((b & 128) != 0)
+        throw new Error("invalid varint");
+      this.assertBounds();
+      return result >>> 0;
+    }
+    exports2.varint32read = varint32read;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js
+var require_pb_long = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.PbLong = exports2.PbULong = exports2.detectBi = void 0;
+    var goog_varint_1 = require_goog_varint();
+    var BI;
+    function detectBi() {
+      const dv = new DataView(new ArrayBuffer(8));
+      const ok = globalThis.BigInt !== void 0 && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function";
+      BI = ok ? {
+        MIN: BigInt("-9223372036854775808"),
+        MAX: BigInt("9223372036854775807"),
+        UMIN: BigInt("0"),
+        UMAX: BigInt("18446744073709551615"),
+        C: BigInt,
+        V: dv
+      } : void 0;
+    }
+    exports2.detectBi = detectBi;
+    detectBi();
+    function assertBi(bi) {
+      if (!bi)
+        throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support");
+    }
+    var RE_DECIMAL_STR = /^-?[0-9]+$/;
+    var TWO_PWR_32_DBL2 = 4294967296;
+    var HALF_2_PWR_32 = 2147483648;
+    var SharedPbLong = class {
+      /**
+       * Create a new instance with the given bits.
+       */
+      constructor(lo, hi) {
+        this.lo = lo | 0;
+        this.hi = hi | 0;
+      }
+      /**
+       * Is this instance equal to 0?
+       */
+      isZero() {
+        return this.lo == 0 && this.hi == 0;
+      }
+      /**
+       * Convert to a native number.
+       */
+      toNumber() {
+        let result = this.hi * TWO_PWR_32_DBL2 + (this.lo >>> 0);
+        if (!Number.isSafeInteger(result))
+          throw new Error("cannot convert to safe number");
+        return result;
+      }
+    };
+    var PbULong = class _PbULong extends SharedPbLong {
+      /**
+       * Create instance from a `string`, `number` or `bigint`.
+       */
+      static from(value) {
+        if (BI)
+          switch (typeof value) {
+            case "string":
+              if (value == "0")
+                return this.ZERO;
+              if (value == "")
+                throw new Error("string is no integer");
+              value = BI.C(value);
+            case "number":
+              if (value === 0)
+                return this.ZERO;
+              value = BI.C(value);
+            case "bigint":
+              if (!value)
+                return this.ZERO;
+              if (value < BI.UMIN)
+                throw new Error("signed value for ulong");
+              if (value > BI.UMAX)
+                throw new Error("ulong too large");
+              BI.V.setBigUint64(0, value, true);
+              return new _PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
+          }
+        else
+          switch (typeof value) {
+            case "string":
+              if (value == "0")
+                return this.ZERO;
+              value = value.trim();
+              if (!RE_DECIMAL_STR.test(value))
+                throw new Error("string is no integer");
+              let [minus, lo, hi] = goog_varint_1.int64fromString(value);
+              if (minus)
+                throw new Error("signed value for ulong");
+              return new _PbULong(lo, hi);
+            case "number":
+              if (value == 0)
+                return this.ZERO;
+              if (!Number.isSafeInteger(value))
+                throw new Error("number is no integer");
+              if (value < 0)
+                throw new Error("signed value for ulong");
+              return new _PbULong(value, value / TWO_PWR_32_DBL2);
+          }
+        throw new Error("unknown value " + typeof value);
+      }
+      /**
+       * Convert to decimal string.
+       */
+      toString() {
+        return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi);
+      }
+      /**
+       * Convert to native bigint.
+       */
+      toBigInt() {
+        assertBi(BI);
+        BI.V.setInt32(0, this.lo, true);
+        BI.V.setInt32(4, this.hi, true);
+        return BI.V.getBigUint64(0, true);
+      }
+    };
+    exports2.PbULong = PbULong;
+    PbULong.ZERO = new PbULong(0, 0);
+    var PbLong = class _PbLong extends SharedPbLong {
+      /**
+       * Create instance from a `string`, `number` or `bigint`.
+       */
+      static from(value) {
+        if (BI)
+          switch (typeof value) {
+            case "string":
+              if (value == "0")
+                return this.ZERO;
+              if (value == "")
+                throw new Error("string is no integer");
+              value = BI.C(value);
+            case "number":
+              if (value === 0)
+                return this.ZERO;
+              value = BI.C(value);
+            case "bigint":
+              if (!value)
+                return this.ZERO;
+              if (value < BI.MIN)
+                throw new Error("signed long too small");
+              if (value > BI.MAX)
+                throw new Error("signed long too large");
+              BI.V.setBigInt64(0, value, true);
+              return new _PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
+          }
+        else
+          switch (typeof value) {
+            case "string":
+              if (value == "0")
+                return this.ZERO;
+              value = value.trim();
+              if (!RE_DECIMAL_STR.test(value))
+                throw new Error("string is no integer");
+              let [minus, lo, hi] = goog_varint_1.int64fromString(value);
+              if (minus) {
+                if (hi > HALF_2_PWR_32 || hi == HALF_2_PWR_32 && lo != 0)
+                  throw new Error("signed long too small");
+              } else if (hi >= HALF_2_PWR_32)
+                throw new Error("signed long too large");
+              let pbl = new _PbLong(lo, hi);
+              return minus ? pbl.negate() : pbl;
+            case "number":
+              if (value == 0)
+                return this.ZERO;
+              if (!Number.isSafeInteger(value))
+                throw new Error("number is no integer");
+              return value > 0 ? new _PbLong(value, value / TWO_PWR_32_DBL2) : new _PbLong(-value, -value / TWO_PWR_32_DBL2).negate();
+          }
+        throw new Error("unknown value " + typeof value);
+      }
+      /**
+       * Do we have a minus sign?
+       */
+      isNegative() {
+        return (this.hi & HALF_2_PWR_32) !== 0;
+      }
+      /**
+       * Negate two's complement.
+       * Invert all the bits and add one to the result.
+       */
+      negate() {
+        let hi = ~this.hi, lo = this.lo;
+        if (lo)
+          lo = ~lo + 1;
+        else
+          hi += 1;
+        return new _PbLong(lo, hi);
+      }
+      /**
+       * Convert to decimal string.
+       */
+      toString() {
+        if (BI)
+          return this.toBigInt().toString();
+        if (this.isNegative()) {
+          let n = this.negate();
+          return "-" + goog_varint_1.int64toString(n.lo, n.hi);
+        }
+        return goog_varint_1.int64toString(this.lo, this.hi);
+      }
+      /**
+       * Convert to native bigint.
+       */
+      toBigInt() {
+        assertBi(BI);
+        BI.V.setInt32(0, this.lo, true);
+        BI.V.setInt32(4, this.hi, true);
+        return BI.V.getBigInt64(0, true);
       }
-      return base64;
-    }
-    exports2.base64encode = base64encode;
+    };
+    exports2.PbLong = PbLong;
+    PbLong.ZERO = new PbLong(0, 0);
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js
-var require_protobufjs_utf8 = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/protobufjs-utf8.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js
+var require_binary_reader = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.utf8read = void 0;
-    var fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk);
-    function utf8read(bytes) {
-      if (bytes.length < 1)
-        return "";
-      let pos = 0, parts = [], chunk = [], i = 0, t;
-      let len = bytes.length;
-      while (pos < len) {
-        t = bytes[pos++];
-        if (t < 128)
-          chunk[i++] = t;
-        else if (t > 191 && t < 224)
-          chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63;
-        else if (t > 239 && t < 365) {
-          t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 65536;
-          chunk[i++] = 55296 + (t >> 10);
-          chunk[i++] = 56320 + (t & 1023);
-        } else
-          chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63;
-        if (i > 8191) {
-          parts.push(fromCharCodes(chunk));
-          i = 0;
+    exports2.BinaryReader = exports2.binaryReadOptions = void 0;
+    var binary_format_contract_1 = require_binary_format_contract();
+    var pb_long_1 = require_pb_long();
+    var goog_varint_1 = require_goog_varint();
+    var defaultsRead = {
+      readUnknownField: true,
+      readerFactory: (bytes) => new BinaryReader(bytes)
+    };
+    function binaryReadOptions(options) {
+      return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
+    }
+    exports2.binaryReadOptions = binaryReadOptions;
+    var BinaryReader = class {
+      constructor(buf, textDecoder) {
+        this.varint64 = goog_varint_1.varint64read;
+        this.uint32 = goog_varint_1.varint32read;
+        this.buf = buf;
+        this.len = buf.length;
+        this.pos = 0;
+        this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
+        this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", {
+          fatal: true,
+          ignoreBOM: true
+        });
+      }
+      /**
+       * Reads a tag - field number and wire type.
+       */
+      tag() {
+        let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;
+        if (fieldNo <= 0 || wireType < 0 || wireType > 5)
+          throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
+        return [fieldNo, wireType];
+      }
+      /**
+       * Skip one element on the wire and return the skipped data.
+       * Supports WireType.StartGroup since v2.0.0-alpha.23.
+       */
+      skip(wireType) {
+        let start = this.pos;
+        switch (wireType) {
+          case binary_format_contract_1.WireType.Varint:
+            while (this.buf[this.pos++] & 128) {
+            }
+            break;
+          case binary_format_contract_1.WireType.Bit64:
+            this.pos += 4;
+          case binary_format_contract_1.WireType.Bit32:
+            this.pos += 4;
+            break;
+          case binary_format_contract_1.WireType.LengthDelimited:
+            let len = this.uint32();
+            this.pos += len;
+            break;
+          case binary_format_contract_1.WireType.StartGroup:
+            let t;
+            while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) {
+              this.skip(t);
+            }
+            break;
+          default:
+            throw new Error("cant skip wire type " + wireType);
         }
+        this.assertBounds();
+        return this.buf.subarray(start, this.pos);
       }
-      if (parts.length) {
-        if (i)
-          parts.push(fromCharCodes(chunk.slice(0, i)));
-        return parts.join("");
+      /**
+       * Throws error if position in byte array is out of range.
+       */
+      assertBounds() {
+        if (this.pos > this.len)
+          throw new RangeError("premature EOF");
       }
-      return fromCharCodes(chunk.slice(0, i));
-    }
-    exports2.utf8read = utf8read;
+      /**
+       * Read a `int32` field, a signed 32 bit varint.
+       */
+      int32() {
+        return this.uint32() | 0;
+      }
+      /**
+       * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
+       */
+      sint32() {
+        let zze = this.uint32();
+        return zze >>> 1 ^ -(zze & 1);
+      }
+      /**
+       * Read a `int64` field, a signed 64-bit varint.
+       */
+      int64() {
+        return new pb_long_1.PbLong(...this.varint64());
+      }
+      /**
+       * Read a `uint64` field, an unsigned 64-bit varint.
+       */
+      uint64() {
+        return new pb_long_1.PbULong(...this.varint64());
+      }
+      /**
+       * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
+       */
+      sint64() {
+        let [lo, hi] = this.varint64();
+        let s = -(lo & 1);
+        lo = (lo >>> 1 | (hi & 1) << 31) ^ s;
+        hi = hi >>> 1 ^ s;
+        return new pb_long_1.PbLong(lo, hi);
+      }
+      /**
+       * Read a `bool` field, a variant.
+       */
+      bool() {
+        let [lo, hi] = this.varint64();
+        return lo !== 0 || hi !== 0;
+      }
+      /**
+       * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
+       */
+      fixed32() {
+        return this.view.getUint32((this.pos += 4) - 4, true);
+      }
+      /**
+       * Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
+       */
+      sfixed32() {
+        return this.view.getInt32((this.pos += 4) - 4, true);
+      }
+      /**
+       * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
+       */
+      fixed64() {
+        return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32());
+      }
+      /**
+       * Read a `fixed64` field, a signed, fixed-length 64-bit integer.
+       */
+      sfixed64() {
+        return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32());
+      }
+      /**
+       * Read a `float` field, 32-bit floating point number.
+       */
+      float() {
+        return this.view.getFloat32((this.pos += 4) - 4, true);
+      }
+      /**
+       * Read a `double` field, a 64-bit floating point number.
+       */
+      double() {
+        return this.view.getFloat64((this.pos += 8) - 8, true);
+      }
+      /**
+       * Read a `bytes` field, length-delimited arbitrary data.
+       */
+      bytes() {
+        let len = this.uint32();
+        let start = this.pos;
+        this.pos += len;
+        this.assertBounds();
+        return this.buf.subarray(start, start + len);
+      }
+      /**
+       * Read a `string` field, length-delimited data converted to UTF-8 text.
+       */
+      string() {
+        return this.textDecoder.decode(this.bytes());
+      }
+    };
+    exports2.BinaryReader = BinaryReader;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js
-var require_binary_format_contract = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/binary-format-contract.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js
+var require_assert = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.WireType = exports2.mergeBinaryOptions = exports2.UnknownFieldHandler = void 0;
-    var UnknownFieldHandler;
-    (function(UnknownFieldHandler2) {
-      UnknownFieldHandler2.symbol = Symbol.for("protobuf-ts/unknown");
-      UnknownFieldHandler2.onRead = (typeName, message, fieldNo, wireType, data) => {
-        let container = is(message) ? message[UnknownFieldHandler2.symbol] : message[UnknownFieldHandler2.symbol] = [];
-        container.push({ no: fieldNo, wireType, data });
-      };
-      UnknownFieldHandler2.onWrite = (typeName, message, writer) => {
-        for (let { no, wireType, data } of UnknownFieldHandler2.list(message))
-          writer.tag(no, wireType).raw(data);
-      };
-      UnknownFieldHandler2.list = (message, fieldNo) => {
-        if (is(message)) {
-          let all = message[UnknownFieldHandler2.symbol];
-          return fieldNo ? all.filter((uf) => uf.no == fieldNo) : all;
-        }
-        return [];
-      };
-      UnknownFieldHandler2.last = (message, fieldNo) => UnknownFieldHandler2.list(message, fieldNo).slice(-1)[0];
-      const is = (message) => message && Array.isArray(message[UnknownFieldHandler2.symbol]);
-    })(UnknownFieldHandler = exports2.UnknownFieldHandler || (exports2.UnknownFieldHandler = {}));
-    function mergeBinaryOptions(a, b) {
-      return Object.assign(Object.assign({}, a), b);
+    exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0;
+    function assert(condition, msg) {
+      if (!condition) {
+        throw new Error(msg);
+      }
     }
-    exports2.mergeBinaryOptions = mergeBinaryOptions;
-    var WireType;
-    (function(WireType2) {
-      WireType2[WireType2["Varint"] = 0] = "Varint";
-      WireType2[WireType2["Bit64"] = 1] = "Bit64";
-      WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited";
-      WireType2[WireType2["StartGroup"] = 3] = "StartGroup";
-      WireType2[WireType2["EndGroup"] = 4] = "EndGroup";
-      WireType2[WireType2["Bit32"] = 5] = "Bit32";
-    })(WireType = exports2.WireType || (exports2.WireType = {}));
+    exports2.assert = assert;
+    function assertNever2(value, msg) {
+      throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value);
+    }
+    exports2.assertNever = assertNever2;
+    var FLOAT32_MAX = 34028234663852886e22;
+    var FLOAT32_MIN = -34028234663852886e22;
+    var UINT32_MAX = 4294967295;
+    var INT32_MAX = 2147483647;
+    var INT32_MIN = -2147483648;
+    function assertInt32(arg) {
+      if (typeof arg !== "number")
+        throw new Error("invalid int 32: " + typeof arg);
+      if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN)
+        throw new Error("invalid int 32: " + arg);
+    }
+    exports2.assertInt32 = assertInt32;
+    function assertUInt32(arg) {
+      if (typeof arg !== "number")
+        throw new Error("invalid uint 32: " + typeof arg);
+      if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0)
+        throw new Error("invalid uint 32: " + arg);
+    }
+    exports2.assertUInt32 = assertUInt32;
+    function assertFloat32(arg) {
+      if (typeof arg !== "number")
+        throw new Error("invalid float 32: " + typeof arg);
+      if (!Number.isFinite(arg))
+        return;
+      if (arg > FLOAT32_MAX || arg < FLOAT32_MIN)
+        throw new Error("invalid float 32: " + arg);
+    }
+    exports2.assertFloat32 = assertFloat32;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js
-var require_goog_varint = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/goog-varint.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js
+var require_binary_writer = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.varint32read = exports2.varint32write = exports2.int64toString = exports2.int64fromString = exports2.varint64write = exports2.varint64read = void 0;
-    function varint64read() {
-      let lowBits = 0;
-      let highBits = 0;
-      for (let shift = 0; shift < 28; shift += 7) {
-        let b = this.buf[this.pos++];
-        lowBits |= (b & 127) << shift;
-        if ((b & 128) == 0) {
-          this.assertBounds();
-          return [lowBits, highBits];
-        }
-      }
-      let middleByte = this.buf[this.pos++];
-      lowBits |= (middleByte & 15) << 28;
-      highBits = (middleByte & 112) >> 4;
-      if ((middleByte & 128) == 0) {
-        this.assertBounds();
-        return [lowBits, highBits];
-      }
-      for (let shift = 3; shift <= 31; shift += 7) {
-        let b = this.buf[this.pos++];
-        highBits |= (b & 127) << shift;
-        if ((b & 128) == 0) {
-          this.assertBounds();
-          return [lowBits, highBits];
-        }
-      }
-      throw new Error("invalid varint");
+    exports2.BinaryWriter = exports2.binaryWriteOptions = void 0;
+    var pb_long_1 = require_pb_long();
+    var goog_varint_1 = require_goog_varint();
+    var assert_1 = require_assert();
+    var defaultsWrite = {
+      writeUnknownFields: true,
+      writerFactory: () => new BinaryWriter()
+    };
+    function binaryWriteOptions(options) {
+      return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
     }
-    exports2.varint64read = varint64read;
-    function varint64write(lo, hi, bytes) {
-      for (let i = 0; i < 28; i = i + 7) {
-        const shift = lo >>> i;
-        const hasNext = !(shift >>> 7 == 0 && hi == 0);
-        const byte = (hasNext ? shift | 128 : shift) & 255;
-        bytes.push(byte);
-        if (!hasNext) {
-          return;
-        }
-      }
-      const splitBits = lo >>> 28 & 15 | (hi & 7) << 4;
-      const hasMoreBits = !(hi >> 3 == 0);
-      bytes.push((hasMoreBits ? splitBits | 128 : splitBits) & 255);
-      if (!hasMoreBits) {
-        return;
-      }
-      for (let i = 3; i < 31; i = i + 7) {
-        const shift = hi >>> i;
-        const hasNext = !(shift >>> 7 == 0);
-        const byte = (hasNext ? shift | 128 : shift) & 255;
-        bytes.push(byte);
-        if (!hasNext) {
-          return;
-        }
+    exports2.binaryWriteOptions = binaryWriteOptions;
+    var BinaryWriter = class {
+      constructor(textEncoder) {
+        this.stack = [];
+        this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder();
+        this.chunks = [];
+        this.buf = [];
       }
-      bytes.push(hi >>> 31 & 1);
-    }
-    exports2.varint64write = varint64write;
-    var TWO_PWR_32_DBL2 = (1 << 16) * (1 << 16);
-    function int64fromString(dec) {
-      let minus = dec[0] == "-";
-      if (minus)
-        dec = dec.slice(1);
-      const base = 1e6;
-      let lowBits = 0;
-      let highBits = 0;
-      function add1e6digit(begin, end) {
-        const digit1e6 = Number(dec.slice(begin, end));
-        highBits *= base;
-        lowBits = lowBits * base + digit1e6;
-        if (lowBits >= TWO_PWR_32_DBL2) {
-          highBits = highBits + (lowBits / TWO_PWR_32_DBL2 | 0);
-          lowBits = lowBits % TWO_PWR_32_DBL2;
+      /**
+       * Return all bytes written and reset this writer.
+       */
+      finish() {
+        this.chunks.push(new Uint8Array(this.buf));
+        let len = 0;
+        for (let i = 0; i < this.chunks.length; i++)
+          len += this.chunks[i].length;
+        let bytes = new Uint8Array(len);
+        let offset = 0;
+        for (let i = 0; i < this.chunks.length; i++) {
+          bytes.set(this.chunks[i], offset);
+          offset += this.chunks[i].length;
         }
+        this.chunks = [];
+        return bytes;
       }
-      add1e6digit(-24, -18);
-      add1e6digit(-18, -12);
-      add1e6digit(-12, -6);
-      add1e6digit(-6);
-      return [minus, lowBits, highBits];
-    }
-    exports2.int64fromString = int64fromString;
-    function int64toString(bitsLow, bitsHigh) {
-      if (bitsHigh >>> 0 <= 2097151) {
-        return "" + (TWO_PWR_32_DBL2 * bitsHigh + (bitsLow >>> 0));
+      /**
+       * Start a new fork for length-delimited data like a message
+       * or a packed repeated field.
+       *
+       * Must be joined later with `join()`.
+       */
+      fork() {
+        this.stack.push({ chunks: this.chunks, buf: this.buf });
+        this.chunks = [];
+        this.buf = [];
+        return this;
       }
-      let low = bitsLow & 16777215;
-      let mid = (bitsLow >>> 24 | bitsHigh << 8) >>> 0 & 16777215;
-      let high = bitsHigh >> 16 & 65535;
-      let digitA = low + mid * 6777216 + high * 6710656;
-      let digitB = mid + high * 8147497;
-      let digitC = high * 2;
-      let base = 1e7;
-      if (digitA >= base) {
-        digitB += Math.floor(digitA / base);
-        digitA %= base;
+      /**
+       * Join the last fork. Write its length and bytes, then
+       * return to the previous state.
+       */
+      join() {
+        let chunk = this.finish();
+        let prev = this.stack.pop();
+        if (!prev)
+          throw new Error("invalid state, fork stack empty");
+        this.chunks = prev.chunks;
+        this.buf = prev.buf;
+        this.uint32(chunk.byteLength);
+        return this.raw(chunk);
       }
-      if (digitB >= base) {
-        digitC += Math.floor(digitB / base);
-        digitB %= base;
+      /**
+       * Writes a tag (field number and wire type).
+       *
+       * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
+       *
+       * Generated code should compute the tag ahead of time and call `uint32()`.
+       */
+      tag(fieldNo, type2) {
+        return this.uint32((fieldNo << 3 | type2) >>> 0);
       }
-      function decimalFrom1e7(digit1e7, needLeadingZeros) {
-        let partial = digit1e7 ? String(digit1e7) : "";
-        if (needLeadingZeros) {
-          return "0000000".slice(partial.length) + partial;
+      /**
+       * Write a chunk of raw bytes.
+       */
+      raw(chunk) {
+        if (this.buf.length) {
+          this.chunks.push(new Uint8Array(this.buf));
+          this.buf = [];
         }
-        return partial;
+        this.chunks.push(chunk);
+        return this;
       }
-      return decimalFrom1e7(
-        digitC,
-        /*needLeadingZeros=*/
-        0
-      ) + decimalFrom1e7(
-        digitB,
-        /*needLeadingZeros=*/
-        digitC
-      ) + // If the final 1e7 digit didn't need leading zeros, we would have
-      // returned via the trivial code path at the top.
-      decimalFrom1e7(
-        digitA,
-        /*needLeadingZeros=*/
-        1
-      );
-    }
-    exports2.int64toString = int64toString;
-    function varint32write(value, bytes) {
-      if (value >= 0) {
+      /**
+       * Write a `uint32` value, an unsigned 32 bit varint.
+       */
+      uint32(value) {
+        assert_1.assertUInt32(value);
         while (value > 127) {
-          bytes.push(value & 127 | 128);
+          this.buf.push(value & 127 | 128);
           value = value >>> 7;
         }
-        bytes.push(value);
-      } else {
-        for (let i = 0; i < 9; i++) {
-          bytes.push(value & 127 | 128);
-          value = value >> 7;
-        }
-        bytes.push(1);
-      }
-    }
-    exports2.varint32write = varint32write;
-    function varint32read() {
-      let b = this.buf[this.pos++];
-      let result = b & 127;
-      if ((b & 128) == 0) {
-        this.assertBounds();
-        return result;
+        this.buf.push(value);
+        return this;
       }
-      b = this.buf[this.pos++];
-      result |= (b & 127) << 7;
-      if ((b & 128) == 0) {
-        this.assertBounds();
-        return result;
+      /**
+       * Write a `int32` value, a signed 32 bit varint.
+       */
+      int32(value) {
+        assert_1.assertInt32(value);
+        goog_varint_1.varint32write(value, this.buf);
+        return this;
       }
-      b = this.buf[this.pos++];
-      result |= (b & 127) << 14;
-      if ((b & 128) == 0) {
-        this.assertBounds();
-        return result;
+      /**
+       * Write a `bool` value, a variant.
+       */
+      bool(value) {
+        this.buf.push(value ? 1 : 0);
+        return this;
       }
-      b = this.buf[this.pos++];
-      result |= (b & 127) << 21;
-      if ((b & 128) == 0) {
-        this.assertBounds();
-        return result;
+      /**
+       * Write a `bytes` value, length-delimited arbitrary data.
+       */
+      bytes(value) {
+        this.uint32(value.byteLength);
+        return this.raw(value);
       }
-      b = this.buf[this.pos++];
-      result |= (b & 15) << 28;
-      for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++)
-        b = this.buf[this.pos++];
-      if ((b & 128) != 0)
-        throw new Error("invalid varint");
-      this.assertBounds();
-      return result >>> 0;
-    }
-    exports2.varint32read = varint32read;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js
-var require_pb_long = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/pb-long.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.PbLong = exports2.PbULong = exports2.detectBi = void 0;
-    var goog_varint_1 = require_goog_varint();
-    var BI;
-    function detectBi() {
-      const dv = new DataView(new ArrayBuffer(8));
-      const ok = globalThis.BigInt !== void 0 && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function";
-      BI = ok ? {
-        MIN: BigInt("-9223372036854775808"),
-        MAX: BigInt("9223372036854775807"),
-        UMIN: BigInt("0"),
-        UMAX: BigInt("18446744073709551615"),
-        C: BigInt,
-        V: dv
-      } : void 0;
-    }
-    exports2.detectBi = detectBi;
-    detectBi();
-    function assertBi(bi) {
-      if (!bi)
-        throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support");
-    }
-    var RE_DECIMAL_STR = /^-?[0-9]+$/;
-    var TWO_PWR_32_DBL2 = 4294967296;
-    var HALF_2_PWR_32 = 2147483648;
-    var SharedPbLong = class {
       /**
-       * Create a new instance with the given bits.
+       * Write a `string` value, length-delimited data converted to UTF-8 text.
        */
-      constructor(lo, hi) {
-        this.lo = lo | 0;
-        this.hi = hi | 0;
+      string(value) {
+        let chunk = this.textEncoder.encode(value);
+        this.uint32(chunk.byteLength);
+        return this.raw(chunk);
       }
       /**
-       * Is this instance equal to 0?
+       * Write a `float` value, 32-bit floating point number.
        */
-      isZero() {
-        return this.lo == 0 && this.hi == 0;
+      float(value) {
+        assert_1.assertFloat32(value);
+        let chunk = new Uint8Array(4);
+        new DataView(chunk.buffer).setFloat32(0, value, true);
+        return this.raw(chunk);
       }
       /**
-       * Convert to a native number.
+       * Write a `double` value, a 64-bit floating point number.
        */
-      toNumber() {
-        let result = this.hi * TWO_PWR_32_DBL2 + (this.lo >>> 0);
-        if (!Number.isSafeInteger(result))
-          throw new Error("cannot convert to safe number");
-        return result;
+      double(value) {
+        let chunk = new Uint8Array(8);
+        new DataView(chunk.buffer).setFloat64(0, value, true);
+        return this.raw(chunk);
       }
-    };
-    var PbULong = class _PbULong extends SharedPbLong {
       /**
-       * Create instance from a `string`, `number` or `bigint`.
+       * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
        */
-      static from(value) {
-        if (BI)
-          switch (typeof value) {
-            case "string":
-              if (value == "0")
-                return this.ZERO;
-              if (value == "")
-                throw new Error("string is no integer");
-              value = BI.C(value);
-            case "number":
-              if (value === 0)
-                return this.ZERO;
-              value = BI.C(value);
-            case "bigint":
-              if (!value)
-                return this.ZERO;
-              if (value < BI.UMIN)
-                throw new Error("signed value for ulong");
-              if (value > BI.UMAX)
-                throw new Error("ulong too large");
-              BI.V.setBigUint64(0, value, true);
-              return new _PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
-          }
-        else
-          switch (typeof value) {
-            case "string":
-              if (value == "0")
-                return this.ZERO;
-              value = value.trim();
-              if (!RE_DECIMAL_STR.test(value))
-                throw new Error("string is no integer");
-              let [minus, lo, hi] = goog_varint_1.int64fromString(value);
-              if (minus)
-                throw new Error("signed value for ulong");
-              return new _PbULong(lo, hi);
-            case "number":
-              if (value == 0)
-                return this.ZERO;
-              if (!Number.isSafeInteger(value))
-                throw new Error("number is no integer");
-              if (value < 0)
-                throw new Error("signed value for ulong");
-              return new _PbULong(value, value / TWO_PWR_32_DBL2);
-          }
-        throw new Error("unknown value " + typeof value);
+      fixed32(value) {
+        assert_1.assertUInt32(value);
+        let chunk = new Uint8Array(4);
+        new DataView(chunk.buffer).setUint32(0, value, true);
+        return this.raw(chunk);
       }
       /**
-       * Convert to decimal string.
+       * Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
        */
-      toString() {
-        return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi);
+      sfixed32(value) {
+        assert_1.assertInt32(value);
+        let chunk = new Uint8Array(4);
+        new DataView(chunk.buffer).setInt32(0, value, true);
+        return this.raw(chunk);
       }
       /**
-       * Convert to native bigint.
+       * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
        */
-      toBigInt() {
-        assertBi(BI);
-        BI.V.setInt32(0, this.lo, true);
-        BI.V.setInt32(4, this.hi, true);
-        return BI.V.getBigUint64(0, true);
+      sint32(value) {
+        assert_1.assertInt32(value);
+        value = (value << 1 ^ value >> 31) >>> 0;
+        goog_varint_1.varint32write(value, this.buf);
+        return this;
       }
-    };
-    exports2.PbULong = PbULong;
-    PbULong.ZERO = new PbULong(0, 0);
-    var PbLong = class _PbLong extends SharedPbLong {
       /**
-       * Create instance from a `string`, `number` or `bigint`.
+       * Write a `fixed64` value, a signed, fixed-length 64-bit integer.
        */
-      static from(value) {
-        if (BI)
-          switch (typeof value) {
-            case "string":
-              if (value == "0")
-                return this.ZERO;
-              if (value == "")
-                throw new Error("string is no integer");
-              value = BI.C(value);
-            case "number":
-              if (value === 0)
-                return this.ZERO;
-              value = BI.C(value);
-            case "bigint":
-              if (!value)
-                return this.ZERO;
-              if (value < BI.MIN)
-                throw new Error("signed long too small");
-              if (value > BI.MAX)
-                throw new Error("signed long too large");
-              BI.V.setBigInt64(0, value, true);
-              return new _PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
-          }
-        else
-          switch (typeof value) {
-            case "string":
-              if (value == "0")
-                return this.ZERO;
-              value = value.trim();
-              if (!RE_DECIMAL_STR.test(value))
-                throw new Error("string is no integer");
-              let [minus, lo, hi] = goog_varint_1.int64fromString(value);
-              if (minus) {
-                if (hi > HALF_2_PWR_32 || hi == HALF_2_PWR_32 && lo != 0)
-                  throw new Error("signed long too small");
-              } else if (hi >= HALF_2_PWR_32)
-                throw new Error("signed long too large");
-              let pbl = new _PbLong(lo, hi);
-              return minus ? pbl.negate() : pbl;
-            case "number":
-              if (value == 0)
-                return this.ZERO;
-              if (!Number.isSafeInteger(value))
-                throw new Error("number is no integer");
-              return value > 0 ? new _PbLong(value, value / TWO_PWR_32_DBL2) : new _PbLong(-value, -value / TWO_PWR_32_DBL2).negate();
-          }
-        throw new Error("unknown value " + typeof value);
+      sfixed64(value) {
+        let chunk = new Uint8Array(8);
+        let view = new DataView(chunk.buffer);
+        let long = pb_long_1.PbLong.from(value);
+        view.setInt32(0, long.lo, true);
+        view.setInt32(4, long.hi, true);
+        return this.raw(chunk);
       }
       /**
-       * Do we have a minus sign?
+       * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
        */
-      isNegative() {
-        return (this.hi & HALF_2_PWR_32) !== 0;
+      fixed64(value) {
+        let chunk = new Uint8Array(8);
+        let view = new DataView(chunk.buffer);
+        let long = pb_long_1.PbULong.from(value);
+        view.setInt32(0, long.lo, true);
+        view.setInt32(4, long.hi, true);
+        return this.raw(chunk);
       }
       /**
-       * Negate two's complement.
-       * Invert all the bits and add one to the result.
+       * Write a `int64` value, a signed 64-bit varint.
        */
-      negate() {
-        let hi = ~this.hi, lo = this.lo;
-        if (lo)
-          lo = ~lo + 1;
-        else
-          hi += 1;
-        return new _PbLong(lo, hi);
+      int64(value) {
+        let long = pb_long_1.PbLong.from(value);
+        goog_varint_1.varint64write(long.lo, long.hi, this.buf);
+        return this;
       }
       /**
-       * Convert to decimal string.
+       * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
        */
-      toString() {
-        if (BI)
-          return this.toBigInt().toString();
-        if (this.isNegative()) {
-          let n = this.negate();
-          return "-" + goog_varint_1.int64toString(n.lo, n.hi);
-        }
-        return goog_varint_1.int64toString(this.lo, this.hi);
+      sint64(value) {
+        let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign;
+        goog_varint_1.varint64write(lo, hi, this.buf);
+        return this;
       }
       /**
-       * Convert to native bigint.
+       * Write a `uint64` value, an unsigned 64-bit varint.
        */
-      toBigInt() {
-        assertBi(BI);
-        BI.V.setInt32(0, this.lo, true);
-        BI.V.setInt32(4, this.hi, true);
-        return BI.V.getBigInt64(0, true);
+      uint64(value) {
+        let long = pb_long_1.PbULong.from(value);
+        goog_varint_1.varint64write(long.lo, long.hi, this.buf);
+        return this;
+      }
+    };
+    exports2.BinaryWriter = BinaryWriter;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js
+var require_json_format_contract = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0;
+    var defaultsWrite = {
+      emitDefaultValues: false,
+      enumAsInteger: false,
+      useProtoFieldName: false,
+      prettySpaces: 0
+    };
+    var defaultsRead = {
+      ignoreUnknownFields: false
+    };
+    function jsonReadOptions(options) {
+      return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
+    }
+    exports2.jsonReadOptions = jsonReadOptions;
+    function jsonWriteOptions(options) {
+      return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
+    }
+    exports2.jsonWriteOptions = jsonWriteOptions;
+    function mergeJsonOptions(a, b) {
+      var _a, _b;
+      let c = Object.assign(Object.assign({}, a), b);
+      c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []];
+      return c;
+    }
+    exports2.mergeJsonOptions = mergeJsonOptions;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js
+var require_message_type_contract = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.MESSAGE_TYPE = void 0;
+    exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type");
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js
+var require_lower_camel_case = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.lowerCamelCase = void 0;
+    function lowerCamelCase(snakeCase) {
+      let capNext = false;
+      const sb = [];
+      for (let i = 0; i < snakeCase.length; i++) {
+        let next = snakeCase.charAt(i);
+        if (next == "_") {
+          capNext = true;
+        } else if (/\d/.test(next)) {
+          sb.push(next);
+          capNext = true;
+        } else if (capNext) {
+          sb.push(next.toUpperCase());
+          capNext = false;
+        } else if (i == 0) {
+          sb.push(next.toLowerCase());
+        } else {
+          sb.push(next);
+        }
+      }
+      return sb.join("");
+    }
+    exports2.lowerCamelCase = lowerCamelCase;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js
+var require_reflection_info = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0;
+    var lower_camel_case_1 = require_lower_camel_case();
+    var ScalarType;
+    (function(ScalarType2) {
+      ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE";
+      ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT";
+      ScalarType2[ScalarType2["INT64"] = 3] = "INT64";
+      ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64";
+      ScalarType2[ScalarType2["INT32"] = 5] = "INT32";
+      ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64";
+      ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32";
+      ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL";
+      ScalarType2[ScalarType2["STRING"] = 9] = "STRING";
+      ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES";
+      ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32";
+      ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32";
+      ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64";
+      ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32";
+      ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64";
+    })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {}));
+    var LongType;
+    (function(LongType2) {
+      LongType2[LongType2["BIGINT"] = 0] = "BIGINT";
+      LongType2[LongType2["STRING"] = 1] = "STRING";
+      LongType2[LongType2["NUMBER"] = 2] = "NUMBER";
+    })(LongType = exports2.LongType || (exports2.LongType = {}));
+    var RepeatType;
+    (function(RepeatType2) {
+      RepeatType2[RepeatType2["NO"] = 0] = "NO";
+      RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED";
+      RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED";
+    })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {}));
+    function normalizeFieldInfo(field) {
+      var _a, _b, _c, _d;
+      field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name);
+      field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name);
+      field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO;
+      field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message";
+      return field;
+    }
+    exports2.normalizeFieldInfo = normalizeFieldInfo;
+    function readFieldOptions(messageType, fieldName, extensionName, extensionType) {
+      var _a;
+      const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options;
+      return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0;
+    }
+    exports2.readFieldOptions = readFieldOptions;
+    function readFieldOption(messageType, fieldName, extensionName, extensionType) {
+      var _a;
+      const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options;
+      if (!options) {
+        return void 0;
+      }
+      const optionVal = options[extensionName];
+      if (optionVal === void 0) {
+        return optionVal;
+      }
+      return extensionType ? extensionType.fromJson(optionVal) : optionVal;
+    }
+    exports2.readFieldOption = readFieldOption;
+    function readMessageOption(messageType, extensionName, extensionType) {
+      const options = messageType.options;
+      const optionVal = options[extensionName];
+      if (optionVal === void 0) {
+        return optionVal;
+      }
+      return extensionType ? extensionType.fromJson(optionVal) : optionVal;
+    }
+    exports2.readMessageOption = readMessageOption;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js
+var require_oneof = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0;
+    function isOneofGroup(any) {
+      if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) {
+        return false;
+      }
+      switch (typeof any.oneofKind) {
+        case "string":
+          if (any[any.oneofKind] === void 0)
+            return false;
+          return Object.keys(any).length == 2;
+        case "undefined":
+          return Object.keys(any).length == 1;
+        default:
+          return false;
+      }
+    }
+    exports2.isOneofGroup = isOneofGroup;
+    function getOneofValue(oneof, kind) {
+      return oneof[kind];
+    }
+    exports2.getOneofValue = getOneofValue;
+    function setOneofValue(oneof, kind, value) {
+      if (oneof.oneofKind !== void 0) {
+        delete oneof[oneof.oneofKind];
+      }
+      oneof.oneofKind = kind;
+      if (value !== void 0) {
+        oneof[kind] = value;
+      }
+    }
+    exports2.setOneofValue = setOneofValue;
+    function setUnknownOneofValue(oneof, kind, value) {
+      if (oneof.oneofKind !== void 0) {
+        delete oneof[oneof.oneofKind];
+      }
+      oneof.oneofKind = kind;
+      if (value !== void 0 && kind !== void 0) {
+        oneof[kind] = value;
+      }
+    }
+    exports2.setUnknownOneofValue = setUnknownOneofValue;
+    function clearOneofValue(oneof) {
+      if (oneof.oneofKind !== void 0) {
+        delete oneof[oneof.oneofKind];
       }
-    };
-    exports2.PbLong = PbLong;
-    PbLong.ZERO = new PbLong(0, 0);
+      oneof.oneofKind = void 0;
+    }
+    exports2.clearOneofValue = clearOneofValue;
+    function getSelectedOneofValue(oneof) {
+      if (oneof.oneofKind === void 0) {
+        return void 0;
+      }
+      return oneof[oneof.oneofKind];
+    }
+    exports2.getSelectedOneofValue = getSelectedOneofValue;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js
-var require_binary_reader = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/binary-reader.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js
+var require_reflection_type_check = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.BinaryReader = exports2.binaryReadOptions = void 0;
-    var binary_format_contract_1 = require_binary_format_contract();
-    var pb_long_1 = require_pb_long();
-    var goog_varint_1 = require_goog_varint();
-    var defaultsRead = {
-      readUnknownField: true,
-      readerFactory: (bytes) => new BinaryReader(bytes)
-    };
-    function binaryReadOptions(options) {
-      return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
-    }
-    exports2.binaryReadOptions = binaryReadOptions;
-    var BinaryReader = class {
-      constructor(buf, textDecoder) {
-        this.varint64 = goog_varint_1.varint64read;
-        this.uint32 = goog_varint_1.varint32read;
-        this.buf = buf;
-        this.len = buf.length;
-        this.pos = 0;
-        this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
-        this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", {
-          fatal: true,
-          ignoreBOM: true
-        });
-      }
-      /**
-       * Reads a tag - field number and wire type.
-       */
-      tag() {
-        let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;
-        if (fieldNo <= 0 || wireType < 0 || wireType > 5)
-          throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
-        return [fieldNo, wireType];
+    exports2.ReflectionTypeCheck = void 0;
+    var reflection_info_1 = require_reflection_info();
+    var oneof_1 = require_oneof();
+    var ReflectionTypeCheck = class {
+      constructor(info6) {
+        var _a;
+        this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : [];
       }
-      /**
-       * Skip one element on the wire and return the skipped data.
-       * Supports WireType.StartGroup since v2.0.0-alpha.23.
-       */
-      skip(wireType) {
-        let start = this.pos;
-        switch (wireType) {
-          case binary_format_contract_1.WireType.Varint:
-            while (this.buf[this.pos++] & 128) {
+      prepare() {
+        if (this.data)
+          return;
+        const req = [], known = [], oneofs = [];
+        for (let field of this.fields) {
+          if (field.oneof) {
+            if (!oneofs.includes(field.oneof)) {
+              oneofs.push(field.oneof);
+              req.push(field.oneof);
+              known.push(field.oneof);
             }
-            break;
-          case binary_format_contract_1.WireType.Bit64:
-            this.pos += 4;
-          case binary_format_contract_1.WireType.Bit32:
-            this.pos += 4;
-            break;
-          case binary_format_contract_1.WireType.LengthDelimited:
-            let len = this.uint32();
-            this.pos += len;
-            break;
-          case binary_format_contract_1.WireType.StartGroup:
-            let t;
-            while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) {
-              this.skip(t);
+          } else {
+            known.push(field.localName);
+            switch (field.kind) {
+              case "scalar":
+              case "enum":
+                if (!field.opt || field.repeat)
+                  req.push(field.localName);
+                break;
+              case "message":
+                if (field.repeat)
+                  req.push(field.localName);
+                break;
+              case "map":
+                req.push(field.localName);
+                break;
             }
-            break;
-          default:
-            throw new Error("cant skip wire type " + wireType);
+          }
         }
-        this.assertBounds();
-        return this.buf.subarray(start, this.pos);
-      }
-      /**
-       * Throws error if position in byte array is out of range.
-       */
-      assertBounds() {
-        if (this.pos > this.len)
-          throw new RangeError("premature EOF");
+        this.data = { req, known, oneofs: Object.values(oneofs) };
       }
       /**
-       * Read a `int32` field, a signed 32 bit varint.
+       * Is the argument a valid message as specified by the
+       * reflection information?
+       *
+       * Checks all field types recursively. The `depth`
+       * specifies how deep into the structure the check will be.
+       *
+       * With a depth of 0, only the presence of fields
+       * is checked.
+       *
+       * With a depth of 1 or more, the field types are checked.
+       *
+       * With a depth of 2 or more, the members of map, repeated
+       * and message fields are checked.
+       *
+       * Message fields will be checked recursively with depth - 1.
+       *
+       * The number of map entries / repeated values being checked
+       * is < depth.
        */
-      int32() {
-        return this.uint32() | 0;
+      is(message, depth, allowExcessProperties = false) {
+        if (depth < 0)
+          return true;
+        if (message === null || message === void 0 || typeof message != "object")
+          return false;
+        this.prepare();
+        let keys = Object.keys(message), data = this.data;
+        if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n)))
+          return false;
+        if (!allowExcessProperties) {
+          if (keys.some((k) => !data.known.includes(k)))
+            return false;
+        }
+        if (depth < 1) {
+          return true;
+        }
+        for (const name of data.oneofs) {
+          const group = message[name];
+          if (!oneof_1.isOneofGroup(group))
+            return false;
+          if (group.oneofKind === void 0)
+            continue;
+          const field = this.fields.find((f) => f.localName === group.oneofKind);
+          if (!field)
+            return false;
+          if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth))
+            return false;
+        }
+        for (const field of this.fields) {
+          if (field.oneof !== void 0)
+            continue;
+          if (!this.field(message[field.localName], field, allowExcessProperties, depth))
+            return false;
+        }
+        return true;
       }
-      /**
-       * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
-       */
-      sint32() {
-        let zze = this.uint32();
-        return zze >>> 1 ^ -(zze & 1);
+      field(arg, field, allowExcessProperties, depth) {
+        let repeated = field.repeat;
+        switch (field.kind) {
+          case "scalar":
+            if (arg === void 0)
+              return field.opt;
+            if (repeated)
+              return this.scalars(arg, field.T, depth, field.L);
+            return this.scalar(arg, field.T, field.L);
+          case "enum":
+            if (arg === void 0)
+              return field.opt;
+            if (repeated)
+              return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth);
+            return this.scalar(arg, reflection_info_1.ScalarType.INT32);
+          case "message":
+            if (arg === void 0)
+              return true;
+            if (repeated)
+              return this.messages(arg, field.T(), allowExcessProperties, depth);
+            return this.message(arg, field.T(), allowExcessProperties, depth);
+          case "map":
+            if (typeof arg != "object" || arg === null)
+              return false;
+            if (depth < 2)
+              return true;
+            if (!this.mapKeys(arg, field.K, depth))
+              return false;
+            switch (field.V.kind) {
+              case "scalar":
+                return this.scalars(Object.values(arg), field.V.T, depth, field.V.L);
+              case "enum":
+                return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth);
+              case "message":
+                return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth);
+            }
+            break;
+        }
+        return true;
       }
-      /**
-       * Read a `int64` field, a signed 64-bit varint.
-       */
-      int64() {
-        return new pb_long_1.PbLong(...this.varint64());
+      message(arg, type2, allowExcessProperties, depth) {
+        if (allowExcessProperties) {
+          return type2.isAssignable(arg, depth);
+        }
+        return type2.is(arg, depth);
       }
-      /**
-       * Read a `uint64` field, an unsigned 64-bit varint.
-       */
-      uint64() {
-        return new pb_long_1.PbULong(...this.varint64());
+      messages(arg, type2, allowExcessProperties, depth) {
+        if (!Array.isArray(arg))
+          return false;
+        if (depth < 2)
+          return true;
+        if (allowExcessProperties) {
+          for (let i = 0; i < arg.length && i < depth; i++)
+            if (!type2.isAssignable(arg[i], depth - 1))
+              return false;
+        } else {
+          for (let i = 0; i < arg.length && i < depth; i++)
+            if (!type2.is(arg[i], depth - 1))
+              return false;
+        }
+        return true;
       }
-      /**
-       * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
-       */
-      sint64() {
-        let [lo, hi] = this.varint64();
-        let s = -(lo & 1);
-        lo = (lo >>> 1 | (hi & 1) << 31) ^ s;
-        hi = hi >>> 1 ^ s;
-        return new pb_long_1.PbLong(lo, hi);
+      scalar(arg, type2, longType) {
+        let argType = typeof arg;
+        switch (type2) {
+          case reflection_info_1.ScalarType.UINT64:
+          case reflection_info_1.ScalarType.FIXED64:
+          case reflection_info_1.ScalarType.INT64:
+          case reflection_info_1.ScalarType.SFIXED64:
+          case reflection_info_1.ScalarType.SINT64:
+            switch (longType) {
+              case reflection_info_1.LongType.BIGINT:
+                return argType == "bigint";
+              case reflection_info_1.LongType.NUMBER:
+                return argType == "number" && !isNaN(arg);
+              default:
+                return argType == "string";
+            }
+          case reflection_info_1.ScalarType.BOOL:
+            return argType == "boolean";
+          case reflection_info_1.ScalarType.STRING:
+            return argType == "string";
+          case reflection_info_1.ScalarType.BYTES:
+            return arg instanceof Uint8Array;
+          case reflection_info_1.ScalarType.DOUBLE:
+          case reflection_info_1.ScalarType.FLOAT:
+            return argType == "number" && !isNaN(arg);
+          default:
+            return argType == "number" && Number.isInteger(arg);
+        }
       }
-      /**
-       * Read a `bool` field, a variant.
-       */
-      bool() {
-        let [lo, hi] = this.varint64();
-        return lo !== 0 || hi !== 0;
+      scalars(arg, type2, depth, longType) {
+        if (!Array.isArray(arg))
+          return false;
+        if (depth < 2)
+          return true;
+        if (Array.isArray(arg)) {
+          for (let i = 0; i < arg.length && i < depth; i++)
+            if (!this.scalar(arg[i], type2, longType))
+              return false;
+        }
+        return true;
       }
-      /**
-       * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
-       */
-      fixed32() {
-        return this.view.getUint32((this.pos += 4) - 4, true);
+      mapKeys(map2, type2, depth) {
+        let keys = Object.keys(map2);
+        switch (type2) {
+          case reflection_info_1.ScalarType.INT32:
+          case reflection_info_1.ScalarType.FIXED32:
+          case reflection_info_1.ScalarType.SFIXED32:
+          case reflection_info_1.ScalarType.SINT32:
+          case reflection_info_1.ScalarType.UINT32:
+            return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth);
+          case reflection_info_1.ScalarType.BOOL:
+            return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth);
+          default:
+            return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING);
+        }
       }
-      /**
-       * Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
-       */
-      sfixed32() {
-        return this.view.getInt32((this.pos += 4) - 4, true);
+    };
+    exports2.ReflectionTypeCheck = ReflectionTypeCheck;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js
+var require_reflection_long_convert = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.reflectionLongConvert = void 0;
+    var reflection_info_1 = require_reflection_info();
+    function reflectionLongConvert(long, type2) {
+      switch (type2) {
+        case reflection_info_1.LongType.BIGINT:
+          return long.toBigInt();
+        case reflection_info_1.LongType.NUMBER:
+          return long.toNumber();
+        default:
+          return long.toString();
       }
-      /**
-       * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
-       */
-      fixed64() {
-        return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32());
+    }
+    exports2.reflectionLongConvert = reflectionLongConvert;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js
+var require_reflection_json_reader = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.ReflectionJsonReader = void 0;
+    var json_typings_1 = require_json_typings();
+    var base64_1 = require_base642();
+    var reflection_info_1 = require_reflection_info();
+    var pb_long_1 = require_pb_long();
+    var assert_1 = require_assert();
+    var reflection_long_convert_1 = require_reflection_long_convert();
+    var ReflectionJsonReader = class {
+      constructor(info6) {
+        this.info = info6;
       }
-      /**
-       * Read a `fixed64` field, a signed, fixed-length 64-bit integer.
-       */
-      sfixed64() {
-        return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32());
+      prepare() {
+        var _a;
+        if (this.fMap === void 0) {
+          this.fMap = {};
+          const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
+          for (const field of fieldsInput) {
+            this.fMap[field.name] = field;
+            this.fMap[field.jsonName] = field;
+            this.fMap[field.localName] = field;
+          }
+        }
       }
-      /**
-       * Read a `float` field, 32-bit floating point number.
-       */
-      float() {
-        return this.view.getFloat32((this.pos += 4) - 4, true);
+      // Cannot parse JSON  for #.
+      assert(condition, fieldName, jsonValue) {
+        if (!condition) {
+          let what = json_typings_1.typeofJsonValue(jsonValue);
+          if (what == "number" || what == "boolean")
+            what = jsonValue.toString();
+          throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`);
+        }
       }
       /**
-       * Read a `double` field, a 64-bit floating point number.
+       * Reads a message from canonical JSON format into the target message.
+       *
+       * Repeated fields are appended. Map entries are added, overwriting
+       * existing keys.
+       *
+       * If a message field is already present, it will be merged with the
+       * new data.
        */
-      double() {
-        return this.view.getFloat64((this.pos += 8) - 8, true);
+      read(input, message, options) {
+        this.prepare();
+        const oneofsHandled = [];
+        for (const [jsonKey, jsonValue] of Object.entries(input)) {
+          const field = this.fMap[jsonKey];
+          if (!field) {
+            if (!options.ignoreUnknownFields)
+              throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`);
+            continue;
+          }
+          const localName = field.localName;
+          let target;
+          if (field.oneof) {
+            if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) {
+              continue;
+            }
+            if (oneofsHandled.includes(field.oneof))
+              throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`);
+            oneofsHandled.push(field.oneof);
+            target = message[field.oneof] = {
+              oneofKind: localName
+            };
+          } else {
+            target = message;
+          }
+          if (field.kind == "map") {
+            if (jsonValue === null) {
+              continue;
+            }
+            this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue);
+            const fieldObj = target[localName];
+            for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) {
+              this.assert(jsonObjValue !== null, field.name + " map value", null);
+              let val2;
+              switch (field.V.kind) {
+                case "message":
+                  val2 = field.V.T().internalJsonRead(jsonObjValue, options);
+                  break;
+                case "enum":
+                  val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields);
+                  if (val2 === false)
+                    continue;
+                  break;
+                case "scalar":
+                  val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name);
+                  break;
+              }
+              this.assert(val2 !== void 0, field.name + " map value", jsonObjValue);
+              let key = jsonObjKey;
+              if (field.K == reflection_info_1.ScalarType.BOOL)
+                key = key == "true" ? true : key == "false" ? false : key;
+              key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString();
+              fieldObj[key] = val2;
+            }
+          } else if (field.repeat) {
+            if (jsonValue === null)
+              continue;
+            this.assert(Array.isArray(jsonValue), field.name, jsonValue);
+            const fieldArr = target[localName];
+            for (const jsonItem of jsonValue) {
+              this.assert(jsonItem !== null, field.name, null);
+              let val2;
+              switch (field.kind) {
+                case "message":
+                  val2 = field.T().internalJsonRead(jsonItem, options);
+                  break;
+                case "enum":
+                  val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields);
+                  if (val2 === false)
+                    continue;
+                  break;
+                case "scalar":
+                  val2 = this.scalar(jsonItem, field.T, field.L, field.name);
+                  break;
+              }
+              this.assert(val2 !== void 0, field.name, jsonValue);
+              fieldArr.push(val2);
+            }
+          } else {
+            switch (field.kind) {
+              case "message":
+                if (jsonValue === null && field.T().typeName != "google.protobuf.Value") {
+                  this.assert(field.oneof === void 0, field.name + " (oneof member)", null);
+                  continue;
+                }
+                target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]);
+                break;
+              case "enum":
+                if (jsonValue === null)
+                  continue;
+                let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields);
+                if (val2 === false)
+                  continue;
+                target[localName] = val2;
+                break;
+              case "scalar":
+                if (jsonValue === null)
+                  continue;
+                target[localName] = this.scalar(jsonValue, field.T, field.L, field.name);
+                break;
+            }
+          }
+        }
       }
       /**
-       * Read a `bytes` field, length-delimited arbitrary data.
+       * Returns `false` for unrecognized string representations.
+       *
+       * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`).
        */
-      bytes() {
-        let len = this.uint32();
-        let start = this.pos;
-        this.pos += len;
-        this.assertBounds();
-        return this.buf.subarray(start, start + len);
+      enum(type2, json2, fieldName, ignoreUnknownFields) {
+        if (type2[0] == "google.protobuf.NullValue")
+          assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`);
+        if (json2 === null)
+          return 0;
+        switch (typeof json2) {
+          case "number":
+            assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`);
+            return json2;
+          case "string":
+            let localEnumName = json2;
+            if (type2[2] && json2.substring(0, type2[2].length) === type2[2])
+              localEnumName = json2.substring(type2[2].length);
+            let enumNumber = type2[1][localEnumName];
+            if (typeof enumNumber === "undefined" && ignoreUnknownFields) {
+              return false;
+            }
+            assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`);
+            return enumNumber;
+        }
+        assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`);
       }
-      /**
-       * Read a `string` field, length-delimited data converted to UTF-8 text.
-       */
-      string() {
-        return this.textDecoder.decode(this.bytes());
+      scalar(json2, type2, longType, fieldName) {
+        let e;
+        try {
+          switch (type2) {
+            // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
+            // Either numbers or strings are accepted. Exponent notation is also accepted.
+            case reflection_info_1.ScalarType.DOUBLE:
+            case reflection_info_1.ScalarType.FLOAT:
+              if (json2 === null)
+                return 0;
+              if (json2 === "NaN")
+                return Number.NaN;
+              if (json2 === "Infinity")
+                return Number.POSITIVE_INFINITY;
+              if (json2 === "-Infinity")
+                return Number.NEGATIVE_INFINITY;
+              if (json2 === "") {
+                e = "empty string";
+                break;
+              }
+              if (typeof json2 == "string" && json2.trim().length !== json2.length) {
+                e = "extra whitespace";
+                break;
+              }
+              if (typeof json2 != "string" && typeof json2 != "number") {
+                break;
+              }
+              let float2 = Number(json2);
+              if (Number.isNaN(float2)) {
+                e = "not a number";
+                break;
+              }
+              if (!Number.isFinite(float2)) {
+                e = "too large or small";
+                break;
+              }
+              if (type2 == reflection_info_1.ScalarType.FLOAT)
+                assert_1.assertFloat32(float2);
+              return float2;
+            // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
+            case reflection_info_1.ScalarType.INT32:
+            case reflection_info_1.ScalarType.FIXED32:
+            case reflection_info_1.ScalarType.SFIXED32:
+            case reflection_info_1.ScalarType.SINT32:
+            case reflection_info_1.ScalarType.UINT32:
+              if (json2 === null)
+                return 0;
+              let int32;
+              if (typeof json2 == "number")
+                int32 = json2;
+              else if (json2 === "")
+                e = "empty string";
+              else if (typeof json2 == "string") {
+                if (json2.trim().length !== json2.length)
+                  e = "extra whitespace";
+                else
+                  int32 = Number(json2);
+              }
+              if (int32 === void 0)
+                break;
+              if (type2 == reflection_info_1.ScalarType.UINT32)
+                assert_1.assertUInt32(int32);
+              else
+                assert_1.assertInt32(int32);
+              return int32;
+            // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted.
+            case reflection_info_1.ScalarType.INT64:
+            case reflection_info_1.ScalarType.SFIXED64:
+            case reflection_info_1.ScalarType.SINT64:
+              if (json2 === null)
+                return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType);
+              if (typeof json2 != "number" && typeof json2 != "string")
+                break;
+              return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType);
+            case reflection_info_1.ScalarType.FIXED64:
+            case reflection_info_1.ScalarType.UINT64:
+              if (json2 === null)
+                return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType);
+              if (typeof json2 != "number" && typeof json2 != "string")
+                break;
+              return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType);
+            // bool:
+            case reflection_info_1.ScalarType.BOOL:
+              if (json2 === null)
+                return false;
+              if (typeof json2 !== "boolean")
+                break;
+              return json2;
+            // string:
+            case reflection_info_1.ScalarType.STRING:
+              if (json2 === null)
+                return "";
+              if (typeof json2 !== "string") {
+                e = "extra whitespace";
+                break;
+              }
+              try {
+                encodeURIComponent(json2);
+              } catch (e2) {
+                e2 = "invalid UTF8";
+                break;
+              }
+              return json2;
+            // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
+            // Either standard or URL-safe base64 encoding with/without paddings are accepted.
+            case reflection_info_1.ScalarType.BYTES:
+              if (json2 === null || json2 === "")
+                return new Uint8Array(0);
+              if (typeof json2 !== "string")
+                break;
+              return base64_1.base64decode(json2);
+          }
+        } catch (error4) {
+          e = error4.message;
+        }
+        this.assert(false, fieldName + (e ? " - " + e : ""), json2);
       }
     };
-    exports2.BinaryReader = BinaryReader;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime/build/commonjs/assert.js
-var require_assert = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/assert.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.assertFloat32 = exports2.assertUInt32 = exports2.assertInt32 = exports2.assertNever = exports2.assert = void 0;
-    function assert(condition, msg) {
-      if (!condition) {
-        throw new Error(msg);
-      }
-    }
-    exports2.assert = assert;
-    function assertNever2(value, msg) {
-      throw new Error(msg !== null && msg !== void 0 ? msg : "Unexpected object: " + value);
-    }
-    exports2.assertNever = assertNever2;
-    var FLOAT32_MAX = 34028234663852886e22;
-    var FLOAT32_MIN = -34028234663852886e22;
-    var UINT32_MAX = 4294967295;
-    var INT32_MAX = 2147483647;
-    var INT32_MIN = -2147483648;
-    function assertInt32(arg) {
-      if (typeof arg !== "number")
-        throw new Error("invalid int 32: " + typeof arg);
-      if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN)
-        throw new Error("invalid int 32: " + arg);
-    }
-    exports2.assertInt32 = assertInt32;
-    function assertUInt32(arg) {
-      if (typeof arg !== "number")
-        throw new Error("invalid uint 32: " + typeof arg);
-      if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0)
-        throw new Error("invalid uint 32: " + arg);
-    }
-    exports2.assertUInt32 = assertUInt32;
-    function assertFloat32(arg) {
-      if (typeof arg !== "number")
-        throw new Error("invalid float 32: " + typeof arg);
-      if (!Number.isFinite(arg))
-        return;
-      if (arg > FLOAT32_MAX || arg < FLOAT32_MIN)
-        throw new Error("invalid float 32: " + arg);
-    }
-    exports2.assertFloat32 = assertFloat32;
+    exports2.ReflectionJsonReader = ReflectionJsonReader;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js
-var require_binary_writer = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/binary-writer.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js
+var require_reflection_json_writer = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.BinaryWriter = exports2.binaryWriteOptions = void 0;
+    exports2.ReflectionJsonWriter = void 0;
+    var base64_1 = require_base642();
     var pb_long_1 = require_pb_long();
-    var goog_varint_1 = require_goog_varint();
+    var reflection_info_1 = require_reflection_info();
     var assert_1 = require_assert();
-    var defaultsWrite = {
-      writeUnknownFields: true,
-      writerFactory: () => new BinaryWriter()
-    };
-    function binaryWriteOptions(options) {
-      return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
-    }
-    exports2.binaryWriteOptions = binaryWriteOptions;
-    var BinaryWriter = class {
-      constructor(textEncoder) {
-        this.stack = [];
-        this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder();
-        this.chunks = [];
-        this.buf = [];
+    var ReflectionJsonWriter = class {
+      constructor(info6) {
+        var _a;
+        this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : [];
       }
       /**
-       * Return all bytes written and reset this writer.
+       * Converts the message to a JSON object, based on the field descriptors.
        */
-      finish() {
-        this.chunks.push(new Uint8Array(this.buf));
-        let len = 0;
-        for (let i = 0; i < this.chunks.length; i++)
-          len += this.chunks[i].length;
-        let bytes = new Uint8Array(len);
-        let offset = 0;
-        for (let i = 0; i < this.chunks.length; i++) {
-          bytes.set(this.chunks[i], offset);
-          offset += this.chunks[i].length;
+      write(message, options) {
+        const json2 = {}, source = message;
+        for (const field of this.fields) {
+          if (!field.oneof) {
+            let jsonValue2 = this.field(field, source[field.localName], options);
+            if (jsonValue2 !== void 0)
+              json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2;
+            continue;
+          }
+          const group = source[field.oneof];
+          if (group.oneofKind !== field.localName)
+            continue;
+          const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options;
+          let jsonValue = this.field(field, group[field.localName], opt);
+          assert_1.assert(jsonValue !== void 0);
+          json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue;
         }
-        this.chunks = [];
-        return bytes;
-      }
-      /**
-       * Start a new fork for length-delimited data like a message
-       * or a packed repeated field.
-       *
-       * Must be joined later with `join()`.
-       */
-      fork() {
-        this.stack.push({ chunks: this.chunks, buf: this.buf });
-        this.chunks = [];
-        this.buf = [];
-        return this;
-      }
-      /**
-       * Join the last fork. Write its length and bytes, then
-       * return to the previous state.
-       */
-      join() {
-        let chunk = this.finish();
-        let prev = this.stack.pop();
-        if (!prev)
-          throw new Error("invalid state, fork stack empty");
-        this.chunks = prev.chunks;
-        this.buf = prev.buf;
-        this.uint32(chunk.byteLength);
-        return this.raw(chunk);
-      }
-      /**
-       * Writes a tag (field number and wire type).
-       *
-       * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
-       *
-       * Generated code should compute the tag ahead of time and call `uint32()`.
-       */
-      tag(fieldNo, type2) {
-        return this.uint32((fieldNo << 3 | type2) >>> 0);
+        return json2;
       }
-      /**
-       * Write a chunk of raw bytes.
-       */
-      raw(chunk) {
-        if (this.buf.length) {
-          this.chunks.push(new Uint8Array(this.buf));
-          this.buf = [];
+      field(field, value, options) {
+        let jsonValue = void 0;
+        if (field.kind == "map") {
+          assert_1.assert(typeof value == "object" && value !== null);
+          const jsonObj = {};
+          switch (field.V.kind) {
+            case "scalar":
+              for (const [entryKey, entryValue] of Object.entries(value)) {
+                const val2 = this.scalar(field.V.T, entryValue, field.name, false, true);
+                assert_1.assert(val2 !== void 0);
+                jsonObj[entryKey.toString()] = val2;
+              }
+              break;
+            case "message":
+              const messageType = field.V.T();
+              for (const [entryKey, entryValue] of Object.entries(value)) {
+                const val2 = this.message(messageType, entryValue, field.name, options);
+                assert_1.assert(val2 !== void 0);
+                jsonObj[entryKey.toString()] = val2;
+              }
+              break;
+            case "enum":
+              const enumInfo = field.V.T();
+              for (const [entryKey, entryValue] of Object.entries(value)) {
+                assert_1.assert(entryValue === void 0 || typeof entryValue == "number");
+                const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger);
+                assert_1.assert(val2 !== void 0);
+                jsonObj[entryKey.toString()] = val2;
+              }
+              break;
+          }
+          if (options.emitDefaultValues || Object.keys(jsonObj).length > 0)
+            jsonValue = jsonObj;
+        } else if (field.repeat) {
+          assert_1.assert(Array.isArray(value));
+          const jsonArr = [];
+          switch (field.kind) {
+            case "scalar":
+              for (let i = 0; i < value.length; i++) {
+                const val2 = this.scalar(field.T, value[i], field.name, field.opt, true);
+                assert_1.assert(val2 !== void 0);
+                jsonArr.push(val2);
+              }
+              break;
+            case "enum":
+              const enumInfo = field.T();
+              for (let i = 0; i < value.length; i++) {
+                assert_1.assert(value[i] === void 0 || typeof value[i] == "number");
+                const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger);
+                assert_1.assert(val2 !== void 0);
+                jsonArr.push(val2);
+              }
+              break;
+            case "message":
+              const messageType = field.T();
+              for (let i = 0; i < value.length; i++) {
+                const val2 = this.message(messageType, value[i], field.name, options);
+                assert_1.assert(val2 !== void 0);
+                jsonArr.push(val2);
+              }
+              break;
+          }
+          if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues)
+            jsonValue = jsonArr;
+        } else {
+          switch (field.kind) {
+            case "scalar":
+              jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues);
+              break;
+            case "enum":
+              jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger);
+              break;
+            case "message":
+              jsonValue = this.message(field.T(), value, field.name, options);
+              break;
+          }
         }
-        this.chunks.push(chunk);
-        return this;
+        return jsonValue;
       }
       /**
-       * Write a `uint32` value, an unsigned 32 bit varint.
+       * Returns `null` as the default for google.protobuf.NullValue.
        */
-      uint32(value) {
-        assert_1.assertUInt32(value);
-        while (value > 127) {
-          this.buf.push(value & 127 | 128);
-          value = value >>> 7;
+      enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) {
+        if (type2[0] == "google.protobuf.NullValue")
+          return !emitDefaultValues && !optional ? void 0 : null;
+        if (value === void 0) {
+          assert_1.assert(optional);
+          return void 0;
         }
-        this.buf.push(value);
-        return this;
-      }
-      /**
-       * Write a `int32` value, a signed 32 bit varint.
-       */
-      int32(value) {
-        assert_1.assertInt32(value);
-        goog_varint_1.varint32write(value, this.buf);
-        return this;
-      }
-      /**
-       * Write a `bool` value, a variant.
-       */
-      bool(value) {
-        this.buf.push(value ? 1 : 0);
-        return this;
-      }
-      /**
-       * Write a `bytes` value, length-delimited arbitrary data.
-       */
-      bytes(value) {
-        this.uint32(value.byteLength);
-        return this.raw(value);
-      }
-      /**
-       * Write a `string` value, length-delimited data converted to UTF-8 text.
-       */
-      string(value) {
-        let chunk = this.textEncoder.encode(value);
-        this.uint32(chunk.byteLength);
-        return this.raw(chunk);
-      }
-      /**
-       * Write a `float` value, 32-bit floating point number.
-       */
-      float(value) {
-        assert_1.assertFloat32(value);
-        let chunk = new Uint8Array(4);
-        new DataView(chunk.buffer).setFloat32(0, value, true);
-        return this.raw(chunk);
-      }
-      /**
-       * Write a `double` value, a 64-bit floating point number.
-       */
-      double(value) {
-        let chunk = new Uint8Array(8);
-        new DataView(chunk.buffer).setFloat64(0, value, true);
-        return this.raw(chunk);
-      }
-      /**
-       * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
-       */
-      fixed32(value) {
-        assert_1.assertUInt32(value);
-        let chunk = new Uint8Array(4);
-        new DataView(chunk.buffer).setUint32(0, value, true);
-        return this.raw(chunk);
-      }
-      /**
-       * Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
-       */
-      sfixed32(value) {
-        assert_1.assertInt32(value);
-        let chunk = new Uint8Array(4);
-        new DataView(chunk.buffer).setInt32(0, value, true);
-        return this.raw(chunk);
-      }
-      /**
-       * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
-       */
-      sint32(value) {
-        assert_1.assertInt32(value);
-        value = (value << 1 ^ value >> 31) >>> 0;
-        goog_varint_1.varint32write(value, this.buf);
-        return this;
-      }
-      /**
-       * Write a `fixed64` value, a signed, fixed-length 64-bit integer.
-       */
-      sfixed64(value) {
-        let chunk = new Uint8Array(8);
-        let view = new DataView(chunk.buffer);
-        let long = pb_long_1.PbLong.from(value);
-        view.setInt32(0, long.lo, true);
-        view.setInt32(4, long.hi, true);
-        return this.raw(chunk);
-      }
-      /**
-       * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
-       */
-      fixed64(value) {
-        let chunk = new Uint8Array(8);
-        let view = new DataView(chunk.buffer);
-        let long = pb_long_1.PbULong.from(value);
-        view.setInt32(0, long.lo, true);
-        view.setInt32(4, long.hi, true);
-        return this.raw(chunk);
-      }
-      /**
-       * Write a `int64` value, a signed 64-bit varint.
-       */
-      int64(value) {
-        let long = pb_long_1.PbLong.from(value);
-        goog_varint_1.varint64write(long.lo, long.hi, this.buf);
-        return this;
+        if (value === 0 && !emitDefaultValues && !optional)
+          return void 0;
+        assert_1.assert(typeof value == "number");
+        assert_1.assert(Number.isInteger(value));
+        if (enumAsInteger || !type2[1].hasOwnProperty(value))
+          return value;
+        if (type2[2])
+          return type2[2] + type2[1][value];
+        return type2[1][value];
       }
-      /**
-       * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
-       */
-      sint64(value) {
-        let long = pb_long_1.PbLong.from(value), sign = long.hi >> 31, lo = long.lo << 1 ^ sign, hi = (long.hi << 1 | long.lo >>> 31) ^ sign;
-        goog_varint_1.varint64write(lo, hi, this.buf);
-        return this;
+      message(type2, value, fieldName, options) {
+        if (value === void 0)
+          return options.emitDefaultValues ? null : void 0;
+        return type2.internalJsonWrite(value, options);
       }
-      /**
-       * Write a `uint64` value, an unsigned 64-bit varint.
-       */
-      uint64(value) {
-        let long = pb_long_1.PbULong.from(value);
-        goog_varint_1.varint64write(long.lo, long.hi, this.buf);
-        return this;
+      scalar(type2, value, fieldName, optional, emitDefaultValues) {
+        if (value === void 0) {
+          assert_1.assert(optional);
+          return void 0;
+        }
+        const ed = emitDefaultValues || optional;
+        switch (type2) {
+          // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
+          case reflection_info_1.ScalarType.INT32:
+          case reflection_info_1.ScalarType.SFIXED32:
+          case reflection_info_1.ScalarType.SINT32:
+            if (value === 0)
+              return ed ? 0 : void 0;
+            assert_1.assertInt32(value);
+            return value;
+          case reflection_info_1.ScalarType.FIXED32:
+          case reflection_info_1.ScalarType.UINT32:
+            if (value === 0)
+              return ed ? 0 : void 0;
+            assert_1.assertUInt32(value);
+            return value;
+          // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
+          // Either numbers or strings are accepted. Exponent notation is also accepted.
+          case reflection_info_1.ScalarType.FLOAT:
+            assert_1.assertFloat32(value);
+          case reflection_info_1.ScalarType.DOUBLE:
+            if (value === 0)
+              return ed ? 0 : void 0;
+            assert_1.assert(typeof value == "number");
+            if (Number.isNaN(value))
+              return "NaN";
+            if (value === Number.POSITIVE_INFINITY)
+              return "Infinity";
+            if (value === Number.NEGATIVE_INFINITY)
+              return "-Infinity";
+            return value;
+          // string:
+          case reflection_info_1.ScalarType.STRING:
+            if (value === "")
+              return ed ? "" : void 0;
+            assert_1.assert(typeof value == "string");
+            return value;
+          // bool:
+          case reflection_info_1.ScalarType.BOOL:
+            if (value === false)
+              return ed ? false : void 0;
+            assert_1.assert(typeof value == "boolean");
+            return value;
+          // JSON value will be a decimal string. Either numbers or strings are accepted.
+          case reflection_info_1.ScalarType.UINT64:
+          case reflection_info_1.ScalarType.FIXED64:
+            assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint");
+            let ulong = pb_long_1.PbULong.from(value);
+            if (ulong.isZero() && !ed)
+              return void 0;
+            return ulong.toString();
+          // JSON value will be a decimal string. Either numbers or strings are accepted.
+          case reflection_info_1.ScalarType.INT64:
+          case reflection_info_1.ScalarType.SFIXED64:
+          case reflection_info_1.ScalarType.SINT64:
+            assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint");
+            let long = pb_long_1.PbLong.from(value);
+            if (long.isZero() && !ed)
+              return void 0;
+            return long.toString();
+          // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
+          // Either standard or URL-safe base64 encoding with/without paddings are accepted.
+          case reflection_info_1.ScalarType.BYTES:
+            assert_1.assert(value instanceof Uint8Array);
+            if (!value.byteLength)
+              return ed ? "" : void 0;
+            return base64_1.base64encode(value);
+        }
       }
     };
-    exports2.BinaryWriter = BinaryWriter;
+    exports2.ReflectionJsonWriter = ReflectionJsonWriter;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js
-var require_json_format_contract = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/json-format-contract.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js
+var require_reflection_scalar_default = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.mergeJsonOptions = exports2.jsonWriteOptions = exports2.jsonReadOptions = void 0;
-    var defaultsWrite = {
-      emitDefaultValues: false,
-      enumAsInteger: false,
-      useProtoFieldName: false,
-      prettySpaces: 0
-    };
-    var defaultsRead = {
-      ignoreUnknownFields: false
-    };
-    function jsonReadOptions(options) {
-      return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
-    }
-    exports2.jsonReadOptions = jsonReadOptions;
-    function jsonWriteOptions(options) {
-      return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
-    }
-    exports2.jsonWriteOptions = jsonWriteOptions;
-    function mergeJsonOptions(a, b) {
-      var _a, _b;
-      let c = Object.assign(Object.assign({}, a), b);
-      c.typeRegistry = [...(_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : [], ...(_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : []];
-      return c;
+    exports2.reflectionScalarDefault = void 0;
+    var reflection_info_1 = require_reflection_info();
+    var reflection_long_convert_1 = require_reflection_long_convert();
+    var pb_long_1 = require_pb_long();
+    function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) {
+      switch (type2) {
+        case reflection_info_1.ScalarType.BOOL:
+          return false;
+        case reflection_info_1.ScalarType.UINT64:
+        case reflection_info_1.ScalarType.FIXED64:
+          return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType);
+        case reflection_info_1.ScalarType.INT64:
+        case reflection_info_1.ScalarType.SFIXED64:
+        case reflection_info_1.ScalarType.SINT64:
+          return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType);
+        case reflection_info_1.ScalarType.DOUBLE:
+        case reflection_info_1.ScalarType.FLOAT:
+          return 0;
+        case reflection_info_1.ScalarType.BYTES:
+          return new Uint8Array(0);
+        case reflection_info_1.ScalarType.STRING:
+          return "";
+        default:
+          return 0;
+      }
     }
-    exports2.mergeJsonOptions = mergeJsonOptions;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js
-var require_message_type_contract = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/message-type-contract.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.MESSAGE_TYPE = void 0;
-    exports2.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type");
+    exports2.reflectionScalarDefault = reflectionScalarDefault;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js
-var require_lower_camel_case = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/lower-camel-case.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js
+var require_reflection_binary_reader = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.lowerCamelCase = void 0;
-    function lowerCamelCase(snakeCase) {
-      let capNext = false;
-      const sb = [];
-      for (let i = 0; i < snakeCase.length; i++) {
-        let next = snakeCase.charAt(i);
-        if (next == "_") {
-          capNext = true;
-        } else if (/\d/.test(next)) {
-          sb.push(next);
-          capNext = true;
-        } else if (capNext) {
-          sb.push(next.toUpperCase());
-          capNext = false;
-        } else if (i == 0) {
-          sb.push(next.toLowerCase());
-        } else {
-          sb.push(next);
+    exports2.ReflectionBinaryReader = void 0;
+    var binary_format_contract_1 = require_binary_format_contract();
+    var reflection_info_1 = require_reflection_info();
+    var reflection_long_convert_1 = require_reflection_long_convert();
+    var reflection_scalar_default_1 = require_reflection_scalar_default();
+    var ReflectionBinaryReader = class {
+      constructor(info6) {
+        this.info = info6;
+      }
+      prepare() {
+        var _a;
+        if (!this.fieldNoToField) {
+          const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
+          this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field]));
         }
       }
-      return sb.join("");
-    }
-    exports2.lowerCamelCase = lowerCamelCase;
+      /**
+       * Reads a message from binary format into the target message.
+       *
+       * Repeated fields are appended. Map entries are added, overwriting
+       * existing keys.
+       *
+       * If a message field is already present, it will be merged with the
+       * new data.
+       */
+      read(reader, message, options, length) {
+        this.prepare();
+        const end = length === void 0 ? reader.len : reader.pos + length;
+        while (reader.pos < end) {
+          const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo);
+          if (!field) {
+            let u = options.readUnknownField;
+            if (u == "throw")
+              throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`);
+            let d = reader.skip(wireType);
+            if (u !== false)
+              (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d);
+            continue;
+          }
+          let target = message, repeated = field.repeat, localName = field.localName;
+          if (field.oneof) {
+            target = target[field.oneof];
+            if (target.oneofKind !== localName)
+              target = message[field.oneof] = {
+                oneofKind: localName
+              };
+          }
+          switch (field.kind) {
+            case "scalar":
+            case "enum":
+              let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
+              let L = field.kind == "scalar" ? field.L : void 0;
+              if (repeated) {
+                let arr = target[localName];
+                if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) {
+                  let e = reader.uint32() + reader.pos;
+                  while (reader.pos < e)
+                    arr.push(this.scalar(reader, T, L));
+                } else
+                  arr.push(this.scalar(reader, T, L));
+              } else
+                target[localName] = this.scalar(reader, T, L);
+              break;
+            case "message":
+              if (repeated) {
+                let arr = target[localName];
+                let msg = field.T().internalBinaryRead(reader, reader.uint32(), options);
+                arr.push(msg);
+              } else
+                target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]);
+              break;
+            case "map":
+              let [mapKey, mapVal] = this.mapEntry(field, reader, options);
+              target[localName][mapKey] = mapVal;
+              break;
+          }
+        }
+      }
+      /**
+       * Read a map field, expecting key field = 1, value field = 2
+       */
+      mapEntry(field, reader, options) {
+        let length = reader.uint32();
+        let end = reader.pos + length;
+        let key = void 0;
+        let val2 = void 0;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case 1:
+              if (field.K == reflection_info_1.ScalarType.BOOL)
+                key = reader.bool().toString();
+              else
+                key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING);
+              break;
+            case 2:
+              switch (field.V.kind) {
+                case "scalar":
+                  val2 = this.scalar(reader, field.V.T, field.V.L);
+                  break;
+                case "enum":
+                  val2 = reader.int32();
+                  break;
+                case "message":
+                  val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options);
+                  break;
+              }
+              break;
+            default:
+              throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`);
+          }
+        }
+        if (key === void 0) {
+          let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K);
+          key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw;
+        }
+        if (val2 === void 0)
+          switch (field.V.kind) {
+            case "scalar":
+              val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L);
+              break;
+            case "enum":
+              val2 = 0;
+              break;
+            case "message":
+              val2 = field.V.T().create();
+              break;
+          }
+        return [key, val2];
+      }
+      scalar(reader, type2, longType) {
+        switch (type2) {
+          case reflection_info_1.ScalarType.INT32:
+            return reader.int32();
+          case reflection_info_1.ScalarType.STRING:
+            return reader.string();
+          case reflection_info_1.ScalarType.BOOL:
+            return reader.bool();
+          case reflection_info_1.ScalarType.DOUBLE:
+            return reader.double();
+          case reflection_info_1.ScalarType.FLOAT:
+            return reader.float();
+          case reflection_info_1.ScalarType.INT64:
+            return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType);
+          case reflection_info_1.ScalarType.UINT64:
+            return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType);
+          case reflection_info_1.ScalarType.FIXED64:
+            return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType);
+          case reflection_info_1.ScalarType.FIXED32:
+            return reader.fixed32();
+          case reflection_info_1.ScalarType.BYTES:
+            return reader.bytes();
+          case reflection_info_1.ScalarType.UINT32:
+            return reader.uint32();
+          case reflection_info_1.ScalarType.SFIXED32:
+            return reader.sfixed32();
+          case reflection_info_1.ScalarType.SFIXED64:
+            return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType);
+          case reflection_info_1.ScalarType.SINT32:
+            return reader.sint32();
+          case reflection_info_1.ScalarType.SINT64:
+            return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType);
+        }
+      }
+    };
+    exports2.ReflectionBinaryReader = ReflectionBinaryReader;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js
-var require_reflection_info = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-info.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js
+var require_reflection_binary_writer = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.readMessageOption = exports2.readFieldOption = exports2.readFieldOptions = exports2.normalizeFieldInfo = exports2.RepeatType = exports2.LongType = exports2.ScalarType = void 0;
-    var lower_camel_case_1 = require_lower_camel_case();
-    var ScalarType;
-    (function(ScalarType2) {
-      ScalarType2[ScalarType2["DOUBLE"] = 1] = "DOUBLE";
-      ScalarType2[ScalarType2["FLOAT"] = 2] = "FLOAT";
-      ScalarType2[ScalarType2["INT64"] = 3] = "INT64";
-      ScalarType2[ScalarType2["UINT64"] = 4] = "UINT64";
-      ScalarType2[ScalarType2["INT32"] = 5] = "INT32";
-      ScalarType2[ScalarType2["FIXED64"] = 6] = "FIXED64";
-      ScalarType2[ScalarType2["FIXED32"] = 7] = "FIXED32";
-      ScalarType2[ScalarType2["BOOL"] = 8] = "BOOL";
-      ScalarType2[ScalarType2["STRING"] = 9] = "STRING";
-      ScalarType2[ScalarType2["BYTES"] = 12] = "BYTES";
-      ScalarType2[ScalarType2["UINT32"] = 13] = "UINT32";
-      ScalarType2[ScalarType2["SFIXED32"] = 15] = "SFIXED32";
-      ScalarType2[ScalarType2["SFIXED64"] = 16] = "SFIXED64";
-      ScalarType2[ScalarType2["SINT32"] = 17] = "SINT32";
-      ScalarType2[ScalarType2["SINT64"] = 18] = "SINT64";
-    })(ScalarType = exports2.ScalarType || (exports2.ScalarType = {}));
-    var LongType;
-    (function(LongType2) {
-      LongType2[LongType2["BIGINT"] = 0] = "BIGINT";
-      LongType2[LongType2["STRING"] = 1] = "STRING";
-      LongType2[LongType2["NUMBER"] = 2] = "NUMBER";
-    })(LongType = exports2.LongType || (exports2.LongType = {}));
-    var RepeatType;
-    (function(RepeatType2) {
-      RepeatType2[RepeatType2["NO"] = 0] = "NO";
-      RepeatType2[RepeatType2["PACKED"] = 1] = "PACKED";
-      RepeatType2[RepeatType2["UNPACKED"] = 2] = "UNPACKED";
-    })(RepeatType = exports2.RepeatType || (exports2.RepeatType = {}));
-    function normalizeFieldInfo(field) {
-      var _a, _b, _c, _d;
-      field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name);
-      field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name);
-      field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO;
-      field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : field.repeat ? false : field.oneof ? false : field.kind == "message";
-      return field;
-    }
-    exports2.normalizeFieldInfo = normalizeFieldInfo;
-    function readFieldOptions(messageType, fieldName, extensionName, extensionType) {
-      var _a;
-      const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options;
-      return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0;
-    }
-    exports2.readFieldOptions = readFieldOptions;
-    function readFieldOption(messageType, fieldName, extensionName, extensionType) {
-      var _a;
-      const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options;
-      if (!options) {
-        return void 0;
+    exports2.ReflectionBinaryWriter = void 0;
+    var binary_format_contract_1 = require_binary_format_contract();
+    var reflection_info_1 = require_reflection_info();
+    var assert_1 = require_assert();
+    var pb_long_1 = require_pb_long();
+    var ReflectionBinaryWriter = class {
+      constructor(info6) {
+        this.info = info6;
+      }
+      prepare() {
+        if (!this.fields) {
+          const fieldsInput = this.info.fields ? this.info.fields.concat() : [];
+          this.fields = fieldsInput.sort((a, b) => a.no - b.no);
+        }
+      }
+      /**
+       * Writes the message to binary format.
+       */
+      write(message, writer, options) {
+        this.prepare();
+        for (const field of this.fields) {
+          let value, emitDefault, repeated = field.repeat, localName = field.localName;
+          if (field.oneof) {
+            const group = message[field.oneof];
+            if (group.oneofKind !== localName)
+              continue;
+            value = group[localName];
+            emitDefault = true;
+          } else {
+            value = message[localName];
+            emitDefault = false;
+          }
+          switch (field.kind) {
+            case "scalar":
+            case "enum":
+              let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
+              if (repeated) {
+                assert_1.assert(Array.isArray(value));
+                if (repeated == reflection_info_1.RepeatType.PACKED)
+                  this.packed(writer, T, field.no, value);
+                else
+                  for (const item of value)
+                    this.scalar(writer, T, field.no, item, true);
+              } else if (value === void 0)
+                assert_1.assert(field.opt);
+              else
+                this.scalar(writer, T, field.no, value, emitDefault || field.opt);
+              break;
+            case "message":
+              if (repeated) {
+                assert_1.assert(Array.isArray(value));
+                for (const item of value)
+                  this.message(writer, options, field.T(), field.no, item);
+              } else {
+                this.message(writer, options, field.T(), field.no, value);
+              }
+              break;
+            case "map":
+              assert_1.assert(typeof value == "object" && value !== null);
+              for (const [key, val2] of Object.entries(value))
+                this.mapEntry(writer, options, field, key, val2);
+              break;
+          }
+        }
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer);
+      }
+      mapEntry(writer, options, field, key, value) {
+        writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited);
+        writer.fork();
+        let keyValue = key;
+        switch (field.K) {
+          case reflection_info_1.ScalarType.INT32:
+          case reflection_info_1.ScalarType.FIXED32:
+          case reflection_info_1.ScalarType.UINT32:
+          case reflection_info_1.ScalarType.SFIXED32:
+          case reflection_info_1.ScalarType.SINT32:
+            keyValue = Number.parseInt(key);
+            break;
+          case reflection_info_1.ScalarType.BOOL:
+            assert_1.assert(key == "true" || key == "false");
+            keyValue = key == "true";
+            break;
+        }
+        this.scalar(writer, field.K, 1, keyValue, true);
+        switch (field.V.kind) {
+          case "scalar":
+            this.scalar(writer, field.V.T, 2, value, true);
+            break;
+          case "enum":
+            this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true);
+            break;
+          case "message":
+            this.message(writer, options, field.V.T(), 2, value);
+            break;
+        }
+        writer.join();
       }
-      const optionVal = options[extensionName];
-      if (optionVal === void 0) {
-        return optionVal;
+      message(writer, options, handler, fieldNo, value) {
+        if (value === void 0)
+          return;
+        handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options);
+        writer.join();
       }
-      return extensionType ? extensionType.fromJson(optionVal) : optionVal;
-    }
-    exports2.readFieldOption = readFieldOption;
-    function readMessageOption(messageType, extensionName, extensionType) {
-      const options = messageType.options;
-      const optionVal = options[extensionName];
-      if (optionVal === void 0) {
-        return optionVal;
+      /**
+       * Write a single scalar value.
+       */
+      scalar(writer, type2, fieldNo, value, emitDefault) {
+        let [wireType, method, isDefault] = this.scalarInfo(type2, value);
+        if (!isDefault || emitDefault) {
+          writer.tag(fieldNo, wireType);
+          writer[method](value);
+        }
       }
-      return extensionType ? extensionType.fromJson(optionVal) : optionVal;
-    }
-    exports2.readMessageOption = readMessageOption;
+      /**
+       * Write an array of scalar values in packed format.
+       */
+      packed(writer, type2, fieldNo, value) {
+        if (!value.length)
+          return;
+        assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING);
+        writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited);
+        writer.fork();
+        let [, method] = this.scalarInfo(type2);
+        for (let i = 0; i < value.length; i++)
+          writer[method](value[i]);
+        writer.join();
+      }
+      /**
+       * Get information for writing a scalar value.
+       *
+       * Returns tuple:
+       * [0]: appropriate WireType
+       * [1]: name of the appropriate method of IBinaryWriter
+       * [2]: whether the given value is a default value
+       *
+       * If argument `value` is omitted, [2] is always false.
+       */
+      scalarInfo(type2, value) {
+        let t = binary_format_contract_1.WireType.Varint;
+        let m;
+        let i = value === void 0;
+        let d = value === 0;
+        switch (type2) {
+          case reflection_info_1.ScalarType.INT32:
+            m = "int32";
+            break;
+          case reflection_info_1.ScalarType.STRING:
+            d = i || !value.length;
+            t = binary_format_contract_1.WireType.LengthDelimited;
+            m = "string";
+            break;
+          case reflection_info_1.ScalarType.BOOL:
+            d = value === false;
+            m = "bool";
+            break;
+          case reflection_info_1.ScalarType.UINT32:
+            m = "uint32";
+            break;
+          case reflection_info_1.ScalarType.DOUBLE:
+            t = binary_format_contract_1.WireType.Bit64;
+            m = "double";
+            break;
+          case reflection_info_1.ScalarType.FLOAT:
+            t = binary_format_contract_1.WireType.Bit32;
+            m = "float";
+            break;
+          case reflection_info_1.ScalarType.INT64:
+            d = i || pb_long_1.PbLong.from(value).isZero();
+            m = "int64";
+            break;
+          case reflection_info_1.ScalarType.UINT64:
+            d = i || pb_long_1.PbULong.from(value).isZero();
+            m = "uint64";
+            break;
+          case reflection_info_1.ScalarType.FIXED64:
+            d = i || pb_long_1.PbULong.from(value).isZero();
+            t = binary_format_contract_1.WireType.Bit64;
+            m = "fixed64";
+            break;
+          case reflection_info_1.ScalarType.BYTES:
+            d = i || !value.byteLength;
+            t = binary_format_contract_1.WireType.LengthDelimited;
+            m = "bytes";
+            break;
+          case reflection_info_1.ScalarType.FIXED32:
+            t = binary_format_contract_1.WireType.Bit32;
+            m = "fixed32";
+            break;
+          case reflection_info_1.ScalarType.SFIXED32:
+            t = binary_format_contract_1.WireType.Bit32;
+            m = "sfixed32";
+            break;
+          case reflection_info_1.ScalarType.SFIXED64:
+            d = i || pb_long_1.PbLong.from(value).isZero();
+            t = binary_format_contract_1.WireType.Bit64;
+            m = "sfixed64";
+            break;
+          case reflection_info_1.ScalarType.SINT32:
+            m = "sint32";
+            break;
+          case reflection_info_1.ScalarType.SINT64:
+            d = i || pb_long_1.PbLong.from(value).isZero();
+            m = "sint64";
+            break;
+        }
+        return [t, m, i || d];
+      }
+    };
+    exports2.ReflectionBinaryWriter = ReflectionBinaryWriter;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js
-var require_oneof = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/oneof.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js
+var require_reflection_create = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.getSelectedOneofValue = exports2.clearOneofValue = exports2.setUnknownOneofValue = exports2.setOneofValue = exports2.getOneofValue = exports2.isOneofGroup = void 0;
-    function isOneofGroup(any) {
-      if (typeof any != "object" || any === null || !any.hasOwnProperty("oneofKind")) {
-        return false;
-      }
-      switch (typeof any.oneofKind) {
-        case "string":
-          if (any[any.oneofKind] === void 0)
-            return false;
-          return Object.keys(any).length == 2;
-        case "undefined":
-          return Object.keys(any).length == 1;
-        default:
-          return false;
-      }
-    }
-    exports2.isOneofGroup = isOneofGroup;
-    function getOneofValue(oneof, kind) {
-      return oneof[kind];
-    }
-    exports2.getOneofValue = getOneofValue;
-    function setOneofValue(oneof, kind, value) {
-      if (oneof.oneofKind !== void 0) {
-        delete oneof[oneof.oneofKind];
-      }
-      oneof.oneofKind = kind;
-      if (value !== void 0) {
-        oneof[kind] = value;
-      }
-    }
-    exports2.setOneofValue = setOneofValue;
-    function setUnknownOneofValue(oneof, kind, value) {
-      if (oneof.oneofKind !== void 0) {
-        delete oneof[oneof.oneofKind];
-      }
-      oneof.oneofKind = kind;
-      if (value !== void 0 && kind !== void 0) {
-        oneof[kind] = value;
-      }
-    }
-    exports2.setUnknownOneofValue = setUnknownOneofValue;
-    function clearOneofValue(oneof) {
-      if (oneof.oneofKind !== void 0) {
-        delete oneof[oneof.oneofKind];
-      }
-      oneof.oneofKind = void 0;
-    }
-    exports2.clearOneofValue = clearOneofValue;
-    function getSelectedOneofValue(oneof) {
-      if (oneof.oneofKind === void 0) {
-        return void 0;
+    exports2.reflectionCreate = void 0;
+    var reflection_scalar_default_1 = require_reflection_scalar_default();
+    var message_type_contract_1 = require_message_type_contract();
+    function reflectionCreate(type2) {
+      const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 });
+      for (let field of type2.fields) {
+        let name = field.localName;
+        if (field.opt)
+          continue;
+        if (field.oneof)
+          msg[field.oneof] = { oneofKind: void 0 };
+        else if (field.repeat)
+          msg[name] = [];
+        else
+          switch (field.kind) {
+            case "scalar":
+              msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L);
+              break;
+            case "enum":
+              msg[name] = 0;
+              break;
+            case "map":
+              msg[name] = {};
+              break;
+          }
       }
-      return oneof[oneof.oneofKind];
+      return msg;
     }
-    exports2.getSelectedOneofValue = getSelectedOneofValue;
+    exports2.reflectionCreate = reflectionCreate;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js
-var require_reflection_type_check = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-type-check.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js
+var require_reflection_merge_partial = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ReflectionTypeCheck = void 0;
-    var reflection_info_1 = require_reflection_info();
-    var oneof_1 = require_oneof();
-    var ReflectionTypeCheck = class {
-      constructor(info6) {
-        var _a;
-        this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : [];
-      }
-      prepare() {
-        if (this.data)
-          return;
-        const req = [], known = [], oneofs = [];
-        for (let field of this.fields) {
-          if (field.oneof) {
-            if (!oneofs.includes(field.oneof)) {
-              oneofs.push(field.oneof);
-              req.push(field.oneof);
-              known.push(field.oneof);
-            }
-          } else {
-            known.push(field.localName);
-            switch (field.kind) {
-              case "scalar":
-              case "enum":
-                if (!field.opt || field.repeat)
-                  req.push(field.localName);
-                break;
-              case "message":
-                if (field.repeat)
-                  req.push(field.localName);
-                break;
-              case "map":
-                req.push(field.localName);
-                break;
-            }
+    exports2.reflectionMergePartial = void 0;
+    function reflectionMergePartial(info6, target, source) {
+      let fieldValue, input = source, output;
+      for (let field of info6.fields) {
+        let name = field.localName;
+        if (field.oneof) {
+          const group = input[field.oneof];
+          if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) {
+            continue;
           }
-        }
-        this.data = { req, known, oneofs: Object.values(oneofs) };
-      }
-      /**
-       * Is the argument a valid message as specified by the
-       * reflection information?
-       *
-       * Checks all field types recursively. The `depth`
-       * specifies how deep into the structure the check will be.
-       *
-       * With a depth of 0, only the presence of fields
-       * is checked.
-       *
-       * With a depth of 1 or more, the field types are checked.
-       *
-       * With a depth of 2 or more, the members of map, repeated
-       * and message fields are checked.
-       *
-       * Message fields will be checked recursively with depth - 1.
-       *
-       * The number of map entries / repeated values being checked
-       * is < depth.
-       */
-      is(message, depth, allowExcessProperties = false) {
-        if (depth < 0)
-          return true;
-        if (message === null || message === void 0 || typeof message != "object")
-          return false;
-        this.prepare();
-        let keys = Object.keys(message), data = this.data;
-        if (keys.length < data.req.length || data.req.some((n) => !keys.includes(n)))
-          return false;
-        if (!allowExcessProperties) {
-          if (keys.some((k) => !data.known.includes(k)))
-            return false;
-        }
-        if (depth < 1) {
-          return true;
-        }
-        for (const name of data.oneofs) {
-          const group = message[name];
-          if (!oneof_1.isOneofGroup(group))
-            return false;
-          if (group.oneofKind === void 0)
+          fieldValue = group[name];
+          output = target[field.oneof];
+          output.oneofKind = group.oneofKind;
+          if (fieldValue == void 0) {
+            delete output[name];
             continue;
-          const field = this.fields.find((f) => f.localName === group.oneofKind);
-          if (!field)
-            return false;
-          if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth))
-            return false;
-        }
-        for (const field of this.fields) {
-          if (field.oneof !== void 0)
+          }
+        } else {
+          fieldValue = input[name];
+          output = target;
+          if (fieldValue == void 0) {
             continue;
-          if (!this.field(message[field.localName], field, allowExcessProperties, depth))
-            return false;
+          }
         }
-        return true;
-      }
-      field(arg, field, allowExcessProperties, depth) {
-        let repeated = field.repeat;
+        if (field.repeat)
+          output[name].length = fieldValue.length;
         switch (field.kind) {
           case "scalar":
-            if (arg === void 0)
-              return field.opt;
-            if (repeated)
-              return this.scalars(arg, field.T, depth, field.L);
-            return this.scalar(arg, field.T, field.L);
           case "enum":
-            if (arg === void 0)
-              return field.opt;
-            if (repeated)
-              return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth);
-            return this.scalar(arg, reflection_info_1.ScalarType.INT32);
+            if (field.repeat)
+              for (let i = 0; i < fieldValue.length; i++)
+                output[name][i] = fieldValue[i];
+            else
+              output[name] = fieldValue;
+            break;
           case "message":
-            if (arg === void 0)
-              return true;
-            if (repeated)
-              return this.messages(arg, field.T(), allowExcessProperties, depth);
-            return this.message(arg, field.T(), allowExcessProperties, depth);
+            let T = field.T();
+            if (field.repeat)
+              for (let i = 0; i < fieldValue.length; i++)
+                output[name][i] = T.create(fieldValue[i]);
+            else if (output[name] === void 0)
+              output[name] = T.create(fieldValue);
+            else
+              T.mergePartial(output[name], fieldValue);
+            break;
           case "map":
-            if (typeof arg != "object" || arg === null)
-              return false;
-            if (depth < 2)
-              return true;
-            if (!this.mapKeys(arg, field.K, depth))
-              return false;
             switch (field.V.kind) {
               case "scalar":
-                return this.scalars(Object.values(arg), field.V.T, depth, field.V.L);
               case "enum":
-                return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth);
+                Object.assign(output[name], fieldValue);
+                break;
               case "message":
-                return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth);
+                let T2 = field.V.T();
+                for (let k of Object.keys(fieldValue))
+                  output[name][k] = T2.create(fieldValue[k]);
+                break;
             }
             break;
         }
-        return true;
-      }
-      message(arg, type2, allowExcessProperties, depth) {
-        if (allowExcessProperties) {
-          return type2.isAssignable(arg, depth);
-        }
-        return type2.is(arg, depth);
-      }
-      messages(arg, type2, allowExcessProperties, depth) {
-        if (!Array.isArray(arg))
-          return false;
-        if (depth < 2)
-          return true;
-        if (allowExcessProperties) {
-          for (let i = 0; i < arg.length && i < depth; i++)
-            if (!type2.isAssignable(arg[i], depth - 1))
-              return false;
-        } else {
-          for (let i = 0; i < arg.length && i < depth; i++)
-            if (!type2.is(arg[i], depth - 1))
-              return false;
-        }
-        return true;
-      }
-      scalar(arg, type2, longType) {
-        let argType = typeof arg;
-        switch (type2) {
-          case reflection_info_1.ScalarType.UINT64:
-          case reflection_info_1.ScalarType.FIXED64:
-          case reflection_info_1.ScalarType.INT64:
-          case reflection_info_1.ScalarType.SFIXED64:
-          case reflection_info_1.ScalarType.SINT64:
-            switch (longType) {
-              case reflection_info_1.LongType.BIGINT:
-                return argType == "bigint";
-              case reflection_info_1.LongType.NUMBER:
-                return argType == "number" && !isNaN(arg);
-              default:
-                return argType == "string";
-            }
-          case reflection_info_1.ScalarType.BOOL:
-            return argType == "boolean";
-          case reflection_info_1.ScalarType.STRING:
-            return argType == "string";
-          case reflection_info_1.ScalarType.BYTES:
-            return arg instanceof Uint8Array;
-          case reflection_info_1.ScalarType.DOUBLE:
-          case reflection_info_1.ScalarType.FLOAT:
-            return argType == "number" && !isNaN(arg);
-          default:
-            return argType == "number" && Number.isInteger(arg);
-        }
-      }
-      scalars(arg, type2, depth, longType) {
-        if (!Array.isArray(arg))
-          return false;
-        if (depth < 2)
-          return true;
-        if (Array.isArray(arg)) {
-          for (let i = 0; i < arg.length && i < depth; i++)
-            if (!this.scalar(arg[i], type2, longType))
-              return false;
-        }
-        return true;
-      }
-      mapKeys(map2, type2, depth) {
-        let keys = Object.keys(map2);
-        switch (type2) {
-          case reflection_info_1.ScalarType.INT32:
-          case reflection_info_1.ScalarType.FIXED32:
-          case reflection_info_1.ScalarType.SFIXED32:
-          case reflection_info_1.ScalarType.SINT32:
-          case reflection_info_1.ScalarType.UINT32:
-            return this.scalars(keys.slice(0, depth).map((k) => parseInt(k)), type2, depth);
-          case reflection_info_1.ScalarType.BOOL:
-            return this.scalars(keys.slice(0, depth).map((k) => k == "true" ? true : k == "false" ? false : k), type2, depth);
-          default:
-            return this.scalars(keys, type2, depth, reflection_info_1.LongType.STRING);
-        }
       }
-    };
-    exports2.ReflectionTypeCheck = ReflectionTypeCheck;
+    }
+    exports2.reflectionMergePartial = reflectionMergePartial;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js
-var require_reflection_long_convert = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-long-convert.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js
+var require_reflection_equals = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.reflectionLongConvert = void 0;
+    exports2.reflectionEquals = void 0;
     var reflection_info_1 = require_reflection_info();
-    function reflectionLongConvert(long, type2) {
-      switch (type2) {
-        case reflection_info_1.LongType.BIGINT:
-          return long.toBigInt();
-        case reflection_info_1.LongType.NUMBER:
-          return long.toNumber();
-        default:
-          return long.toString();
+    function reflectionEquals(info6, a, b) {
+      if (a === b)
+        return true;
+      if (!a || !b)
+        return false;
+      for (let field of info6.fields) {
+        let localName = field.localName;
+        let val_a = field.oneof ? a[field.oneof][localName] : a[localName];
+        let val_b = field.oneof ? b[field.oneof][localName] : b[localName];
+        switch (field.kind) {
+          case "enum":
+          case "scalar":
+            let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
+            if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b)))
+              return false;
+            break;
+          case "map":
+            if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b))))
+              return false;
+            break;
+          case "message":
+            let T = field.T();
+            if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b)))
+              return false;
+            break;
+        }
       }
+      return true;
+    }
+    exports2.reflectionEquals = reflectionEquals;
+    var objectValues = Object.values;
+    function primitiveEq(type2, a, b) {
+      if (a === b)
+        return true;
+      if (type2 !== reflection_info_1.ScalarType.BYTES)
+        return false;
+      let ba = a;
+      let bb = b;
+      if (ba.length !== bb.length)
+        return false;
+      for (let i = 0; i < ba.length; i++)
+        if (ba[i] != bb[i])
+          return false;
+      return true;
+    }
+    function repeatedPrimitiveEq(type2, a, b) {
+      if (a.length !== b.length)
+        return false;
+      for (let i = 0; i < a.length; i++)
+        if (!primitiveEq(type2, a[i], b[i]))
+          return false;
+      return true;
+    }
+    function repeatedMsgEq(type2, a, b) {
+      if (a.length !== b.length)
+        return false;
+      for (let i = 0; i < a.length; i++)
+        if (!type2.equals(a[i], b[i]))
+          return false;
+      return true;
     }
-    exports2.reflectionLongConvert = reflectionLongConvert;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js
-var require_reflection_json_reader = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-reader.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js
+var require_message_type = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ReflectionJsonReader = void 0;
-    var json_typings_1 = require_json_typings();
-    var base64_1 = require_base642();
+    exports2.MessageType = void 0;
+    var message_type_contract_1 = require_message_type_contract();
     var reflection_info_1 = require_reflection_info();
-    var pb_long_1 = require_pb_long();
-    var assert_1 = require_assert();
-    var reflection_long_convert_1 = require_reflection_long_convert();
-    var ReflectionJsonReader = class {
-      constructor(info6) {
-        this.info = info6;
-      }
-      prepare() {
-        var _a;
-        if (this.fMap === void 0) {
-          this.fMap = {};
-          const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
-          for (const field of fieldsInput) {
-            this.fMap[field.name] = field;
-            this.fMap[field.jsonName] = field;
-            this.fMap[field.localName] = field;
-          }
-        }
+    var reflection_type_check_1 = require_reflection_type_check();
+    var reflection_json_reader_1 = require_reflection_json_reader();
+    var reflection_json_writer_1 = require_reflection_json_writer();
+    var reflection_binary_reader_1 = require_reflection_binary_reader();
+    var reflection_binary_writer_1 = require_reflection_binary_writer();
+    var reflection_create_1 = require_reflection_create();
+    var reflection_merge_partial_1 = require_reflection_merge_partial();
+    var json_typings_1 = require_json_typings();
+    var json_format_contract_1 = require_json_format_contract();
+    var reflection_equals_1 = require_reflection_equals();
+    var binary_writer_1 = require_binary_writer();
+    var binary_reader_1 = require_binary_reader();
+    var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));
+    var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {};
+    var MessageType = class {
+      constructor(name, fields, options) {
+        this.defaultCheckDepth = 16;
+        this.typeName = name;
+        this.fields = fields.map(reflection_info_1.normalizeFieldInfo);
+        this.options = options !== null && options !== void 0 ? options : {};
+        messageTypeDescriptor.value = this;
+        this.messagePrototype = Object.create(null, baseDescriptors);
+        this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this);
+        this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this);
+        this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this);
+        this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this);
+        this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this);
       }
-      // Cannot parse JSON  for #.
-      assert(condition, fieldName, jsonValue) {
-        if (!condition) {
-          let what = json_typings_1.typeofJsonValue(jsonValue);
-          if (what == "number" || what == "boolean")
-            what = jsonValue.toString();
-          throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`);
+      create(value) {
+        let message = reflection_create_1.reflectionCreate(this);
+        if (value !== void 0) {
+          reflection_merge_partial_1.reflectionMergePartial(this, message, value);
         }
+        return message;
       }
       /**
-       * Reads a message from canonical JSON format into the target message.
-       *
-       * Repeated fields are appended. Map entries are added, overwriting
-       * existing keys.
+       * Clone the message.
        *
-       * If a message field is already present, it will be merged with the
-       * new data.
+       * Unknown fields are discarded.
        */
-      read(input, message, options) {
-        this.prepare();
-        const oneofsHandled = [];
-        for (const [jsonKey, jsonValue] of Object.entries(input)) {
-          const field = this.fMap[jsonKey];
-          if (!field) {
-            if (!options.ignoreUnknownFields)
-              throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`);
-            continue;
-          }
-          const localName = field.localName;
-          let target;
-          if (field.oneof) {
-            if (jsonValue === null && (field.kind !== "enum" || field.T()[0] !== "google.protobuf.NullValue")) {
-              continue;
-            }
-            if (oneofsHandled.includes(field.oneof))
-              throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`);
-            oneofsHandled.push(field.oneof);
-            target = message[field.oneof] = {
-              oneofKind: localName
-            };
-          } else {
-            target = message;
-          }
-          if (field.kind == "map") {
-            if (jsonValue === null) {
-              continue;
-            }
-            this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue);
-            const fieldObj = target[localName];
-            for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) {
-              this.assert(jsonObjValue !== null, field.name + " map value", null);
-              let val2;
-              switch (field.V.kind) {
-                case "message":
-                  val2 = field.V.T().internalJsonRead(jsonObjValue, options);
-                  break;
-                case "enum":
-                  val2 = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields);
-                  if (val2 === false)
-                    continue;
-                  break;
-                case "scalar":
-                  val2 = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name);
-                  break;
-              }
-              this.assert(val2 !== void 0, field.name + " map value", jsonObjValue);
-              let key = jsonObjKey;
-              if (field.K == reflection_info_1.ScalarType.BOOL)
-                key = key == "true" ? true : key == "false" ? false : key;
-              key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString();
-              fieldObj[key] = val2;
-            }
-          } else if (field.repeat) {
-            if (jsonValue === null)
-              continue;
-            this.assert(Array.isArray(jsonValue), field.name, jsonValue);
-            const fieldArr = target[localName];
-            for (const jsonItem of jsonValue) {
-              this.assert(jsonItem !== null, field.name, null);
-              let val2;
-              switch (field.kind) {
-                case "message":
-                  val2 = field.T().internalJsonRead(jsonItem, options);
-                  break;
-                case "enum":
-                  val2 = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields);
-                  if (val2 === false)
-                    continue;
-                  break;
-                case "scalar":
-                  val2 = this.scalar(jsonItem, field.T, field.L, field.name);
-                  break;
-              }
-              this.assert(val2 !== void 0, field.name, jsonValue);
-              fieldArr.push(val2);
-            }
-          } else {
-            switch (field.kind) {
-              case "message":
-                if (jsonValue === null && field.T().typeName != "google.protobuf.Value") {
-                  this.assert(field.oneof === void 0, field.name + " (oneof member)", null);
-                  continue;
-                }
-                target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]);
-                break;
-              case "enum":
-                if (jsonValue === null)
-                  continue;
-                let val2 = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields);
-                if (val2 === false)
-                  continue;
-                target[localName] = val2;
-                break;
-              case "scalar":
-                if (jsonValue === null)
-                  continue;
-                target[localName] = this.scalar(jsonValue, field.T, field.L, field.name);
-                break;
-            }
-          }
-        }
+      clone(message) {
+        let copy = this.create();
+        reflection_merge_partial_1.reflectionMergePartial(this, copy, message);
+        return copy;
       }
       /**
-       * Returns `false` for unrecognized string representations.
-       *
-       * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`).
+       * Determines whether two message of the same type have the same field values.
+       * Checks for deep equality, traversing repeated fields, oneof groups, maps
+       * and messages recursively.
+       * Will also return true if both messages are `undefined`.
        */
-      enum(type2, json2, fieldName, ignoreUnknownFields) {
-        if (type2[0] == "google.protobuf.NullValue")
-          assert_1.assert(json2 === null || json2 === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} only accepts null.`);
-        if (json2 === null)
-          return 0;
-        switch (typeof json2) {
-          case "number":
-            assert_1.assert(Number.isInteger(json2), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json2}.`);
-            return json2;
-          case "string":
-            let localEnumName = json2;
-            if (type2[2] && json2.substring(0, type2[2].length) === type2[2])
-              localEnumName = json2.substring(type2[2].length);
-            let enumNumber = type2[1][localEnumName];
-            if (typeof enumNumber === "undefined" && ignoreUnknownFields) {
-              return false;
-            }
-            assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type2[0]} has no value for "${json2}".`);
-            return enumNumber;
-        }
-        assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json2}".`);
+      equals(a, b) {
+        return reflection_equals_1.reflectionEquals(this, a, b);
       }
-      scalar(json2, type2, longType, fieldName) {
-        let e;
-        try {
-          switch (type2) {
-            // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
-            // Either numbers or strings are accepted. Exponent notation is also accepted.
-            case reflection_info_1.ScalarType.DOUBLE:
-            case reflection_info_1.ScalarType.FLOAT:
-              if (json2 === null)
-                return 0;
-              if (json2 === "NaN")
-                return Number.NaN;
-              if (json2 === "Infinity")
-                return Number.POSITIVE_INFINITY;
-              if (json2 === "-Infinity")
-                return Number.NEGATIVE_INFINITY;
-              if (json2 === "") {
-                e = "empty string";
-                break;
-              }
-              if (typeof json2 == "string" && json2.trim().length !== json2.length) {
-                e = "extra whitespace";
-                break;
-              }
-              if (typeof json2 != "string" && typeof json2 != "number") {
-                break;
-              }
-              let float2 = Number(json2);
-              if (Number.isNaN(float2)) {
-                e = "not a number";
-                break;
-              }
-              if (!Number.isFinite(float2)) {
-                e = "too large or small";
-                break;
-              }
-              if (type2 == reflection_info_1.ScalarType.FLOAT)
-                assert_1.assertFloat32(float2);
-              return float2;
-            // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
-            case reflection_info_1.ScalarType.INT32:
-            case reflection_info_1.ScalarType.FIXED32:
-            case reflection_info_1.ScalarType.SFIXED32:
-            case reflection_info_1.ScalarType.SINT32:
-            case reflection_info_1.ScalarType.UINT32:
-              if (json2 === null)
-                return 0;
-              let int32;
-              if (typeof json2 == "number")
-                int32 = json2;
-              else if (json2 === "")
-                e = "empty string";
-              else if (typeof json2 == "string") {
-                if (json2.trim().length !== json2.length)
-                  e = "extra whitespace";
-                else
-                  int32 = Number(json2);
-              }
-              if (int32 === void 0)
-                break;
-              if (type2 == reflection_info_1.ScalarType.UINT32)
-                assert_1.assertUInt32(int32);
-              else
-                assert_1.assertInt32(int32);
-              return int32;
-            // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted.
-            case reflection_info_1.ScalarType.INT64:
-            case reflection_info_1.ScalarType.SFIXED64:
-            case reflection_info_1.ScalarType.SINT64:
-              if (json2 === null)
-                return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType);
-              if (typeof json2 != "number" && typeof json2 != "string")
-                break;
-              return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json2), longType);
-            case reflection_info_1.ScalarType.FIXED64:
-            case reflection_info_1.ScalarType.UINT64:
-              if (json2 === null)
-                return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType);
-              if (typeof json2 != "number" && typeof json2 != "string")
-                break;
-              return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json2), longType);
-            // bool:
-            case reflection_info_1.ScalarType.BOOL:
-              if (json2 === null)
-                return false;
-              if (typeof json2 !== "boolean")
-                break;
-              return json2;
-            // string:
-            case reflection_info_1.ScalarType.STRING:
-              if (json2 === null)
-                return "";
-              if (typeof json2 !== "string") {
-                e = "extra whitespace";
-                break;
-              }
-              try {
-                encodeURIComponent(json2);
-              } catch (e2) {
-                e2 = "invalid UTF8";
-                break;
-              }
-              return json2;
-            // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
-            // Either standard or URL-safe base64 encoding with/without paddings are accepted.
-            case reflection_info_1.ScalarType.BYTES:
-              if (json2 === null || json2 === "")
-                return new Uint8Array(0);
-              if (typeof json2 !== "string")
-                break;
-              return base64_1.base64decode(json2);
-          }
-        } catch (error4) {
-          e = error4.message;
-        }
-        this.assert(false, fieldName + (e ? " - " + e : ""), json2);
+      /**
+       * Is the given value assignable to our message type
+       * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
+       */
+      is(arg, depth = this.defaultCheckDepth) {
+        return this.refTypeCheck.is(arg, depth, false);
       }
-    };
-    exports2.ReflectionJsonReader = ReflectionJsonReader;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js
-var require_reflection_json_writer = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-json-writer.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ReflectionJsonWriter = void 0;
-    var base64_1 = require_base642();
-    var pb_long_1 = require_pb_long();
-    var reflection_info_1 = require_reflection_info();
-    var assert_1 = require_assert();
-    var ReflectionJsonWriter = class {
-      constructor(info6) {
-        var _a;
-        this.fields = (_a = info6.fields) !== null && _a !== void 0 ? _a : [];
+      /**
+       * Is the given value assignable to our message type,
+       * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
+       */
+      isAssignable(arg, depth = this.defaultCheckDepth) {
+        return this.refTypeCheck.is(arg, depth, true);
       }
       /**
-       * Converts the message to a JSON object, based on the field descriptors.
+       * Copy partial data into the target message.
        */
-      write(message, options) {
-        const json2 = {}, source = message;
-        for (const field of this.fields) {
-          if (!field.oneof) {
-            let jsonValue2 = this.field(field, source[field.localName], options);
-            if (jsonValue2 !== void 0)
-              json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue2;
-            continue;
-          }
-          const group = source[field.oneof];
-          if (group.oneofKind !== field.localName)
-            continue;
-          const opt = field.kind == "scalar" || field.kind == "enum" ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options;
-          let jsonValue = this.field(field, group[field.localName], opt);
-          assert_1.assert(jsonValue !== void 0);
-          json2[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue;
-        }
-        return json2;
+      mergePartial(target, source) {
+        reflection_merge_partial_1.reflectionMergePartial(this, target, source);
       }
-      field(field, value, options) {
-        let jsonValue = void 0;
-        if (field.kind == "map") {
-          assert_1.assert(typeof value == "object" && value !== null);
-          const jsonObj = {};
-          switch (field.V.kind) {
-            case "scalar":
-              for (const [entryKey, entryValue] of Object.entries(value)) {
-                const val2 = this.scalar(field.V.T, entryValue, field.name, false, true);
-                assert_1.assert(val2 !== void 0);
-                jsonObj[entryKey.toString()] = val2;
-              }
-              break;
-            case "message":
-              const messageType = field.V.T();
-              for (const [entryKey, entryValue] of Object.entries(value)) {
-                const val2 = this.message(messageType, entryValue, field.name, options);
-                assert_1.assert(val2 !== void 0);
-                jsonObj[entryKey.toString()] = val2;
-              }
-              break;
-            case "enum":
-              const enumInfo = field.V.T();
-              for (const [entryKey, entryValue] of Object.entries(value)) {
-                assert_1.assert(entryValue === void 0 || typeof entryValue == "number");
-                const val2 = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger);
-                assert_1.assert(val2 !== void 0);
-                jsonObj[entryKey.toString()] = val2;
-              }
-              break;
-          }
-          if (options.emitDefaultValues || Object.keys(jsonObj).length > 0)
-            jsonValue = jsonObj;
-        } else if (field.repeat) {
-          assert_1.assert(Array.isArray(value));
-          const jsonArr = [];
-          switch (field.kind) {
-            case "scalar":
-              for (let i = 0; i < value.length; i++) {
-                const val2 = this.scalar(field.T, value[i], field.name, field.opt, true);
-                assert_1.assert(val2 !== void 0);
-                jsonArr.push(val2);
-              }
-              break;
-            case "enum":
-              const enumInfo = field.T();
-              for (let i = 0; i < value.length; i++) {
-                assert_1.assert(value[i] === void 0 || typeof value[i] == "number");
-                const val2 = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger);
-                assert_1.assert(val2 !== void 0);
-                jsonArr.push(val2);
-              }
-              break;
-            case "message":
-              const messageType = field.T();
-              for (let i = 0; i < value.length; i++) {
-                const val2 = this.message(messageType, value[i], field.name, options);
-                assert_1.assert(val2 !== void 0);
-                jsonArr.push(val2);
-              }
-              break;
-          }
-          if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues)
-            jsonValue = jsonArr;
-        } else {
-          switch (field.kind) {
-            case "scalar":
-              jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues);
-              break;
-            case "enum":
-              jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger);
-              break;
-            case "message":
-              jsonValue = this.message(field.T(), value, field.name, options);
-              break;
-          }
-        }
-        return jsonValue;
+      /**
+       * Create a new message from binary format.
+       */
+      fromBinary(data, options) {
+        let opt = binary_reader_1.binaryReadOptions(options);
+        return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt);
+      }
+      /**
+       * Read a new message from a JSON value.
+       */
+      fromJson(json2, options) {
+        return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options));
+      }
+      /**
+       * Read a new message from a JSON string.
+       * This is equivalent to `T.fromJson(JSON.parse(json))`.
+       */
+      fromJsonString(json2, options) {
+        let value = JSON.parse(json2);
+        return this.fromJson(value, options);
+      }
+      /**
+       * Write the message to canonical JSON value.
+       */
+      toJson(message, options) {
+        return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options));
+      }
+      /**
+       * Convert the message to canonical JSON string.
+       * This is equivalent to `JSON.stringify(T.toJson(t))`
+       */
+      toJsonString(message, options) {
+        var _a;
+        let value = this.toJson(message, options);
+        return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
       }
       /**
-       * Returns `null` as the default for google.protobuf.NullValue.
+       * Write the message to binary format.
        */
-      enum(type2, value, fieldName, optional, emitDefaultValues, enumAsInteger) {
-        if (type2[0] == "google.protobuf.NullValue")
-          return !emitDefaultValues && !optional ? void 0 : null;
-        if (value === void 0) {
-          assert_1.assert(optional);
-          return void 0;
+      toBinary(message, options) {
+        let opt = binary_writer_1.binaryWriteOptions(options);
+        return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish();
+      }
+      /**
+       * This is an internal method. If you just want to read a message from
+       * JSON, use `fromJson()` or `fromJsonString()`.
+       *
+       * Reads JSON value and merges the fields into the target
+       * according to protobuf rules. If the target is omitted,
+       * a new instance is created first.
+       */
+      internalJsonRead(json2, options, target) {
+        if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) {
+          let message = target !== null && target !== void 0 ? target : this.create();
+          this.refJsonReader.read(json2, message, options);
+          return message;
         }
-        if (value === 0 && !emitDefaultValues && !optional)
-          return void 0;
-        assert_1.assert(typeof value == "number");
-        assert_1.assert(Number.isInteger(value));
-        if (enumAsInteger || !type2[1].hasOwnProperty(value))
-          return value;
-        if (type2[2])
-          return type2[2] + type2[1][value];
-        return type2[1][value];
+        throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`);
       }
-      message(type2, value, fieldName, options) {
-        if (value === void 0)
-          return options.emitDefaultValues ? null : void 0;
-        return type2.internalJsonWrite(value, options);
+      /**
+       * This is an internal method. If you just want to write a message
+       * to JSON, use `toJson()` or `toJsonString().
+       *
+       * Writes JSON value and returns it.
+       */
+      internalJsonWrite(message, options) {
+        return this.refJsonWriter.write(message, options);
       }
-      scalar(type2, value, fieldName, optional, emitDefaultValues) {
-        if (value === void 0) {
-          assert_1.assert(optional);
-          return void 0;
-        }
-        const ed = emitDefaultValues || optional;
-        switch (type2) {
-          // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
-          case reflection_info_1.ScalarType.INT32:
-          case reflection_info_1.ScalarType.SFIXED32:
-          case reflection_info_1.ScalarType.SINT32:
-            if (value === 0)
-              return ed ? 0 : void 0;
-            assert_1.assertInt32(value);
-            return value;
-          case reflection_info_1.ScalarType.FIXED32:
-          case reflection_info_1.ScalarType.UINT32:
-            if (value === 0)
-              return ed ? 0 : void 0;
-            assert_1.assertUInt32(value);
-            return value;
-          // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
-          // Either numbers or strings are accepted. Exponent notation is also accepted.
-          case reflection_info_1.ScalarType.FLOAT:
-            assert_1.assertFloat32(value);
-          case reflection_info_1.ScalarType.DOUBLE:
-            if (value === 0)
-              return ed ? 0 : void 0;
-            assert_1.assert(typeof value == "number");
-            if (Number.isNaN(value))
-              return "NaN";
-            if (value === Number.POSITIVE_INFINITY)
-              return "Infinity";
-            if (value === Number.NEGATIVE_INFINITY)
-              return "-Infinity";
-            return value;
-          // string:
-          case reflection_info_1.ScalarType.STRING:
-            if (value === "")
-              return ed ? "" : void 0;
-            assert_1.assert(typeof value == "string");
-            return value;
-          // bool:
-          case reflection_info_1.ScalarType.BOOL:
-            if (value === false)
-              return ed ? false : void 0;
-            assert_1.assert(typeof value == "boolean");
-            return value;
-          // JSON value will be a decimal string. Either numbers or strings are accepted.
-          case reflection_info_1.ScalarType.UINT64:
-          case reflection_info_1.ScalarType.FIXED64:
-            assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint");
-            let ulong = pb_long_1.PbULong.from(value);
-            if (ulong.isZero() && !ed)
-              return void 0;
-            return ulong.toString();
-          // JSON value will be a decimal string. Either numbers or strings are accepted.
-          case reflection_info_1.ScalarType.INT64:
-          case reflection_info_1.ScalarType.SFIXED64:
-          case reflection_info_1.ScalarType.SINT64:
-            assert_1.assert(typeof value == "number" || typeof value == "string" || typeof value == "bigint");
-            let long = pb_long_1.PbLong.from(value);
-            if (long.isZero() && !ed)
-              return void 0;
-            return long.toString();
-          // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
-          // Either standard or URL-safe base64 encoding with/without paddings are accepted.
-          case reflection_info_1.ScalarType.BYTES:
-            assert_1.assert(value instanceof Uint8Array);
-            if (!value.byteLength)
-              return ed ? "" : void 0;
-            return base64_1.base64encode(value);
-        }
+      /**
+       * This is an internal method. If you just want to write a message
+       * in binary format, use `toBinary()`.
+       *
+       * Serializes the message in binary format and appends it to the given
+       * writer. Returns passed writer.
+       */
+      internalBinaryWrite(message, writer, options) {
+        this.refBinWriter.write(message, writer, options);
+        return writer;
+      }
+      /**
+       * This is an internal method. If you just want to read a message from
+       * binary data, use `fromBinary()`.
+       *
+       * Reads data from binary format and merges the fields into
+       * the target according to protobuf rules. If the target is
+       * omitted, a new instance is created first.
+       */
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create();
+        this.refBinReader.read(reader, message, options, length);
+        return message;
       }
     };
-    exports2.ReflectionJsonWriter = ReflectionJsonWriter;
+    exports2.MessageType = MessageType;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js
-var require_reflection_scalar_default = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-scalar-default.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js
+var require_reflection_contains_message_type = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.reflectionScalarDefault = void 0;
-    var reflection_info_1 = require_reflection_info();
-    var reflection_long_convert_1 = require_reflection_long_convert();
-    var pb_long_1 = require_pb_long();
-    function reflectionScalarDefault(type2, longType = reflection_info_1.LongType.STRING) {
-      switch (type2) {
-        case reflection_info_1.ScalarType.BOOL:
-          return false;
-        case reflection_info_1.ScalarType.UINT64:
-        case reflection_info_1.ScalarType.FIXED64:
-          return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType);
-        case reflection_info_1.ScalarType.INT64:
-        case reflection_info_1.ScalarType.SFIXED64:
-        case reflection_info_1.ScalarType.SINT64:
-          return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType);
-        case reflection_info_1.ScalarType.DOUBLE:
-        case reflection_info_1.ScalarType.FLOAT:
-          return 0;
-        case reflection_info_1.ScalarType.BYTES:
-          return new Uint8Array(0);
-        case reflection_info_1.ScalarType.STRING:
-          return "";
-        default:
-          return 0;
-      }
+    exports2.containsMessageType = void 0;
+    var message_type_contract_1 = require_message_type_contract();
+    function containsMessageType(msg) {
+      return msg[message_type_contract_1.MESSAGE_TYPE] != null;
     }
-    exports2.reflectionScalarDefault = reflectionScalarDefault;
+    exports2.containsMessageType = containsMessageType;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js
-var require_reflection_binary_reader = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-reader.js"(exports2) {
+// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js
+var require_enum_object = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ReflectionBinaryReader = void 0;
-    var binary_format_contract_1 = require_binary_format_contract();
-    var reflection_info_1 = require_reflection_info();
-    var reflection_long_convert_1 = require_reflection_long_convert();
-    var reflection_scalar_default_1 = require_reflection_scalar_default();
-    var ReflectionBinaryReader = class {
-      constructor(info6) {
-        this.info = info6;
-      }
-      prepare() {
-        var _a;
-        if (!this.fieldNoToField) {
-          const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
-          this.fieldNoToField = new Map(fieldsInput.map((field) => [field.no, field]));
-        }
-      }
-      /**
-       * Reads a message from binary format into the target message.
-       *
-       * Repeated fields are appended. Map entries are added, overwriting
-       * existing keys.
-       *
-       * If a message field is already present, it will be merged with the
-       * new data.
-       */
-      read(reader, message, options, length) {
-        this.prepare();
-        const end = length === void 0 ? reader.len : reader.pos + length;
-        while (reader.pos < end) {
-          const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo);
-          if (!field) {
-            let u = options.readUnknownField;
-            if (u == "throw")
-              throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`);
-            let d = reader.skip(wireType);
-            if (u !== false)
-              (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d);
-            continue;
-          }
-          let target = message, repeated = field.repeat, localName = field.localName;
-          if (field.oneof) {
-            target = target[field.oneof];
-            if (target.oneofKind !== localName)
-              target = message[field.oneof] = {
-                oneofKind: localName
-              };
-          }
-          switch (field.kind) {
-            case "scalar":
-            case "enum":
-              let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
-              let L = field.kind == "scalar" ? field.L : void 0;
-              if (repeated) {
-                let arr = target[localName];
-                if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) {
-                  let e = reader.uint32() + reader.pos;
-                  while (reader.pos < e)
-                    arr.push(this.scalar(reader, T, L));
-                } else
-                  arr.push(this.scalar(reader, T, L));
-              } else
-                target[localName] = this.scalar(reader, T, L);
-              break;
-            case "message":
-              if (repeated) {
-                let arr = target[localName];
-                let msg = field.T().internalBinaryRead(reader, reader.uint32(), options);
-                arr.push(msg);
-              } else
-                target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]);
-              break;
-            case "map":
-              let [mapKey, mapVal] = this.mapEntry(field, reader, options);
-              target[localName][mapKey] = mapVal;
-              break;
-          }
-        }
+    exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0;
+    function isEnumObject(arg) {
+      if (typeof arg != "object" || arg === null) {
+        return false;
       }
-      /**
-       * Read a map field, expecting key field = 1, value field = 2
-       */
-      mapEntry(field, reader, options) {
-        let length = reader.uint32();
-        let end = reader.pos + length;
-        let key = void 0;
-        let val2 = void 0;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case 1:
-              if (field.K == reflection_info_1.ScalarType.BOOL)
-                key = reader.bool().toString();
-              else
-                key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING);
-              break;
-            case 2:
-              switch (field.V.kind) {
-                case "scalar":
-                  val2 = this.scalar(reader, field.V.T, field.V.L);
-                  break;
-                case "enum":
-                  val2 = reader.int32();
-                  break;
-                case "message":
-                  val2 = field.V.T().internalBinaryRead(reader, reader.uint32(), options);
-                  break;
-              }
-              break;
-            default:
-              throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`);
-          }
-        }
-        if (key === void 0) {
-          let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K);
-          key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw;
-        }
-        if (val2 === void 0)
-          switch (field.V.kind) {
-            case "scalar":
-              val2 = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L);
-              break;
-            case "enum":
-              val2 = 0;
-              break;
-            case "message":
-              val2 = field.V.T().create();
-              break;
-          }
-        return [key, val2];
+      if (!arg.hasOwnProperty(0)) {
+        return false;
       }
-      scalar(reader, type2, longType) {
-        switch (type2) {
-          case reflection_info_1.ScalarType.INT32:
-            return reader.int32();
-          case reflection_info_1.ScalarType.STRING:
-            return reader.string();
-          case reflection_info_1.ScalarType.BOOL:
-            return reader.bool();
-          case reflection_info_1.ScalarType.DOUBLE:
-            return reader.double();
-          case reflection_info_1.ScalarType.FLOAT:
-            return reader.float();
-          case reflection_info_1.ScalarType.INT64:
-            return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType);
-          case reflection_info_1.ScalarType.UINT64:
-            return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType);
-          case reflection_info_1.ScalarType.FIXED64:
-            return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType);
-          case reflection_info_1.ScalarType.FIXED32:
-            return reader.fixed32();
-          case reflection_info_1.ScalarType.BYTES:
-            return reader.bytes();
-          case reflection_info_1.ScalarType.UINT32:
-            return reader.uint32();
-          case reflection_info_1.ScalarType.SFIXED32:
-            return reader.sfixed32();
-          case reflection_info_1.ScalarType.SFIXED64:
-            return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType);
-          case reflection_info_1.ScalarType.SINT32:
-            return reader.sint32();
-          case reflection_info_1.ScalarType.SINT64:
-            return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType);
+      for (let k of Object.keys(arg)) {
+        let num = parseInt(k);
+        if (!Number.isNaN(num)) {
+          let nam = arg[num];
+          if (nam === void 0)
+            return false;
+          if (arg[nam] !== num)
+            return false;
+        } else {
+          let num2 = arg[k];
+          if (num2 === void 0)
+            return false;
+          if (typeof num2 !== "number")
+            return false;
+          if (arg[num2] === void 0)
+            return false;
         }
       }
-    };
-    exports2.ReflectionBinaryReader = ReflectionBinaryReader;
+      return true;
+    }
+    exports2.isEnumObject = isEnumObject;
+    function listEnumValues(enumObject) {
+      if (!isEnumObject(enumObject))
+        throw new Error("not a typescript enum object");
+      let values = [];
+      for (let [name, number] of Object.entries(enumObject))
+        if (typeof number == "number")
+          values.push({ name, number });
+      return values;
+    }
+    exports2.listEnumValues = listEnumValues;
+    function listEnumNames(enumObject) {
+      return listEnumValues(enumObject).map((val2) => val2.name);
+    }
+    exports2.listEnumNames = listEnumNames;
+    function listEnumNumbers(enumObject) {
+      return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index);
+    }
+    exports2.listEnumNumbers = listEnumNumbers;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime/build/commonjs/index.js
+var require_commonjs11 = __commonJS({
+  "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    var json_typings_1 = require_json_typings();
+    Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() {
+      return json_typings_1.typeofJsonValue;
+    } });
+    Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() {
+      return json_typings_1.isJsonObject;
+    } });
+    var base64_1 = require_base642();
+    Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() {
+      return base64_1.base64decode;
+    } });
+    Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() {
+      return base64_1.base64encode;
+    } });
+    var protobufjs_utf8_1 = require_protobufjs_utf8();
+    Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() {
+      return protobufjs_utf8_1.utf8read;
+    } });
+    var binary_format_contract_1 = require_binary_format_contract();
+    Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() {
+      return binary_format_contract_1.WireType;
+    } });
+    Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() {
+      return binary_format_contract_1.mergeBinaryOptions;
+    } });
+    Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() {
+      return binary_format_contract_1.UnknownFieldHandler;
+    } });
+    var binary_reader_1 = require_binary_reader();
+    Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() {
+      return binary_reader_1.BinaryReader;
+    } });
+    Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() {
+      return binary_reader_1.binaryReadOptions;
+    } });
+    var binary_writer_1 = require_binary_writer();
+    Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() {
+      return binary_writer_1.BinaryWriter;
+    } });
+    Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() {
+      return binary_writer_1.binaryWriteOptions;
+    } });
+    var pb_long_1 = require_pb_long();
+    Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() {
+      return pb_long_1.PbLong;
+    } });
+    Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() {
+      return pb_long_1.PbULong;
+    } });
+    var json_format_contract_1 = require_json_format_contract();
+    Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() {
+      return json_format_contract_1.jsonReadOptions;
+    } });
+    Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() {
+      return json_format_contract_1.jsonWriteOptions;
+    } });
+    Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() {
+      return json_format_contract_1.mergeJsonOptions;
+    } });
+    var message_type_contract_1 = require_message_type_contract();
+    Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() {
+      return message_type_contract_1.MESSAGE_TYPE;
+    } });
+    var message_type_1 = require_message_type();
+    Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() {
+      return message_type_1.MessageType;
+    } });
+    var reflection_info_1 = require_reflection_info();
+    Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() {
+      return reflection_info_1.ScalarType;
+    } });
+    Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() {
+      return reflection_info_1.LongType;
+    } });
+    Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() {
+      return reflection_info_1.RepeatType;
+    } });
+    Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() {
+      return reflection_info_1.normalizeFieldInfo;
+    } });
+    Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() {
+      return reflection_info_1.readFieldOptions;
+    } });
+    Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() {
+      return reflection_info_1.readFieldOption;
+    } });
+    Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() {
+      return reflection_info_1.readMessageOption;
+    } });
+    var reflection_type_check_1 = require_reflection_type_check();
+    Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() {
+      return reflection_type_check_1.ReflectionTypeCheck;
+    } });
+    var reflection_create_1 = require_reflection_create();
+    Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() {
+      return reflection_create_1.reflectionCreate;
+    } });
+    var reflection_scalar_default_1 = require_reflection_scalar_default();
+    Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() {
+      return reflection_scalar_default_1.reflectionScalarDefault;
+    } });
+    var reflection_merge_partial_1 = require_reflection_merge_partial();
+    Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() {
+      return reflection_merge_partial_1.reflectionMergePartial;
+    } });
+    var reflection_equals_1 = require_reflection_equals();
+    Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() {
+      return reflection_equals_1.reflectionEquals;
+    } });
+    var reflection_binary_reader_1 = require_reflection_binary_reader();
+    Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() {
+      return reflection_binary_reader_1.ReflectionBinaryReader;
+    } });
+    var reflection_binary_writer_1 = require_reflection_binary_writer();
+    Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() {
+      return reflection_binary_writer_1.ReflectionBinaryWriter;
+    } });
+    var reflection_json_reader_1 = require_reflection_json_reader();
+    Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() {
+      return reflection_json_reader_1.ReflectionJsonReader;
+    } });
+    var reflection_json_writer_1 = require_reflection_json_writer();
+    Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() {
+      return reflection_json_writer_1.ReflectionJsonWriter;
+    } });
+    var reflection_contains_message_type_1 = require_reflection_contains_message_type();
+    Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() {
+      return reflection_contains_message_type_1.containsMessageType;
+    } });
+    var oneof_1 = require_oneof();
+    Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() {
+      return oneof_1.isOneofGroup;
+    } });
+    Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() {
+      return oneof_1.setOneofValue;
+    } });
+    Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() {
+      return oneof_1.getOneofValue;
+    } });
+    Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() {
+      return oneof_1.clearOneofValue;
+    } });
+    Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() {
+      return oneof_1.getSelectedOneofValue;
+    } });
+    var enum_object_1 = require_enum_object();
+    Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() {
+      return enum_object_1.listEnumValues;
+    } });
+    Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() {
+      return enum_object_1.listEnumNames;
+    } });
+    Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() {
+      return enum_object_1.listEnumNumbers;
+    } });
+    Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() {
+      return enum_object_1.isEnumObject;
+    } });
+    var lower_camel_case_1 = require_lower_camel_case();
+    Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() {
+      return lower_camel_case_1.lowerCamelCase;
+    } });
+    var assert_1 = require_assert();
+    Object.defineProperty(exports2, "assert", { enumerable: true, get: function() {
+      return assert_1.assert;
+    } });
+    Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() {
+      return assert_1.assertNever;
+    } });
+    Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() {
+      return assert_1.assertInt32;
+    } });
+    Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() {
+      return assert_1.assertUInt32;
+    } });
+    Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() {
+      return assert_1.assertFloat32;
+    } });
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js
-var require_reflection_binary_writer = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-binary-writer.js"(exports2) {
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js
+var require_reflection_info2 = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ReflectionBinaryWriter = void 0;
-    var binary_format_contract_1 = require_binary_format_contract();
-    var reflection_info_1 = require_reflection_info();
-    var assert_1 = require_assert();
-    var pb_long_1 = require_pb_long();
-    var ReflectionBinaryWriter = class {
-      constructor(info6) {
-        this.info = info6;
-      }
-      prepare() {
-        if (!this.fields) {
-          const fieldsInput = this.info.fields ? this.info.fields.concat() : [];
-          this.fields = fieldsInput.sort((a, b) => a.no - b.no);
-        }
-      }
-      /**
-       * Writes the message to binary format.
-       */
-      write(message, writer, options) {
-        this.prepare();
-        for (const field of this.fields) {
-          let value, emitDefault, repeated = field.repeat, localName = field.localName;
-          if (field.oneof) {
-            const group = message[field.oneof];
-            if (group.oneofKind !== localName)
-              continue;
-            value = group[localName];
-            emitDefault = true;
-          } else {
-            value = message[localName];
-            emitDefault = false;
-          }
-          switch (field.kind) {
-            case "scalar":
-            case "enum":
-              let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
-              if (repeated) {
-                assert_1.assert(Array.isArray(value));
-                if (repeated == reflection_info_1.RepeatType.PACKED)
-                  this.packed(writer, T, field.no, value);
-                else
-                  for (const item of value)
-                    this.scalar(writer, T, field.no, item, true);
-              } else if (value === void 0)
-                assert_1.assert(field.opt);
-              else
-                this.scalar(writer, T, field.no, value, emitDefault || field.opt);
-              break;
-            case "message":
-              if (repeated) {
-                assert_1.assert(Array.isArray(value));
-                for (const item of value)
-                  this.message(writer, options, field.T(), field.no, item);
-              } else {
-                this.message(writer, options, field.T(), field.no, value);
-              }
-              break;
-            case "map":
-              assert_1.assert(typeof value == "object" && value !== null);
-              for (const [key, val2] of Object.entries(value))
-                this.mapEntry(writer, options, field, key, val2);
-              break;
-          }
-        }
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer);
-      }
-      mapEntry(writer, options, field, key, value) {
-        writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited);
-        writer.fork();
-        let keyValue = key;
-        switch (field.K) {
-          case reflection_info_1.ScalarType.INT32:
-          case reflection_info_1.ScalarType.FIXED32:
-          case reflection_info_1.ScalarType.UINT32:
-          case reflection_info_1.ScalarType.SFIXED32:
-          case reflection_info_1.ScalarType.SINT32:
-            keyValue = Number.parseInt(key);
-            break;
-          case reflection_info_1.ScalarType.BOOL:
-            assert_1.assert(key == "true" || key == "false");
-            keyValue = key == "true";
-            break;
-        }
-        this.scalar(writer, field.K, 1, keyValue, true);
-        switch (field.V.kind) {
-          case "scalar":
-            this.scalar(writer, field.V.T, 2, value, true);
-            break;
-          case "enum":
-            this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true);
-            break;
-          case "message":
-            this.message(writer, options, field.V.T(), 2, value);
-            break;
-        }
-        writer.join();
-      }
-      message(writer, options, handler, fieldNo, value) {
-        if (value === void 0)
-          return;
-        handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options);
-        writer.join();
+    exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0;
+    var runtime_1 = require_commonjs11();
+    function normalizeMethodInfo(method, service) {
+      var _a, _b, _c;
+      let m = method;
+      m.service = service;
+      m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name);
+      m.serverStreaming = !!m.serverStreaming;
+      m.clientStreaming = !!m.clientStreaming;
+      m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {};
+      m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0;
+      return m;
+    }
+    exports2.normalizeMethodInfo = normalizeMethodInfo;
+    function readMethodOptions(service, methodName, extensionName, extensionType) {
+      var _a;
+      const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options;
+      return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0;
+    }
+    exports2.readMethodOptions = readMethodOptions;
+    function readMethodOption(service, methodName, extensionName, extensionType) {
+      var _a;
+      const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options;
+      if (!options) {
+        return void 0;
       }
-      /**
-       * Write a single scalar value.
-       */
-      scalar(writer, type2, fieldNo, value, emitDefault) {
-        let [wireType, method, isDefault] = this.scalarInfo(type2, value);
-        if (!isDefault || emitDefault) {
-          writer.tag(fieldNo, wireType);
-          writer[method](value);
-        }
+      const optionVal = options[extensionName];
+      if (optionVal === void 0) {
+        return optionVal;
       }
-      /**
-       * Write an array of scalar values in packed format.
-       */
-      packed(writer, type2, fieldNo, value) {
-        if (!value.length)
-          return;
-        assert_1.assert(type2 !== reflection_info_1.ScalarType.BYTES && type2 !== reflection_info_1.ScalarType.STRING);
-        writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited);
-        writer.fork();
-        let [, method] = this.scalarInfo(type2);
-        for (let i = 0; i < value.length; i++)
-          writer[method](value[i]);
-        writer.join();
+      return extensionType ? extensionType.fromJson(optionVal) : optionVal;
+    }
+    exports2.readMethodOption = readMethodOption;
+    function readServiceOption(service, extensionName, extensionType) {
+      const options = service.options;
+      if (!options) {
+        return void 0;
       }
-      /**
-       * Get information for writing a scalar value.
-       *
-       * Returns tuple:
-       * [0]: appropriate WireType
-       * [1]: name of the appropriate method of IBinaryWriter
-       * [2]: whether the given value is a default value
-       *
-       * If argument `value` is omitted, [2] is always false.
-       */
-      scalarInfo(type2, value) {
-        let t = binary_format_contract_1.WireType.Varint;
-        let m;
-        let i = value === void 0;
-        let d = value === 0;
-        switch (type2) {
-          case reflection_info_1.ScalarType.INT32:
-            m = "int32";
-            break;
-          case reflection_info_1.ScalarType.STRING:
-            d = i || !value.length;
-            t = binary_format_contract_1.WireType.LengthDelimited;
-            m = "string";
-            break;
-          case reflection_info_1.ScalarType.BOOL:
-            d = value === false;
-            m = "bool";
-            break;
-          case reflection_info_1.ScalarType.UINT32:
-            m = "uint32";
-            break;
-          case reflection_info_1.ScalarType.DOUBLE:
-            t = binary_format_contract_1.WireType.Bit64;
-            m = "double";
-            break;
-          case reflection_info_1.ScalarType.FLOAT:
-            t = binary_format_contract_1.WireType.Bit32;
-            m = "float";
-            break;
-          case reflection_info_1.ScalarType.INT64:
-            d = i || pb_long_1.PbLong.from(value).isZero();
-            m = "int64";
-            break;
-          case reflection_info_1.ScalarType.UINT64:
-            d = i || pb_long_1.PbULong.from(value).isZero();
-            m = "uint64";
-            break;
-          case reflection_info_1.ScalarType.FIXED64:
-            d = i || pb_long_1.PbULong.from(value).isZero();
-            t = binary_format_contract_1.WireType.Bit64;
-            m = "fixed64";
-            break;
-          case reflection_info_1.ScalarType.BYTES:
-            d = i || !value.byteLength;
-            t = binary_format_contract_1.WireType.LengthDelimited;
-            m = "bytes";
-            break;
-          case reflection_info_1.ScalarType.FIXED32:
-            t = binary_format_contract_1.WireType.Bit32;
-            m = "fixed32";
-            break;
-          case reflection_info_1.ScalarType.SFIXED32:
-            t = binary_format_contract_1.WireType.Bit32;
-            m = "sfixed32";
-            break;
-          case reflection_info_1.ScalarType.SFIXED64:
-            d = i || pb_long_1.PbLong.from(value).isZero();
-            t = binary_format_contract_1.WireType.Bit64;
-            m = "sfixed64";
-            break;
-          case reflection_info_1.ScalarType.SINT32:
-            m = "sint32";
-            break;
-          case reflection_info_1.ScalarType.SINT64:
-            d = i || pb_long_1.PbLong.from(value).isZero();
-            m = "sint64";
-            break;
-        }
-        return [t, m, i || d];
+      const optionVal = options[extensionName];
+      if (optionVal === void 0) {
+        return optionVal;
       }
-    };
-    exports2.ReflectionBinaryWriter = ReflectionBinaryWriter;
+      return extensionType ? extensionType.fromJson(optionVal) : optionVal;
+    }
+    exports2.readServiceOption = readServiceOption;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js
-var require_reflection_create = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-create.js"(exports2) {
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js
+var require_service_type = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.reflectionCreate = void 0;
-    var reflection_scalar_default_1 = require_reflection_scalar_default();
-    var message_type_contract_1 = require_message_type_contract();
-    function reflectionCreate(type2) {
-      const msg = type2.messagePrototype ? Object.create(type2.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type2 });
-      for (let field of type2.fields) {
-        let name = field.localName;
-        if (field.opt)
-          continue;
-        if (field.oneof)
-          msg[field.oneof] = { oneofKind: void 0 };
-        else if (field.repeat)
-          msg[name] = [];
-        else
-          switch (field.kind) {
-            case "scalar":
-              msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L);
-              break;
-            case "enum":
-              msg[name] = 0;
-              break;
-            case "map":
-              msg[name] = {};
-              break;
-          }
+    exports2.ServiceType = void 0;
+    var reflection_info_1 = require_reflection_info2();
+    var ServiceType = class {
+      constructor(typeName, methods, options) {
+        this.typeName = typeName;
+        this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this));
+        this.options = options !== null && options !== void 0 ? options : {};
       }
-      return msg;
-    }
-    exports2.reflectionCreate = reflectionCreate;
+    };
+    exports2.ServiceType = ServiceType;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js
-var require_reflection_merge_partial = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-merge-partial.js"(exports2) {
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js
+var require_rpc_error = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.reflectionMergePartial = void 0;
-    function reflectionMergePartial(info6, target, source) {
-      let fieldValue, input = source, output;
-      for (let field of info6.fields) {
-        let name = field.localName;
-        if (field.oneof) {
-          const group = input[field.oneof];
-          if ((group === null || group === void 0 ? void 0 : group.oneofKind) == void 0) {
-            continue;
-          }
-          fieldValue = group[name];
-          output = target[field.oneof];
-          output.oneofKind = group.oneofKind;
-          if (fieldValue == void 0) {
-            delete output[name];
-            continue;
-          }
-        } else {
-          fieldValue = input[name];
-          output = target;
-          if (fieldValue == void 0) {
-            continue;
-          }
+    exports2.RpcError = void 0;
+    var RpcError = class extends Error {
+      constructor(message, code = "UNKNOWN", meta) {
+        super(message);
+        this.name = "RpcError";
+        Object.setPrototypeOf(this, new.target.prototype);
+        this.code = code;
+        this.meta = meta !== null && meta !== void 0 ? meta : {};
+      }
+      toString() {
+        const l = [this.name + ": " + this.message];
+        if (this.code) {
+          l.push("");
+          l.push("Code: " + this.code);
         }
-        if (field.repeat)
-          output[name].length = fieldValue.length;
-        switch (field.kind) {
-          case "scalar":
-          case "enum":
-            if (field.repeat)
-              for (let i = 0; i < fieldValue.length; i++)
-                output[name][i] = fieldValue[i];
-            else
-              output[name] = fieldValue;
-            break;
-          case "message":
-            let T = field.T();
-            if (field.repeat)
-              for (let i = 0; i < fieldValue.length; i++)
-                output[name][i] = T.create(fieldValue[i]);
-            else if (output[name] === void 0)
-              output[name] = T.create(fieldValue);
-            else
-              T.mergePartial(output[name], fieldValue);
-            break;
-          case "map":
-            switch (field.V.kind) {
-              case "scalar":
-              case "enum":
-                Object.assign(output[name], fieldValue);
-                break;
-              case "message":
-                let T2 = field.V.T();
-                for (let k of Object.keys(fieldValue))
-                  output[name][k] = T2.create(fieldValue[k]);
-                break;
-            }
-            break;
+        if (this.serviceName && this.methodName) {
+          l.push("Method: " + this.serviceName + "/" + this.methodName);
+        }
+        let m = Object.entries(this.meta);
+        if (m.length) {
+          l.push("");
+          l.push("Meta:");
+          for (let [k, v] of m) {
+            l.push(`  ${k}: ${v}`);
+          }
         }
+        return l.join("\n");
       }
-    }
-    exports2.reflectionMergePartial = reflectionMergePartial;
+    };
+    exports2.RpcError = RpcError;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js
-var require_reflection_equals = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-equals.js"(exports2) {
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js
+var require_rpc_options = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.reflectionEquals = void 0;
-    var reflection_info_1 = require_reflection_info();
-    function reflectionEquals(info6, a, b) {
-      if (a === b)
-        return true;
-      if (!a || !b)
-        return false;
-      for (let field of info6.fields) {
-        let localName = field.localName;
-        let val_a = field.oneof ? a[field.oneof][localName] : a[localName];
-        let val_b = field.oneof ? b[field.oneof][localName] : b[localName];
-        switch (field.kind) {
-          case "enum":
-          case "scalar":
-            let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
-            if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b)))
-              return false;
+    exports2.mergeRpcOptions = void 0;
+    var runtime_1 = require_commonjs11();
+    function mergeRpcOptions(defaults, options) {
+      if (!options)
+        return defaults;
+      let o = {};
+      copy(defaults, o);
+      copy(options, o);
+      for (let key of Object.keys(options)) {
+        let val2 = options[key];
+        switch (key) {
+          case "jsonOptions":
+            o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions);
             break;
-          case "map":
-            if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b))))
-              return false;
+          case "binaryOptions":
+            o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions);
             break;
-          case "message":
-            let T = field.T();
-            if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b)))
-              return false;
+          case "meta":
+            o.meta = {};
+            copy(defaults.meta, o.meta);
+            copy(options.meta, o.meta);
+            break;
+          case "interceptors":
+            o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat();
             break;
         }
       }
-      return true;
-    }
-    exports2.reflectionEquals = reflectionEquals;
-    var objectValues = Object.values;
-    function primitiveEq(type2, a, b) {
-      if (a === b)
-        return true;
-      if (type2 !== reflection_info_1.ScalarType.BYTES)
-        return false;
-      let ba = a;
-      let bb = b;
-      if (ba.length !== bb.length)
-        return false;
-      for (let i = 0; i < ba.length; i++)
-        if (ba[i] != bb[i])
-          return false;
-      return true;
-    }
-    function repeatedPrimitiveEq(type2, a, b) {
-      if (a.length !== b.length)
-        return false;
-      for (let i = 0; i < a.length; i++)
-        if (!primitiveEq(type2, a[i], b[i]))
-          return false;
-      return true;
+      return o;
     }
-    function repeatedMsgEq(type2, a, b) {
-      if (a.length !== b.length)
-        return false;
-      for (let i = 0; i < a.length; i++)
-        if (!type2.equals(a[i], b[i]))
-          return false;
-      return true;
+    exports2.mergeRpcOptions = mergeRpcOptions;
+    function copy(a, into) {
+      if (!a)
+        return;
+      let c = into;
+      for (let [k, v] of Object.entries(a)) {
+        if (v instanceof Date)
+          c[k] = new Date(v.getTime());
+        else if (Array.isArray(v))
+          c[k] = v.concat();
+        else
+          c[k] = v;
+      }
     }
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js
-var require_message_type = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/message-type.js"(exports2) {
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js
+var require_deferred = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.MessageType = void 0;
-    var message_type_contract_1 = require_message_type_contract();
-    var reflection_info_1 = require_reflection_info();
-    var reflection_type_check_1 = require_reflection_type_check();
-    var reflection_json_reader_1 = require_reflection_json_reader();
-    var reflection_json_writer_1 = require_reflection_json_writer();
-    var reflection_binary_reader_1 = require_reflection_binary_reader();
-    var reflection_binary_writer_1 = require_reflection_binary_writer();
-    var reflection_create_1 = require_reflection_create();
-    var reflection_merge_partial_1 = require_reflection_merge_partial();
-    var json_typings_1 = require_json_typings();
-    var json_format_contract_1 = require_json_format_contract();
-    var reflection_equals_1 = require_reflection_equals();
-    var binary_writer_1 = require_binary_writer();
-    var binary_reader_1 = require_binary_reader();
-    var baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));
-    var messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {};
-    var MessageType = class {
-      constructor(name, fields, options) {
-        this.defaultCheckDepth = 16;
-        this.typeName = name;
-        this.fields = fields.map(reflection_info_1.normalizeFieldInfo);
-        this.options = options !== null && options !== void 0 ? options : {};
-        messageTypeDescriptor.value = this;
-        this.messagePrototype = Object.create(null, baseDescriptors);
-        this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this);
-        this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this);
-        this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this);
-        this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this);
-        this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this);
-      }
-      create(value) {
-        let message = reflection_create_1.reflectionCreate(this);
-        if (value !== void 0) {
-          reflection_merge_partial_1.reflectionMergePartial(this, message, value);
+    exports2.Deferred = exports2.DeferredState = void 0;
+    var DeferredState;
+    (function(DeferredState2) {
+      DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING";
+      DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED";
+      DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED";
+    })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {}));
+    var Deferred = class {
+      /**
+       * @param preventUnhandledRejectionWarning - prevents the warning
+       * "Unhandled Promise rejection" by adding a noop rejection handler.
+       * Working with calls returned from the runtime-rpc package in an
+       * async function usually means awaiting one call property after
+       * the other. This means that the "status" is not being awaited when
+       * an earlier await for the "headers" is rejected. This causes the
+       * "unhandled promise reject" warning. A more correct behaviour for
+       * calls might be to become aware whether at least one of the
+       * promises is handled and swallow the rejection warning for the
+       * others.
+       */
+      constructor(preventUnhandledRejectionWarning = true) {
+        this._state = DeferredState.PENDING;
+        this._promise = new Promise((resolve6, reject) => {
+          this._resolve = resolve6;
+          this._reject = reject;
+        });
+        if (preventUnhandledRejectionWarning) {
+          this._promise.catch((_) => {
+          });
         }
-        return message;
       }
       /**
-       * Clone the message.
-       *
-       * Unknown fields are discarded.
+       * Get the current state of the promise.
        */
-      clone(message) {
-        let copy = this.create();
-        reflection_merge_partial_1.reflectionMergePartial(this, copy, message);
-        return copy;
+      get state() {
+        return this._state;
       }
       /**
-       * Determines whether two message of the same type have the same field values.
-       * Checks for deep equality, traversing repeated fields, oneof groups, maps
-       * and messages recursively.
-       * Will also return true if both messages are `undefined`.
+       * Get the deferred promise.
        */
-      equals(a, b) {
-        return reflection_equals_1.reflectionEquals(this, a, b);
+      get promise() {
+        return this._promise;
       }
       /**
-       * Is the given value assignable to our message type
-       * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
+       * Resolve the promise. Throws if the promise is already resolved or rejected.
        */
-      is(arg, depth = this.defaultCheckDepth) {
-        return this.refTypeCheck.is(arg, depth, false);
+      resolve(value) {
+        if (this.state !== DeferredState.PENDING)
+          throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`);
+        this._resolve(value);
+        this._state = DeferredState.RESOLVED;
       }
       /**
-       * Is the given value assignable to our message type,
-       * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
+       * Reject the promise. Throws if the promise is already resolved or rejected.
        */
-      isAssignable(arg, depth = this.defaultCheckDepth) {
-        return this.refTypeCheck.is(arg, depth, true);
+      reject(reason) {
+        if (this.state !== DeferredState.PENDING)
+          throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`);
+        this._reject(reason);
+        this._state = DeferredState.REJECTED;
       }
       /**
-       * Copy partial data into the target message.
+       * Resolve the promise. Ignore if not pending.
        */
-      mergePartial(target, source) {
-        reflection_merge_partial_1.reflectionMergePartial(this, target, source);
+      resolvePending(val2) {
+        if (this._state === DeferredState.PENDING)
+          this.resolve(val2);
       }
       /**
-       * Create a new message from binary format.
+       * Reject the promise. Ignore if not pending.
        */
-      fromBinary(data, options) {
-        let opt = binary_reader_1.binaryReadOptions(options);
-        return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt);
+      rejectPending(reason) {
+        if (this._state === DeferredState.PENDING)
+          this.reject(reason);
+      }
+    };
+    exports2.Deferred = Deferred;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js
+var require_rpc_output_stream = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.RpcOutputStreamController = void 0;
+    var deferred_1 = require_deferred();
+    var runtime_1 = require_commonjs11();
+    var RpcOutputStreamController = class {
+      constructor() {
+        this._lis = {
+          nxt: [],
+          msg: [],
+          err: [],
+          cmp: []
+        };
+        this._closed = false;
+        this._itState = { q: [] };
+      }
+      // --- RpcOutputStream callback API
+      onNext(callback) {
+        return this.addLis(callback, this._lis.nxt);
+      }
+      onMessage(callback) {
+        return this.addLis(callback, this._lis.msg);
+      }
+      onError(callback) {
+        return this.addLis(callback, this._lis.err);
+      }
+      onComplete(callback) {
+        return this.addLis(callback, this._lis.cmp);
+      }
+      addLis(callback, list) {
+        list.push(callback);
+        return () => {
+          let i = list.indexOf(callback);
+          if (i >= 0)
+            list.splice(i, 1);
+        };
+      }
+      // remove all listeners
+      clearLis() {
+        for (let l of Object.values(this._lis))
+          l.splice(0, l.length);
       }
+      // --- Controller API
       /**
-       * Read a new message from a JSON value.
+       * Is this stream already closed by a completion or error?
        */
-      fromJson(json2, options) {
-        return this.internalJsonRead(json2, json_format_contract_1.jsonReadOptions(options));
+      get closed() {
+        return this._closed !== false;
       }
       /**
-       * Read a new message from a JSON string.
-       * This is equivalent to `T.fromJson(JSON.parse(json))`.
+       * Emit message, close with error, or close successfully, but only one
+       * at a time.
+       * Can be used to wrap a stream by using the other stream's `onNext`.
        */
-      fromJsonString(json2, options) {
-        let value = JSON.parse(json2);
-        return this.fromJson(value, options);
+      notifyNext(message, error4, complete) {
+        runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time");
+        if (message)
+          this.notifyMessage(message);
+        if (error4)
+          this.notifyError(error4);
+        if (complete)
+          this.notifyComplete();
+      }
+      /**
+       * Emits a new message. Throws if stream is closed.
+       *
+       * Triggers onNext and onMessage callbacks.
+       */
+      notifyMessage(message) {
+        runtime_1.assert(!this.closed, "stream is closed");
+        this.pushIt({ value: message, done: false });
+        this._lis.msg.forEach((l) => l(message));
+        this._lis.nxt.forEach((l) => l(message, void 0, false));
+      }
+      /**
+       * Closes the stream with an error. Throws if stream is closed.
+       *
+       * Triggers onNext and onError callbacks.
+       */
+      notifyError(error4) {
+        runtime_1.assert(!this.closed, "stream is closed");
+        this._closed = error4;
+        this.pushIt(error4);
+        this._lis.err.forEach((l) => l(error4));
+        this._lis.nxt.forEach((l) => l(void 0, error4, false));
+        this.clearLis();
+      }
+      /**
+       * Closes the stream successfully. Throws if stream is closed.
+       *
+       * Triggers onNext and onComplete callbacks.
+       */
+      notifyComplete() {
+        runtime_1.assert(!this.closed, "stream is closed");
+        this._closed = true;
+        this.pushIt({ value: null, done: true });
+        this._lis.cmp.forEach((l) => l());
+        this._lis.nxt.forEach((l) => l(void 0, void 0, true));
+        this.clearLis();
+      }
+      /**
+       * Creates an async iterator (that can be used with `for await {...}`)
+       * to consume the stream.
+       *
+       * Some things to note:
+       * - If an error occurs, the `for await` will throw it.
+       * - If an error occurred before the `for await` was started, `for await`
+       *   will re-throw it.
+       * - If the stream is already complete, the `for await` will be empty.
+       * - If your `for await` consumes slower than the stream produces,
+       *   for example because you are relaying messages in a slow operation,
+       *   messages are queued.
+       */
+      [Symbol.asyncIterator]() {
+        if (this._closed === true)
+          this.pushIt({ value: null, done: true });
+        else if (this._closed !== false)
+          this.pushIt(this._closed);
+        return {
+          next: () => {
+            let state = this._itState;
+            runtime_1.assert(state, "bad state");
+            runtime_1.assert(!state.p, "iterator contract broken");
+            let first = state.q.shift();
+            if (first)
+              return "value" in first ? Promise.resolve(first) : Promise.reject(first);
+            state.p = new deferred_1.Deferred();
+            return state.p.promise;
+          }
+        };
+      }
+      // "push" a new iterator result.
+      // this either resolves a pending promise, or enqueues the result.
+      pushIt(result) {
+        let state = this._itState;
+        if (state.p) {
+          const p = state.p;
+          runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken");
+          "value" in result ? p.resolve(result) : p.reject(result);
+          delete state.p;
+        } else {
+          state.q.push(result);
+        }
+      }
+    };
+    exports2.RpcOutputStreamController = RpcOutputStreamController;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js
+var require_unary_call = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.UnaryCall = void 0;
+    var UnaryCall = class {
+      constructor(method, requestHeaders, request, headers, response, status, trailers) {
+        this.method = method;
+        this.requestHeaders = requestHeaders;
+        this.request = request;
+        this.headers = headers;
+        this.response = response;
+        this.status = status;
+        this.trailers = trailers;
+      }
+      /**
+       * If you are only interested in the final outcome of this call,
+       * you can await it to receive a `FinishedUnaryCall`.
+       */
+      then(onfulfilled, onrejected) {
+        return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+      }
+      promiseFinished() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]);
+          return {
+            method: this.method,
+            requestHeaders: this.requestHeaders,
+            request: this.request,
+            headers,
+            response,
+            status,
+            trailers
+          };
+        });
+      }
+    };
+    exports2.UnaryCall = UnaryCall;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js
+var require_server_streaming_call = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.ServerStreamingCall = void 0;
+    var ServerStreamingCall = class {
+      constructor(method, requestHeaders, request, headers, response, status, trailers) {
+        this.method = method;
+        this.requestHeaders = requestHeaders;
+        this.request = request;
+        this.headers = headers;
+        this.responses = response;
+        this.status = status;
+        this.trailers = trailers;
+      }
+      /**
+       * Instead of awaiting the response status and trailers, you can
+       * just as well await this call itself to receive the server outcome.
+       * You should first setup some listeners to the `request` to
+       * see the actual messages the server replied with.
+       */
+      then(onfulfilled, onrejected) {
+        return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+      }
+      promiseFinished() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]);
+          return {
+            method: this.method,
+            requestHeaders: this.requestHeaders,
+            request: this.request,
+            headers,
+            status,
+            trailers
+          };
+        });
+      }
+    };
+    exports2.ServerStreamingCall = ServerStreamingCall;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js
+var require_client_streaming_call = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.ClientStreamingCall = void 0;
+    var ClientStreamingCall = class {
+      constructor(method, requestHeaders, request, headers, response, status, trailers) {
+        this.method = method;
+        this.requestHeaders = requestHeaders;
+        this.requests = request;
+        this.headers = headers;
+        this.response = response;
+        this.status = status;
+        this.trailers = trailers;
       }
       /**
-       * Write the message to canonical JSON value.
+       * Instead of awaiting the response status and trailers, you can
+       * just as well await this call itself to receive the server outcome.
+       * Note that it may still be valid to send more request messages.
        */
-      toJson(message, options) {
-        return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options));
+      then(onfulfilled, onrejected) {
+        return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
       }
-      /**
-       * Convert the message to canonical JSON string.
-       * This is equivalent to `JSON.stringify(T.toJson(t))`
-       */
-      toJsonString(message, options) {
-        var _a;
-        let value = this.toJson(message, options);
-        return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
+      promiseFinished() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]);
+          return {
+            method: this.method,
+            requestHeaders: this.requestHeaders,
+            headers,
+            response,
+            status,
+            trailers
+          };
+        });
       }
-      /**
-       * Write the message to binary format.
-       */
-      toBinary(message, options) {
-        let opt = binary_writer_1.binaryWriteOptions(options);
-        return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish();
+    };
+    exports2.ClientStreamingCall = ClientStreamingCall;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js
+var require_duplex_streaming_call = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) {
+    "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
       }
-      /**
-       * This is an internal method. If you just want to read a message from
-       * JSON, use `fromJson()` or `fromJsonString()`.
-       *
-       * Reads JSON value and merges the fields into the target
-       * according to protobuf rules. If the target is omitted,
-       * a new instance is created first.
-       */
-      internalJsonRead(json2, options, target) {
-        if (json2 !== null && typeof json2 == "object" && !Array.isArray(json2)) {
-          let message = target !== null && target !== void 0 ? target : this.create();
-          this.refJsonReader.read(json2, message, options);
-          return message;
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json2)}.`);
-      }
-      /**
-       * This is an internal method. If you just want to write a message
-       * to JSON, use `toJson()` or `toJsonString().
-       *
-       * Writes JSON value and returns it.
-       */
-      internalJsonWrite(message, options) {
-        return this.refJsonWriter.write(message, options);
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.DuplexStreamingCall = void 0;
+    var DuplexStreamingCall = class {
+      constructor(method, requestHeaders, request, headers, response, status, trailers) {
+        this.method = method;
+        this.requestHeaders = requestHeaders;
+        this.requests = request;
+        this.headers = headers;
+        this.responses = response;
+        this.status = status;
+        this.trailers = trailers;
       }
       /**
-       * This is an internal method. If you just want to write a message
-       * in binary format, use `toBinary()`.
-       *
-       * Serializes the message in binary format and appends it to the given
-       * writer. Returns passed writer.
+       * Instead of awaiting the response status and trailers, you can
+       * just as well await this call itself to receive the server outcome.
+       * Note that it may still be valid to send more request messages.
        */
-      internalBinaryWrite(message, writer, options) {
-        this.refBinWriter.write(message, writer, options);
-        return writer;
+      then(onfulfilled, onrejected) {
+        return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
       }
-      /**
-       * This is an internal method. If you just want to read a message from
-       * binary data, use `fromBinary()`.
-       *
-       * Reads data from binary format and merges the fields into
-       * the target according to protobuf rules. If the target is
-       * omitted, a new instance is created first.
-       */
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create();
-        this.refBinReader.read(reader, message, options, length);
-        return message;
+      promiseFinished() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]);
+          return {
+            method: this.method,
+            requestHeaders: this.requestHeaders,
+            headers,
+            status,
+            trailers
+          };
+        });
       }
     };
-    exports2.MessageType = MessageType;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js
-var require_reflection_contains_message_type = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/reflection-contains-message-type.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.containsMessageType = void 0;
-    var message_type_contract_1 = require_message_type_contract();
-    function containsMessageType(msg) {
-      return msg[message_type_contract_1.MESSAGE_TYPE] != null;
-    }
-    exports2.containsMessageType = containsMessageType;
+    exports2.DuplexStreamingCall = DuplexStreamingCall;
   }
 });
 
-// node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js
-var require_enum_object = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/enum-object.js"(exports2) {
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js
+var require_test_transport = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) {
     "use strict";
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.listEnumNumbers = exports2.listEnumNames = exports2.listEnumValues = exports2.isEnumObject = void 0;
-    function isEnumObject(arg) {
-      if (typeof arg != "object" || arg === null) {
-        return false;
+    exports2.TestTransport = void 0;
+    var rpc_error_1 = require_rpc_error();
+    var runtime_1 = require_commonjs11();
+    var rpc_output_stream_1 = require_rpc_output_stream();
+    var rpc_options_1 = require_rpc_options();
+    var unary_call_1 = require_unary_call();
+    var server_streaming_call_1 = require_server_streaming_call();
+    var client_streaming_call_1 = require_client_streaming_call();
+    var duplex_streaming_call_1 = require_duplex_streaming_call();
+    var TestTransport = class _TestTransport {
+      /**
+       * Initialize with mock data. Omitted fields have default value.
+       */
+      constructor(data) {
+        this.suppressUncaughtRejections = true;
+        this.headerDelay = 10;
+        this.responseDelay = 50;
+        this.betweenResponseDelay = 10;
+        this.afterResponseDelay = 10;
+        this.data = data !== null && data !== void 0 ? data : {};
       }
-      if (!arg.hasOwnProperty(0)) {
+      /**
+       * Sent message(s) during the last operation.
+       */
+      get sentMessages() {
+        if (this.lastInput instanceof TestInputStream) {
+          return this.lastInput.sent;
+        } else if (typeof this.lastInput == "object") {
+          return [this.lastInput.single];
+        }
+        return [];
+      }
+      /**
+       * Sending message(s) completed?
+       */
+      get sendComplete() {
+        if (this.lastInput instanceof TestInputStream) {
+          return this.lastInput.completed;
+        } else if (typeof this.lastInput == "object") {
+          return true;
+        }
         return false;
       }
-      for (let k of Object.keys(arg)) {
-        let num = parseInt(k);
-        if (!Number.isNaN(num)) {
-          let nam = arg[num];
-          if (nam === void 0)
-            return false;
-          if (arg[nam] !== num)
-            return false;
+      // Creates a promise for response headers from the mock data.
+      promiseHeaders() {
+        var _a;
+        const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders;
+        return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers);
+      }
+      // Creates a promise for a single, valid, message from the mock data.
+      promiseSingleResponse(method) {
+        if (this.data.response instanceof rpc_error_1.RpcError) {
+          return Promise.reject(this.data.response);
+        }
+        let r;
+        if (Array.isArray(this.data.response)) {
+          runtime_1.assert(this.data.response.length > 0);
+          r = this.data.response[0];
+        } else if (this.data.response !== void 0) {
+          r = this.data.response;
         } else {
-          let num2 = arg[k];
-          if (num2 === void 0)
-            return false;
-          if (typeof num2 !== "number")
-            return false;
-          if (arg[num2] === void 0)
-            return false;
+          r = method.O.create();
         }
+        runtime_1.assert(method.O.is(r));
+        return Promise.resolve(r);
       }
-      return true;
-    }
-    exports2.isEnumObject = isEnumObject;
-    function listEnumValues(enumObject) {
-      if (!isEnumObject(enumObject))
-        throw new Error("not a typescript enum object");
-      let values = [];
-      for (let [name, number] of Object.entries(enumObject))
-        if (typeof number == "number")
-          values.push({ name, number });
-      return values;
-    }
-    exports2.listEnumValues = listEnumValues;
-    function listEnumNames(enumObject) {
-      return listEnumValues(enumObject).map((val2) => val2.name);
-    }
-    exports2.listEnumNames = listEnumNames;
-    function listEnumNumbers(enumObject) {
-      return listEnumValues(enumObject).map((val2) => val2.number).filter((num, index, arr) => arr.indexOf(num) == index);
-    }
-    exports2.listEnumNumbers = listEnumNumbers;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime/build/commonjs/index.js
-var require_commonjs11 = __commonJS({
-  "node_modules/@protobuf-ts/runtime/build/commonjs/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    var json_typings_1 = require_json_typings();
-    Object.defineProperty(exports2, "typeofJsonValue", { enumerable: true, get: function() {
-      return json_typings_1.typeofJsonValue;
-    } });
-    Object.defineProperty(exports2, "isJsonObject", { enumerable: true, get: function() {
-      return json_typings_1.isJsonObject;
-    } });
-    var base64_1 = require_base642();
-    Object.defineProperty(exports2, "base64decode", { enumerable: true, get: function() {
-      return base64_1.base64decode;
-    } });
-    Object.defineProperty(exports2, "base64encode", { enumerable: true, get: function() {
-      return base64_1.base64encode;
-    } });
-    var protobufjs_utf8_1 = require_protobufjs_utf8();
-    Object.defineProperty(exports2, "utf8read", { enumerable: true, get: function() {
-      return protobufjs_utf8_1.utf8read;
-    } });
-    var binary_format_contract_1 = require_binary_format_contract();
-    Object.defineProperty(exports2, "WireType", { enumerable: true, get: function() {
-      return binary_format_contract_1.WireType;
-    } });
-    Object.defineProperty(exports2, "mergeBinaryOptions", { enumerable: true, get: function() {
-      return binary_format_contract_1.mergeBinaryOptions;
-    } });
-    Object.defineProperty(exports2, "UnknownFieldHandler", { enumerable: true, get: function() {
-      return binary_format_contract_1.UnknownFieldHandler;
-    } });
-    var binary_reader_1 = require_binary_reader();
-    Object.defineProperty(exports2, "BinaryReader", { enumerable: true, get: function() {
-      return binary_reader_1.BinaryReader;
-    } });
-    Object.defineProperty(exports2, "binaryReadOptions", { enumerable: true, get: function() {
-      return binary_reader_1.binaryReadOptions;
-    } });
-    var binary_writer_1 = require_binary_writer();
-    Object.defineProperty(exports2, "BinaryWriter", { enumerable: true, get: function() {
-      return binary_writer_1.BinaryWriter;
-    } });
-    Object.defineProperty(exports2, "binaryWriteOptions", { enumerable: true, get: function() {
-      return binary_writer_1.binaryWriteOptions;
-    } });
-    var pb_long_1 = require_pb_long();
-    Object.defineProperty(exports2, "PbLong", { enumerable: true, get: function() {
-      return pb_long_1.PbLong;
-    } });
-    Object.defineProperty(exports2, "PbULong", { enumerable: true, get: function() {
-      return pb_long_1.PbULong;
-    } });
-    var json_format_contract_1 = require_json_format_contract();
-    Object.defineProperty(exports2, "jsonReadOptions", { enumerable: true, get: function() {
-      return json_format_contract_1.jsonReadOptions;
-    } });
-    Object.defineProperty(exports2, "jsonWriteOptions", { enumerable: true, get: function() {
-      return json_format_contract_1.jsonWriteOptions;
-    } });
-    Object.defineProperty(exports2, "mergeJsonOptions", { enumerable: true, get: function() {
-      return json_format_contract_1.mergeJsonOptions;
-    } });
-    var message_type_contract_1 = require_message_type_contract();
-    Object.defineProperty(exports2, "MESSAGE_TYPE", { enumerable: true, get: function() {
-      return message_type_contract_1.MESSAGE_TYPE;
-    } });
-    var message_type_1 = require_message_type();
-    Object.defineProperty(exports2, "MessageType", { enumerable: true, get: function() {
-      return message_type_1.MessageType;
-    } });
-    var reflection_info_1 = require_reflection_info();
-    Object.defineProperty(exports2, "ScalarType", { enumerable: true, get: function() {
-      return reflection_info_1.ScalarType;
-    } });
-    Object.defineProperty(exports2, "LongType", { enumerable: true, get: function() {
-      return reflection_info_1.LongType;
-    } });
-    Object.defineProperty(exports2, "RepeatType", { enumerable: true, get: function() {
-      return reflection_info_1.RepeatType;
-    } });
-    Object.defineProperty(exports2, "normalizeFieldInfo", { enumerable: true, get: function() {
-      return reflection_info_1.normalizeFieldInfo;
-    } });
-    Object.defineProperty(exports2, "readFieldOptions", { enumerable: true, get: function() {
-      return reflection_info_1.readFieldOptions;
-    } });
-    Object.defineProperty(exports2, "readFieldOption", { enumerable: true, get: function() {
-      return reflection_info_1.readFieldOption;
-    } });
-    Object.defineProperty(exports2, "readMessageOption", { enumerable: true, get: function() {
-      return reflection_info_1.readMessageOption;
-    } });
-    var reflection_type_check_1 = require_reflection_type_check();
-    Object.defineProperty(exports2, "ReflectionTypeCheck", { enumerable: true, get: function() {
-      return reflection_type_check_1.ReflectionTypeCheck;
-    } });
-    var reflection_create_1 = require_reflection_create();
-    Object.defineProperty(exports2, "reflectionCreate", { enumerable: true, get: function() {
-      return reflection_create_1.reflectionCreate;
-    } });
-    var reflection_scalar_default_1 = require_reflection_scalar_default();
-    Object.defineProperty(exports2, "reflectionScalarDefault", { enumerable: true, get: function() {
-      return reflection_scalar_default_1.reflectionScalarDefault;
-    } });
-    var reflection_merge_partial_1 = require_reflection_merge_partial();
-    Object.defineProperty(exports2, "reflectionMergePartial", { enumerable: true, get: function() {
-      return reflection_merge_partial_1.reflectionMergePartial;
-    } });
-    var reflection_equals_1 = require_reflection_equals();
-    Object.defineProperty(exports2, "reflectionEquals", { enumerable: true, get: function() {
-      return reflection_equals_1.reflectionEquals;
-    } });
-    var reflection_binary_reader_1 = require_reflection_binary_reader();
-    Object.defineProperty(exports2, "ReflectionBinaryReader", { enumerable: true, get: function() {
-      return reflection_binary_reader_1.ReflectionBinaryReader;
-    } });
-    var reflection_binary_writer_1 = require_reflection_binary_writer();
-    Object.defineProperty(exports2, "ReflectionBinaryWriter", { enumerable: true, get: function() {
-      return reflection_binary_writer_1.ReflectionBinaryWriter;
-    } });
-    var reflection_json_reader_1 = require_reflection_json_reader();
-    Object.defineProperty(exports2, "ReflectionJsonReader", { enumerable: true, get: function() {
-      return reflection_json_reader_1.ReflectionJsonReader;
-    } });
-    var reflection_json_writer_1 = require_reflection_json_writer();
-    Object.defineProperty(exports2, "ReflectionJsonWriter", { enumerable: true, get: function() {
-      return reflection_json_writer_1.ReflectionJsonWriter;
-    } });
-    var reflection_contains_message_type_1 = require_reflection_contains_message_type();
-    Object.defineProperty(exports2, "containsMessageType", { enumerable: true, get: function() {
-      return reflection_contains_message_type_1.containsMessageType;
-    } });
-    var oneof_1 = require_oneof();
-    Object.defineProperty(exports2, "isOneofGroup", { enumerable: true, get: function() {
-      return oneof_1.isOneofGroup;
-    } });
-    Object.defineProperty(exports2, "setOneofValue", { enumerable: true, get: function() {
-      return oneof_1.setOneofValue;
-    } });
-    Object.defineProperty(exports2, "getOneofValue", { enumerable: true, get: function() {
-      return oneof_1.getOneofValue;
-    } });
-    Object.defineProperty(exports2, "clearOneofValue", { enumerable: true, get: function() {
-      return oneof_1.clearOneofValue;
-    } });
-    Object.defineProperty(exports2, "getSelectedOneofValue", { enumerable: true, get: function() {
-      return oneof_1.getSelectedOneofValue;
-    } });
-    var enum_object_1 = require_enum_object();
-    Object.defineProperty(exports2, "listEnumValues", { enumerable: true, get: function() {
-      return enum_object_1.listEnumValues;
-    } });
-    Object.defineProperty(exports2, "listEnumNames", { enumerable: true, get: function() {
-      return enum_object_1.listEnumNames;
-    } });
-    Object.defineProperty(exports2, "listEnumNumbers", { enumerable: true, get: function() {
-      return enum_object_1.listEnumNumbers;
-    } });
-    Object.defineProperty(exports2, "isEnumObject", { enumerable: true, get: function() {
-      return enum_object_1.isEnumObject;
-    } });
-    var lower_camel_case_1 = require_lower_camel_case();
-    Object.defineProperty(exports2, "lowerCamelCase", { enumerable: true, get: function() {
-      return lower_camel_case_1.lowerCamelCase;
-    } });
-    var assert_1 = require_assert();
-    Object.defineProperty(exports2, "assert", { enumerable: true, get: function() {
-      return assert_1.assert;
-    } });
-    Object.defineProperty(exports2, "assertNever", { enumerable: true, get: function() {
-      return assert_1.assertNever;
-    } });
-    Object.defineProperty(exports2, "assertInt32", { enumerable: true, get: function() {
-      return assert_1.assertInt32;
-    } });
-    Object.defineProperty(exports2, "assertUInt32", { enumerable: true, get: function() {
-      return assert_1.assertUInt32;
-    } });
-    Object.defineProperty(exports2, "assertFloat32", { enumerable: true, get: function() {
-      return assert_1.assertFloat32;
-    } });
-  }
-});
-
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js
-var require_reflection_info2 = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/reflection-info.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.readServiceOption = exports2.readMethodOption = exports2.readMethodOptions = exports2.normalizeMethodInfo = void 0;
-    var runtime_1 = require_commonjs11();
-    function normalizeMethodInfo(method, service) {
-      var _a, _b, _c;
-      let m = method;
-      m.service = service;
-      m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name);
-      m.serverStreaming = !!m.serverStreaming;
-      m.clientStreaming = !!m.clientStreaming;
-      m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {};
-      m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : void 0;
-      return m;
-    }
-    exports2.normalizeMethodInfo = normalizeMethodInfo;
-    function readMethodOptions(service, methodName, extensionName, extensionType) {
-      var _a;
-      const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options;
-      return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : void 0;
-    }
-    exports2.readMethodOptions = readMethodOptions;
-    function readMethodOption(service, methodName, extensionName, extensionType) {
-      var _a;
-      const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options;
-      if (!options) {
-        return void 0;
+      /**
+       * Pushes response messages from the mock data to the output stream.
+       * If an error response, status or trailers are mocked, the stream is
+       * closed with the respective error.
+       * Otherwise, stream is completed successfully.
+       *
+       * The returned promise resolves when the stream is closed. It should
+       * not reject. If it does, code is broken.
+       */
+      streamResponses(method, stream2, abort) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const messages = [];
+          if (this.data.response === void 0) {
+            messages.push(method.O.create());
+          } else if (Array.isArray(this.data.response)) {
+            for (let msg of this.data.response) {
+              runtime_1.assert(method.O.is(msg));
+              messages.push(msg);
+            }
+          } else if (!(this.data.response instanceof rpc_error_1.RpcError)) {
+            runtime_1.assert(method.O.is(this.data.response));
+            messages.push(this.data.response);
+          }
+          try {
+            yield delay2(this.responseDelay, abort)(void 0);
+          } catch (error4) {
+            stream2.notifyError(error4);
+            return;
+          }
+          if (this.data.response instanceof rpc_error_1.RpcError) {
+            stream2.notifyError(this.data.response);
+            return;
+          }
+          for (let msg of messages) {
+            stream2.notifyMessage(msg);
+            try {
+              yield delay2(this.betweenResponseDelay, abort)(void 0);
+            } catch (error4) {
+              stream2.notifyError(error4);
+              return;
+            }
+          }
+          if (this.data.status instanceof rpc_error_1.RpcError) {
+            stream2.notifyError(this.data.status);
+            return;
+          }
+          if (this.data.trailers instanceof rpc_error_1.RpcError) {
+            stream2.notifyError(this.data.trailers);
+            return;
+          }
+          stream2.notifyComplete();
+        });
       }
-      const optionVal = options[extensionName];
-      if (optionVal === void 0) {
-        return optionVal;
+      // Creates a promise for response status from the mock data.
+      promiseStatus() {
+        var _a;
+        const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus;
+        return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status);
       }
-      return extensionType ? extensionType.fromJson(optionVal) : optionVal;
-    }
-    exports2.readMethodOption = readMethodOption;
-    function readServiceOption(service, extensionName, extensionType) {
-      const options = service.options;
-      if (!options) {
-        return void 0;
+      // Creates a promise for response trailers from the mock data.
+      promiseTrailers() {
+        var _a;
+        const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers;
+        return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers);
       }
-      const optionVal = options[extensionName];
-      if (optionVal === void 0) {
-        return optionVal;
+      maybeSuppressUncaught(...promise) {
+        if (this.suppressUncaughtRejections) {
+          for (let p of promise) {
+            p.catch(() => {
+            });
+          }
+        }
       }
-      return extensionType ? extensionType.fromJson(optionVal) : optionVal;
-    }
-    exports2.readServiceOption = readServiceOption;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js
-var require_service_type = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/service-type.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ServiceType = void 0;
-    var reflection_info_1 = require_reflection_info2();
-    var ServiceType = class {
-      constructor(typeName, methods, options) {
-        this.typeName = typeName;
-        this.methods = methods.map((i) => reflection_info_1.normalizeMethodInfo(i, this));
-        this.options = options !== null && options !== void 0 ? options : {};
+      mergeOptions(options) {
+        return rpc_options_1.mergeRpcOptions({}, options);
       }
-    };
-    exports2.ServiceType = ServiceType;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js
-var require_rpc_error = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-error.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.RpcError = void 0;
-    var RpcError = class extends Error {
-      constructor(message, code = "UNKNOWN", meta) {
-        super(message);
-        this.name = "RpcError";
-        Object.setPrototypeOf(this, new.target.prototype);
-        this.code = code;
-        this.meta = meta !== null && meta !== void 0 ? meta : {};
+      unary(method, input, options) {
+        var _a;
+        const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => {
+        }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => {
+        }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => {
+        }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers());
+        this.maybeSuppressUncaught(statusPromise, trailersPromise);
+        this.lastInput = { single: input };
+        return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise);
       }
-      toString() {
-        const l = [this.name + ": " + this.message];
-        if (this.code) {
-          l.push("");
-          l.push("Code: " + this.code);
+      serverStreaming(method, input, options) {
+        var _a;
+        const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => {
+        }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers());
+        this.maybeSuppressUncaught(statusPromise, trailersPromise);
+        this.lastInput = { single: input };
+        return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise);
+      }
+      clientStreaming(method, options) {
+        var _a;
+        const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => {
+        }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => {
+        }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => {
+        }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers());
+        this.maybeSuppressUncaught(statusPromise, trailersPromise);
+        this.lastInput = new TestInputStream(this.data, options.abort);
+        return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise);
+      }
+      duplex(method, options) {
+        var _a;
+        const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => {
+        }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers());
+        this.maybeSuppressUncaught(statusPromise, trailersPromise);
+        this.lastInput = new TestInputStream(this.data, options.abort);
+        return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise);
+      }
+    };
+    exports2.TestTransport = TestTransport;
+    TestTransport.defaultHeaders = {
+      responseHeader: "test"
+    };
+    TestTransport.defaultStatus = {
+      code: "OK",
+      detail: "all good"
+    };
+    TestTransport.defaultTrailers = {
+      responseTrailer: "test"
+    };
+    function delay2(ms, abort) {
+      return (v) => new Promise((resolve6, reject) => {
+        if (abort === null || abort === void 0 ? void 0 : abort.aborted) {
+          reject(new rpc_error_1.RpcError("user cancel", "CANCELLED"));
+        } else {
+          const id = setTimeout(() => resolve6(v), ms);
+          if (abort) {
+            abort.addEventListener("abort", (ev) => {
+              clearTimeout(id);
+              reject(new rpc_error_1.RpcError("user cancel", "CANCELLED"));
+            });
+          }
         }
-        if (this.serviceName && this.methodName) {
-          l.push("Method: " + this.serviceName + "/" + this.methodName);
+      });
+    }
+    var TestInputStream = class {
+      constructor(data, abort) {
+        this._completed = false;
+        this._sent = [];
+        this.data = data;
+        this.abort = abort;
+      }
+      get sent() {
+        return this._sent;
+      }
+      get completed() {
+        return this._completed;
+      }
+      send(message) {
+        if (this.data.inputMessage instanceof rpc_error_1.RpcError) {
+          return Promise.reject(this.data.inputMessage);
         }
-        let m = Object.entries(this.meta);
-        if (m.length) {
-          l.push("");
-          l.push("Meta:");
-          for (let [k, v] of m) {
-            l.push(`  ${k}: ${v}`);
-          }
+        const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage;
+        return Promise.resolve(void 0).then(() => {
+          this._sent.push(message);
+        }).then(delay2(delayMs, this.abort));
+      }
+      complete() {
+        if (this.data.inputComplete instanceof rpc_error_1.RpcError) {
+          return Promise.reject(this.data.inputComplete);
         }
-        return l.join("\n");
+        const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete;
+        return Promise.resolve(void 0).then(() => {
+          this._completed = true;
+        }).then(delay2(delayMs, this.abort));
       }
     };
-    exports2.RpcError = RpcError;
   }
 });
 
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js
-var require_rpc_options = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-options.js"(exports2) {
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js
+var require_rpc_interceptor = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.mergeRpcOptions = void 0;
+    exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0;
     var runtime_1 = require_commonjs11();
-    function mergeRpcOptions(defaults, options) {
-      if (!options)
-        return defaults;
-      let o = {};
-      copy(defaults, o);
-      copy(options, o);
-      for (let key of Object.keys(options)) {
-        let val2 = options[key];
-        switch (key) {
-          case "jsonOptions":
-            o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions);
-            break;
-          case "binaryOptions":
-            o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions);
-            break;
-          case "meta":
-            o.meta = {};
-            copy(defaults.meta, o.meta);
-            copy(options.meta, o.meta);
-            break;
-          case "interceptors":
-            o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val2) : val2.concat();
-            break;
+    function stackIntercept(kind, transport, method, options, input) {
+      var _a, _b, _c, _d;
+      if (kind == "unary") {
+        let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt);
+        for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) {
+          const next = tail;
+          tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt);
         }
+        return tail(method, input, options);
       }
-      return o;
-    }
-    exports2.mergeRpcOptions = mergeRpcOptions;
-    function copy(a, into) {
-      if (!a)
-        return;
-      let c = into;
-      for (let [k, v] of Object.entries(a)) {
-        if (v instanceof Date)
-          c[k] = new Date(v.getTime());
-        else if (Array.isArray(v))
-          c[k] = v.concat();
-        else
-          c[k] = v;
+      if (kind == "serverStreaming") {
+        let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt);
+        for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) {
+          const next = tail;
+          tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt);
+        }
+        return tail(method, input, options);
+      }
+      if (kind == "clientStreaming") {
+        let tail = (mtd, opt) => transport.clientStreaming(mtd, opt);
+        for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) {
+          const next = tail;
+          tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt);
+        }
+        return tail(method, options);
+      }
+      if (kind == "duplex") {
+        let tail = (mtd, opt) => transport.duplex(mtd, opt);
+        for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) {
+          const next = tail;
+          tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt);
+        }
+        return tail(method, options);
       }
+      runtime_1.assertNever(kind);
+    }
+    exports2.stackIntercept = stackIntercept;
+    function stackUnaryInterceptors(transport, method, input, options) {
+      return stackIntercept("unary", transport, method, options, input);
+    }
+    exports2.stackUnaryInterceptors = stackUnaryInterceptors;
+    function stackServerStreamingInterceptors(transport, method, input, options) {
+      return stackIntercept("serverStreaming", transport, method, options, input);
+    }
+    exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors;
+    function stackClientStreamingInterceptors(transport, method, options) {
+      return stackIntercept("clientStreaming", transport, method, options);
+    }
+    exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors;
+    function stackDuplexStreamingInterceptors(transport, method, options) {
+      return stackIntercept("duplex", transport, method, options);
     }
+    exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors;
   }
 });
 
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js
-var require_deferred = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/deferred.js"(exports2) {
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js
+var require_server_call_context = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.Deferred = exports2.DeferredState = void 0;
-    var DeferredState;
-    (function(DeferredState2) {
-      DeferredState2[DeferredState2["PENDING"] = 0] = "PENDING";
-      DeferredState2[DeferredState2["REJECTED"] = 1] = "REJECTED";
-      DeferredState2[DeferredState2["RESOLVED"] = 2] = "RESOLVED";
-    })(DeferredState = exports2.DeferredState || (exports2.DeferredState = {}));
-    var Deferred = class {
-      /**
-       * @param preventUnhandledRejectionWarning - prevents the warning
-       * "Unhandled Promise rejection" by adding a noop rejection handler.
-       * Working with calls returned from the runtime-rpc package in an
-       * async function usually means awaiting one call property after
-       * the other. This means that the "status" is not being awaited when
-       * an earlier await for the "headers" is rejected. This causes the
-       * "unhandled promise reject" warning. A more correct behaviour for
-       * calls might be to become aware whether at least one of the
-       * promises is handled and swallow the rejection warning for the
-       * others.
-       */
-      constructor(preventUnhandledRejectionWarning = true) {
-        this._state = DeferredState.PENDING;
-        this._promise = new Promise((resolve6, reject) => {
-          this._resolve = resolve6;
-          this._reject = reject;
-        });
-        if (preventUnhandledRejectionWarning) {
-          this._promise.catch((_) => {
-          });
-        }
-      }
-      /**
-       * Get the current state of the promise.
-       */
-      get state() {
-        return this._state;
-      }
-      /**
-       * Get the deferred promise.
-       */
-      get promise() {
-        return this._promise;
+    exports2.ServerCallContextController = void 0;
+    var ServerCallContextController = class {
+      constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) {
+        this._cancelled = false;
+        this._listeners = [];
+        this.method = method;
+        this.headers = headers;
+        this.deadline = deadline;
+        this.trailers = {};
+        this._sendRH = sendResponseHeadersFn;
+        this.status = defaultStatus;
       }
       /**
-       * Resolve the promise. Throws if the promise is already resolved or rejected.
+       * Set the call cancelled.
+       *
+       * Invokes all callbacks registered with onCancel() and
+       * sets `cancelled = true`.
        */
-      resolve(value) {
-        if (this.state !== DeferredState.PENDING)
-          throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`);
-        this._resolve(value);
-        this._state = DeferredState.RESOLVED;
+      notifyCancelled() {
+        if (!this._cancelled) {
+          this._cancelled = true;
+          for (let l of this._listeners) {
+            l();
+          }
+        }
       }
       /**
-       * Reject the promise. Throws if the promise is already resolved or rejected.
+       * Send response headers.
        */
-      reject(reason) {
-        if (this.state !== DeferredState.PENDING)
-          throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`);
-        this._reject(reason);
-        this._state = DeferredState.REJECTED;
+      sendResponseHeaders(data) {
+        this._sendRH(data);
       }
       /**
-       * Resolve the promise. Ignore if not pending.
+       * Is the call cancelled?
+       *
+       * When the client closes the connection before the server
+       * is done, the call is cancelled.
+       *
+       * If you want to cancel a request on the server, throw a
+       * RpcError with the CANCELLED status code.
        */
-      resolvePending(val2) {
-        if (this._state === DeferredState.PENDING)
-          this.resolve(val2);
+      get cancelled() {
+        return this._cancelled;
       }
       /**
-       * Reject the promise. Ignore if not pending.
+       * Add a callback for cancellation.
        */
-      rejectPending(reason) {
-        if (this._state === DeferredState.PENDING)
-          this.reject(reason);
+      onCancel(callback) {
+        const l = this._listeners;
+        l.push(callback);
+        return () => {
+          let i = l.indexOf(callback);
+          if (i >= 0)
+            l.splice(i, 1);
+        };
       }
     };
-    exports2.Deferred = Deferred;
+    exports2.ServerCallContextController = ServerCallContextController;
+  }
+});
+
+// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js
+var require_commonjs12 = __commonJS({
+  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    var service_type_1 = require_service_type();
+    Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() {
+      return service_type_1.ServiceType;
+    } });
+    var reflection_info_1 = require_reflection_info2();
+    Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() {
+      return reflection_info_1.readMethodOptions;
+    } });
+    Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() {
+      return reflection_info_1.readMethodOption;
+    } });
+    Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() {
+      return reflection_info_1.readServiceOption;
+    } });
+    var rpc_error_1 = require_rpc_error();
+    Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() {
+      return rpc_error_1.RpcError;
+    } });
+    var rpc_options_1 = require_rpc_options();
+    Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() {
+      return rpc_options_1.mergeRpcOptions;
+    } });
+    var rpc_output_stream_1 = require_rpc_output_stream();
+    Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() {
+      return rpc_output_stream_1.RpcOutputStreamController;
+    } });
+    var test_transport_1 = require_test_transport();
+    Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() {
+      return test_transport_1.TestTransport;
+    } });
+    var deferred_1 = require_deferred();
+    Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() {
+      return deferred_1.Deferred;
+    } });
+    Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() {
+      return deferred_1.DeferredState;
+    } });
+    var duplex_streaming_call_1 = require_duplex_streaming_call();
+    Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() {
+      return duplex_streaming_call_1.DuplexStreamingCall;
+    } });
+    var client_streaming_call_1 = require_client_streaming_call();
+    Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() {
+      return client_streaming_call_1.ClientStreamingCall;
+    } });
+    var server_streaming_call_1 = require_server_streaming_call();
+    Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() {
+      return server_streaming_call_1.ServerStreamingCall;
+    } });
+    var unary_call_1 = require_unary_call();
+    Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() {
+      return unary_call_1.UnaryCall;
+    } });
+    var rpc_interceptor_1 = require_rpc_interceptor();
+    Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() {
+      return rpc_interceptor_1.stackIntercept;
+    } });
+    Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() {
+      return rpc_interceptor_1.stackDuplexStreamingInterceptors;
+    } });
+    Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() {
+      return rpc_interceptor_1.stackClientStreamingInterceptors;
+    } });
+    Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() {
+      return rpc_interceptor_1.stackServerStreamingInterceptors;
+    } });
+    Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() {
+      return rpc_interceptor_1.stackUnaryInterceptors;
+    } });
+    var server_call_context_1 = require_server_call_context();
+    Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() {
+      return server_call_context_1.ServerCallContextController;
+    } });
   }
 });
 
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js
-var require_rpc_output_stream = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-output-stream.js"(exports2) {
+// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js
+var require_cachescope = __commonJS({
+  "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.RpcOutputStreamController = void 0;
-    var deferred_1 = require_deferred();
+    exports2.CacheScope = void 0;
     var runtime_1 = require_commonjs11();
-    var RpcOutputStreamController = class {
+    var runtime_2 = require_commonjs11();
+    var runtime_3 = require_commonjs11();
+    var runtime_4 = require_commonjs11();
+    var runtime_5 = require_commonjs11();
+    var CacheScope$Type = class extends runtime_5.MessageType {
       constructor() {
-        this._lis = {
-          nxt: [],
-          msg: [],
-          err: [],
-          cmp: []
-        };
-        this._closed = false;
-        this._itState = { q: [] };
-      }
-      // --- RpcOutputStream callback API
-      onNext(callback) {
-        return this.addLis(callback, this._lis.nxt);
-      }
-      onMessage(callback) {
-        return this.addLis(callback, this._lis.msg);
-      }
-      onError(callback) {
-        return this.addLis(callback, this._lis.err);
-      }
-      onComplete(callback) {
-        return this.addLis(callback, this._lis.cmp);
-      }
-      addLis(callback, list) {
-        list.push(callback);
-        return () => {
-          let i = list.indexOf(callback);
-          if (i >= 0)
-            list.splice(i, 1);
-        };
-      }
-      // remove all listeners
-      clearLis() {
-        for (let l of Object.values(this._lis))
-          l.splice(0, l.length);
-      }
-      // --- Controller API
-      /**
-       * Is this stream already closed by a completion or error?
-       */
-      get closed() {
-        return this._closed !== false;
-      }
-      /**
-       * Emit message, close with error, or close successfully, but only one
-       * at a time.
-       * Can be used to wrap a stream by using the other stream's `onNext`.
-       */
-      notifyNext(message, error4, complete) {
-        runtime_1.assert((message ? 1 : 0) + (error4 ? 1 : 0) + (complete ? 1 : 0) <= 1, "only one emission at a time");
-        if (message)
-          this.notifyMessage(message);
-        if (error4)
-          this.notifyError(error4);
-        if (complete)
-          this.notifyComplete();
-      }
-      /**
-       * Emits a new message. Throws if stream is closed.
-       *
-       * Triggers onNext and onMessage callbacks.
-       */
-      notifyMessage(message) {
-        runtime_1.assert(!this.closed, "stream is closed");
-        this.pushIt({ value: message, done: false });
-        this._lis.msg.forEach((l) => l(message));
-        this._lis.nxt.forEach((l) => l(message, void 0, false));
-      }
-      /**
-       * Closes the stream with an error. Throws if stream is closed.
-       *
-       * Triggers onNext and onError callbacks.
-       */
-      notifyError(error4) {
-        runtime_1.assert(!this.closed, "stream is closed");
-        this._closed = error4;
-        this.pushIt(error4);
-        this._lis.err.forEach((l) => l(error4));
-        this._lis.nxt.forEach((l) => l(void 0, error4, false));
-        this.clearLis();
+        super("github.actions.results.entities.v1.CacheScope", [
+          {
+            no: 1,
+            name: "scope",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 2,
+            name: "permission",
+            kind: "scalar",
+            T: 3
+            /*ScalarType.INT64*/
+          }
+        ]);
       }
-      /**
-       * Closes the stream successfully. Throws if stream is closed.
-       *
-       * Triggers onNext and onComplete callbacks.
-       */
-      notifyComplete() {
-        runtime_1.assert(!this.closed, "stream is closed");
-        this._closed = true;
-        this.pushIt({ value: null, done: true });
-        this._lis.cmp.forEach((l) => l());
-        this._lis.nxt.forEach((l) => l(void 0, void 0, true));
-        this.clearLis();
+      create(value) {
+        const message = { scope: "", permission: "0" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
       }
-      /**
-       * Creates an async iterator (that can be used with `for await {...}`)
-       * to consume the stream.
-       *
-       * Some things to note:
-       * - If an error occurs, the `for await` will throw it.
-       * - If an error occurred before the `for await` was started, `for await`
-       *   will re-throw it.
-       * - If the stream is already complete, the `for await` will be empty.
-       * - If your `for await` consumes slower than the stream produces,
-       *   for example because you are relaying messages in a slow operation,
-       *   messages are queued.
-       */
-      [Symbol.asyncIterator]() {
-        if (this._closed === true)
-          this.pushIt({ value: null, done: true });
-        else if (this._closed !== false)
-          this.pushIt(this._closed);
-        return {
-          next: () => {
-            let state = this._itState;
-            runtime_1.assert(state, "bad state");
-            runtime_1.assert(!state.p, "iterator contract broken");
-            let first = state.q.shift();
-            if (first)
-              return "value" in first ? Promise.resolve(first) : Promise.reject(first);
-            state.p = new deferred_1.Deferred();
-            return state.p.promise;
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* string scope */
+            1:
+              message.scope = reader.string();
+              break;
+            case /* int64 permission */
+            2:
+              message.permission = reader.int64().toString();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
-        };
-      }
-      // "push" a new iterator result.
-      // this either resolves a pending promise, or enqueues the result.
-      pushIt(result) {
-        let state = this._itState;
-        if (state.p) {
-          const p = state.p;
-          runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken");
-          "value" in result ? p.resolve(result) : p.reject(result);
-          delete state.p;
-        } else {
-          state.q.push(result);
         }
+        return message;
+      }
+      internalBinaryWrite(message, writer, options) {
+        if (message.scope !== "")
+          writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope);
+        if (message.permission !== "0")
+          writer.tag(2, runtime_1.WireType.Varint).int64(message.permission);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
     };
-    exports2.RpcOutputStreamController = RpcOutputStreamController;
+    exports2.CacheScope = new CacheScope$Type();
   }
 });
 
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js
-var require_unary_call = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/unary-call.js"(exports2) {
+// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js
+var require_cachemetadata = __commonJS({
+  "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) {
     "use strict";
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
-        });
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.CacheMetadata = void 0;
+    var runtime_1 = require_commonjs11();
+    var runtime_2 = require_commonjs11();
+    var runtime_3 = require_commonjs11();
+    var runtime_4 = require_commonjs11();
+    var runtime_5 = require_commonjs11();
+    var cachescope_1 = require_cachescope();
+    var CacheMetadata$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.entities.v1.CacheMetadata", [
+          {
+            no: 1,
+            name: "repository_id",
+            kind: "scalar",
+            T: 3
+            /*ScalarType.INT64*/
+          },
+          { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope }
+        ]);
       }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+      create(value) {
+        const message = { repositoryId: "0", scope: [] };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
+      }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* int64 repository_id */
+            1:
+              message.repositoryId = reader.int64().toString();
+              break;
+            case /* repeated github.actions.results.entities.v1.CacheScope scope */
+            2:
+              message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options));
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.UnaryCall = void 0;
-    var UnaryCall = class {
-      constructor(method, requestHeaders, request, headers, response, status, trailers) {
-        this.method = method;
-        this.requestHeaders = requestHeaders;
-        this.request = request;
-        this.headers = headers;
-        this.response = response;
-        this.status = status;
-        this.trailers = trailers;
-      }
-      /**
-       * If you are only interested in the final outcome of this call,
-       * you can await it to receive a `FinishedUnaryCall`.
-       */
-      then(onfulfilled, onrejected) {
-        return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+        return message;
       }
-      promiseFinished() {
-        return __awaiter4(this, void 0, void 0, function* () {
-          let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]);
-          return {
-            method: this.method,
-            requestHeaders: this.requestHeaders,
-            request: this.request,
-            headers,
-            response,
-            status,
-            trailers
-          };
-        });
+      internalBinaryWrite(message, writer, options) {
+        if (message.repositoryId !== "0")
+          writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId);
+        for (let i = 0; i < message.scope.length; i++)
+          cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join();
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
     };
-    exports2.UnaryCall = UnaryCall;
+    exports2.CacheMetadata = new CacheMetadata$Type();
   }
 });
 
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js
-var require_server_streaming_call = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-streaming-call.js"(exports2) {
+// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js
+var require_cache2 = __commonJS({
+  "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) {
     "use strict";
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0;
+    var runtime_rpc_1 = require_commonjs12();
+    var runtime_1 = require_commonjs11();
+    var runtime_2 = require_commonjs11();
+    var runtime_3 = require_commonjs11();
+    var runtime_4 = require_commonjs11();
+    var runtime_5 = require_commonjs11();
+    var cachemetadata_1 = require_cachemetadata();
+    var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.CreateCacheEntryRequest", [
+          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
+          {
+            no: 2,
+            name: "key",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "version",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
           }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+        ]);
+      }
+      create(value) {
+        const message = { key: "", version: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
+      }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* github.actions.results.entities.v1.CacheMetadata metadata */
+            1:
+              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
+              break;
+            case /* string key */
+            2:
+              message.key = reader.string();
+              break;
+            case /* string version */
+            3:
+              message.version = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ServerStreamingCall = void 0;
-    var ServerStreamingCall = class {
-      constructor(method, requestHeaders, request, headers, response, status, trailers) {
-        this.method = method;
-        this.requestHeaders = requestHeaders;
-        this.request = request;
-        this.headers = headers;
-        this.responses = response;
-        this.status = status;
-        this.trailers = trailers;
-      }
-      /**
-       * Instead of awaiting the response status and trailers, you can
-       * just as well await this call itself to receive the server outcome.
-       * You should first setup some listeners to the `request` to
-       * see the actual messages the server replied with.
-       */
-      then(onfulfilled, onrejected) {
-        return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+        return message;
       }
-      promiseFinished() {
-        return __awaiter4(this, void 0, void 0, function* () {
-          let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]);
-          return {
-            method: this.method,
-            requestHeaders: this.requestHeaders,
-            request: this.request,
-            headers,
-            status,
-            trailers
-          };
-        });
+      internalBinaryWrite(message, writer, options) {
+        if (message.metadata)
+          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
+        if (message.key !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
+        if (message.version !== "")
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
     };
-    exports2.ServerStreamingCall = ServerStreamingCall;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js
-var require_client_streaming_call = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/client-streaming-call.js"(exports2) {
-    "use strict";
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
+    exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type();
+    var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.CreateCacheEntryResponse", [
+          {
+            no: 1,
+            name: "ok",
+            kind: "scalar",
+            T: 8
+            /*ScalarType.BOOL*/
+          },
+          {
+            no: 2,
+            name: "signed_upload_url",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "message",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
           }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+        ]);
+      }
+      create(value) {
+        const message = { ok: false, signedUploadUrl: "", message: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
+      }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* bool ok */
+            1:
+              message.ok = reader.bool();
+              break;
+            case /* string signed_upload_url */
+            2:
+              message.signedUploadUrl = reader.string();
+              break;
+            case /* string message */
+            3:
+              message.message = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ClientStreamingCall = void 0;
-    var ClientStreamingCall = class {
-      constructor(method, requestHeaders, request, headers, response, status, trailers) {
-        this.method = method;
-        this.requestHeaders = requestHeaders;
-        this.requests = request;
-        this.headers = headers;
-        this.response = response;
-        this.status = status;
-        this.trailers = trailers;
-      }
-      /**
-       * Instead of awaiting the response status and trailers, you can
-       * just as well await this call itself to receive the server outcome.
-       * Note that it may still be valid to send more request messages.
-       */
-      then(onfulfilled, onrejected) {
-        return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+        return message;
       }
-      promiseFinished() {
-        return __awaiter4(this, void 0, void 0, function* () {
-          let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]);
-          return {
-            method: this.method,
-            requestHeaders: this.requestHeaders,
-            headers,
-            response,
-            status,
-            trailers
-          };
-        });
+      internalBinaryWrite(message, writer, options) {
+        if (message.ok !== false)
+          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
+        if (message.signedUploadUrl !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl);
+        if (message.message !== "")
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
     };
-    exports2.ClientStreamingCall = ClientStreamingCall;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js
-var require_duplex_streaming_call = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/duplex-streaming-call.js"(exports2) {
-    "use strict";
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
+    exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type();
+    var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [
+          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
+          {
+            no: 2,
+            name: "key",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "size_bytes",
+            kind: "scalar",
+            T: 3
+            /*ScalarType.INT64*/
+          },
+          {
+            no: 4,
+            name: "version",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
           }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+        ]);
+      }
+      create(value) {
+        const message = { key: "", sizeBytes: "0", version: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
+      }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* github.actions.results.entities.v1.CacheMetadata metadata */
+            1:
+              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
+              break;
+            case /* string key */
+            2:
+              message.key = reader.string();
+              break;
+            case /* int64 size_bytes */
+            3:
+              message.sizeBytes = reader.int64().toString();
+              break;
+            case /* string version */
+            4:
+              message.version = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.DuplexStreamingCall = void 0;
-    var DuplexStreamingCall = class {
-      constructor(method, requestHeaders, request, headers, response, status, trailers) {
-        this.method = method;
-        this.requestHeaders = requestHeaders;
-        this.requests = request;
-        this.headers = headers;
-        this.responses = response;
-        this.status = status;
-        this.trailers = trailers;
-      }
-      /**
-       * Instead of awaiting the response status and trailers, you can
-       * just as well await this call itself to receive the server outcome.
-       * Note that it may still be valid to send more request messages.
-       */
-      then(onfulfilled, onrejected) {
-        return this.promiseFinished().then((value) => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, (reason) => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+        return message;
       }
-      promiseFinished() {
-        return __awaiter4(this, void 0, void 0, function* () {
-          let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]);
-          return {
-            method: this.method,
-            requestHeaders: this.requestHeaders,
-            headers,
-            status,
-            trailers
-          };
-        });
+      internalBinaryWrite(message, writer, options) {
+        if (message.metadata)
+          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
+        if (message.key !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
+        if (message.sizeBytes !== "0")
+          writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes);
+        if (message.version !== "")
+          writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
     };
-    exports2.DuplexStreamingCall = DuplexStreamingCall;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js
-var require_test_transport = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/test-transport.js"(exports2) {
-    "use strict";
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
+    exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type();
+    var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [
+          {
+            no: 1,
+            name: "ok",
+            kind: "scalar",
+            T: 8
+            /*ScalarType.BOOL*/
+          },
+          {
+            no: 2,
+            name: "entry_id",
+            kind: "scalar",
+            T: 3
+            /*ScalarType.INT64*/
+          },
+          {
+            no: 3,
+            name: "message",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
           }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+        ]);
+      }
+      create(value) {
+        const message = { ok: false, entryId: "0", message: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
+      }
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* bool ok */
+            1:
+              message.ok = reader.bool();
+              break;
+            case /* int64 entry_id */
+            2:
+              message.entryId = reader.int64().toString();
+              break;
+            case /* string message */
+            3:
+              message.message = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.TestTransport = void 0;
-    var rpc_error_1 = require_rpc_error();
-    var runtime_1 = require_commonjs11();
-    var rpc_output_stream_1 = require_rpc_output_stream();
-    var rpc_options_1 = require_rpc_options();
-    var unary_call_1 = require_unary_call();
-    var server_streaming_call_1 = require_server_streaming_call();
-    var client_streaming_call_1 = require_client_streaming_call();
-    var duplex_streaming_call_1 = require_duplex_streaming_call();
-    var TestTransport = class _TestTransport {
-      /**
-       * Initialize with mock data. Omitted fields have default value.
-       */
-      constructor(data) {
-        this.suppressUncaughtRejections = true;
-        this.headerDelay = 10;
-        this.responseDelay = 50;
-        this.betweenResponseDelay = 10;
-        this.afterResponseDelay = 10;
-        this.data = data !== null && data !== void 0 ? data : {};
+        return message;
       }
-      /**
-       * Sent message(s) during the last operation.
-       */
-      get sentMessages() {
-        if (this.lastInput instanceof TestInputStream) {
-          return this.lastInput.sent;
-        } else if (typeof this.lastInput == "object") {
-          return [this.lastInput.single];
-        }
-        return [];
+      internalBinaryWrite(message, writer, options) {
+        if (message.ok !== false)
+          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
+        if (message.entryId !== "0")
+          writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId);
+        if (message.message !== "")
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
-      /**
-       * Sending message(s) completed?
-       */
-      get sendComplete() {
-        if (this.lastInput instanceof TestInputStream) {
-          return this.lastInput.completed;
-        } else if (typeof this.lastInput == "object") {
-          return true;
-        }
-        return false;
+    };
+    exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type();
+    var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [
+          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
+          {
+            no: 2,
+            name: "key",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "restore_keys",
+            kind: "scalar",
+            repeat: 2,
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 4,
+            name: "version",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          }
+        ]);
       }
-      // Creates a promise for response headers from the mock data.
-      promiseHeaders() {
-        var _a;
-        const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : _TestTransport.defaultHeaders;
-        return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers);
+      create(value) {
+        const message = { key: "", restoreKeys: [], version: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
       }
-      // Creates a promise for a single, valid, message from the mock data.
-      promiseSingleResponse(method) {
-        if (this.data.response instanceof rpc_error_1.RpcError) {
-          return Promise.reject(this.data.response);
-        }
-        let r;
-        if (Array.isArray(this.data.response)) {
-          runtime_1.assert(this.data.response.length > 0);
-          r = this.data.response[0];
-        } else if (this.data.response !== void 0) {
-          r = this.data.response;
-        } else {
-          r = method.O.create();
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* github.actions.results.entities.v1.CacheMetadata metadata */
+            1:
+              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
+              break;
+            case /* string key */
+            2:
+              message.key = reader.string();
+              break;
+            case /* repeated string restore_keys */
+            3:
+              message.restoreKeys.push(reader.string());
+              break;
+            case /* string version */
+            4:
+              message.version = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
+          }
         }
-        runtime_1.assert(method.O.is(r));
-        return Promise.resolve(r);
+        return message;
       }
-      /**
-       * Pushes response messages from the mock data to the output stream.
-       * If an error response, status or trailers are mocked, the stream is
-       * closed with the respective error.
-       * Otherwise, stream is completed successfully.
-       *
-       * The returned promise resolves when the stream is closed. It should
-       * not reject. If it does, code is broken.
-       */
-      streamResponses(method, stream2, abort) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const messages = [];
-          if (this.data.response === void 0) {
-            messages.push(method.O.create());
-          } else if (Array.isArray(this.data.response)) {
-            for (let msg of this.data.response) {
-              runtime_1.assert(method.O.is(msg));
-              messages.push(msg);
-            }
-          } else if (!(this.data.response instanceof rpc_error_1.RpcError)) {
-            runtime_1.assert(method.O.is(this.data.response));
-            messages.push(this.data.response);
-          }
-          try {
-            yield delay2(this.responseDelay, abort)(void 0);
-          } catch (error4) {
-            stream2.notifyError(error4);
-            return;
-          }
-          if (this.data.response instanceof rpc_error_1.RpcError) {
-            stream2.notifyError(this.data.response);
-            return;
-          }
-          for (let msg of messages) {
-            stream2.notifyMessage(msg);
-            try {
-              yield delay2(this.betweenResponseDelay, abort)(void 0);
-            } catch (error4) {
-              stream2.notifyError(error4);
-              return;
-            }
-          }
-          if (this.data.status instanceof rpc_error_1.RpcError) {
-            stream2.notifyError(this.data.status);
-            return;
-          }
-          if (this.data.trailers instanceof rpc_error_1.RpcError) {
-            stream2.notifyError(this.data.trailers);
-            return;
+      internalBinaryWrite(message, writer, options) {
+        if (message.metadata)
+          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
+        if (message.key !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
+        for (let i = 0; i < message.restoreKeys.length; i++)
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]);
+        if (message.version !== "")
+          writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
+      }
+    };
+    exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type();
+    var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType {
+      constructor() {
+        super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [
+          {
+            no: 1,
+            name: "ok",
+            kind: "scalar",
+            T: 8
+            /*ScalarType.BOOL*/
+          },
+          {
+            no: 2,
+            name: "signed_download_url",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
+          },
+          {
+            no: 3,
+            name: "matched_key",
+            kind: "scalar",
+            T: 9
+            /*ScalarType.STRING*/
           }
-          stream2.notifyComplete();
-        });
-      }
-      // Creates a promise for response status from the mock data.
-      promiseStatus() {
-        var _a;
-        const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : _TestTransport.defaultStatus;
-        return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status);
+        ]);
       }
-      // Creates a promise for response trailers from the mock data.
-      promiseTrailers() {
-        var _a;
-        const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : _TestTransport.defaultTrailers;
-        return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers);
+      create(value) {
+        const message = { ok: false, signedDownloadUrl: "", matchedKey: "" };
+        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
+        if (value !== void 0)
+          (0, runtime_3.reflectionMergePartial)(this, message, value);
+        return message;
       }
-      maybeSuppressUncaught(...promise) {
-        if (this.suppressUncaughtRejections) {
-          for (let p of promise) {
-            p.catch(() => {
-            });
+      internalBinaryRead(reader, length, options, target) {
+        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
+        while (reader.pos < end) {
+          let [fieldNo, wireType] = reader.tag();
+          switch (fieldNo) {
+            case /* bool ok */
+            1:
+              message.ok = reader.bool();
+              break;
+            case /* string signed_download_url */
+            2:
+              message.signedDownloadUrl = reader.string();
+              break;
+            case /* string matched_key */
+            3:
+              message.matchedKey = reader.string();
+              break;
+            default:
+              let u = options.readUnknownField;
+              if (u === "throw")
+                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
+              let d = reader.skip(wireType);
+              if (u !== false)
+                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
+        return message;
       }
-      mergeOptions(options) {
-        return rpc_options_1.mergeRpcOptions({}, options);
+      internalBinaryWrite(message, writer, options) {
+        if (message.ok !== false)
+          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
+        if (message.signedDownloadUrl !== "")
+          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl);
+        if (message.matchedKey !== "")
+          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey);
+        let u = options.writeUnknownFields;
+        if (u !== false)
+          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
+        return writer;
       }
-      unary(method, input, options) {
-        var _a;
-        const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => {
-        }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => {
-        }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => {
-        }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers());
-        this.maybeSuppressUncaught(statusPromise, trailersPromise);
-        this.lastInput = { single: input };
-        return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise);
+    };
+    exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type();
+    exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [
+      { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse },
+      { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse },
+      { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse }
+    ]);
+  }
+});
+
+// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js
+var require_cache_twirp_client = __commonJS({
+  "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0;
+    var cache_1 = require_cache2();
+    var CacheServiceClientJSON = class {
+      constructor(rpc) {
+        this.rpc = rpc;
+        this.CreateCacheEntry.bind(this);
+        this.FinalizeCacheEntryUpload.bind(this);
+        this.GetCacheEntryDownloadURL.bind(this);
       }
-      serverStreaming(method, input, options) {
-        var _a;
-        const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => {
-        }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers());
-        this.maybeSuppressUncaught(statusPromise, trailersPromise);
-        this.lastInput = { single: input };
-        return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise);
+      CreateCacheEntry(request) {
+        const data = cache_1.CreateCacheEntryRequest.toJson(request, {
+          useProtoFieldName: true,
+          emitDefaultValues: false
+        });
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data);
+        return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, {
+          ignoreUnknownFields: true
+        }));
       }
-      clientStreaming(method, options) {
-        var _a;
-        const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), responsePromise = headersPromise.catch((_) => {
-        }).then(delay2(this.responseDelay, options.abort)).then((_) => this.promiseSingleResponse(method)), statusPromise = responsePromise.catch((_) => {
-        }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseStatus()), trailersPromise = responsePromise.catch((_) => {
-        }).then(delay2(this.afterResponseDelay, options.abort)).then((_) => this.promiseTrailers());
-        this.maybeSuppressUncaught(statusPromise, trailersPromise);
-        this.lastInput = new TestInputStream(this.data, options.abort);
-        return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise);
+      FinalizeCacheEntryUpload(request) {
+        const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, {
+          useProtoFieldName: true,
+          emitDefaultValues: false
+        });
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data);
+        return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, {
+          ignoreUnknownFields: true
+        }));
       }
-      duplex(method, options) {
-        var _a;
-        const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders().then(delay2(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise.then(delay2(this.responseDelay, options.abort)).catch(() => {
-        }).then(() => this.streamResponses(method, outputStream, options.abort)).then(delay2(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise.then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise.then(() => this.promiseTrailers());
-        this.maybeSuppressUncaught(statusPromise, trailersPromise);
-        this.lastInput = new TestInputStream(this.data, options.abort);
-        return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise);
+      GetCacheEntryDownloadURL(request) {
+        const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, {
+          useProtoFieldName: true,
+          emitDefaultValues: false
+        });
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data);
+        return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, {
+          ignoreUnknownFields: true
+        }));
       }
     };
-    exports2.TestTransport = TestTransport;
-    TestTransport.defaultHeaders = {
-      responseHeader: "test"
-    };
-    TestTransport.defaultStatus = {
-      code: "OK",
-      detail: "all good"
-    };
-    TestTransport.defaultTrailers = {
-      responseTrailer: "test"
-    };
-    function delay2(ms, abort) {
-      return (v) => new Promise((resolve6, reject) => {
-        if (abort === null || abort === void 0 ? void 0 : abort.aborted) {
-          reject(new rpc_error_1.RpcError("user cancel", "CANCELLED"));
-        } else {
-          const id = setTimeout(() => resolve6(v), ms);
-          if (abort) {
-            abort.addEventListener("abort", (ev) => {
-              clearTimeout(id);
-              reject(new rpc_error_1.RpcError("user cancel", "CANCELLED"));
-            });
-          }
-        }
-      });
-    }
-    var TestInputStream = class {
-      constructor(data, abort) {
-        this._completed = false;
-        this._sent = [];
-        this.data = data;
-        this.abort = abort;
-      }
-      get sent() {
-        return this._sent;
+    exports2.CacheServiceClientJSON = CacheServiceClientJSON;
+    var CacheServiceClientProtobuf = class {
+      constructor(rpc) {
+        this.rpc = rpc;
+        this.CreateCacheEntry.bind(this);
+        this.FinalizeCacheEntryUpload.bind(this);
+        this.GetCacheEntryDownloadURL.bind(this);
       }
-      get completed() {
-        return this._completed;
+      CreateCacheEntry(request) {
+        const data = cache_1.CreateCacheEntryRequest.toBinary(request);
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data);
+        return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2));
       }
-      send(message) {
-        if (this.data.inputMessage instanceof rpc_error_1.RpcError) {
-          return Promise.reject(this.data.inputMessage);
-        }
-        const delayMs = this.data.inputMessage === void 0 ? 10 : this.data.inputMessage;
-        return Promise.resolve(void 0).then(() => {
-          this._sent.push(message);
-        }).then(delay2(delayMs, this.abort));
+      FinalizeCacheEntryUpload(request) {
+        const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request);
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data);
+        return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2));
       }
-      complete() {
-        if (this.data.inputComplete instanceof rpc_error_1.RpcError) {
-          return Promise.reject(this.data.inputComplete);
-        }
-        const delayMs = this.data.inputComplete === void 0 ? 10 : this.data.inputComplete;
-        return Promise.resolve(void 0).then(() => {
-          this._completed = true;
-        }).then(delay2(delayMs, this.abort));
+      GetCacheEntryDownloadURL(request) {
+        const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request);
+        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data);
+        return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2));
       }
     };
+    exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf;
   }
 });
 
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js
-var require_rpc_interceptor = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/rpc-interceptor.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/shared/util.js
+var require_util10 = __commonJS({
+  "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) {
     "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.stackDuplexStreamingInterceptors = exports2.stackClientStreamingInterceptors = exports2.stackServerStreamingInterceptors = exports2.stackUnaryInterceptors = exports2.stackIntercept = void 0;
-    var runtime_1 = require_commonjs11();
-    function stackIntercept(kind, transport, method, options, input) {
-      var _a, _b, _c, _d;
-      if (kind == "unary") {
-        let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt);
-        for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter((i) => i.interceptUnary).reverse()) {
-          const next = tail;
-          tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt);
+    exports2.maskSecretUrls = exports2.maskSigUrl = void 0;
+    var core_1 = require_core();
+    function maskSigUrl(url2) {
+      if (!url2)
+        return;
+      try {
+        const parsedUrl = new URL(url2);
+        const signature = parsedUrl.searchParams.get("sig");
+        if (signature) {
+          (0, core_1.setSecret)(signature);
+          (0, core_1.setSecret)(encodeURIComponent(signature));
         }
-        return tail(method, input, options);
+      } catch (error4) {
+        (0, core_1.debug)(`Failed to parse URL: ${url2} ${error4 instanceof Error ? error4.message : String(error4)}`);
       }
-      if (kind == "serverStreaming") {
-        let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt);
-        for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter((i) => i.interceptServerStreaming).reverse()) {
-          const next = tail;
-          tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt);
-        }
-        return tail(method, input, options);
+    }
+    exports2.maskSigUrl = maskSigUrl;
+    function maskSecretUrls(body) {
+      if (typeof body !== "object" || body === null) {
+        (0, core_1.debug)("body is not an object or is null");
+        return;
       }
-      if (kind == "clientStreaming") {
-        let tail = (mtd, opt) => transport.clientStreaming(mtd, opt);
-        for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter((i) => i.interceptClientStreaming).reverse()) {
-          const next = tail;
-          tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt);
-        }
-        return tail(method, options);
+      if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") {
+        maskSigUrl(body.signed_upload_url);
       }
-      if (kind == "duplex") {
-        let tail = (mtd, opt) => transport.duplex(mtd, opt);
-        for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter((i) => i.interceptDuplex).reverse()) {
-          const next = tail;
-          tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt);
-        }
-        return tail(method, options);
+      if ("signed_download_url" in body && typeof body.signed_download_url === "string") {
+        maskSigUrl(body.signed_download_url);
       }
-      runtime_1.assertNever(kind);
-    }
-    exports2.stackIntercept = stackIntercept;
-    function stackUnaryInterceptors(transport, method, input, options) {
-      return stackIntercept("unary", transport, method, options, input);
-    }
-    exports2.stackUnaryInterceptors = stackUnaryInterceptors;
-    function stackServerStreamingInterceptors(transport, method, input, options) {
-      return stackIntercept("serverStreaming", transport, method, options, input);
-    }
-    exports2.stackServerStreamingInterceptors = stackServerStreamingInterceptors;
-    function stackClientStreamingInterceptors(transport, method, options) {
-      return stackIntercept("clientStreaming", transport, method, options);
-    }
-    exports2.stackClientStreamingInterceptors = stackClientStreamingInterceptors;
-    function stackDuplexStreamingInterceptors(transport, method, options) {
-      return stackIntercept("duplex", transport, method, options);
     }
-    exports2.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors;
+    exports2.maskSecretUrls = maskSecretUrls;
   }
 });
 
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js
-var require_server_call_context = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/server-call-context.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js
+var require_cacheTwirpClient = __commonJS({
+  "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.ServerCallContextController = void 0;
-    var ServerCallContextController = class {
-      constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: "OK", detail: "" }) {
-        this._cancelled = false;
-        this._listeners = [];
-        this.method = method;
-        this.headers = headers;
-        this.deadline = deadline;
-        this.trailers = {};
-        this._sendRH = sendResponseHeadersFn;
-        this.status = defaultStatus;
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
       }
-      /**
-       * Set the call cancelled.
-       *
-       * Invokes all callbacks registered with onCancel() and
-       * sets `cancelled = true`.
-       */
-      notifyCancelled() {
-        if (!this._cancelled) {
-          this._cancelled = true;
-          for (let l of this._listeners) {
-            l();
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
           }
         }
-      }
-      /**
-       * Send response headers.
-       */
-      sendResponseHeaders(data) {
-        this._sendRH(data);
-      }
-      /**
-       * Is the call cancelled?
-       *
-       * When the client closes the connection before the server
-       * is done, the call is cancelled.
-       *
-       * If you want to cancel a request on the server, throw a
-       * RpcError with the CANCELLED status code.
-       */
-      get cancelled() {
-        return this._cancelled;
-      }
-      /**
-       * Add a callback for cancellation.
-       */
-      onCancel(callback) {
-        const l = this._listeners;
-        l.push(callback);
-        return () => {
-          let i = l.indexOf(callback);
-          if (i >= 0)
-            l.splice(i, 1);
-        };
-      }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    exports2.ServerCallContextController = ServerCallContextController;
-  }
-});
-
-// node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js
-var require_commonjs12 = __commonJS({
-  "node_modules/@protobuf-ts/runtime-rpc/build/commonjs/index.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    var service_type_1 = require_service_type();
-    Object.defineProperty(exports2, "ServiceType", { enumerable: true, get: function() {
-      return service_type_1.ServiceType;
-    } });
-    var reflection_info_1 = require_reflection_info2();
-    Object.defineProperty(exports2, "readMethodOptions", { enumerable: true, get: function() {
-      return reflection_info_1.readMethodOptions;
-    } });
-    Object.defineProperty(exports2, "readMethodOption", { enumerable: true, get: function() {
-      return reflection_info_1.readMethodOption;
-    } });
-    Object.defineProperty(exports2, "readServiceOption", { enumerable: true, get: function() {
-      return reflection_info_1.readServiceOption;
-    } });
-    var rpc_error_1 = require_rpc_error();
-    Object.defineProperty(exports2, "RpcError", { enumerable: true, get: function() {
-      return rpc_error_1.RpcError;
-    } });
-    var rpc_options_1 = require_rpc_options();
-    Object.defineProperty(exports2, "mergeRpcOptions", { enumerable: true, get: function() {
-      return rpc_options_1.mergeRpcOptions;
-    } });
-    var rpc_output_stream_1 = require_rpc_output_stream();
-    Object.defineProperty(exports2, "RpcOutputStreamController", { enumerable: true, get: function() {
-      return rpc_output_stream_1.RpcOutputStreamController;
-    } });
-    var test_transport_1 = require_test_transport();
-    Object.defineProperty(exports2, "TestTransport", { enumerable: true, get: function() {
-      return test_transport_1.TestTransport;
-    } });
-    var deferred_1 = require_deferred();
-    Object.defineProperty(exports2, "Deferred", { enumerable: true, get: function() {
-      return deferred_1.Deferred;
-    } });
-    Object.defineProperty(exports2, "DeferredState", { enumerable: true, get: function() {
-      return deferred_1.DeferredState;
-    } });
-    var duplex_streaming_call_1 = require_duplex_streaming_call();
-    Object.defineProperty(exports2, "DuplexStreamingCall", { enumerable: true, get: function() {
-      return duplex_streaming_call_1.DuplexStreamingCall;
-    } });
-    var client_streaming_call_1 = require_client_streaming_call();
-    Object.defineProperty(exports2, "ClientStreamingCall", { enumerable: true, get: function() {
-      return client_streaming_call_1.ClientStreamingCall;
-    } });
-    var server_streaming_call_1 = require_server_streaming_call();
-    Object.defineProperty(exports2, "ServerStreamingCall", { enumerable: true, get: function() {
-      return server_streaming_call_1.ServerStreamingCall;
-    } });
-    var unary_call_1 = require_unary_call();
-    Object.defineProperty(exports2, "UnaryCall", { enumerable: true, get: function() {
-      return unary_call_1.UnaryCall;
-    } });
-    var rpc_interceptor_1 = require_rpc_interceptor();
-    Object.defineProperty(exports2, "stackIntercept", { enumerable: true, get: function() {
-      return rpc_interceptor_1.stackIntercept;
-    } });
-    Object.defineProperty(exports2, "stackDuplexStreamingInterceptors", { enumerable: true, get: function() {
-      return rpc_interceptor_1.stackDuplexStreamingInterceptors;
-    } });
-    Object.defineProperty(exports2, "stackClientStreamingInterceptors", { enumerable: true, get: function() {
-      return rpc_interceptor_1.stackClientStreamingInterceptors;
-    } });
-    Object.defineProperty(exports2, "stackServerStreamingInterceptors", { enumerable: true, get: function() {
-      return rpc_interceptor_1.stackServerStreamingInterceptors;
-    } });
-    Object.defineProperty(exports2, "stackUnaryInterceptors", { enumerable: true, get: function() {
-      return rpc_interceptor_1.stackUnaryInterceptors;
-    } });
-    var server_call_context_1 = require_server_call_context();
-    Object.defineProperty(exports2, "ServerCallContextController", { enumerable: true, get: function() {
-      return server_call_context_1.ServerCallContextController;
-    } });
-  }
-});
-
-// node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js
-var require_cachescope = __commonJS({
-  "node_modules/@actions/cache/lib/generated/results/entities/v1/cachescope.js"(exports2) {
-    "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.CacheScope = void 0;
-    var runtime_1 = require_commonjs11();
-    var runtime_2 = require_commonjs11();
-    var runtime_3 = require_commonjs11();
-    var runtime_4 = require_commonjs11();
-    var runtime_5 = require_commonjs11();
-    var CacheScope$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.entities.v1.CacheScope", [
-          {
-            no: 1,
-            name: "scope",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 2,
-            name: "permission",
-            kind: "scalar",
-            T: 3
-            /*ScalarType.INT64*/
-          }
+    exports2.internalCacheTwirpClient = void 0;
+    var core_1 = require_core();
+    var user_agent_1 = require_user_agent();
+    var errors_1 = require_errors2();
+    var config_1 = require_config();
+    var cacheUtils_1 = require_cacheUtils();
+    var auth_1 = require_auth2();
+    var http_client_1 = require_lib3();
+    var cache_twirp_client_1 = require_cache_twirp_client();
+    var util_1 = require_util10();
+    var CacheServiceClient = class {
+      constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) {
+        this.maxAttempts = 5;
+        this.baseRetryIntervalMilliseconds = 3e3;
+        this.retryMultiplier = 1.5;
+        const token = (0, cacheUtils_1.getRuntimeToken)();
+        this.baseUrl = (0, config_1.getCacheServiceURL)();
+        if (maxAttempts) {
+          this.maxAttempts = maxAttempts;
+        }
+        if (baseRetryIntervalMilliseconds) {
+          this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds;
+        }
+        if (retryMultiplier) {
+          this.retryMultiplier = retryMultiplier;
+        }
+        this.httpClient = new http_client_1.HttpClient(userAgent, [
+          new auth_1.BearerCredentialHandler(token)
         ]);
       }
-      create(value) {
-        const message = { scope: "", permission: "0" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      // This function satisfies the Rpc interface. It is compatible with the JSON
+      // JSON generated client.
+      request(service, method, contentType, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const url2 = new URL(`/twirp/${service}/${method}`, this.baseUrl).href;
+          (0, core_1.debug)(`[Request] ${method} ${url2}`);
+          const headers = {
+            "Content-Type": contentType
+          };
+          try {
+            const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () {
+              return this.httpClient.post(url2, JSON.stringify(data), headers);
+            }));
+            return body;
+          } catch (error4) {
+            throw new Error(`Failed to ${method}: ${error4.message}`);
+          }
+        });
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* string scope */
-            1:
-              message.scope = reader.string();
-              break;
-            case /* int64 permission */
-            2:
-              message.permission = reader.int64().toString();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
+      retryableRequest(operation) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          let attempt = 0;
+          let errorMessage = "";
+          let rawBody = "";
+          while (attempt < this.maxAttempts) {
+            let isRetryable = false;
+            try {
+              const response = yield operation();
+              const statusCode = response.message.statusCode;
+              rawBody = yield response.readBody();
+              (0, core_1.debug)(`[Response] - ${response.message.statusCode}`);
+              (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`);
+              const body = JSON.parse(rawBody);
+              (0, util_1.maskSecretUrls)(body);
+              (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`);
+              if (this.isSuccessStatusCode(statusCode)) {
+                return { response, body };
+              }
+              isRetryable = this.isRetryableHttpStatusCode(statusCode);
+              errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`;
+              if (body.msg) {
+                if (errors_1.UsageError.isUsageErrorMessage(body.msg)) {
+                  throw new errors_1.UsageError();
+                }
+                errorMessage = `${errorMessage}: ${body.msg}`;
+              }
+            } catch (error4) {
+              if (error4 instanceof SyntaxError) {
+                (0, core_1.debug)(`Raw Body: ${rawBody}`);
+              }
+              if (error4 instanceof errors_1.UsageError) {
+                throw error4;
+              }
+              if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) {
+                throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code);
+              }
+              isRetryable = true;
+              errorMessage = error4.message;
+            }
+            if (!isRetryable) {
+              throw new Error(`Received non-retryable error: ${errorMessage}`);
+            }
+            if (attempt + 1 === this.maxAttempts) {
+              throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`);
+            }
+            const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt);
+            (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`);
+            yield this.sleep(retryTimeMilliseconds);
+            attempt++;
           }
-        }
-        return message;
+          throw new Error(`Request failed`);
+        });
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.scope !== "")
-          writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope);
-        if (message.permission !== "0")
-          writer.tag(2, runtime_1.WireType.Varint).int64(message.permission);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+      isSuccessStatusCode(statusCode) {
+        if (!statusCode)
+          return false;
+        return statusCode >= 200 && statusCode < 300;
+      }
+      isRetryableHttpStatusCode(statusCode) {
+        if (!statusCode)
+          return false;
+        const retryableStatusCodes = [
+          http_client_1.HttpCodes.BadGateway,
+          http_client_1.HttpCodes.GatewayTimeout,
+          http_client_1.HttpCodes.InternalServerError,
+          http_client_1.HttpCodes.ServiceUnavailable,
+          http_client_1.HttpCodes.TooManyRequests
+        ];
+        return retryableStatusCodes.includes(statusCode);
+      }
+      sleep(milliseconds) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => setTimeout(resolve6, milliseconds));
+        });
+      }
+      getExponentialRetryTimeMilliseconds(attempt) {
+        if (attempt < 0) {
+          throw new Error("attempt should be a positive integer");
+        }
+        if (attempt === 0) {
+          return this.baseRetryIntervalMilliseconds;
+        }
+        const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt);
+        const maxTime = minTime * this.retryMultiplier;
+        return Math.trunc(Math.random() * (maxTime - minTime) + minTime);
       }
     };
-    exports2.CacheScope = new CacheScope$Type();
+    function internalCacheTwirpClient(options) {
+      const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier);
+      return new cache_twirp_client_1.CacheServiceClientJSON(client);
+    }
+    exports2.internalCacheTwirpClient = internalCacheTwirpClient;
   }
 });
 
-// node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js
-var require_cachemetadata = __commonJS({
-  "node_modules/@actions/cache/lib/generated/results/entities/v1/cachemetadata.js"(exports2) {
+// node_modules/@actions/cache/lib/internal/tar.js
+var require_tar = __commonJS({
+  "node_modules/@actions/cache/lib/internal/tar.js"(exports2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.CacheMetadata = void 0;
-    var runtime_1 = require_commonjs11();
-    var runtime_2 = require_commonjs11();
-    var runtime_3 = require_commonjs11();
-    var runtime_4 = require_commonjs11();
-    var runtime_5 = require_commonjs11();
-    var cachescope_1 = require_cachescope();
-    var CacheMetadata$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.entities.v1.CacheMetadata", [
-          {
-            no: 1,
-            name: "repository_id",
-            kind: "scalar",
-            T: 3
-            /*ScalarType.INT64*/
-          },
-          { no: 2, name: "scope", kind: "message", repeat: 1, T: () => cachescope_1.CacheScope }
-        ]);
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      create(value) {
-        const message = { repositoryId: "0", scope: [] };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* int64 repository_id */
-            1:
-              message.repositoryId = reader.int64().toString();
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
+      }
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.createTar = exports2.extractTar = exports2.listTar = void 0;
+    var exec_1 = require_exec();
+    var io6 = __importStar4(require_io());
+    var fs_1 = require("fs");
+    var path12 = __importStar4(require("path"));
+    var utils = __importStar4(require_cacheUtils());
+    var constants_1 = require_constants7();
+    var IS_WINDOWS = process.platform === "win32";
+    function getTarPath() {
+      return __awaiter4(this, void 0, void 0, function* () {
+        switch (process.platform) {
+          case "win32": {
+            const gnuTar = yield utils.getGnuTarPathOnWindows();
+            const systemTar = constants_1.SystemTarPathOnWindows;
+            if (gnuTar) {
+              return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
+            } else if ((0, fs_1.existsSync)(systemTar)) {
+              return { path: systemTar, type: constants_1.ArchiveToolType.BSD };
+            }
+            break;
+          }
+          case "darwin": {
+            const gnuTar = yield io6.which("gtar", false);
+            if (gnuTar) {
+              return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
+            } else {
+              return {
+                path: yield io6.which("tar", true),
+                type: constants_1.ArchiveToolType.BSD
+              };
+            }
+          }
+          default:
+            break;
+        }
+        return {
+          path: yield io6.which("tar", true),
+          type: constants_1.ArchiveToolType.GNU
+        };
+      });
+    }
+    function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const args = [`"${tarPath.path}"`];
+        const cacheFileName = utils.getCacheFileName(compressionMethod);
+        const tarFile = "cache.tar";
+        const workingDirectory = getWorkingDirectory();
+        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
+        switch (type2) {
+          case "create":
+            args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename);
+            break;
+          case "extract":
+            args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path12.sep}`, "g"), "/"));
+            break;
+          case "list":
+            args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "-P");
+            break;
+        }
+        if (tarPath.type === constants_1.ArchiveToolType.GNU) {
+          switch (process.platform) {
+            case "win32":
+              args.push("--force-local");
               break;
-            case /* repeated github.actions.results.entities.v1.CacheScope scope */
-            2:
-              message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options));
+            case "darwin":
+              args.push("--delay-directory-restore");
               break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
           }
         }
-        return message;
-      }
-      internalBinaryWrite(message, writer, options) {
-        if (message.repositoryId !== "0")
-          writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId);
-        for (let i = 0; i < message.scope.length; i++)
-          cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join();
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
-      }
-    };
-    exports2.CacheMetadata = new CacheMetadata$Type();
+        return args;
+      });
+    }
+    function getCommands(compressionMethod, type2, archivePath = "") {
+      return __awaiter4(this, void 0, void 0, function* () {
+        let args;
+        const tarPath = yield getTarPath();
+        const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath);
+        const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod);
+        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
+        if (BSD_TAR_ZSTD && type2 !== "create") {
+          args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")];
+        } else {
+          args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")];
+        }
+        if (BSD_TAR_ZSTD) {
+          return args;
+        }
+        return [args.join(" ")];
+      });
+    }
+    function getWorkingDirectory() {
+      var _a;
+      return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd();
+    }
+    function getDecompressionProgram(tarPath, compressionMethod, archivePath) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
+        switch (compressionMethod) {
+          case constants_1.CompressionMethod.Zstd:
+            return BSD_TAR_ZSTD ? [
+              "zstd -d --long=30 --force -o",
+              constants_1.TarFilename,
+              archivePath.replace(new RegExp(`\\${path12.sep}`, "g"), "/")
+            ] : [
+              "--use-compress-program",
+              IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30"
+            ];
+          case constants_1.CompressionMethod.ZstdWithoutLong:
+            return BSD_TAR_ZSTD ? [
+              "zstd -d --force -o",
+              constants_1.TarFilename,
+              archivePath.replace(new RegExp(`\\${path12.sep}`, "g"), "/")
+            ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"];
+          default:
+            return ["-z"];
+        }
+      });
+    }
+    function getCompressionProgram(tarPath, compressionMethod) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const cacheFileName = utils.getCacheFileName(compressionMethod);
+        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
+        switch (compressionMethod) {
+          case constants_1.CompressionMethod.Zstd:
+            return BSD_TAR_ZSTD ? [
+              "zstd -T0 --long=30 --force -o",
+              cacheFileName.replace(new RegExp(`\\${path12.sep}`, "g"), "/"),
+              constants_1.TarFilename
+            ] : [
+              "--use-compress-program",
+              IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30"
+            ];
+          case constants_1.CompressionMethod.ZstdWithoutLong:
+            return BSD_TAR_ZSTD ? [
+              "zstd -T0 --force -o",
+              cacheFileName.replace(new RegExp(`\\${path12.sep}`, "g"), "/"),
+              constants_1.TarFilename
+            ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"];
+          default:
+            return ["-z"];
+        }
+      });
+    }
+    function execCommands(commands, cwd) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        for (const command of commands) {
+          try {
+            yield (0, exec_1.exec)(command, void 0, {
+              cwd,
+              env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" })
+            });
+          } catch (error4) {
+            throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`);
+          }
+        }
+      });
+    }
+    function listTar(archivePath, compressionMethod) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const commands = yield getCommands(compressionMethod, "list", archivePath);
+        yield execCommands(commands);
+      });
+    }
+    exports2.listTar = listTar;
+    function extractTar2(archivePath, compressionMethod) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const workingDirectory = getWorkingDirectory();
+        yield io6.mkdirP(workingDirectory);
+        const commands = yield getCommands(compressionMethod, "extract", archivePath);
+        yield execCommands(commands);
+      });
+    }
+    exports2.extractTar = extractTar2;
+    function createTar(archiveFolder, sourceDirectories, compressionMethod) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        (0, fs_1.writeFileSync)(path12.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n"));
+        const commands = yield getCommands(compressionMethod, "create");
+        yield execCommands(commands, archiveFolder);
+      });
+    }
+    exports2.createTar = createTar;
   }
 });
 
-// node_modules/@actions/cache/lib/generated/results/api/v1/cache.js
-var require_cache2 = __commonJS({
-  "node_modules/@actions/cache/lib/generated/results/api/v1/cache.js"(exports2) {
+// node_modules/@actions/cache/lib/cache.js
+var require_cache3 = __commonJS({
+  "node_modules/@actions/cache/lib/cache.js"(exports2) {
     "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.CacheService = exports2.GetCacheEntryDownloadURLResponse = exports2.GetCacheEntryDownloadURLRequest = exports2.FinalizeCacheEntryUploadResponse = exports2.FinalizeCacheEntryUploadRequest = exports2.CreateCacheEntryResponse = exports2.CreateCacheEntryRequest = void 0;
-    var runtime_rpc_1 = require_commonjs12();
-    var runtime_1 = require_commonjs11();
-    var runtime_2 = require_commonjs11();
-    var runtime_3 = require_commonjs11();
-    var runtime_4 = require_commonjs11();
-    var runtime_5 = require_commonjs11();
-    var cachemetadata_1 = require_cachemetadata();
-    var CreateCacheEntryRequest$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.CreateCacheEntryRequest", [
-          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
-          {
-            no: 2,
-            name: "key",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "version",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          }
-        ]);
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
-      create(value) {
-        const message = { key: "", version: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* github.actions.results.entities.v1.CacheMetadata metadata */
-            1:
-              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
-              break;
-            case /* string key */
-            2:
-              message.key = reader.string();
-              break;
-            case /* string version */
-            3:
-              message.version = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
           }
         }
-        return message;
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0;
+    var core14 = __importStar4(require_core());
+    var path12 = __importStar4(require("path"));
+    var utils = __importStar4(require_cacheUtils());
+    var cacheHttpClient = __importStar4(require_cacheHttpClient());
+    var cacheTwirpClient = __importStar4(require_cacheTwirpClient());
+    var config_1 = require_config();
+    var tar_1 = require_tar();
+    var http_client_1 = require_lib3();
+    var ValidationError = class _ValidationError extends Error {
+      constructor(message) {
+        super(message);
+        this.name = "ValidationError";
+        Object.setPrototypeOf(this, _ValidationError.prototype);
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.metadata)
-          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
-        if (message.key !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
-        if (message.version !== "")
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+    };
+    exports2.ValidationError = ValidationError;
+    var ReserveCacheError = class _ReserveCacheError extends Error {
+      constructor(message) {
+        super(message);
+        this.name = "ReserveCacheError";
+        Object.setPrototypeOf(this, _ReserveCacheError.prototype);
       }
     };
-    exports2.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type();
-    var CreateCacheEntryResponse$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.CreateCacheEntryResponse", [
-          {
-            no: 1,
-            name: "ok",
-            kind: "scalar",
-            T: 8
-            /*ScalarType.BOOL*/
-          },
-          {
-            no: 2,
-            name: "signed_upload_url",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "message",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          }
-        ]);
+    exports2.ReserveCacheError = ReserveCacheError;
+    var FinalizeCacheError = class _FinalizeCacheError extends Error {
+      constructor(message) {
+        super(message);
+        this.name = "FinalizeCacheError";
+        Object.setPrototypeOf(this, _FinalizeCacheError.prototype);
       }
-      create(value) {
-        const message = { ok: false, signedUploadUrl: "", message: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+    };
+    exports2.FinalizeCacheError = FinalizeCacheError;
+    function checkPaths(paths) {
+      if (!paths || paths.length === 0) {
+        throw new ValidationError(`Path Validation Error: At least one directory or file path is required`);
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* bool ok */
-            1:
-              message.ok = reader.bool();
-              break;
-            case /* string signed_upload_url */
-            2:
-              message.signedUploadUrl = reader.string();
-              break;
-            case /* string message */
-            3:
-              message.message = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
-          }
-        }
-        return message;
+    }
+    function checkKey(key) {
+      if (key.length > 512) {
+        throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`);
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.ok !== false)
-          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
-        if (message.signedUploadUrl !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl);
-        if (message.message !== "")
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+      const regex = /^[^,]*$/;
+      if (!regex.test(key)) {
+        throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`);
       }
-    };
-    exports2.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type();
-    var FinalizeCacheEntryUploadRequest$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [
-          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
-          {
-            no: 2,
-            name: "key",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "size_bytes",
-            kind: "scalar",
-            T: 3
-            /*ScalarType.INT64*/
-          },
-          {
-            no: 4,
-            name: "version",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
+    }
+    function isFeatureAvailable() {
+      const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
+      switch (cacheServiceVersion) {
+        case "v2":
+          return !!process.env["ACTIONS_RESULTS_URL"];
+        case "v1":
+        default:
+          return !!process.env["ACTIONS_CACHE_URL"];
+      }
+    }
+    exports2.isFeatureAvailable = isFeatureAvailable;
+    function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
+        core14.debug(`Cache service version: ${cacheServiceVersion}`);
+        checkPaths(paths);
+        switch (cacheServiceVersion) {
+          case "v2":
+            return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
+          case "v1":
+          default:
+            return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
+        }
+      });
+    }
+    exports2.restoreCache = restoreCache3;
+    function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        restoreKeys = restoreKeys || [];
+        const keys = [primaryKey, ...restoreKeys];
+        core14.debug("Resolved Keys:");
+        core14.debug(JSON.stringify(keys));
+        if (keys.length > 10) {
+          throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`);
+        }
+        for (const key of keys) {
+          checkKey(key);
+        }
+        const compressionMethod = yield utils.getCompressionMethod();
+        let archivePath = "";
+        try {
+          const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, {
+            compressionMethod,
+            enableCrossOsArchive
+          });
+          if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) {
+            return void 0;
+          }
+          if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
+            core14.info("Lookup only - skipping download");
+            return cacheEntry.cacheKey;
+          }
+          archivePath = path12.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
+          core14.debug(`Archive Path: ${archivePath}`);
+          yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options);
+          if (core14.isDebug()) {
+            yield (0, tar_1.listTar)(archivePath, compressionMethod);
+          }
+          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
+          core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
+          yield (0, tar_1.extractTar)(archivePath, compressionMethod);
+          core14.info("Cache restored successfully");
+          return cacheEntry.cacheKey;
+        } catch (error4) {
+          const typedError = error4;
+          if (typedError.name === ValidationError.name) {
+            throw error4;
+          } else {
+            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
+              core14.error(`Failed to restore: ${error4.message}`);
+            } else {
+              core14.warning(`Failed to restore: ${error4.message}`);
+            }
+          }
+        } finally {
+          try {
+            yield utils.unlinkFile(archivePath);
+          } catch (error4) {
+            core14.debug(`Failed to delete archive: ${error4}`);
+          }
+        }
+        return void 0;
+      });
+    }
+    function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        options = Object.assign(Object.assign({}, options), { useAzureSdk: true });
+        restoreKeys = restoreKeys || [];
+        const keys = [primaryKey, ...restoreKeys];
+        core14.debug("Resolved Keys:");
+        core14.debug(JSON.stringify(keys));
+        if (keys.length > 10) {
+          throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`);
+        }
+        for (const key of keys) {
+          checkKey(key);
+        }
+        let archivePath = "";
+        try {
+          const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
+          const compressionMethod = yield utils.getCompressionMethod();
+          const request = {
+            key: primaryKey,
+            restoreKeys,
+            version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive)
+          };
+          const response = yield twirpClient.GetCacheEntryDownloadURL(request);
+          if (!response.ok) {
+            core14.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`);
+            return void 0;
+          }
+          const isRestoreKeyMatch = request.key !== response.matchedKey;
+          if (isRestoreKeyMatch) {
+            core14.info(`Cache hit for restore-key: ${response.matchedKey}`);
+          } else {
+            core14.info(`Cache hit for: ${response.matchedKey}`);
+          }
+          if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
+            core14.info("Lookup only - skipping download");
+            return response.matchedKey;
+          }
+          archivePath = path12.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
+          core14.debug(`Archive path: ${archivePath}`);
+          core14.debug(`Starting download of archive to: ${archivePath}`);
+          yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options);
+          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
+          core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
+          if (core14.isDebug()) {
+            yield (0, tar_1.listTar)(archivePath, compressionMethod);
+          }
+          yield (0, tar_1.extractTar)(archivePath, compressionMethod);
+          core14.info("Cache restored successfully");
+          return response.matchedKey;
+        } catch (error4) {
+          const typedError = error4;
+          if (typedError.name === ValidationError.name) {
+            throw error4;
+          } else {
+            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
+              core14.error(`Failed to restore: ${error4.message}`);
+            } else {
+              core14.warning(`Failed to restore: ${error4.message}`);
+            }
+          }
+        } finally {
+          try {
+            if (archivePath) {
+              yield utils.unlinkFile(archivePath);
+            }
+          } catch (error4) {
+            core14.debug(`Failed to delete archive: ${error4}`);
+          }
+        }
+        return void 0;
+      });
+    }
+    function saveCache3(paths, key, options, enableCrossOsArchive = false) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
+        core14.debug(`Cache service version: ${cacheServiceVersion}`);
+        checkPaths(paths);
+        checkKey(key);
+        switch (cacheServiceVersion) {
+          case "v2":
+            return yield saveCacheV2(paths, key, options, enableCrossOsArchive);
+          case "v1":
+          default:
+            return yield saveCacheV1(paths, key, options, enableCrossOsArchive);
+        }
+      });
+    }
+    exports2.saveCache = saveCache3;
+    function saveCacheV1(paths, key, options, enableCrossOsArchive = false) {
+      var _a, _b, _c, _d, _e;
+      return __awaiter4(this, void 0, void 0, function* () {
+        const compressionMethod = yield utils.getCompressionMethod();
+        let cacheId = -1;
+        const cachePaths = yield utils.resolvePaths(paths);
+        core14.debug("Cache Paths:");
+        core14.debug(`${JSON.stringify(cachePaths)}`);
+        if (cachePaths.length === 0) {
+          throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);
+        }
+        const archiveFolder = yield utils.createTempDirectory();
+        const archivePath = path12.join(archiveFolder, utils.getCacheFileName(compressionMethod));
+        core14.debug(`Archive Path: ${archivePath}`);
+        try {
+          yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
+          if (core14.isDebug()) {
+            yield (0, tar_1.listTar)(archivePath, compressionMethod);
+          }
+          const fileSizeLimit = 10 * 1024 * 1024 * 1024;
+          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
+          core14.debug(`File Size: ${archiveFileSize}`);
+          if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) {
+            throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`);
+          }
+          core14.debug("Reserving Cache");
+          const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, {
+            compressionMethod,
+            enableCrossOsArchive,
+            cacheSize: archiveFileSize
+          });
+          if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) {
+            cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId;
+          } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) {
+            throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`);
+          } else {
+            throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`);
+          }
+          core14.debug(`Saving Cache (ID: ${cacheId})`);
+          yield cacheHttpClient.saveCache(cacheId, archivePath, "", options);
+        } catch (error4) {
+          const typedError = error4;
+          if (typedError.name === ValidationError.name) {
+            throw error4;
+          } else if (typedError.name === ReserveCacheError.name) {
+            core14.info(`Failed to save: ${typedError.message}`);
+          } else {
+            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
+              core14.error(`Failed to save: ${typedError.message}`);
+            } else {
+              core14.warning(`Failed to save: ${typedError.message}`);
+            }
+          }
+        } finally {
+          try {
+            yield utils.unlinkFile(archivePath);
+          } catch (error4) {
+            core14.debug(`Failed to delete archive: ${error4}`);
+          }
+        }
+        return cacheId;
+      });
+    }
+    function saveCacheV2(paths, key, options, enableCrossOsArchive = false) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true });
+        const compressionMethod = yield utils.getCompressionMethod();
+        const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
+        let cacheId = -1;
+        const cachePaths = yield utils.resolvePaths(paths);
+        core14.debug("Cache Paths:");
+        core14.debug(`${JSON.stringify(cachePaths)}`);
+        if (cachePaths.length === 0) {
+          throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);
+        }
+        const archiveFolder = yield utils.createTempDirectory();
+        const archivePath = path12.join(archiveFolder, utils.getCacheFileName(compressionMethod));
+        core14.debug(`Archive Path: ${archivePath}`);
+        try {
+          yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
+          if (core14.isDebug()) {
+            yield (0, tar_1.listTar)(archivePath, compressionMethod);
+          }
+          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
+          core14.debug(`File Size: ${archiveFileSize}`);
+          options.archiveSizeBytes = archiveFileSize;
+          core14.debug("Reserving Cache");
+          const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive);
+          const request = {
+            key,
+            version
+          };
+          let signedUploadUrl;
+          try {
+            const response = yield twirpClient.CreateCacheEntry(request);
+            if (!response.ok) {
+              if (response.message) {
+                core14.warning(`Cache reservation failed: ${response.message}`);
+              }
+              throw new Error(response.message || "Response was not ok");
+            }
+            signedUploadUrl = response.signedUploadUrl;
+          } catch (error4) {
+            core14.debug(`Failed to reserve cache: ${error4}`);
+            throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`);
+          }
+          core14.debug(`Attempting to upload cache located at: ${archivePath}`);
+          yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options);
+          const finalizeRequest = {
+            key,
+            version,
+            sizeBytes: `${archiveFileSize}`
+          };
+          const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest);
+          core14.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`);
+          if (!finalizeResponse.ok) {
+            if (finalizeResponse.message) {
+              throw new FinalizeCacheError(finalizeResponse.message);
+            }
+            throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`);
+          }
+          cacheId = parseInt(finalizeResponse.entryId);
+        } catch (error4) {
+          const typedError = error4;
+          if (typedError.name === ValidationError.name) {
+            throw error4;
+          } else if (typedError.name === ReserveCacheError.name) {
+            core14.info(`Failed to save: ${typedError.message}`);
+          } else if (typedError.name === FinalizeCacheError.name) {
+            core14.warning(typedError.message);
+          } else {
+            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
+              core14.error(`Failed to save: ${typedError.message}`);
+            } else {
+              core14.warning(`Failed to save: ${typedError.message}`);
+            }
           }
-        ]);
-      }
-      create(value) {
-        const message = { key: "", sizeBytes: "0", version: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
-      }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* github.actions.results.entities.v1.CacheMetadata metadata */
-            1:
-              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
-              break;
-            case /* string key */
-            2:
-              message.key = reader.string();
-              break;
-            case /* int64 size_bytes */
-            3:
-              message.sizeBytes = reader.int64().toString();
-              break;
-            case /* string version */
-            4:
-              message.version = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
+        } finally {
+          try {
+            yield utils.unlinkFile(archivePath);
+          } catch (error4) {
+            core14.debug(`Failed to delete archive: ${error4}`);
           }
         }
-        return message;
+        return cacheId;
+      });
+    }
+  }
+});
+
+// node_modules/jsonschema/lib/helpers.js
+var require_helpers3 = __commonJS({
+  "node_modules/jsonschema/lib/helpers.js"(exports2, module2) {
+    "use strict";
+    var uri = require("url");
+    var ValidationError = exports2.ValidationError = function ValidationError2(message, instance, schema2, path12, name, argument) {
+      if (Array.isArray(path12)) {
+        this.path = path12;
+        this.property = path12.reduce(function(sum, item) {
+          return sum + makeSuffix(item);
+        }, "instance");
+      } else if (path12 !== void 0) {
+        this.property = path12;
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.metadata)
-          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
-        if (message.key !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
-        if (message.sizeBytes !== "0")
-          writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes);
-        if (message.version !== "")
-          writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+      if (message) {
+        this.message = message;
       }
-    };
-    exports2.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type();
-    var FinalizeCacheEntryUploadResponse$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [
-          {
-            no: 1,
-            name: "ok",
-            kind: "scalar",
-            T: 8
-            /*ScalarType.BOOL*/
-          },
-          {
-            no: 2,
-            name: "entry_id",
-            kind: "scalar",
-            T: 3
-            /*ScalarType.INT64*/
-          },
-          {
-            no: 3,
-            name: "message",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          }
-        ]);
+      if (schema2) {
+        var id = schema2.$id || schema2.id;
+        this.schema = id || schema2;
       }
-      create(value) {
-        const message = { ok: false, entryId: "0", message: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+      if (instance !== void 0) {
+        this.instance = instance;
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* bool ok */
-            1:
-              message.ok = reader.bool();
-              break;
-            case /* int64 entry_id */
-            2:
-              message.entryId = reader.int64().toString();
-              break;
-            case /* string message */
-            3:
-              message.message = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
-          }
-        }
-        return message;
+      this.name = name;
+      this.argument = argument;
+      this.stack = this.toString();
+    };
+    ValidationError.prototype.toString = function toString3() {
+      return this.property + " " + this.message;
+    };
+    var ValidatorResult = exports2.ValidatorResult = function ValidatorResult2(instance, schema2, options, ctx) {
+      this.instance = instance;
+      this.schema = schema2;
+      this.options = options;
+      this.path = ctx.path;
+      this.propertyPath = ctx.propertyPath;
+      this.errors = [];
+      this.throwError = options && options.throwError;
+      this.throwFirst = options && options.throwFirst;
+      this.throwAll = options && options.throwAll;
+      this.disableFormat = options && options.disableFormat === true;
+    };
+    ValidatorResult.prototype.addError = function addError(detail) {
+      var err;
+      if (typeof detail == "string") {
+        err = new ValidationError(detail, this.instance, this.schema, this.path);
+      } else {
+        if (!detail) throw new Error("Missing error detail");
+        if (!detail.message) throw new Error("Missing error message");
+        if (!detail.name) throw new Error("Missing validator type");
+        err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument);
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.ok !== false)
-          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
-        if (message.entryId !== "0")
-          writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId);
-        if (message.message !== "")
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.message);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+      this.errors.push(err);
+      if (this.throwFirst) {
+        throw new ValidatorResultError(this);
+      } else if (this.throwError) {
+        throw err;
       }
+      return err;
     };
-    exports2.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type();
-    var GetCacheEntryDownloadURLRequest$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [
-          { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
-          {
-            no: 2,
-            name: "key",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "restore_keys",
-            kind: "scalar",
-            repeat: 2,
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 4,
-            name: "version",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          }
-        ]);
+    ValidatorResult.prototype.importErrors = function importErrors(res) {
+      if (typeof res == "string" || res && res.validatorType) {
+        this.addError(res);
+      } else if (res && res.errors) {
+        this.errors = this.errors.concat(res.errors);
       }
-      create(value) {
-        const message = { key: "", restoreKeys: [], version: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+    };
+    function stringizer(v, i) {
+      return i + ": " + v.toString() + "\n";
+    }
+    ValidatorResult.prototype.toString = function toString3(res) {
+      return this.errors.map(stringizer).join("");
+    };
+    Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() {
+      return !this.errors.length;
+    } });
+    module2.exports.ValidatorResultError = ValidatorResultError;
+    function ValidatorResultError(result) {
+      if (Error.captureStackTrace) {
+        Error.captureStackTrace(this, ValidatorResultError);
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* github.actions.results.entities.v1.CacheMetadata metadata */
-            1:
-              message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
-              break;
-            case /* string key */
-            2:
-              message.key = reader.string();
-              break;
-            case /* repeated string restore_keys */
-            3:
-              message.restoreKeys.push(reader.string());
-              break;
-            case /* string version */
-            4:
-              message.version = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
-          }
-        }
-        return message;
+      this.instance = result.instance;
+      this.schema = result.schema;
+      this.options = result.options;
+      this.errors = result.errors;
+    }
+    ValidatorResultError.prototype = new Error();
+    ValidatorResultError.prototype.constructor = ValidatorResultError;
+    ValidatorResultError.prototype.name = "Validation Error";
+    var SchemaError = exports2.SchemaError = function SchemaError2(msg, schema2) {
+      this.message = msg;
+      this.schema = schema2;
+      Error.call(this, msg);
+      Error.captureStackTrace(this, SchemaError2);
+    };
+    SchemaError.prototype = Object.create(
+      Error.prototype,
+      {
+        constructor: { value: SchemaError, enumerable: false },
+        name: { value: "SchemaError", enumerable: false }
       }
-      internalBinaryWrite(message, writer, options) {
-        if (message.metadata)
-          cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
-        if (message.key !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
-        for (let i = 0; i < message.restoreKeys.length; i++)
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]);
-        if (message.version !== "")
-          writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+    );
+    var SchemaContext = exports2.SchemaContext = function SchemaContext2(schema2, options, path12, base, schemas) {
+      this.schema = schema2;
+      this.options = options;
+      if (Array.isArray(path12)) {
+        this.path = path12;
+        this.propertyPath = path12.reduce(function(sum, item) {
+          return sum + makeSuffix(item);
+        }, "instance");
+      } else {
+        this.propertyPath = path12;
       }
+      this.base = base;
+      this.schemas = schemas;
     };
-    exports2.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type();
-    var GetCacheEntryDownloadURLResponse$Type = class extends runtime_5.MessageType {
-      constructor() {
-        super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [
-          {
-            no: 1,
-            name: "ok",
-            kind: "scalar",
-            T: 8
-            /*ScalarType.BOOL*/
-          },
-          {
-            no: 2,
-            name: "signed_download_url",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          },
-          {
-            no: 3,
-            name: "matched_key",
-            kind: "scalar",
-            T: 9
-            /*ScalarType.STRING*/
-          }
-        ]);
-      }
-      create(value) {
-        const message = { ok: false, signedDownloadUrl: "", matchedKey: "" };
-        globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
-        if (value !== void 0)
-          (0, runtime_3.reflectionMergePartial)(this, message, value);
-        return message;
+    SchemaContext.prototype.resolve = function resolve6(target) {
+      return uri.resolve(this.base, target);
+    };
+    SchemaContext.prototype.makeChild = function makeChild(schema2, propertyName) {
+      var path12 = propertyName === void 0 ? this.path : this.path.concat([propertyName]);
+      var id = schema2.$id || schema2.id;
+      var base = uri.resolve(this.base, id || "");
+      var ctx = new SchemaContext(schema2, this.options, path12, base, Object.create(this.schemas));
+      if (id && !ctx.schemas[base]) {
+        ctx.schemas[base] = schema2;
       }
-      internalBinaryRead(reader, length, options, target) {
-        let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
-        while (reader.pos < end) {
-          let [fieldNo, wireType] = reader.tag();
-          switch (fieldNo) {
-            case /* bool ok */
-            1:
-              message.ok = reader.bool();
-              break;
-            case /* string signed_download_url */
-            2:
-              message.signedDownloadUrl = reader.string();
-              break;
-            case /* string matched_key */
-            3:
-              message.matchedKey = reader.string();
-              break;
-            default:
-              let u = options.readUnknownField;
-              if (u === "throw")
-                throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
-              let d = reader.skip(wireType);
-              if (u !== false)
-                (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
-          }
+      return ctx;
+    };
+    var FORMAT_REGEXPS = exports2.FORMAT_REGEXPS = {
+      // 7.3.1. Dates, Times, and Duration
+      "date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,
+      "date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,
+      "time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,
+      "duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,
+      // 7.3.2. Email Addresses
+      // TODO: fix the email production
+      "email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,
+      "idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,
+      // 7.3.3. Hostnames
+      // 7.3.4. IP Addresses
+      "ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
+      // FIXME whitespace is invalid
+      "ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,
+      // 7.3.5. Resource Identifiers
+      // TODO: A more accurate regular expression for "uri" goes:
+      // [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)?
+      "uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
+      "uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,
+      "iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
+      "iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,
+      "uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
+      // 7.3.6. uri-template
+      "uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,
+      // 7.3.7. JSON Pointers
+      "json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,
+      "relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,
+      // hostname regex from: http://stackoverflow.com/a/1420225/5628
+      "hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
+      "host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
+      "utc-millisec": function(input) {
+        return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input);
+      },
+      // 7.3.8. regex
+      "regex": function(input) {
+        var result = true;
+        try {
+          new RegExp(input);
+        } catch (e) {
+          result = false;
         }
-        return message;
-      }
-      internalBinaryWrite(message, writer, options) {
-        if (message.ok !== false)
-          writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
-        if (message.signedDownloadUrl !== "")
-          writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl);
-        if (message.matchedKey !== "")
-          writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey);
-        let u = options.writeUnknownFields;
-        if (u !== false)
-          (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
-        return writer;
+        return result;
+      },
+      // Other definitions
+      // "style" was removed from JSON Schema in draft-4 and is deprecated
+      "style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,
+      // "color" was removed from JSON Schema in draft-4 and is deprecated
+      "color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,
+      "phone": /^\+(?:[0-9] ?){6,14}[0-9]$/,
+      "alpha": /^[a-zA-Z]+$/,
+      "alphanumeric": /^[a-zA-Z0-9]+$/
+    };
+    FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex;
+    FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex;
+    FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"];
+    exports2.isFormat = function isFormat(input, format, validator) {
+      if (typeof input === "string" && FORMAT_REGEXPS[format] !== void 0) {
+        if (FORMAT_REGEXPS[format] instanceof RegExp) {
+          return FORMAT_REGEXPS[format].test(input);
+        }
+        if (typeof FORMAT_REGEXPS[format] === "function") {
+          return FORMAT_REGEXPS[format](input);
+        }
+      } else if (validator && validator.customFormats && typeof validator.customFormats[format] === "function") {
+        return validator.customFormats[format](input);
       }
+      return true;
     };
-    exports2.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type();
-    exports2.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [
-      { name: "CreateCacheEntry", options: {}, I: exports2.CreateCacheEntryRequest, O: exports2.CreateCacheEntryResponse },
-      { name: "FinalizeCacheEntryUpload", options: {}, I: exports2.FinalizeCacheEntryUploadRequest, O: exports2.FinalizeCacheEntryUploadResponse },
-      { name: "GetCacheEntryDownloadURL", options: {}, I: exports2.GetCacheEntryDownloadURLRequest, O: exports2.GetCacheEntryDownloadURLResponse }
-    ]);
-  }
-});
-
-// node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js
-var require_cache_twirp_client = __commonJS({
-  "node_modules/@actions/cache/lib/generated/results/api/v1/cache.twirp-client.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.CacheServiceClientProtobuf = exports2.CacheServiceClientJSON = void 0;
-    var cache_1 = require_cache2();
-    var CacheServiceClientJSON = class {
-      constructor(rpc) {
-        this.rpc = rpc;
-        this.CreateCacheEntry.bind(this);
-        this.FinalizeCacheEntryUpload.bind(this);
-        this.GetCacheEntryDownloadURL.bind(this);
+    var makeSuffix = exports2.makeSuffix = function makeSuffix2(key) {
+      key = key.toString();
+      if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) {
+        return "." + key;
       }
-      CreateCacheEntry(request) {
-        const data = cache_1.CreateCacheEntryRequest.toJson(request, {
-          useProtoFieldName: true,
-          emitDefaultValues: false
-        });
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data);
-        return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromJson(data2, {
-          ignoreUnknownFields: true
-        }));
+      if (key.match(/^\d+$/)) {
+        return "[" + key + "]";
+      }
+      return "[" + JSON.stringify(key) + "]";
+    };
+    exports2.deepCompareStrict = function deepCompareStrict(a, b) {
+      if (typeof a !== typeof b) {
+        return false;
       }
-      FinalizeCacheEntryUpload(request) {
-        const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, {
-          useProtoFieldName: true,
-          emitDefaultValues: false
+      if (Array.isArray(a)) {
+        if (!Array.isArray(b)) {
+          return false;
+        }
+        if (a.length !== b.length) {
+          return false;
+        }
+        return a.every(function(v, i) {
+          return deepCompareStrict(a[i], b[i]);
         });
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data);
-        return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data2, {
-          ignoreUnknownFields: true
-        }));
       }
-      GetCacheEntryDownloadURL(request) {
-        const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, {
-          useProtoFieldName: true,
-          emitDefaultValues: false
+      if (typeof a === "object") {
+        if (!a || !b) {
+          return a === b;
+        }
+        var aKeys = Object.keys(a);
+        var bKeys = Object.keys(b);
+        if (aKeys.length !== bKeys.length) {
+          return false;
+        }
+        return aKeys.every(function(v) {
+          return deepCompareStrict(a[v], b[v]);
         });
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data);
-        return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data2, {
-          ignoreUnknownFields: true
-        }));
       }
+      return a === b;
     };
-    exports2.CacheServiceClientJSON = CacheServiceClientJSON;
-    var CacheServiceClientProtobuf = class {
-      constructor(rpc) {
-        this.rpc = rpc;
-        this.CreateCacheEntry.bind(this);
-        this.FinalizeCacheEntryUpload.bind(this);
-        this.GetCacheEntryDownloadURL.bind(this);
+    function deepMerger(target, dst, e, i) {
+      if (typeof e === "object") {
+        dst[i] = deepMerge(target[i], e);
+      } else {
+        if (target.indexOf(e) === -1) {
+          dst.push(e);
+        }
       }
-      CreateCacheEntry(request) {
-        const data = cache_1.CreateCacheEntryRequest.toBinary(request);
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data);
-        return promise.then((data2) => cache_1.CreateCacheEntryResponse.fromBinary(data2));
+    }
+    function copyist(src, dst, key) {
+      dst[key] = src[key];
+    }
+    function copyistWithDeepMerge(target, src, dst, key) {
+      if (typeof src[key] !== "object" || !src[key]) {
+        dst[key] = src[key];
+      } else {
+        if (!target[key]) {
+          dst[key] = src[key];
+        } else {
+          dst[key] = deepMerge(target[key], src[key]);
+        }
       }
-      FinalizeCacheEntryUpload(request) {
-        const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request);
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data);
-        return promise.then((data2) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data2));
+    }
+    function deepMerge(target, src) {
+      var array = Array.isArray(src);
+      var dst = array && [] || {};
+      if (array) {
+        target = target || [];
+        dst = dst.concat(target);
+        src.forEach(deepMerger.bind(null, target, dst));
+      } else {
+        if (target && typeof target === "object") {
+          Object.keys(target).forEach(copyist.bind(null, target, dst));
+        }
+        Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst));
       }
-      GetCacheEntryDownloadURL(request) {
-        const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request);
-        const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data);
-        return promise.then((data2) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data2));
+      return dst;
+    }
+    module2.exports.deepMerge = deepMerge;
+    exports2.objectGetPath = function objectGetPath(o, s) {
+      var parts = s.split("/").slice(1);
+      var k;
+      while (typeof (k = parts.shift()) == "string") {
+        var n = decodeURIComponent(k.replace(/~0/, "~").replace(/~1/g, "/"));
+        if (!(n in o)) return;
+        o = o[n];
       }
+      return o;
     };
-    exports2.CacheServiceClientProtobuf = CacheServiceClientProtobuf;
-  }
-});
-
-// node_modules/@actions/cache/lib/internal/shared/util.js
-var require_util10 = __commonJS({
-  "node_modules/@actions/cache/lib/internal/shared/util.js"(exports2) {
-    "use strict";
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.maskSecretUrls = exports2.maskSigUrl = void 0;
-    var core_1 = require_core();
-    function maskSigUrl(url2) {
-      if (!url2)
-        return;
-      try {
-        const parsedUrl = new URL(url2);
-        const signature = parsedUrl.searchParams.get("sig");
-        if (signature) {
-          (0, core_1.setSecret)(signature);
-          (0, core_1.setSecret)(encodeURIComponent(signature));
-        }
-      } catch (error4) {
-        (0, core_1.debug)(`Failed to parse URL: ${url2} ${error4 instanceof Error ? error4.message : String(error4)}`);
-      }
+    function pathEncoder(v) {
+      return "/" + encodeURIComponent(v).replace(/~/g, "%7E");
     }
-    exports2.maskSigUrl = maskSigUrl;
-    function maskSecretUrls(body) {
-      if (typeof body !== "object" || body === null) {
-        (0, core_1.debug)("body is not an object or is null");
-        return;
+    exports2.encodePath = function encodePointer(a) {
+      return a.map(pathEncoder).join("");
+    };
+    exports2.getDecimalPlaces = function getDecimalPlaces(number) {
+      var decimalPlaces = 0;
+      if (isNaN(number)) return decimalPlaces;
+      if (typeof number !== "number") {
+        number = Number(number);
       }
-      if ("signed_upload_url" in body && typeof body.signed_upload_url === "string") {
-        maskSigUrl(body.signed_upload_url);
+      var parts = number.toString().split("e");
+      if (parts.length === 2) {
+        if (parts[1][0] !== "-") {
+          return decimalPlaces;
+        } else {
+          decimalPlaces = Number(parts[1].slice(1));
+        }
       }
-      if ("signed_download_url" in body && typeof body.signed_download_url === "string") {
-        maskSigUrl(body.signed_download_url);
+      var decimalParts = parts[0].split(".");
+      if (decimalParts.length === 2) {
+        decimalPlaces += decimalParts[1].length;
       }
-    }
-    exports2.maskSecretUrls = maskSecretUrls;
+      return decimalPlaces;
+    };
+    exports2.isSchema = function isSchema(val2) {
+      return typeof val2 === "object" && val2 || typeof val2 === "boolean";
+    };
   }
 });
 
-// node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js
-var require_cacheTwirpClient = __commonJS({
-  "node_modules/@actions/cache/lib/internal/shared/cacheTwirpClient.js"(exports2) {
+// node_modules/jsonschema/lib/attribute.js
+var require_attribute = __commonJS({
+  "node_modules/jsonschema/lib/attribute.js"(exports2, module2) {
     "use strict";
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
+    var helpers = require_helpers3();
+    var ValidatorResult = helpers.ValidatorResult;
+    var SchemaError = helpers.SchemaError;
+    var attribute = {};
+    attribute.ignoreProperties = {
+      // informative properties
+      "id": true,
+      "default": true,
+      "description": true,
+      "title": true,
+      // arguments to other properties
+      "additionalItems": true,
+      "then": true,
+      "else": true,
+      // special-handled properties
+      "$schema": true,
+      "$ref": true,
+      "extends": true
+    };
+    var validators = attribute.validators = {};
+    validators.type = function validateType(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var types = Array.isArray(schema2.type) ? schema2.type : [schema2.type];
+      if (!types.some(this.testType.bind(this, instance, schema2, options, ctx))) {
+        var list = types.map(function(v) {
+          if (!v) return;
+          var id = v.$id || v.id;
+          return id ? "<" + id + ">" : v + "";
+        });
+        result.addError({
+          name: "type",
+          argument: list,
+          message: "is not of a type(s) " + list
         });
       }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+      return result;
+    };
+    function testSchemaNoThrow(instance, options, ctx, callback, schema2) {
+      var throwError2 = options.throwError;
+      var throwAll = options.throwAll;
+      options.throwError = false;
+      options.throwAll = false;
+      var res = this.validateSchema(instance, schema2, options, ctx);
+      options.throwError = throwError2;
+      options.throwAll = throwAll;
+      if (!res.valid && callback instanceof Function) {
+        callback(res);
+      }
+      return res.valid;
+    }
+    validators.anyOf = function validateAnyOf(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var inner = new ValidatorResult(instance, schema2, options, ctx);
+      if (!Array.isArray(schema2.anyOf)) {
+        throw new SchemaError("anyOf must be an array");
+      }
+      if (!schema2.anyOf.some(
+        testSchemaNoThrow.bind(
+          this,
+          instance,
+          options,
+          ctx,
+          function(res) {
+            inner.importErrors(res);
           }
+        )
+      )) {
+        var list = schema2.anyOf.map(function(v, i) {
+          var id = v.$id || v.id;
+          if (id) return "<" + id + ">";
+          return v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
+        });
+        if (options.nestedErrors) {
+          result.importErrors(inner);
         }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        result.addError({
+          name: "anyOf",
+          argument: list,
+          message: "is not any of " + list.join(",")
+        });
+      }
+      return result;
+    };
+    validators.allOf = function validateAllOf(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
+      }
+      if (!Array.isArray(schema2.allOf)) {
+        throw new SchemaError("allOf must be an array");
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var self2 = this;
+      schema2.allOf.forEach(function(v, i) {
+        var valid3 = self2.validateSchema(instance, v, options, ctx);
+        if (!valid3.valid) {
+          var id = v.$id || v.id;
+          var msg = id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
+          result.addError({
+            name: "allOf",
+            argument: { id: msg, length: valid3.errors.length, valid: valid3 },
+            message: "does not match allOf schema " + msg + " with " + valid3.errors.length + " error[s]:"
+          });
+          result.importErrors(valid3);
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
       });
+      return result;
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.internalCacheTwirpClient = void 0;
-    var core_1 = require_core();
-    var user_agent_1 = require_user_agent();
-    var errors_1 = require_errors2();
-    var config_1 = require_config();
-    var cacheUtils_1 = require_cacheUtils();
-    var auth_1 = require_auth();
-    var http_client_1 = require_lib();
-    var cache_twirp_client_1 = require_cache_twirp_client();
-    var util_1 = require_util10();
-    var CacheServiceClient = class {
-      constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) {
-        this.maxAttempts = 5;
-        this.baseRetryIntervalMilliseconds = 3e3;
-        this.retryMultiplier = 1.5;
-        const token = (0, cacheUtils_1.getRuntimeToken)();
-        this.baseUrl = (0, config_1.getCacheServiceURL)();
-        if (maxAttempts) {
-          this.maxAttempts = maxAttempts;
-        }
-        if (baseRetryIntervalMilliseconds) {
-          this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds;
-        }
-        if (retryMultiplier) {
-          this.retryMultiplier = retryMultiplier;
-        }
-        this.httpClient = new http_client_1.HttpClient(userAgent, [
-          new auth_1.BearerCredentialHandler(token)
-        ]);
+    validators.oneOf = function validateOneOf(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
       }
-      // This function satisfies the Rpc interface. It is compatible with the JSON
-      // JSON generated client.
-      request(service, method, contentType, data) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          const url2 = new URL(`/twirp/${service}/${method}`, this.baseUrl).href;
-          (0, core_1.debug)(`[Request] ${method} ${url2}`);
-          const headers = {
-            "Content-Type": contentType
-          };
-          try {
-            const { body } = yield this.retryableRequest(() => __awaiter4(this, void 0, void 0, function* () {
-              return this.httpClient.post(url2, JSON.stringify(data), headers);
-            }));
-            return body;
-          } catch (error4) {
-            throw new Error(`Failed to ${method}: ${error4.message}`);
-          }
-        });
+      if (!Array.isArray(schema2.oneOf)) {
+        throw new SchemaError("oneOf must be an array");
       }
-      retryableRequest(operation) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          let attempt = 0;
-          let errorMessage = "";
-          let rawBody = "";
-          while (attempt < this.maxAttempts) {
-            let isRetryable = false;
-            try {
-              const response = yield operation();
-              const statusCode = response.message.statusCode;
-              rawBody = yield response.readBody();
-              (0, core_1.debug)(`[Response] - ${response.message.statusCode}`);
-              (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`);
-              const body = JSON.parse(rawBody);
-              (0, util_1.maskSecretUrls)(body);
-              (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`);
-              if (this.isSuccessStatusCode(statusCode)) {
-                return { response, body };
-              }
-              isRetryable = this.isRetryableHttpStatusCode(statusCode);
-              errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`;
-              if (body.msg) {
-                if (errors_1.UsageError.isUsageErrorMessage(body.msg)) {
-                  throw new errors_1.UsageError();
-                }
-                errorMessage = `${errorMessage}: ${body.msg}`;
-              }
-            } catch (error4) {
-              if (error4 instanceof SyntaxError) {
-                (0, core_1.debug)(`Raw Body: ${rawBody}`);
-              }
-              if (error4 instanceof errors_1.UsageError) {
-                throw error4;
-              }
-              if (errors_1.NetworkError.isNetworkErrorCode(error4 === null || error4 === void 0 ? void 0 : error4.code)) {
-                throw new errors_1.NetworkError(error4 === null || error4 === void 0 ? void 0 : error4.code);
-              }
-              isRetryable = true;
-              errorMessage = error4.message;
-            }
-            if (!isRetryable) {
-              throw new Error(`Received non-retryable error: ${errorMessage}`);
-            }
-            if (attempt + 1 === this.maxAttempts) {
-              throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`);
-            }
-            const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt);
-            (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`);
-            yield this.sleep(retryTimeMilliseconds);
-            attempt++;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var inner = new ValidatorResult(instance, schema2, options, ctx);
+      var count = schema2.oneOf.filter(
+        testSchemaNoThrow.bind(
+          this,
+          instance,
+          options,
+          ctx,
+          function(res) {
+            inner.importErrors(res);
           }
-          throw new Error(`Request failed`);
+        )
+      ).length;
+      var list = schema2.oneOf.map(function(v, i) {
+        var id = v.$id || v.id;
+        return id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
+      });
+      if (count !== 1) {
+        if (options.nestedErrors) {
+          result.importErrors(inner);
+        }
+        result.addError({
+          name: "oneOf",
+          argument: list,
+          message: "is not exactly one from " + list.join(",")
         });
       }
-      isSuccessStatusCode(statusCode) {
-        if (!statusCode)
-          return false;
-        return statusCode >= 200 && statusCode < 300;
+      return result;
+    };
+    validators.if = function validateIf(instance, schema2, options, ctx) {
+      if (instance === void 0) return null;
+      if (!helpers.isSchema(schema2.if)) throw new Error('Expected "if" keyword to be a schema');
+      var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema2.if);
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var res;
+      if (ifValid) {
+        if (schema2.then === void 0) return;
+        if (!helpers.isSchema(schema2.then)) throw new Error('Expected "then" keyword to be a schema');
+        res = this.validateSchema(instance, schema2.then, options, ctx.makeChild(schema2.then));
+        result.importErrors(res);
+      } else {
+        if (schema2.else === void 0) return;
+        if (!helpers.isSchema(schema2.else)) throw new Error('Expected "else" keyword to be a schema');
+        res = this.validateSchema(instance, schema2.else, options, ctx.makeChild(schema2.else));
+        result.importErrors(res);
       }
-      isRetryableHttpStatusCode(statusCode) {
-        if (!statusCode)
-          return false;
-        const retryableStatusCodes = [
-          http_client_1.HttpCodes.BadGateway,
-          http_client_1.HttpCodes.GatewayTimeout,
-          http_client_1.HttpCodes.InternalServerError,
-          http_client_1.HttpCodes.ServiceUnavailable,
-          http_client_1.HttpCodes.TooManyRequests
-        ];
-        return retryableStatusCodes.includes(statusCode);
+      return result;
+    };
+    function getEnumerableProperty(object, key) {
+      if (Object.hasOwnProperty.call(object, key)) return object[key];
+      if (!(key in object)) return;
+      while (object = Object.getPrototypeOf(object)) {
+        if (Object.propertyIsEnumerable.call(object, key)) return object[key];
       }
-      sleep(milliseconds) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          return new Promise((resolve6) => setTimeout(resolve6, milliseconds));
+    }
+    validators.propertyNames = function validatePropertyNames(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var subschema = schema2.propertyNames !== void 0 ? schema2.propertyNames : {};
+      if (!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)');
+      for (var property in instance) {
+        if (getEnumerableProperty(instance, property) !== void 0) {
+          var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema));
+          result.importErrors(res);
+        }
+      }
+      return result;
+    };
+    validators.properties = function validateProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var properties = schema2.properties || {};
+      for (var property in properties) {
+        var subschema = properties[property];
+        if (subschema === void 0) {
+          continue;
+        } else if (subschema === null) {
+          throw new SchemaError('Unexpected null, expected schema in "properties"');
+        }
+        if (typeof options.preValidateProperty == "function") {
+          options.preValidateProperty(instance, property, subschema, options, ctx);
+        }
+        var prop = getEnumerableProperty(instance, property);
+        var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property));
+        if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
+        result.importErrors(res);
+      }
+      return result;
+    };
+    function testAdditionalProperty(instance, schema2, options, ctx, property, result) {
+      if (!this.types.object(instance)) return;
+      if (schema2.properties && schema2.properties[property] !== void 0) {
+        return;
+      }
+      if (schema2.additionalProperties === false) {
+        result.addError({
+          name: "additionalProperties",
+          argument: property,
+          message: "is not allowed to have the additional property " + JSON.stringify(property)
         });
+      } else {
+        var additionalProperties = schema2.additionalProperties || {};
+        if (typeof options.preValidateProperty == "function") {
+          options.preValidateProperty(instance, property, additionalProperties, options, ctx);
+        }
+        var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property));
+        if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
+        result.importErrors(res);
       }
-      getExponentialRetryTimeMilliseconds(attempt) {
-        if (attempt < 0) {
-          throw new Error("attempt should be a positive integer");
+    }
+    validators.patternProperties = function validatePatternProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var patternProperties = schema2.patternProperties || {};
+      for (var property in instance) {
+        var test = true;
+        for (var pattern in patternProperties) {
+          var subschema = patternProperties[pattern];
+          if (subschema === void 0) {
+            continue;
+          } else if (subschema === null) {
+            throw new SchemaError('Unexpected null, expected schema in "patternProperties"');
+          }
+          try {
+            var regexp = new RegExp(pattern, "u");
+          } catch (_e) {
+            regexp = new RegExp(pattern);
+          }
+          if (!regexp.test(property)) {
+            continue;
+          }
+          test = false;
+          if (typeof options.preValidateProperty == "function") {
+            options.preValidateProperty(instance, property, subschema, options, ctx);
+          }
+          var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property));
+          if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
+          result.importErrors(res);
         }
-        if (attempt === 0) {
-          return this.baseRetryIntervalMilliseconds;
+        if (test) {
+          testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result);
         }
-        const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt);
-        const maxTime = minTime * this.retryMultiplier;
-        return Math.trunc(Math.random() * (maxTime - minTime) + minTime);
       }
+      return result;
     };
-    function internalCacheTwirpClient(options) {
-      const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier);
-      return new cache_twirp_client_1.CacheServiceClientJSON(client);
-    }
-    exports2.internalCacheTwirpClient = internalCacheTwirpClient;
-  }
-});
-
-// node_modules/@actions/cache/lib/internal/tar.js
-var require_tar = __commonJS({
-  "node_modules/@actions/cache/lib/internal/tar.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+    validators.additionalProperties = function validateAdditionalProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      if (schema2.patternProperties) {
+        return null;
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      for (var property in instance) {
+        testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result);
       }
-      __setModuleDefault4(result, mod);
       return result;
     };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
+    validators.minProperties = function validateMinProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var keys = Object.keys(instance);
+      if (!(keys.length >= schema2.minProperties)) {
+        result.addError({
+          name: "minProperties",
+          argument: schema2.minProperties,
+          message: "does not meet minimum property length of " + schema2.minProperties
         });
       }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
+      return result;
+    };
+    validators.maxProperties = function validateMaxProperties(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var keys = Object.keys(instance);
+      if (!(keys.length <= schema2.maxProperties)) {
+        result.addError({
+          name: "maxProperties",
+          argument: schema2.maxProperties,
+          message: "does not meet maximum property length of " + schema2.maxProperties
+        });
+      }
+      return result;
+    };
+    validators.items = function validateItems(instance, schema2, options, ctx) {
+      var self2 = this;
+      if (!this.types.array(instance)) return;
+      if (schema2.items === void 0) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      instance.every(function(value, i) {
+        if (Array.isArray(schema2.items)) {
+          var items = schema2.items[i] === void 0 ? schema2.additionalItems : schema2.items[i];
+        } else {
+          var items = schema2.items;
         }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
+        if (items === void 0) {
+          return true;
         }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        if (items === false) {
+          result.addError({
+            name: "items",
+            message: "additionalItems not permitted"
+          });
+          return false;
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
+        var res = self2.validateSchema(value, items, options, ctx.makeChild(items, i));
+        if (res.instance !== result.instance[i]) result.instance[i] = res.instance;
+        result.importErrors(res);
+        return true;
       });
+      return result;
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.createTar = exports2.extractTar = exports2.listTar = void 0;
-    var exec_1 = require_exec();
-    var io6 = __importStar4(require_io());
-    var fs_1 = require("fs");
-    var path12 = __importStar4(require("path"));
-    var utils = __importStar4(require_cacheUtils());
-    var constants_1 = require_constants7();
-    var IS_WINDOWS = process.platform === "win32";
-    function getTarPath() {
-      return __awaiter4(this, void 0, void 0, function* () {
-        switch (process.platform) {
-          case "win32": {
-            const gnuTar = yield utils.getGnuTarPathOnWindows();
-            const systemTar = constants_1.SystemTarPathOnWindows;
-            if (gnuTar) {
-              return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
-            } else if ((0, fs_1.existsSync)(systemTar)) {
-              return { path: systemTar, type: constants_1.ArchiveToolType.BSD };
-            }
-            break;
-          }
-          case "darwin": {
-            const gnuTar = yield io6.which("gtar", false);
-            if (gnuTar) {
-              return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
-            } else {
-              return {
-                path: yield io6.which("tar", true),
-                type: constants_1.ArchiveToolType.BSD
-              };
-            }
-          }
-          default:
-            break;
-        }
-        return {
-          path: yield io6.which("tar", true),
-          type: constants_1.ArchiveToolType.GNU
-        };
-      });
-    }
-    function getTarArgs(tarPath, compressionMethod, type2, archivePath = "") {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const args = [`"${tarPath.path}"`];
-        const cacheFileName = utils.getCacheFileName(compressionMethod);
-        const tarFile = "cache.tar";
-        const workingDirectory = getWorkingDirectory();
-        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
-        switch (type2) {
-          case "create":
-            args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename);
-            break;
-          case "extract":
-            args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path12.sep}`, "g"), "/"));
-            break;
-          case "list":
-            args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path12.sep}`, "g"), "/"), "-P");
-            break;
-        }
-        if (tarPath.type === constants_1.ArchiveToolType.GNU) {
-          switch (process.platform) {
-            case "win32":
-              args.push("--force-local");
-              break;
-            case "darwin":
-              args.push("--delay-directory-restore");
-              break;
-          }
-        }
-        return args;
+    validators.contains = function validateContains(instance, schema2, options, ctx) {
+      var self2 = this;
+      if (!this.types.array(instance)) return;
+      if (schema2.contains === void 0) return;
+      if (!helpers.isSchema(schema2.contains)) throw new Error('Expected "contains" keyword to be a schema');
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var count = instance.some(function(value, i) {
+        var res = self2.validateSchema(value, schema2.contains, options, ctx.makeChild(schema2.contains, i));
+        return res.errors.length === 0;
       });
-    }
-    function getCommands(compressionMethod, type2, archivePath = "") {
-      return __awaiter4(this, void 0, void 0, function* () {
-        let args;
-        const tarPath = yield getTarPath();
-        const tarArgs = yield getTarArgs(tarPath, compressionMethod, type2, archivePath);
-        const compressionArgs = type2 !== "create" ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod);
-        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
-        if (BSD_TAR_ZSTD && type2 !== "create") {
-          args = [[...compressionArgs].join(" "), [...tarArgs].join(" ")];
-        } else {
-          args = [[...tarArgs].join(" "), [...compressionArgs].join(" ")];
+      if (count === false) {
+        result.addError({
+          name: "contains",
+          argument: schema2.contains,
+          message: "must contain an item matching given schema"
+        });
+      }
+      return result;
+    };
+    validators.minimum = function validateMinimum(instance, schema2, options, ctx) {
+      if (!this.types.number(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (schema2.exclusiveMinimum && schema2.exclusiveMinimum === true) {
+        if (!(instance > schema2.minimum)) {
+          result.addError({
+            name: "minimum",
+            argument: schema2.minimum,
+            message: "must be greater than " + schema2.minimum
+          });
         }
-        if (BSD_TAR_ZSTD) {
-          return args;
+      } else {
+        if (!(instance >= schema2.minimum)) {
+          result.addError({
+            name: "minimum",
+            argument: schema2.minimum,
+            message: "must be greater than or equal to " + schema2.minimum
+          });
         }
-        return [args.join(" ")];
-      });
-    }
-    function getWorkingDirectory() {
-      var _a;
-      return (_a = process.env["GITHUB_WORKSPACE"]) !== null && _a !== void 0 ? _a : process.cwd();
-    }
-    function getDecompressionProgram(tarPath, compressionMethod, archivePath) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
-        switch (compressionMethod) {
-          case constants_1.CompressionMethod.Zstd:
-            return BSD_TAR_ZSTD ? [
-              "zstd -d --long=30 --force -o",
-              constants_1.TarFilename,
-              archivePath.replace(new RegExp(`\\${path12.sep}`, "g"), "/")
-            ] : [
-              "--use-compress-program",
-              IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30"
-            ];
-          case constants_1.CompressionMethod.ZstdWithoutLong:
-            return BSD_TAR_ZSTD ? [
-              "zstd -d --force -o",
-              constants_1.TarFilename,
-              archivePath.replace(new RegExp(`\\${path12.sep}`, "g"), "/")
-            ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"];
-          default:
-            return ["-z"];
+      }
+      return result;
+    };
+    validators.maximum = function validateMaximum(instance, schema2, options, ctx) {
+      if (!this.types.number(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (schema2.exclusiveMaximum && schema2.exclusiveMaximum === true) {
+        if (!(instance < schema2.maximum)) {
+          result.addError({
+            name: "maximum",
+            argument: schema2.maximum,
+            message: "must be less than " + schema2.maximum
+          });
         }
-      });
-    }
-    function getCompressionProgram(tarPath, compressionMethod) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const cacheFileName = utils.getCacheFileName(compressionMethod);
-        const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS;
-        switch (compressionMethod) {
-          case constants_1.CompressionMethod.Zstd:
-            return BSD_TAR_ZSTD ? [
-              "zstd -T0 --long=30 --force -o",
-              cacheFileName.replace(new RegExp(`\\${path12.sep}`, "g"), "/"),
-              constants_1.TarFilename
-            ] : [
-              "--use-compress-program",
-              IS_WINDOWS ? '"zstd -T0 --long=30"' : "zstdmt --long=30"
-            ];
-          case constants_1.CompressionMethod.ZstdWithoutLong:
-            return BSD_TAR_ZSTD ? [
-              "zstd -T0 --force -o",
-              cacheFileName.replace(new RegExp(`\\${path12.sep}`, "g"), "/"),
-              constants_1.TarFilename
-            ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"];
-          default:
-            return ["-z"];
+      } else {
+        if (!(instance <= schema2.maximum)) {
+          result.addError({
+            name: "maximum",
+            argument: schema2.maximum,
+            message: "must be less than or equal to " + schema2.maximum
+          });
         }
-      });
-    }
-    function execCommands(commands, cwd) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        for (const command of commands) {
-          try {
-            yield (0, exec_1.exec)(command, void 0, {
-              cwd,
-              env: Object.assign(Object.assign({}, process.env), { MSYS: "winsymlinks:nativestrict" })
+      }
+      return result;
+    };
+    validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema2, options, ctx) {
+      if (typeof schema2.exclusiveMinimum === "boolean") return;
+      if (!this.types.number(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var valid3 = instance > schema2.exclusiveMinimum;
+      if (!valid3) {
+        result.addError({
+          name: "exclusiveMinimum",
+          argument: schema2.exclusiveMinimum,
+          message: "must be strictly greater than " + schema2.exclusiveMinimum
+        });
+      }
+      return result;
+    };
+    validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema2, options, ctx) {
+      if (typeof schema2.exclusiveMaximum === "boolean") return;
+      if (!this.types.number(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var valid3 = instance < schema2.exclusiveMaximum;
+      if (!valid3) {
+        result.addError({
+          name: "exclusiveMaximum",
+          argument: schema2.exclusiveMaximum,
+          message: "must be strictly less than " + schema2.exclusiveMaximum
+        });
+      }
+      return result;
+    };
+    var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema2, options, ctx, validationType, errorMessage) {
+      if (!this.types.number(instance)) return;
+      var validationArgument = schema2[validationType];
+      if (validationArgument == 0) {
+        throw new SchemaError(validationType + " cannot be zero");
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var instanceDecimals = helpers.getDecimalPlaces(instance);
+      var divisorDecimals = helpers.getDecimalPlaces(validationArgument);
+      var maxDecimals = Math.max(instanceDecimals, divisorDecimals);
+      var multiplier = Math.pow(10, maxDecimals);
+      if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) {
+        result.addError({
+          name: validationType,
+          argument: validationArgument,
+          message: errorMessage + JSON.stringify(validationArgument)
+        });
+      }
+      return result;
+    };
+    validators.multipleOf = function validateMultipleOf(instance, schema2, options, ctx) {
+      return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "multipleOf", "is not a multiple of (divisible by) ");
+    };
+    validators.divisibleBy = function validateDivisibleBy(instance, schema2, options, ctx) {
+      return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "divisibleBy", "is not divisible by (multiple of) ");
+    };
+    validators.required = function validateRequired(instance, schema2, options, ctx) {
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (instance === void 0 && schema2.required === true) {
+        result.addError({
+          name: "required",
+          message: "is required"
+        });
+      } else if (this.types.object(instance) && Array.isArray(schema2.required)) {
+        schema2.required.forEach(function(n) {
+          if (getEnumerableProperty(instance, n) === void 0) {
+            result.addError({
+              name: "required",
+              argument: n,
+              message: "requires property " + JSON.stringify(n)
             });
-          } catch (error4) {
-            throw new Error(`${command.split(" ")[0]} failed with error: ${error4 === null || error4 === void 0 ? void 0 : error4.message}`);
           }
-        }
-      });
-    }
-    function listTar(archivePath, compressionMethod) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const commands = yield getCommands(compressionMethod, "list", archivePath);
-        yield execCommands(commands);
-      });
-    }
-    exports2.listTar = listTar;
-    function extractTar2(archivePath, compressionMethod) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const workingDirectory = getWorkingDirectory();
-        yield io6.mkdirP(workingDirectory);
-        const commands = yield getCommands(compressionMethod, "extract", archivePath);
-        yield execCommands(commands);
-      });
-    }
-    exports2.extractTar = extractTar2;
-    function createTar(archiveFolder, sourceDirectories, compressionMethod) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        (0, fs_1.writeFileSync)(path12.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n"));
-        const commands = yield getCommands(compressionMethod, "create");
-        yield execCommands(commands, archiveFolder);
-      });
-    }
-    exports2.createTar = createTar;
-  }
-});
-
-// node_modules/@actions/cache/lib/cache.js
-var require_cache3 = __commonJS({
-  "node_modules/@actions/cache/lib/cache.js"(exports2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+        });
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      return result;
+    };
+    validators.pattern = function validatePattern(instance, schema2, options, ctx) {
+      if (!this.types.string(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var pattern = schema2.pattern;
+      try {
+        var regexp = new RegExp(pattern, "u");
+      } catch (_e) {
+        regexp = new RegExp(pattern);
+      }
+      if (!instance.match(regexp)) {
+        result.addError({
+          name: "pattern",
+          argument: schema2.pattern,
+          message: "does not match pattern " + JSON.stringify(schema2.pattern.toString())
+        });
+      }
+      return result;
+    };
+    validators.format = function validateFormat(instance, schema2, options, ctx) {
+      if (instance === void 0) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!result.disableFormat && !helpers.isFormat(instance, schema2.format, this)) {
+        result.addError({
+          name: "format",
+          argument: schema2.format,
+          message: "does not conform to the " + JSON.stringify(schema2.format) + " format"
+        });
       }
-      __setModuleDefault4(result, mod);
       return result;
     };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
+    validators.minLength = function validateMinLength(instance, schema2, options, ctx) {
+      if (!this.types.string(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var hsp = instance.match(/[\uDC00-\uDFFF]/g);
+      var length = instance.length - (hsp ? hsp.length : 0);
+      if (!(length >= schema2.minLength)) {
+        result.addError({
+          name: "minLength",
+          argument: schema2.minLength,
+          message: "does not meet minimum length of " + schema2.minLength
         });
       }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
+      return result;
     };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.saveCache = exports2.restoreCache = exports2.isFeatureAvailable = exports2.FinalizeCacheError = exports2.ReserveCacheError = exports2.ValidationError = void 0;
-    var core14 = __importStar4(require_core());
-    var path12 = __importStar4(require("path"));
-    var utils = __importStar4(require_cacheUtils());
-    var cacheHttpClient = __importStar4(require_cacheHttpClient());
-    var cacheTwirpClient = __importStar4(require_cacheTwirpClient());
-    var config_1 = require_config();
-    var tar_1 = require_tar();
-    var http_client_1 = require_lib();
-    var ValidationError = class _ValidationError extends Error {
-      constructor(message) {
-        super(message);
-        this.name = "ValidationError";
-        Object.setPrototypeOf(this, _ValidationError.prototype);
+    validators.maxLength = function validateMaxLength(instance, schema2, options, ctx) {
+      if (!this.types.string(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var hsp = instance.match(/[\uDC00-\uDFFF]/g);
+      var length = instance.length - (hsp ? hsp.length : 0);
+      if (!(length <= schema2.maxLength)) {
+        result.addError({
+          name: "maxLength",
+          argument: schema2.maxLength,
+          message: "does not meet maximum length of " + schema2.maxLength
+        });
       }
+      return result;
     };
-    exports2.ValidationError = ValidationError;
-    var ReserveCacheError = class _ReserveCacheError extends Error {
-      constructor(message) {
-        super(message);
-        this.name = "ReserveCacheError";
-        Object.setPrototypeOf(this, _ReserveCacheError.prototype);
+    validators.minItems = function validateMinItems(instance, schema2, options, ctx) {
+      if (!this.types.array(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!(instance.length >= schema2.minItems)) {
+        result.addError({
+          name: "minItems",
+          argument: schema2.minItems,
+          message: "does not meet minimum length of " + schema2.minItems
+        });
       }
+      return result;
     };
-    exports2.ReserveCacheError = ReserveCacheError;
-    var FinalizeCacheError = class _FinalizeCacheError extends Error {
-      constructor(message) {
-        super(message);
-        this.name = "FinalizeCacheError";
-        Object.setPrototypeOf(this, _FinalizeCacheError.prototype);
+    validators.maxItems = function validateMaxItems(instance, schema2, options, ctx) {
+      if (!this.types.array(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!(instance.length <= schema2.maxItems)) {
+        result.addError({
+          name: "maxItems",
+          argument: schema2.maxItems,
+          message: "does not meet maximum length of " + schema2.maxItems
+        });
       }
+      return result;
     };
-    exports2.FinalizeCacheError = FinalizeCacheError;
-    function checkPaths(paths) {
-      if (!paths || paths.length === 0) {
-        throw new ValidationError(`Path Validation Error: At least one directory or file path is required`);
-      }
-    }
-    function checkKey(key) {
-      if (key.length > 512) {
-        throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`);
-      }
-      const regex = /^[^,]*$/;
-      if (!regex.test(key)) {
-        throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`);
+    function testArrays(v, i, a) {
+      var j, len = a.length;
+      for (j = i + 1, len; j < len; j++) {
+        if (helpers.deepCompareStrict(v, a[j])) {
+          return false;
+        }
       }
+      return true;
     }
-    function isFeatureAvailable() {
-      const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
-      switch (cacheServiceVersion) {
-        case "v2":
-          return !!process.env["ACTIONS_RESULTS_URL"];
-        case "v1":
-        default:
-          return !!process.env["ACTIONS_CACHE_URL"];
+    validators.uniqueItems = function validateUniqueItems(instance, schema2, options, ctx) {
+      if (schema2.uniqueItems !== true) return;
+      if (!this.types.array(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!instance.every(testArrays)) {
+        result.addError({
+          name: "uniqueItems",
+          message: "contains duplicate item"
+        });
       }
-    }
-    exports2.isFeatureAvailable = isFeatureAvailable;
-    function restoreCache3(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
-        core14.debug(`Cache service version: ${cacheServiceVersion}`);
-        checkPaths(paths);
-        switch (cacheServiceVersion) {
-          case "v2":
-            return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
-          case "v1":
-          default:
-            return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
-        }
-      });
-    }
-    exports2.restoreCache = restoreCache3;
-    function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        restoreKeys = restoreKeys || [];
-        const keys = [primaryKey, ...restoreKeys];
-        core14.debug("Resolved Keys:");
-        core14.debug(JSON.stringify(keys));
-        if (keys.length > 10) {
-          throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`);
-        }
-        for (const key of keys) {
-          checkKey(key);
-        }
-        const compressionMethod = yield utils.getCompressionMethod();
-        let archivePath = "";
-        try {
-          const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, {
-            compressionMethod,
-            enableCrossOsArchive
-          });
-          if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) {
-            return void 0;
-          }
-          if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
-            core14.info("Lookup only - skipping download");
-            return cacheEntry.cacheKey;
-          }
-          archivePath = path12.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
-          core14.debug(`Archive Path: ${archivePath}`);
-          yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options);
-          if (core14.isDebug()) {
-            yield (0, tar_1.listTar)(archivePath, compressionMethod);
-          }
-          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
-          core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
-          yield (0, tar_1.extractTar)(archivePath, compressionMethod);
-          core14.info("Cache restored successfully");
-          return cacheEntry.cacheKey;
-        } catch (error4) {
-          const typedError = error4;
-          if (typedError.name === ValidationError.name) {
-            throw error4;
-          } else {
-            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
-              core14.error(`Failed to restore: ${error4.message}`);
-            } else {
-              core14.warning(`Failed to restore: ${error4.message}`);
-            }
-          }
-        } finally {
-          try {
-            yield utils.unlinkFile(archivePath);
-          } catch (error4) {
-            core14.debug(`Failed to delete archive: ${error4}`);
-          }
-        }
-        return void 0;
-      });
-    }
-    function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        options = Object.assign(Object.assign({}, options), { useAzureSdk: true });
-        restoreKeys = restoreKeys || [];
-        const keys = [primaryKey, ...restoreKeys];
-        core14.debug("Resolved Keys:");
-        core14.debug(JSON.stringify(keys));
-        if (keys.length > 10) {
-          throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`);
+      return result;
+    };
+    validators.dependencies = function validateDependencies(instance, schema2, options, ctx) {
+      if (!this.types.object(instance)) return;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      for (var property in schema2.dependencies) {
+        if (instance[property] === void 0) {
+          continue;
         }
-        for (const key of keys) {
-          checkKey(key);
+        var dep = schema2.dependencies[property];
+        var childContext = ctx.makeChild(dep, property);
+        if (typeof dep == "string") {
+          dep = [dep];
         }
-        let archivePath = "";
-        try {
-          const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
-          const compressionMethod = yield utils.getCompressionMethod();
-          const request = {
-            key: primaryKey,
-            restoreKeys,
-            version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive)
-          };
-          const response = yield twirpClient.GetCacheEntryDownloadURL(request);
-          if (!response.ok) {
-            core14.debug(`Cache not found for version ${request.version} of keys: ${keys.join(", ")}`);
-            return void 0;
-          }
-          const isRestoreKeyMatch = request.key !== response.matchedKey;
-          if (isRestoreKeyMatch) {
-            core14.info(`Cache hit for restore-key: ${response.matchedKey}`);
-          } else {
-            core14.info(`Cache hit for: ${response.matchedKey}`);
-          }
-          if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
-            core14.info("Lookup only - skipping download");
-            return response.matchedKey;
-          }
-          archivePath = path12.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
-          core14.debug(`Archive path: ${archivePath}`);
-          core14.debug(`Starting download of archive to: ${archivePath}`);
-          yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options);
-          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
-          core14.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
-          if (core14.isDebug()) {
-            yield (0, tar_1.listTar)(archivePath, compressionMethod);
-          }
-          yield (0, tar_1.extractTar)(archivePath, compressionMethod);
-          core14.info("Cache restored successfully");
-          return response.matchedKey;
-        } catch (error4) {
-          const typedError = error4;
-          if (typedError.name === ValidationError.name) {
-            throw error4;
-          } else {
-            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
-              core14.error(`Failed to restore: ${error4.message}`);
-            } else {
-              core14.warning(`Failed to restore: ${error4.message}`);
-            }
-          }
-        } finally {
-          try {
-            if (archivePath) {
-              yield utils.unlinkFile(archivePath);
+        if (Array.isArray(dep)) {
+          dep.forEach(function(prop) {
+            if (instance[prop] === void 0) {
+              result.addError({
+                // FIXME there's two different "dependencies" errors here with slightly different outputs
+                // Can we make these the same? Or should we create different error types?
+                name: "dependencies",
+                argument: childContext.propertyPath,
+                message: "property " + prop + " not found, required by " + childContext.propertyPath
+              });
             }
-          } catch (error4) {
-            core14.debug(`Failed to delete archive: ${error4}`);
-          }
-        }
-        return void 0;
-      });
-    }
-    function saveCache3(paths, key, options, enableCrossOsArchive = false) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
-        core14.debug(`Cache service version: ${cacheServiceVersion}`);
-        checkPaths(paths);
-        checkKey(key);
-        switch (cacheServiceVersion) {
-          case "v2":
-            return yield saveCacheV2(paths, key, options, enableCrossOsArchive);
-          case "v1":
-          default:
-            return yield saveCacheV1(paths, key, options, enableCrossOsArchive);
-        }
-      });
-    }
-    exports2.saveCache = saveCache3;
-    function saveCacheV1(paths, key, options, enableCrossOsArchive = false) {
-      var _a, _b, _c, _d, _e;
-      return __awaiter4(this, void 0, void 0, function* () {
-        const compressionMethod = yield utils.getCompressionMethod();
-        let cacheId = -1;
-        const cachePaths = yield utils.resolvePaths(paths);
-        core14.debug("Cache Paths:");
-        core14.debug(`${JSON.stringify(cachePaths)}`);
-        if (cachePaths.length === 0) {
-          throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);
-        }
-        const archiveFolder = yield utils.createTempDirectory();
-        const archivePath = path12.join(archiveFolder, utils.getCacheFileName(compressionMethod));
-        core14.debug(`Archive Path: ${archivePath}`);
-        try {
-          yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
-          if (core14.isDebug()) {
-            yield (0, tar_1.listTar)(archivePath, compressionMethod);
-          }
-          const fileSizeLimit = 10 * 1024 * 1024 * 1024;
-          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
-          core14.debug(`File Size: ${archiveFileSize}`);
-          if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) {
-            throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`);
-          }
-          core14.debug("Reserving Cache");
-          const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, {
-            compressionMethod,
-            enableCrossOsArchive,
-            cacheSize: archiveFileSize
           });
-          if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) {
-            cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId;
-          } else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) {
-            throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`);
-          } else {
-            throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`);
-          }
-          core14.debug(`Saving Cache (ID: ${cacheId})`);
-          yield cacheHttpClient.saveCache(cacheId, archivePath, "", options);
-        } catch (error4) {
-          const typedError = error4;
-          if (typedError.name === ValidationError.name) {
-            throw error4;
-          } else if (typedError.name === ReserveCacheError.name) {
-            core14.info(`Failed to save: ${typedError.message}`);
-          } else {
-            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
-              core14.error(`Failed to save: ${typedError.message}`);
-            } else {
-              core14.warning(`Failed to save: ${typedError.message}`);
-            }
-          }
-        } finally {
-          try {
-            yield utils.unlinkFile(archivePath);
-          } catch (error4) {
-            core14.debug(`Failed to delete archive: ${error4}`);
+        } else {
+          var res = this.validateSchema(instance, dep, options, childContext);
+          if (result.instance !== res.instance) result.instance = res.instance;
+          if (res && res.errors.length) {
+            result.addError({
+              name: "dependencies",
+              argument: childContext.propertyPath,
+              message: "does not meet dependency required by " + childContext.propertyPath
+            });
+            result.importErrors(res);
           }
         }
-        return cacheId;
-      });
-    }
-    function saveCacheV2(paths, key, options, enableCrossOsArchive = false) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true });
-        const compressionMethod = yield utils.getCompressionMethod();
-        const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
-        let cacheId = -1;
-        const cachePaths = yield utils.resolvePaths(paths);
-        core14.debug("Cache Paths:");
-        core14.debug(`${JSON.stringify(cachePaths)}`);
-        if (cachePaths.length === 0) {
-          throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);
-        }
-        const archiveFolder = yield utils.createTempDirectory();
-        const archivePath = path12.join(archiveFolder, utils.getCacheFileName(compressionMethod));
-        core14.debug(`Archive Path: ${archivePath}`);
-        try {
-          yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
-          if (core14.isDebug()) {
-            yield (0, tar_1.listTar)(archivePath, compressionMethod);
-          }
-          const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
-          core14.debug(`File Size: ${archiveFileSize}`);
-          options.archiveSizeBytes = archiveFileSize;
-          core14.debug("Reserving Cache");
-          const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive);
-          const request = {
-            key,
-            version
-          };
-          let signedUploadUrl;
-          try {
-            const response = yield twirpClient.CreateCacheEntry(request);
-            if (!response.ok) {
-              if (response.message) {
-                core14.warning(`Cache reservation failed: ${response.message}`);
-              }
-              throw new Error(response.message || "Response was not ok");
-            }
-            signedUploadUrl = response.signedUploadUrl;
-          } catch (error4) {
-            core14.debug(`Failed to reserve cache: ${error4}`);
-            throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`);
-          }
-          core14.debug(`Attempting to upload cache located at: ${archivePath}`);
-          yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options);
-          const finalizeRequest = {
-            key,
-            version,
-            sizeBytes: `${archiveFileSize}`
-          };
-          const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest);
-          core14.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`);
-          if (!finalizeResponse.ok) {
-            if (finalizeResponse.message) {
-              throw new FinalizeCacheError(finalizeResponse.message);
-            }
-            throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`);
-          }
-          cacheId = parseInt(finalizeResponse.entryId);
-        } catch (error4) {
-          const typedError = error4;
-          if (typedError.name === ValidationError.name) {
-            throw error4;
-          } else if (typedError.name === ReserveCacheError.name) {
-            core14.info(`Failed to save: ${typedError.message}`);
-          } else if (typedError.name === FinalizeCacheError.name) {
-            core14.warning(typedError.message);
-          } else {
-            if (typedError instanceof http_client_1.HttpClientError && typeof typedError.statusCode === "number" && typedError.statusCode >= 500) {
-              core14.error(`Failed to save: ${typedError.message}`);
-            } else {
-              core14.warning(`Failed to save: ${typedError.message}`);
-            }
-          }
-        } finally {
-          try {
-            yield utils.unlinkFile(archivePath);
-          } catch (error4) {
-            core14.debug(`Failed to delete archive: ${error4}`);
-          }
+      }
+      return result;
+    };
+    validators["enum"] = function validateEnum(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
+      }
+      if (!Array.isArray(schema2["enum"])) {
+        throw new SchemaError("enum expects an array", schema2);
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!schema2["enum"].some(helpers.deepCompareStrict.bind(null, instance))) {
+        result.addError({
+          name: "enum",
+          argument: schema2["enum"],
+          message: "is not one of enum values: " + schema2["enum"].map(String).join(",")
+        });
+      }
+      return result;
+    };
+    validators["const"] = function validateEnum(instance, schema2, options, ctx) {
+      if (instance === void 0) {
+        return null;
+      }
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (!helpers.deepCompareStrict(schema2["const"], instance)) {
+        result.addError({
+          name: "const",
+          argument: schema2["const"],
+          message: "does not exactly match expected constant: " + schema2["const"]
+        });
+      }
+      return result;
+    };
+    validators.not = validators.disallow = function validateNot(instance, schema2, options, ctx) {
+      var self2 = this;
+      if (instance === void 0) return null;
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      var notTypes = schema2.not || schema2.disallow;
+      if (!notTypes) return null;
+      if (!Array.isArray(notTypes)) notTypes = [notTypes];
+      notTypes.forEach(function(type2) {
+        if (self2.testType(instance, schema2, options, ctx, type2)) {
+          var id = type2 && (type2.$id || type2.id);
+          var schemaId = id || type2;
+          result.addError({
+            name: "not",
+            argument: schemaId,
+            message: "is of prohibited type " + schemaId
+          });
         }
-        return cacheId;
       });
-    }
+      return result;
+    };
+    module2.exports = attribute;
   }
 });
 
-// node_modules/jsonschema/lib/helpers.js
-var require_helpers3 = __commonJS({
-  "node_modules/jsonschema/lib/helpers.js"(exports2, module2) {
+// node_modules/jsonschema/lib/scan.js
+var require_scan = __commonJS({
+  "node_modules/jsonschema/lib/scan.js"(exports2, module2) {
     "use strict";
-    var uri = require("url");
-    var ValidationError = exports2.ValidationError = function ValidationError2(message, instance, schema2, path12, name, argument) {
-      if (Array.isArray(path12)) {
-        this.path = path12;
-        this.property = path12.reduce(function(sum, item) {
-          return sum + makeSuffix(item);
-        }, "instance");
-      } else if (path12 !== void 0) {
-        this.property = path12;
-      }
-      if (message) {
-        this.message = message;
+    var urilib = require("url");
+    var helpers = require_helpers3();
+    module2.exports.SchemaScanResult = SchemaScanResult;
+    function SchemaScanResult(found, ref) {
+      this.id = found;
+      this.ref = ref;
+    }
+    module2.exports.scan = function scan(base, schema2) {
+      function scanSchema(baseuri, schema3) {
+        if (!schema3 || typeof schema3 != "object") return;
+        if (schema3.$ref) {
+          var resolvedUri = urilib.resolve(baseuri, schema3.$ref);
+          ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0;
+          return;
+        }
+        var id = schema3.$id || schema3.id;
+        var ourBase = id ? urilib.resolve(baseuri, id) : baseuri;
+        if (ourBase) {
+          if (ourBase.indexOf("#") < 0) ourBase += "#";
+          if (found[ourBase]) {
+            if (!helpers.deepCompareStrict(found[ourBase], schema3)) {
+              throw new Error("Schema <" + ourBase + "> already exists with different definition");
+            }
+            return found[ourBase];
+          }
+          found[ourBase] = schema3;
+          if (ourBase[ourBase.length - 1] == "#") {
+            found[ourBase.substring(0, ourBase.length - 1)] = schema3;
+          }
+        }
+        scanArray(ourBase + "/items", Array.isArray(schema3.items) ? schema3.items : [schema3.items]);
+        scanArray(ourBase + "/extends", Array.isArray(schema3.extends) ? schema3.extends : [schema3.extends]);
+        scanSchema(ourBase + "/additionalItems", schema3.additionalItems);
+        scanObject(ourBase + "/properties", schema3.properties);
+        scanSchema(ourBase + "/additionalProperties", schema3.additionalProperties);
+        scanObject(ourBase + "/definitions", schema3.definitions);
+        scanObject(ourBase + "/patternProperties", schema3.patternProperties);
+        scanObject(ourBase + "/dependencies", schema3.dependencies);
+        scanArray(ourBase + "/disallow", schema3.disallow);
+        scanArray(ourBase + "/allOf", schema3.allOf);
+        scanArray(ourBase + "/anyOf", schema3.anyOf);
+        scanArray(ourBase + "/oneOf", schema3.oneOf);
+        scanSchema(ourBase + "/not", schema3.not);
       }
-      if (schema2) {
-        var id = schema2.$id || schema2.id;
-        this.schema = id || schema2;
+      function scanArray(baseuri, schemas) {
+        if (!Array.isArray(schemas)) return;
+        for (var i = 0; i < schemas.length; i++) {
+          scanSchema(baseuri + "/" + i, schemas[i]);
+        }
       }
-      if (instance !== void 0) {
-        this.instance = instance;
+      function scanObject(baseuri, schemas) {
+        if (!schemas || typeof schemas != "object") return;
+        for (var p in schemas) {
+          scanSchema(baseuri + "/" + p, schemas[p]);
+        }
       }
-      this.name = name;
-      this.argument = argument;
-      this.stack = this.toString();
-    };
-    ValidationError.prototype.toString = function toString3() {
-      return this.property + " " + this.message;
+      var found = {};
+      var ref = {};
+      scanSchema(base, schema2);
+      return new SchemaScanResult(found, ref);
     };
-    var ValidatorResult = exports2.ValidatorResult = function ValidatorResult2(instance, schema2, options, ctx) {
-      this.instance = instance;
-      this.schema = schema2;
-      this.options = options;
-      this.path = ctx.path;
-      this.propertyPath = ctx.propertyPath;
-      this.errors = [];
-      this.throwError = options && options.throwError;
-      this.throwFirst = options && options.throwFirst;
-      this.throwAll = options && options.throwAll;
-      this.disableFormat = options && options.disableFormat === true;
+  }
+});
+
+// node_modules/jsonschema/lib/validator.js
+var require_validator2 = __commonJS({
+  "node_modules/jsonschema/lib/validator.js"(exports2, module2) {
+    "use strict";
+    var urilib = require("url");
+    var attribute = require_attribute();
+    var helpers = require_helpers3();
+    var scanSchema = require_scan().scan;
+    var ValidatorResult = helpers.ValidatorResult;
+    var ValidatorResultError = helpers.ValidatorResultError;
+    var SchemaError = helpers.SchemaError;
+    var SchemaContext = helpers.SchemaContext;
+    var anonymousBase = "/";
+    var Validator3 = function Validator4() {
+      this.customFormats = Object.create(Validator4.prototype.customFormats);
+      this.schemas = {};
+      this.unresolvedRefs = [];
+      this.types = Object.create(types);
+      this.attributes = Object.create(attribute.validators);
     };
-    ValidatorResult.prototype.addError = function addError(detail) {
-      var err;
-      if (typeof detail == "string") {
-        err = new ValidationError(detail, this.instance, this.schema, this.path);
-      } else {
-        if (!detail) throw new Error("Missing error detail");
-        if (!detail.message) throw new Error("Missing error message");
-        if (!detail.name) throw new Error("Missing validator type");
-        err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument);
+    Validator3.prototype.customFormats = {};
+    Validator3.prototype.schemas = null;
+    Validator3.prototype.types = null;
+    Validator3.prototype.attributes = null;
+    Validator3.prototype.unresolvedRefs = null;
+    Validator3.prototype.addSchema = function addSchema(schema2, base) {
+      var self2 = this;
+      if (!schema2) {
+        return null;
       }
-      this.errors.push(err);
-      if (this.throwFirst) {
-        throw new ValidatorResultError(this);
-      } else if (this.throwError) {
-        throw err;
+      var scan = scanSchema(base || anonymousBase, schema2);
+      var ourUri = base || schema2.$id || schema2.id;
+      for (var uri in scan.id) {
+        this.schemas[uri] = scan.id[uri];
       }
-      return err;
-    };
-    ValidatorResult.prototype.importErrors = function importErrors(res) {
-      if (typeof res == "string" || res && res.validatorType) {
-        this.addError(res);
-      } else if (res && res.errors) {
-        this.errors = this.errors.concat(res.errors);
+      for (var uri in scan.ref) {
+        this.unresolvedRefs.push(uri);
       }
+      this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) {
+        return typeof self2.schemas[uri2] === "undefined";
+      });
+      return this.schemas[ourUri];
     };
-    function stringizer(v, i) {
-      return i + ": " + v.toString() + "\n";
-    }
-    ValidatorResult.prototype.toString = function toString3(res) {
-      return this.errors.map(stringizer).join("");
-    };
-    Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() {
-      return !this.errors.length;
-    } });
-    module2.exports.ValidatorResultError = ValidatorResultError;
-    function ValidatorResultError(result) {
-      if (Error.captureStackTrace) {
-        Error.captureStackTrace(this, ValidatorResultError);
+    Validator3.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) {
+      if (!Array.isArray(schemas)) return;
+      for (var i = 0; i < schemas.length; i++) {
+        this.addSubSchema(baseuri, schemas[i]);
       }
-      this.instance = result.instance;
-      this.schema = result.schema;
-      this.options = result.options;
-      this.errors = result.errors;
-    }
-    ValidatorResultError.prototype = new Error();
-    ValidatorResultError.prototype.constructor = ValidatorResultError;
-    ValidatorResultError.prototype.name = "Validation Error";
-    var SchemaError = exports2.SchemaError = function SchemaError2(msg, schema2) {
-      this.message = msg;
-      this.schema = schema2;
-      Error.call(this, msg);
-      Error.captureStackTrace(this, SchemaError2);
     };
-    SchemaError.prototype = Object.create(
-      Error.prototype,
-      {
-        constructor: { value: SchemaError, enumerable: false },
-        name: { value: "SchemaError", enumerable: false }
-      }
-    );
-    var SchemaContext = exports2.SchemaContext = function SchemaContext2(schema2, options, path12, base, schemas) {
-      this.schema = schema2;
-      this.options = options;
-      if (Array.isArray(path12)) {
-        this.path = path12;
-        this.propertyPath = path12.reduce(function(sum, item) {
-          return sum + makeSuffix(item);
-        }, "instance");
-      } else {
-        this.propertyPath = path12;
+    Validator3.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) {
+      if (!schemas || typeof schemas != "object") return;
+      for (var p in schemas) {
+        this.addSubSchema(baseuri, schemas[p]);
       }
-      this.base = base;
+    };
+    Validator3.prototype.setSchemas = function setSchemas(schemas) {
       this.schemas = schemas;
     };
-    SchemaContext.prototype.resolve = function resolve6(target) {
-      return uri.resolve(this.base, target);
+    Validator3.prototype.getSchema = function getSchema(urn) {
+      return this.schemas[urn];
     };
-    SchemaContext.prototype.makeChild = function makeChild(schema2, propertyName) {
-      var path12 = propertyName === void 0 ? this.path : this.path.concat([propertyName]);
-      var id = schema2.$id || schema2.id;
-      var base = uri.resolve(this.base, id || "");
-      var ctx = new SchemaContext(schema2, this.options, path12, base, Object.create(this.schemas));
-      if (id && !ctx.schemas[base]) {
-        ctx.schemas[base] = schema2;
+    Validator3.prototype.validate = function validate(instance, schema2, options, ctx) {
+      if (typeof schema2 !== "boolean" && typeof schema2 !== "object" || schema2 === null) {
+        throw new SchemaError("Expected `schema` to be an object or boolean");
       }
-      return ctx;
-    };
-    var FORMAT_REGEXPS = exports2.FORMAT_REGEXPS = {
-      // 7.3.1. Dates, Times, and Duration
-      "date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,
-      "date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,
-      "time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,
-      "duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,
-      // 7.3.2. Email Addresses
-      // TODO: fix the email production
-      "email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,
-      "idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,
-      // 7.3.3. Hostnames
-      // 7.3.4. IP Addresses
-      "ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
-      // FIXME whitespace is invalid
-      "ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,
-      // 7.3.5. Resource Identifiers
-      // TODO: A more accurate regular expression for "uri" goes:
-      // [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)?
-      "uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
-      "uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,
-      "iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
-      "iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,
-      "uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
-      // 7.3.6. uri-template
-      "uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,
-      // 7.3.7. JSON Pointers
-      "json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,
-      "relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,
-      // hostname regex from: http://stackoverflow.com/a/1420225/5628
-      "hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
-      "host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
-      "utc-millisec": function(input) {
-        return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input);
-      },
-      // 7.3.8. regex
-      "regex": function(input) {
-        var result = true;
-        try {
-          new RegExp(input);
-        } catch (e) {
-          result = false;
+      if (!options) {
+        options = {};
+      }
+      var id = schema2.$id || schema2.id;
+      var base = urilib.resolve(options.base || anonymousBase, id || "");
+      if (!ctx) {
+        ctx = new SchemaContext(schema2, options, [], base, Object.create(this.schemas));
+        if (!ctx.schemas[base]) {
+          ctx.schemas[base] = schema2;
+        }
+        var found = scanSchema(base, schema2);
+        for (var n in found.id) {
+          var sch = found.id[n];
+          ctx.schemas[n] = sch;
         }
+      }
+      if (options.required && instance === void 0) {
+        var result = new ValidatorResult(instance, schema2, options, ctx);
+        result.addError("is required, but is undefined");
         return result;
-      },
-      // Other definitions
-      // "style" was removed from JSON Schema in draft-4 and is deprecated
-      "style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,
-      // "color" was removed from JSON Schema in draft-4 and is deprecated
-      "color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,
-      "phone": /^\+(?:[0-9] ?){6,14}[0-9]$/,
-      "alpha": /^[a-zA-Z]+$/,
-      "alphanumeric": /^[a-zA-Z0-9]+$/
+      }
+      var result = this.validateSchema(instance, schema2, options, ctx);
+      if (!result) {
+        throw new Error("Result undefined");
+      } else if (options.throwAll && result.errors.length) {
+        throw new ValidatorResultError(result);
+      }
+      return result;
     };
-    FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex;
-    FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex;
-    FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"];
-    exports2.isFormat = function isFormat(input, format, validator) {
-      if (typeof input === "string" && FORMAT_REGEXPS[format] !== void 0) {
-        if (FORMAT_REGEXPS[format] instanceof RegExp) {
-          return FORMAT_REGEXPS[format].test(input);
+    function shouldResolve(schema2) {
+      var ref = typeof schema2 === "string" ? schema2 : schema2.$ref;
+      if (typeof ref == "string") return ref;
+      return false;
+    }
+    Validator3.prototype.validateSchema = function validateSchema(instance, schema2, options, ctx) {
+      var result = new ValidatorResult(instance, schema2, options, ctx);
+      if (typeof schema2 === "boolean") {
+        if (schema2 === true) {
+          schema2 = {};
+        } else if (schema2 === false) {
+          schema2 = { type: [] };
         }
-        if (typeof FORMAT_REGEXPS[format] === "function") {
-          return FORMAT_REGEXPS[format](input);
+      } else if (!schema2) {
+        throw new Error("schema is undefined");
+      }
+      if (schema2["extends"]) {
+        if (Array.isArray(schema2["extends"])) {
+          var schemaobj = { schema: schema2, ctx };
+          schema2["extends"].forEach(this.schemaTraverser.bind(this, schemaobj));
+          schema2 = schemaobj.schema;
+          schemaobj.schema = null;
+          schemaobj.ctx = null;
+          schemaobj = null;
+        } else {
+          schema2 = helpers.deepMerge(schema2, this.superResolve(schema2["extends"], ctx));
         }
-      } else if (validator && validator.customFormats && typeof validator.customFormats[format] === "function") {
-        return validator.customFormats[format](input);
       }
-      return true;
+      var switchSchema = shouldResolve(schema2);
+      if (switchSchema) {
+        var resolved = this.resolve(schema2, switchSchema, ctx);
+        var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas);
+        return this.validateSchema(instance, resolved.subschema, options, subctx);
+      }
+      var skipAttributes = options && options.skipAttributes || [];
+      for (var key in schema2) {
+        if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) {
+          var validatorErr = null;
+          var validator = this.attributes[key];
+          if (validator) {
+            validatorErr = validator.call(this, instance, schema2, options, ctx);
+          } else if (options.allowUnknownAttributes === false) {
+            throw new SchemaError("Unsupported attribute: " + key, schema2);
+          }
+          if (validatorErr) {
+            result.importErrors(validatorErr);
+          }
+        }
+      }
+      if (typeof options.rewrite == "function") {
+        var value = options.rewrite.call(this, instance, schema2, options, ctx);
+        result.instance = value;
+      }
+      return result;
     };
-    var makeSuffix = exports2.makeSuffix = function makeSuffix2(key) {
-      key = key.toString();
-      if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) {
-        return "." + key;
+    Validator3.prototype.schemaTraverser = function schemaTraverser(schemaobj, s) {
+      schemaobj.schema = helpers.deepMerge(schemaobj.schema, this.superResolve(s, schemaobj.ctx));
+    };
+    Validator3.prototype.superResolve = function superResolve(schema2, ctx) {
+      var ref = shouldResolve(schema2);
+      if (ref) {
+        return this.resolve(schema2, ref, ctx).subschema;
       }
-      if (key.match(/^\d+$/)) {
-        return "[" + key + "]";
+      return schema2;
+    };
+    Validator3.prototype.resolve = function resolve6(schema2, switchSchema, ctx) {
+      switchSchema = ctx.resolve(switchSchema);
+      if (ctx.schemas[switchSchema]) {
+        return { subschema: ctx.schemas[switchSchema], switchSchema };
       }
-      return "[" + JSON.stringify(key) + "]";
+      var parsed = urilib.parse(switchSchema);
+      var fragment = parsed && parsed.hash;
+      var document2 = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length);
+      if (!document2 || !ctx.schemas[document2]) {
+        throw new SchemaError("no such schema <" + switchSchema + ">", schema2);
+      }
+      var subschema = helpers.objectGetPath(ctx.schemas[document2], fragment.substr(1));
+      if (subschema === void 0) {
+        throw new SchemaError("no such schema " + fragment + " located in <" + document2 + ">", schema2);
+      }
+      return { subschema, switchSchema };
     };
-    exports2.deepCompareStrict = function deepCompareStrict(a, b) {
-      if (typeof a !== typeof b) {
-        return false;
+    Validator3.prototype.testType = function validateType(instance, schema2, options, ctx, type2) {
+      if (type2 === void 0) {
+        return;
+      } else if (type2 === null) {
+        throw new SchemaError('Unexpected null in "type" keyword');
       }
-      if (Array.isArray(a)) {
-        if (!Array.isArray(b)) {
-          return false;
-        }
-        if (a.length !== b.length) {
-          return false;
-        }
-        return a.every(function(v, i) {
-          return deepCompareStrict(a[i], b[i]);
+      if (typeof this.types[type2] == "function") {
+        return this.types[type2].call(this, instance);
+      }
+      if (type2 && typeof type2 == "object") {
+        var res = this.validateSchema(instance, type2, options, ctx);
+        return res === void 0 || !(res && res.errors.length);
+      }
+      return true;
+    };
+    var types = Validator3.prototype.types = {};
+    types.string = function testString(instance) {
+      return typeof instance == "string";
+    };
+    types.number = function testNumber(instance) {
+      return typeof instance == "number" && isFinite(instance);
+    };
+    types.integer = function testInteger(instance) {
+      return typeof instance == "number" && instance % 1 === 0;
+    };
+    types.boolean = function testBoolean(instance) {
+      return typeof instance == "boolean";
+    };
+    types.array = function testArray(instance) {
+      return Array.isArray(instance);
+    };
+    types["null"] = function testNull(instance) {
+      return instance === null;
+    };
+    types.date = function testDate(instance) {
+      return instance instanceof Date;
+    };
+    types.any = function testAny(instance) {
+      return true;
+    };
+    types.object = function testObject(instance) {
+      return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date);
+    };
+    module2.exports = Validator3;
+  }
+});
+
+// node_modules/jsonschema/lib/index.js
+var require_lib4 = __commonJS({
+  "node_modules/jsonschema/lib/index.js"(exports2, module2) {
+    "use strict";
+    var Validator3 = module2.exports.Validator = require_validator2();
+    module2.exports.ValidatorResult = require_helpers3().ValidatorResult;
+    module2.exports.ValidatorResultError = require_helpers3().ValidatorResultError;
+    module2.exports.ValidationError = require_helpers3().ValidationError;
+    module2.exports.SchemaError = require_helpers3().SchemaError;
+    module2.exports.SchemaScanResult = require_scan().SchemaScanResult;
+    module2.exports.scan = require_scan().scan;
+    module2.exports.validate = function(instance, schema2, options) {
+      var v = new Validator3();
+      return v.validate(instance, schema2, options);
+    };
+  }
+});
+
+// node_modules/@actions/tool-cache/lib/manifest.js
+var require_manifest = __commonJS({
+  "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
+      }
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      }
+      __setModuleDefault4(result, mod);
+      return result;
+    };
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
         });
       }
-      if (typeof a === "object") {
-        if (!a || !b) {
-          return a === b;
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        var aKeys = Object.keys(a);
-        var bKeys = Object.keys(b);
-        if (aKeys.length !== bKeys.length) {
-          return false;
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
         }
-        return aKeys.every(function(v) {
-          return deepCompareStrict(a[v], b[v]);
-        });
-      }
-      return a === b;
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    function deepMerger(target, dst, e, i) {
-      if (typeof e === "object") {
-        dst[i] = deepMerge(target[i], e);
-      } else {
-        if (target.indexOf(e) === -1) {
-          dst.push(e);
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0;
+    var semver8 = __importStar4(require_semver2());
+    var core_1 = require_core();
+    var os3 = require("os");
+    var cp = require("child_process");
+    var fs13 = require("fs");
+    function _findMatch(versionSpec, stable, candidates, archFilter) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const platFilter = os3.platform();
+        let result;
+        let match;
+        let file;
+        for (const candidate of candidates) {
+          const version = candidate.version;
+          (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`);
+          if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) {
+            file = candidate.files.find((item) => {
+              (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`);
+              let chk = item.arch === archFilter && item.platform === platFilter;
+              if (chk && item.platform_version) {
+                const osVersion = module2.exports._getOsVersion();
+                if (osVersion === item.platform_version) {
+                  chk = true;
+                } else {
+                  chk = semver8.satisfies(osVersion, item.platform_version);
+                }
+              }
+              return chk;
+            });
+            if (file) {
+              (0, core_1.debug)(`matched ${candidate.version}`);
+              match = candidate;
+              break;
+            }
+          }
+        }
+        if (match && file) {
+          result = Object.assign({}, match);
+          result.files = [file];
+        }
+        return result;
+      });
+    }
+    exports2._findMatch = _findMatch;
+    function _getOsVersion() {
+      const plat = os3.platform();
+      let version = "";
+      if (plat === "darwin") {
+        version = cp.execSync("sw_vers -productVersion").toString();
+      } else if (plat === "linux") {
+        const lsbContents = module2.exports._readLinuxVersionFile();
+        if (lsbContents) {
+          const lines = lsbContents.split("\n");
+          for (const line of lines) {
+            const parts = line.split("=");
+            if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) {
+              version = parts[1].trim().replace(/^"/, "").replace(/"$/, "");
+              break;
+            }
+          }
         }
       }
+      return version;
     }
-    function copyist(src, dst, key) {
-      dst[key] = src[key];
+    exports2._getOsVersion = _getOsVersion;
+    function _readLinuxVersionFile() {
+      const lsbReleaseFile = "/etc/lsb-release";
+      const osReleaseFile = "/etc/os-release";
+      let contents = "";
+      if (fs13.existsSync(lsbReleaseFile)) {
+        contents = fs13.readFileSync(lsbReleaseFile).toString();
+      } else if (fs13.existsSync(osReleaseFile)) {
+        contents = fs13.readFileSync(osReleaseFile).toString();
+      }
+      return contents;
     }
-    function copyistWithDeepMerge(target, src, dst, key) {
-      if (typeof src[key] !== "object" || !src[key]) {
-        dst[key] = src[key];
-      } else {
-        if (!target[key]) {
-          dst[key] = src[key];
+    exports2._readLinuxVersionFile = _readLinuxVersionFile;
+  }
+});
+
+// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js
+var require_proxy4 = __commonJS({
+  "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/proxy.js"(exports2) {
+    "use strict";
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.checkBypass = exports2.getProxyUrl = void 0;
+    function getProxyUrl(reqUrl) {
+      const usingSsl = reqUrl.protocol === "https:";
+      if (checkBypass(reqUrl)) {
+        return void 0;
+      }
+      const proxyVar = (() => {
+        if (usingSsl) {
+          return process.env["https_proxy"] || process.env["HTTPS_PROXY"];
         } else {
-          dst[key] = deepMerge(target[key], src[key]);
+          return process.env["http_proxy"] || process.env["HTTP_PROXY"];
+        }
+      })();
+      if (proxyVar) {
+        try {
+          return new DecodedURL(proxyVar);
+        } catch (_a) {
+          if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://"))
+            return new DecodedURL(`http://${proxyVar}`);
         }
+      } else {
+        return void 0;
       }
     }
-    function deepMerge(target, src) {
-      var array = Array.isArray(src);
-      var dst = array && [] || {};
-      if (array) {
-        target = target || [];
-        dst = dst.concat(target);
-        src.forEach(deepMerger.bind(null, target, dst));
-      } else {
-        if (target && typeof target === "object") {
-          Object.keys(target).forEach(copyist.bind(null, target, dst));
+    exports2.getProxyUrl = getProxyUrl;
+    function checkBypass(reqUrl) {
+      if (!reqUrl.hostname) {
+        return false;
+      }
+      const reqHost = reqUrl.hostname;
+      if (isLoopbackAddress(reqHost)) {
+        return true;
+      }
+      const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || "";
+      if (!noProxy) {
+        return false;
+      }
+      let reqPort;
+      if (reqUrl.port) {
+        reqPort = Number(reqUrl.port);
+      } else if (reqUrl.protocol === "http:") {
+        reqPort = 80;
+      } else if (reqUrl.protocol === "https:") {
+        reqPort = 443;
+      }
+      const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+      if (typeof reqPort === "number") {
+        upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
+      }
+      for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) {
+        if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) {
+          return true;
         }
-        Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst));
       }
-      return dst;
+      return false;
     }
-    module2.exports.deepMerge = deepMerge;
-    exports2.objectGetPath = function objectGetPath(o, s) {
-      var parts = s.split("/").slice(1);
-      var k;
-      while (typeof (k = parts.shift()) == "string") {
-        var n = decodeURIComponent(k.replace(/~0/, "~").replace(/~1/g, "/"));
-        if (!(n in o)) return;
-        o = o[n];
-      }
-      return o;
-    };
-    function pathEncoder(v) {
-      return "/" + encodeURIComponent(v).replace(/~/g, "%7E");
+    exports2.checkBypass = checkBypass;
+    function isLoopbackAddress(host) {
+      const hostLower = host.toLowerCase();
+      return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]");
     }
-    exports2.encodePath = function encodePointer(a) {
-      return a.map(pathEncoder).join("");
-    };
-    exports2.getDecimalPlaces = function getDecimalPlaces(number) {
-      var decimalPlaces = 0;
-      if (isNaN(number)) return decimalPlaces;
-      if (typeof number !== "number") {
-        number = Number(number);
+    var DecodedURL = class extends URL {
+      constructor(url2, base) {
+        super(url2, base);
+        this._decodedUsername = decodeURIComponent(super.username);
+        this._decodedPassword = decodeURIComponent(super.password);
       }
-      var parts = number.toString().split("e");
-      if (parts.length === 2) {
-        if (parts[1][0] !== "-") {
-          return decimalPlaces;
-        } else {
-          decimalPlaces = Number(parts[1].slice(1));
-        }
+      get username() {
+        return this._decodedUsername;
       }
-      var decimalParts = parts[0].split(".");
-      if (decimalParts.length === 2) {
-        decimalPlaces += decimalParts[1].length;
+      get password() {
+        return this._decodedPassword;
       }
-      return decimalPlaces;
-    };
-    exports2.isSchema = function isSchema(val2) {
-      return typeof val2 === "object" && val2 || typeof val2 === "boolean";
     };
   }
 });
 
-// node_modules/jsonschema/lib/attribute.js
-var require_attribute = __commonJS({
-  "node_modules/jsonschema/lib/attribute.js"(exports2, module2) {
+// node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js
+var require_lib5 = __commonJS({
+  "node_modules/@actions/tool-cache/node_modules/@actions/http-client/lib/index.js"(exports2) {
     "use strict";
-    var helpers = require_helpers3();
-    var ValidatorResult = helpers.ValidatorResult;
-    var SchemaError = helpers.SchemaError;
-    var attribute = {};
-    attribute.ignoreProperties = {
-      // informative properties
-      "id": true,
-      "default": true,
-      "description": true,
-      "title": true,
-      // arguments to other properties
-      "additionalItems": true,
-      "then": true,
-      "else": true,
-      // special-handled properties
-      "$schema": true,
-      "$ref": true,
-      "extends": true
-    };
-    var validators = attribute.validators = {};
-    validators.type = function validateType(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var types = Array.isArray(schema2.type) ? schema2.type : [schema2.type];
-      if (!types.some(this.testType.bind(this, instance, schema2, options, ctx))) {
-        var list = types.map(function(v) {
-          if (!v) return;
-          var id = v.$id || v.id;
-          return id ? "<" + id + ">" : v + "";
-        });
-        result.addError({
-          name: "type",
-          argument: list,
-          message: "is not of a type(s) " + list
-        });
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
+      __setModuleDefault4(result, mod);
       return result;
     };
-    function testSchemaNoThrow(instance, options, ctx, callback, schema2) {
-      var throwError2 = options.throwError;
-      var throwAll = options.throwAll;
-      options.throwError = false;
-      options.throwAll = false;
-      var res = this.validateSchema(instance, schema2, options, ctx);
-      options.throwError = throwError2;
-      options.throwAll = throwAll;
-      if (!res.valid && callback instanceof Function) {
-        callback(res);
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
+        });
       }
-      return res.valid;
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.HttpClient = exports2.isHttps = exports2.HttpClientResponse = exports2.HttpClientError = exports2.getProxyUrl = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0;
+    var http = __importStar4(require("http"));
+    var https2 = __importStar4(require("https"));
+    var pm = __importStar4(require_proxy4());
+    var tunnel = __importStar4(require_tunnel2());
+    var undici_1 = require_undici();
+    var HttpCodes;
+    (function(HttpCodes2) {
+      HttpCodes2[HttpCodes2["OK"] = 200] = "OK";
+      HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices";
+      HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently";
+      HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved";
+      HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther";
+      HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified";
+      HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy";
+      HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy";
+      HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+      HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect";
+      HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest";
+      HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized";
+      HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired";
+      HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden";
+      HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound";
+      HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+      HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable";
+      HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+      HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout";
+      HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict";
+      HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone";
+      HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests";
+      HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError";
+      HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented";
+      HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway";
+      HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+      HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout";
+    })(HttpCodes || (exports2.HttpCodes = HttpCodes = {}));
+    var Headers;
+    (function(Headers2) {
+      Headers2["Accept"] = "accept";
+      Headers2["ContentType"] = "content-type";
+    })(Headers || (exports2.Headers = Headers = {}));
+    var MediaTypes;
+    (function(MediaTypes2) {
+      MediaTypes2["ApplicationJson"] = "application/json";
+    })(MediaTypes || (exports2.MediaTypes = MediaTypes = {}));
+    function getProxyUrl(serverUrl) {
+      const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+      return proxyUrl ? proxyUrl.href : "";
     }
-    validators.anyOf = function validateAnyOf(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
+    exports2.getProxyUrl = getProxyUrl;
+    var HttpRedirectCodes = [
+      HttpCodes.MovedPermanently,
+      HttpCodes.ResourceMoved,
+      HttpCodes.SeeOther,
+      HttpCodes.TemporaryRedirect,
+      HttpCodes.PermanentRedirect
+    ];
+    var HttpResponseRetryCodes = [
+      HttpCodes.BadGateway,
+      HttpCodes.ServiceUnavailable,
+      HttpCodes.GatewayTimeout
+    ];
+    var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"];
+    var ExponentialBackoffCeiling = 10;
+    var ExponentialBackoffTimeSlice = 5;
+    var HttpClientError = class _HttpClientError extends Error {
+      constructor(message, statusCode) {
+        super(message);
+        this.name = "HttpClientError";
+        this.statusCode = statusCode;
+        Object.setPrototypeOf(this, _HttpClientError.prototype);
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var inner = new ValidatorResult(instance, schema2, options, ctx);
-      if (!Array.isArray(schema2.anyOf)) {
-        throw new SchemaError("anyOf must be an array");
+    };
+    exports2.HttpClientError = HttpClientError;
+    var HttpClientResponse = class {
+      constructor(message) {
+        this.message = message;
       }
-      if (!schema2.anyOf.some(
-        testSchemaNoThrow.bind(
-          this,
-          instance,
-          options,
-          ctx,
-          function(res) {
-            inner.importErrors(res);
-          }
-        )
-      )) {
-        var list = schema2.anyOf.map(function(v, i) {
-          var id = v.$id || v.id;
-          if (id) return "<" + id + ">";
-          return v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
+      readBody() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () {
+            let output = Buffer.alloc(0);
+            this.message.on("data", (chunk) => {
+              output = Buffer.concat([output, chunk]);
+            });
+            this.message.on("end", () => {
+              resolve6(output.toString());
+            });
+          }));
         });
-        if (options.nestedErrors) {
-          result.importErrors(inner);
+      }
+      readBodyBuffer() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () {
+            const chunks = [];
+            this.message.on("data", (chunk) => {
+              chunks.push(chunk);
+            });
+            this.message.on("end", () => {
+              resolve6(Buffer.concat(chunks));
+            });
+          }));
+        });
+      }
+    };
+    exports2.HttpClientResponse = HttpClientResponse;
+    function isHttps(requestUrl) {
+      const parsedUrl = new URL(requestUrl);
+      return parsedUrl.protocol === "https:";
+    }
+    exports2.isHttps = isHttps;
+    var HttpClient2 = class {
+      constructor(userAgent, handlers, requestOptions) {
+        this._ignoreSslError = false;
+        this._allowRedirects = true;
+        this._allowRedirectDowngrade = false;
+        this._maxRedirects = 50;
+        this._allowRetries = false;
+        this._maxRetries = 1;
+        this._keepAlive = false;
+        this._disposed = false;
+        this.userAgent = userAgent;
+        this.handlers = handlers || [];
+        this.requestOptions = requestOptions;
+        if (requestOptions) {
+          if (requestOptions.ignoreSslError != null) {
+            this._ignoreSslError = requestOptions.ignoreSslError;
+          }
+          this._socketTimeout = requestOptions.socketTimeout;
+          if (requestOptions.allowRedirects != null) {
+            this._allowRedirects = requestOptions.allowRedirects;
+          }
+          if (requestOptions.allowRedirectDowngrade != null) {
+            this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+          }
+          if (requestOptions.maxRedirects != null) {
+            this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+          }
+          if (requestOptions.keepAlive != null) {
+            this._keepAlive = requestOptions.keepAlive;
+          }
+          if (requestOptions.allowRetries != null) {
+            this._allowRetries = requestOptions.allowRetries;
+          }
+          if (requestOptions.maxRetries != null) {
+            this._maxRetries = requestOptions.maxRetries;
+          }
         }
-        result.addError({
-          name: "anyOf",
-          argument: list,
-          message: "is not any of " + list.join(",")
+      }
+      options(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("OPTIONS", requestUrl, null, additionalHeaders || {});
         });
       }
-      return result;
-    };
-    validators.allOf = function validateAllOf(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
+      get(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("GET", requestUrl, null, additionalHeaders || {});
+        });
       }
-      if (!Array.isArray(schema2.allOf)) {
-        throw new SchemaError("allOf must be an array");
+      del(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("DELETE", requestUrl, null, additionalHeaders || {});
+        });
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var self2 = this;
-      schema2.allOf.forEach(function(v, i) {
-        var valid3 = self2.validateSchema(instance, v, options, ctx);
-        if (!valid3.valid) {
-          var id = v.$id || v.id;
-          var msg = id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
-          result.addError({
-            name: "allOf",
-            argument: { id: msg, length: valid3.errors.length, valid: valid3 },
-            message: "does not match allOf schema " + msg + " with " + valid3.errors.length + " error[s]:"
-          });
-          result.importErrors(valid3);
-        }
-      });
-      return result;
-    };
-    validators.oneOf = function validateOneOf(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
+      post(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("POST", requestUrl, data, additionalHeaders || {});
+        });
       }
-      if (!Array.isArray(schema2.oneOf)) {
-        throw new SchemaError("oneOf must be an array");
+      patch(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PATCH", requestUrl, data, additionalHeaders || {});
+        });
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var inner = new ValidatorResult(instance, schema2, options, ctx);
-      var count = schema2.oneOf.filter(
-        testSchemaNoThrow.bind(
-          this,
-          instance,
-          options,
-          ctx,
-          function(res) {
-            inner.importErrors(res);
-          }
-        )
-      ).length;
-      var list = schema2.oneOf.map(function(v, i) {
-        var id = v.$id || v.id;
-        return id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
-      });
-      if (count !== 1) {
-        if (options.nestedErrors) {
-          result.importErrors(inner);
-        }
-        result.addError({
-          name: "oneOf",
-          argument: list,
-          message: "is not exactly one from " + list.join(",")
+      put(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PUT", requestUrl, data, additionalHeaders || {});
         });
       }
-      return result;
-    };
-    validators.if = function validateIf(instance, schema2, options, ctx) {
-      if (instance === void 0) return null;
-      if (!helpers.isSchema(schema2.if)) throw new Error('Expected "if" keyword to be a schema');
-      var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema2.if);
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var res;
-      if (ifValid) {
-        if (schema2.then === void 0) return;
-        if (!helpers.isSchema(schema2.then)) throw new Error('Expected "then" keyword to be a schema');
-        res = this.validateSchema(instance, schema2.then, options, ctx.makeChild(schema2.then));
-        result.importErrors(res);
-      } else {
-        if (schema2.else === void 0) return;
-        if (!helpers.isSchema(schema2.else)) throw new Error('Expected "else" keyword to be a schema');
-        res = this.validateSchema(instance, schema2.else, options, ctx.makeChild(schema2.else));
-        result.importErrors(res);
+      head(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("HEAD", requestUrl, null, additionalHeaders || {});
+        });
       }
-      return result;
-    };
-    function getEnumerableProperty(object, key) {
-      if (Object.hasOwnProperty.call(object, key)) return object[key];
-      if (!(key in object)) return;
-      while (object = Object.getPrototypeOf(object)) {
-        if (Object.propertyIsEnumerable.call(object, key)) return object[key];
+      sendStream(verb, requestUrl, stream2, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request(verb, requestUrl, stream2, additionalHeaders);
+        });
       }
-    }
-    validators.propertyNames = function validatePropertyNames(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var subschema = schema2.propertyNames !== void 0 ? schema2.propertyNames : {};
-      if (!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)');
-      for (var property in instance) {
-        if (getEnumerableProperty(instance, property) !== void 0) {
-          var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema));
-          result.importErrors(res);
-        }
+      /**
+       * Gets a typed object from an endpoint
+       * Be aware that not found returns a null.  Other errors (4xx, 5xx) reject the promise
+       */
+      getJson(requestUrl, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          const res = yield this.get(requestUrl, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      return result;
-    };
-    validators.properties = function validateProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var properties = schema2.properties || {};
-      for (var property in properties) {
-        var subschema = properties[property];
-        if (subschema === void 0) {
-          continue;
-        } else if (subschema === null) {
-          throw new SchemaError('Unexpected null, expected schema in "properties"');
-        }
-        if (typeof options.preValidateProperty == "function") {
-          options.preValidateProperty(instance, property, subschema, options, ctx);
-        }
-        var prop = getEnumerableProperty(instance, property);
-        var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property));
-        if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
-        result.importErrors(res);
+      postJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.post(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      return result;
-    };
-    function testAdditionalProperty(instance, schema2, options, ctx, property, result) {
-      if (!this.types.object(instance)) return;
-      if (schema2.properties && schema2.properties[property] !== void 0) {
-        return;
+      putJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.put(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
       }
-      if (schema2.additionalProperties === false) {
-        result.addError({
-          name: "additionalProperties",
-          argument: property,
-          message: "is not allowed to have the additional property " + JSON.stringify(property)
+      patchJson(requestUrl, obj, additionalHeaders = {}) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+          const res = yield this.patch(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
         });
-      } else {
-        var additionalProperties = schema2.additionalProperties || {};
-        if (typeof options.preValidateProperty == "function") {
-          options.preValidateProperty(instance, property, additionalProperties, options, ctx);
-        }
-        var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property));
-        if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
-        result.importErrors(res);
       }
-    }
-    validators.patternProperties = function validatePatternProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var patternProperties = schema2.patternProperties || {};
-      for (var property in instance) {
-        var test = true;
-        for (var pattern in patternProperties) {
-          var subschema = patternProperties[pattern];
-          if (subschema === void 0) {
-            continue;
-          } else if (subschema === null) {
-            throw new SchemaError('Unexpected null, expected schema in "patternProperties"');
+      /**
+       * Makes a raw http request.
+       * All other methods such as get, post, patch, and request ultimately call this.
+       * Prefer get, del, post and patch
+       */
+      request(verb, requestUrl, data, headers) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          if (this._disposed) {
+            throw new Error("Client has already been disposed.");
           }
-          try {
-            var regexp = new RegExp(pattern, "u");
-          } catch (_e) {
-            regexp = new RegExp(pattern);
+          const parsedUrl = new URL(requestUrl);
+          let info6 = this._prepareRequest(verb, parsedUrl, headers);
+          const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1;
+          let numTries = 0;
+          let response;
+          do {
+            response = yield this.requestRaw(info6, data);
+            if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
+              let authenticationHandler;
+              for (const handler of this.handlers) {
+                if (handler.canHandleAuthentication(response)) {
+                  authenticationHandler = handler;
+                  break;
+                }
+              }
+              if (authenticationHandler) {
+                return authenticationHandler.handleAuthentication(this, info6, data);
+              } else {
+                return response;
+              }
+            }
+            let redirectsRemaining = this._maxRedirects;
+            while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) {
+              const redirectUrl = response.message.headers["location"];
+              if (!redirectUrl) {
+                break;
+              }
+              const parsedRedirectUrl = new URL(redirectUrl);
+              if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
+                throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
+              }
+              yield response.readBody();
+              if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+                for (const header in headers) {
+                  if (header.toLowerCase() === "authorization") {
+                    delete headers[header];
+                  }
+                }
+              }
+              info6 = this._prepareRequest(verb, parsedRedirectUrl, headers);
+              response = yield this.requestRaw(info6, data);
+              redirectsRemaining--;
+            }
+            if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+              return response;
+            }
+            numTries += 1;
+            if (numTries < maxTries) {
+              yield response.readBody();
+              yield this._performExponentialBackoff(numTries);
+            }
+          } while (numTries < maxTries);
+          return response;
+        });
+      }
+      /**
+       * Needs to be called if keepAlive is set to true in request options.
+       */
+      dispose() {
+        if (this._agent) {
+          this._agent.destroy();
+        }
+        this._disposed = true;
+      }
+      /**
+       * Raw request.
+       * @param info
+       * @param data
+       */
+      requestRaw(info6, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6, reject) => {
+            function callbackForResult(err, res) {
+              if (err) {
+                reject(err);
+              } else if (!res) {
+                reject(new Error("Unknown error"));
+              } else {
+                resolve6(res);
+              }
+            }
+            this.requestRawWithCallback(info6, data, callbackForResult);
+          });
+        });
+      }
+      /**
+       * Raw request with callback.
+       * @param info
+       * @param data
+       * @param onResult
+       */
+      requestRawWithCallback(info6, data, onResult) {
+        if (typeof data === "string") {
+          if (!info6.options.headers) {
+            info6.options.headers = {};
           }
-          if (!regexp.test(property)) {
-            continue;
+          info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8");
+        }
+        let callbackCalled = false;
+        function handleResult(err, res) {
+          if (!callbackCalled) {
+            callbackCalled = true;
+            onResult(err, res);
           }
-          test = false;
-          if (typeof options.preValidateProperty == "function") {
-            options.preValidateProperty(instance, property, subschema, options, ctx);
+        }
+        const req = info6.httpModule.request(info6.options, (msg) => {
+          const res = new HttpClientResponse(msg);
+          handleResult(void 0, res);
+        });
+        let socket;
+        req.on("socket", (sock) => {
+          socket = sock;
+        });
+        req.setTimeout(this._socketTimeout || 3 * 6e4, () => {
+          if (socket) {
+            socket.end();
           }
-          var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property));
-          if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
-          result.importErrors(res);
+          handleResult(new Error(`Request timeout: ${info6.options.path}`));
+        });
+        req.on("error", function(err) {
+          handleResult(err);
+        });
+        if (data && typeof data === "string") {
+          req.write(data, "utf8");
         }
-        if (test) {
-          testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result);
+        if (data && typeof data !== "string") {
+          data.on("close", function() {
+            req.end();
+          });
+          data.pipe(req);
+        } else {
+          req.end();
         }
       }
-      return result;
-    };
-    validators.additionalProperties = function validateAdditionalProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      if (schema2.patternProperties) {
-        return null;
+      /**
+       * Gets an http agent. This function is useful when you need an http agent that handles
+       * routing through a proxy server - depending upon the url and proxy environment variables.
+       * @param serverUrl  The server URL where the request will be sent. For example, https://api.github.com
+       */
+      getAgent(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        return this._getAgent(parsedUrl);
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      for (var property in instance) {
-        testAdditionalProperty.call(this, instance, schema2, options, ctx, property, result);
+      getAgentDispatcher(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (!useProxy) {
+          return;
+        }
+        return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
       }
-      return result;
-    };
-    validators.minProperties = function validateMinProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var keys = Object.keys(instance);
-      if (!(keys.length >= schema2.minProperties)) {
-        result.addError({
-          name: "minProperties",
-          argument: schema2.minProperties,
-          message: "does not meet minimum property length of " + schema2.minProperties
-        });
+      _prepareRequest(method, requestUrl, headers) {
+        const info6 = {};
+        info6.parsedUrl = requestUrl;
+        const usingSsl = info6.parsedUrl.protocol === "https:";
+        info6.httpModule = usingSsl ? https2 : http;
+        const defaultPort = usingSsl ? 443 : 80;
+        info6.options = {};
+        info6.options.host = info6.parsedUrl.hostname;
+        info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort;
+        info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || "");
+        info6.options.method = method;
+        info6.options.headers = this._mergeHeaders(headers);
+        if (this.userAgent != null) {
+          info6.options.headers["user-agent"] = this.userAgent;
+        }
+        info6.options.agent = this._getAgent(info6.parsedUrl);
+        if (this.handlers) {
+          for (const handler of this.handlers) {
+            handler.prepareRequest(info6.options);
+          }
+        }
+        return info6;
       }
-      return result;
-    };
-    validators.maxProperties = function validateMaxProperties(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var keys = Object.keys(instance);
-      if (!(keys.length <= schema2.maxProperties)) {
-        result.addError({
-          name: "maxProperties",
-          argument: schema2.maxProperties,
-          message: "does not meet maximum property length of " + schema2.maxProperties
-        });
+      _mergeHeaders(headers) {
+        if (this.requestOptions && this.requestOptions.headers) {
+          return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
+        }
+        return lowercaseKeys(headers || {});
       }
-      return result;
-    };
-    validators.items = function validateItems(instance, schema2, options, ctx) {
-      var self2 = this;
-      if (!this.types.array(instance)) return;
-      if (schema2.items === void 0) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      instance.every(function(value, i) {
-        if (Array.isArray(schema2.items)) {
-          var items = schema2.items[i] === void 0 ? schema2.additionalItems : schema2.items[i];
-        } else {
-          var items = schema2.items;
+      _getExistingOrDefaultHeader(additionalHeaders, header, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
         }
-        if (items === void 0) {
-          return true;
+        return additionalHeaders[header] || clientHeader || _default2;
+      }
+      _getAgent(parsedUrl) {
+        let agent;
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (this._keepAlive && useProxy) {
+          agent = this._proxyAgent;
         }
-        if (items === false) {
-          result.addError({
-            name: "items",
-            message: "additionalItems not permitted"
-          });
-          return false;
+        if (!useProxy) {
+          agent = this._agent;
         }
-        var res = self2.validateSchema(value, items, options, ctx.makeChild(items, i));
-        if (res.instance !== result.instance[i]) result.instance[i] = res.instance;
-        result.importErrors(res);
-        return true;
-      });
-      return result;
-    };
-    validators.contains = function validateContains(instance, schema2, options, ctx) {
-      var self2 = this;
-      if (!this.types.array(instance)) return;
-      if (schema2.contains === void 0) return;
-      if (!helpers.isSchema(schema2.contains)) throw new Error('Expected "contains" keyword to be a schema');
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var count = instance.some(function(value, i) {
-        var res = self2.validateSchema(value, schema2.contains, options, ctx.makeChild(schema2.contains, i));
-        return res.errors.length === 0;
-      });
-      if (count === false) {
-        result.addError({
-          name: "contains",
-          argument: schema2.contains,
-          message: "must contain an item matching given schema"
-        });
-      }
-      return result;
-    };
-    validators.minimum = function validateMinimum(instance, schema2, options, ctx) {
-      if (!this.types.number(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (schema2.exclusiveMinimum && schema2.exclusiveMinimum === true) {
-        if (!(instance > schema2.minimum)) {
-          result.addError({
-            name: "minimum",
-            argument: schema2.minimum,
-            message: "must be greater than " + schema2.minimum
-          });
+        if (agent) {
+          return agent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        let maxSockets = 100;
+        if (this.requestOptions) {
+          maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
+        }
+        if (proxyUrl && proxyUrl.hostname) {
+          const agentOptions = {
+            maxSockets,
+            keepAlive: this._keepAlive,
+            proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && {
+              proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+            }), { host: proxyUrl.hostname, port: proxyUrl.port })
+          };
+          let tunnelAgent;
+          const overHttps = proxyUrl.protocol === "https:";
+          if (usingSsl) {
+            tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+          } else {
+            tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
+          }
+          agent = tunnelAgent(agentOptions);
+          this._proxyAgent = agent;
         }
-      } else {
-        if (!(instance >= schema2.minimum)) {
-          result.addError({
-            name: "minimum",
-            argument: schema2.minimum,
-            message: "must be greater than or equal to " + schema2.minimum
+        if (!agent) {
+          const options = { keepAlive: this._keepAlive, maxSockets };
+          agent = usingSsl ? new https2.Agent(options) : new http.Agent(options);
+          this._agent = agent;
+        }
+        if (usingSsl && this._ignoreSslError) {
+          agent.options = Object.assign(agent.options || {}, {
+            rejectUnauthorized: false
           });
         }
+        return agent;
       }
-      return result;
-    };
-    validators.maximum = function validateMaximum(instance, schema2, options, ctx) {
-      if (!this.types.number(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (schema2.exclusiveMaximum && schema2.exclusiveMaximum === true) {
-        if (!(instance < schema2.maximum)) {
-          result.addError({
-            name: "maximum",
-            argument: schema2.maximum,
-            message: "must be less than " + schema2.maximum
-          });
+      _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+        let proxyAgent;
+        if (this._keepAlive) {
+          proxyAgent = this._proxyAgentDispatcher;
         }
-      } else {
-        if (!(instance <= schema2.maximum)) {
-          result.addError({
-            name: "maximum",
-            argument: schema2.maximum,
-            message: "must be less than or equal to " + schema2.maximum
+        if (proxyAgent) {
+          return proxyAgent;
+        }
+        const usingSsl = parsedUrl.protocol === "https:";
+        proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && {
+          token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}`
+        }));
+        this._proxyAgentDispatcher = proxyAgent;
+        if (usingSsl && this._ignoreSslError) {
+          proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+            rejectUnauthorized: false
           });
         }
+        return proxyAgent;
       }
-      return result;
-    };
-    validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema2, options, ctx) {
-      if (typeof schema2.exclusiveMinimum === "boolean") return;
-      if (!this.types.number(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var valid3 = instance > schema2.exclusiveMinimum;
-      if (!valid3) {
-        result.addError({
-          name: "exclusiveMinimum",
-          argument: schema2.exclusiveMinimum,
-          message: "must be strictly greater than " + schema2.exclusiveMinimum
+      _performExponentialBackoff(retryNumber) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+          const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+          return new Promise((resolve6) => setTimeout(() => resolve6(), ms));
         });
       }
-      return result;
-    };
-    validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema2, options, ctx) {
-      if (typeof schema2.exclusiveMaximum === "boolean") return;
-      if (!this.types.number(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var valid3 = instance < schema2.exclusiveMaximum;
-      if (!valid3) {
-        result.addError({
-          name: "exclusiveMaximum",
-          argument: schema2.exclusiveMaximum,
-          message: "must be strictly less than " + schema2.exclusiveMaximum
+      _processResponse(res, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6, reject) => __awaiter4(this, void 0, void 0, function* () {
+            const statusCode = res.message.statusCode || 0;
+            const response = {
+              statusCode,
+              result: null,
+              headers: {}
+            };
+            if (statusCode === HttpCodes.NotFound) {
+              resolve6(response);
+            }
+            function dateTimeDeserializer(key, value) {
+              if (typeof value === "string") {
+                const a = new Date(value);
+                if (!isNaN(a.valueOf())) {
+                  return a;
+                }
+              }
+              return value;
+            }
+            let obj;
+            let contents;
+            try {
+              contents = yield res.readBody();
+              if (contents && contents.length > 0) {
+                if (options && options.deserializeDates) {
+                  obj = JSON.parse(contents, dateTimeDeserializer);
+                } else {
+                  obj = JSON.parse(contents);
+                }
+                response.result = obj;
+              }
+              response.headers = res.message.headers;
+            } catch (err) {
+            }
+            if (statusCode > 299) {
+              let msg;
+              if (obj && obj.message) {
+                msg = obj.message;
+              } else if (contents && contents.length > 0) {
+                msg = contents;
+              } else {
+                msg = `Failed request: (${statusCode})`;
+              }
+              const err = new HttpClientError(msg, statusCode);
+              err.result = response.result;
+              reject(err);
+            } else {
+              resolve6(response);
+            }
+          }));
         });
       }
-      return result;
     };
-    var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema2, options, ctx, validationType, errorMessage) {
-      if (!this.types.number(instance)) return;
-      var validationArgument = schema2[validationType];
-      if (validationArgument == 0) {
-        throw new SchemaError(validationType + " cannot be zero");
+    exports2.HttpClient = HttpClient2;
+    var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
+  }
+});
+
+// node_modules/@actions/tool-cache/lib/retry-helper.js
+var require_retry_helper = __commonJS({
+  "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var instanceDecimals = helpers.getDecimalPlaces(instance);
-      var divisorDecimals = helpers.getDecimalPlaces(validationArgument);
-      var maxDecimals = Math.max(instanceDecimals, divisorDecimals);
-      var multiplier = Math.pow(10, maxDecimals);
-      if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) {
-        result.addError({
-          name: validationType,
-          argument: validationArgument,
-          message: errorMessage + JSON.stringify(validationArgument)
-        });
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
+      __setModuleDefault4(result, mod);
       return result;
     };
-    validators.multipleOf = function validateMultipleOf(instance, schema2, options, ctx) {
-      return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "multipleOf", "is not a multiple of (divisible by) ");
-    };
-    validators.divisibleBy = function validateDivisibleBy(instance, schema2, options, ctx) {
-      return validateMultipleOfOrDivisbleBy.call(this, instance, schema2, options, ctx, "divisibleBy", "is not divisible by (multiple of) ");
-    };
-    validators.required = function validateRequired(instance, schema2, options, ctx) {
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (instance === void 0 && schema2.required === true) {
-        result.addError({
-          name: "required",
-          message: "is required"
-        });
-      } else if (this.types.object(instance) && Array.isArray(schema2.required)) {
-        schema2.required.forEach(function(n) {
-          if (getEnumerableProperty(instance, n) === void 0) {
-            result.addError({
-              name: "required",
-              argument: n,
-              message: "requires property " + JSON.stringify(n)
-            });
-          }
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
         });
       }
-      return result;
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
     };
-    validators.pattern = function validatePattern(instance, schema2, options, ctx) {
-      if (!this.types.string(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var pattern = schema2.pattern;
-      try {
-        var regexp = new RegExp(pattern, "u");
-      } catch (_e) {
-        regexp = new RegExp(pattern);
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.RetryHelper = void 0;
+    var core14 = __importStar4(require_core());
+    var RetryHelper = class {
+      constructor(maxAttempts, minSeconds, maxSeconds) {
+        if (maxAttempts < 1) {
+          throw new Error("max attempts should be greater than or equal to 1");
+        }
+        this.maxAttempts = maxAttempts;
+        this.minSeconds = Math.floor(minSeconds);
+        this.maxSeconds = Math.floor(maxSeconds);
+        if (this.minSeconds > this.maxSeconds) {
+          throw new Error("min seconds should be less than or equal to max seconds");
+        }
       }
-      if (!instance.match(regexp)) {
-        result.addError({
-          name: "pattern",
-          argument: schema2.pattern,
-          message: "does not match pattern " + JSON.stringify(schema2.pattern.toString())
+      execute(action, isRetryable) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          let attempt = 1;
+          while (attempt < this.maxAttempts) {
+            try {
+              return yield action();
+            } catch (err) {
+              if (isRetryable && !isRetryable(err)) {
+                throw err;
+              }
+              core14.info(err.message);
+            }
+            const seconds = this.getSleepAmount();
+            core14.info(`Waiting ${seconds} seconds before trying again`);
+            yield this.sleep(seconds);
+            attempt++;
+          }
+          return yield action();
         });
       }
-      return result;
-    };
-    validators.format = function validateFormat(instance, schema2, options, ctx) {
-      if (instance === void 0) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!result.disableFormat && !helpers.isFormat(instance, schema2.format, this)) {
-        result.addError({
-          name: "format",
-          argument: schema2.format,
-          message: "does not conform to the " + JSON.stringify(schema2.format) + " format"
-        });
+      getSleepAmount() {
+        return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds;
       }
-      return result;
-    };
-    validators.minLength = function validateMinLength(instance, schema2, options, ctx) {
-      if (!this.types.string(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var hsp = instance.match(/[\uDC00-\uDFFF]/g);
-      var length = instance.length - (hsp ? hsp.length : 0);
-      if (!(length >= schema2.minLength)) {
-        result.addError({
-          name: "minLength",
-          argument: schema2.minLength,
-          message: "does not meet minimum length of " + schema2.minLength
+      sleep(seconds) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => setTimeout(resolve6, seconds * 1e3));
         });
       }
-      return result;
     };
-    validators.maxLength = function validateMaxLength(instance, schema2, options, ctx) {
-      if (!this.types.string(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var hsp = instance.match(/[\uDC00-\uDFFF]/g);
-      var length = instance.length - (hsp ? hsp.length : 0);
-      if (!(length <= schema2.maxLength)) {
-        result.addError({
-          name: "maxLength",
-          argument: schema2.maxLength,
-          message: "does not meet maximum length of " + schema2.maxLength
-        });
+    exports2.RetryHelper = RetryHelper;
+  }
+});
+
+// node_modules/@actions/tool-cache/lib/tool-cache.js
+var require_tool_cache = __commonJS({
+  "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) {
+    "use strict";
+    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      var desc = Object.getOwnPropertyDescriptor(m, k);
+      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+        desc = { enumerable: true, get: function() {
+          return m[k];
+        } };
       }
-      return result;
-    };
-    validators.minItems = function validateMinItems(instance, schema2, options, ctx) {
-      if (!this.types.array(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!(instance.length >= schema2.minItems)) {
-        result.addError({
-          name: "minItems",
-          argument: schema2.minItems,
-          message: "does not meet minimum length of " + schema2.minItems
-        });
+      Object.defineProperty(o, k2, desc);
+    }) : (function(o, m, k, k2) {
+      if (k2 === void 0) k2 = k;
+      o[k2] = m[k];
+    }));
+    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
+      Object.defineProperty(o, "default", { enumerable: true, value: v });
+    }) : function(o, v) {
+      o["default"] = v;
+    });
+    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
+      if (mod && mod.__esModule) return mod;
+      var result = {};
+      if (mod != null) {
+        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
       }
+      __setModuleDefault4(result, mod);
       return result;
     };
-    validators.maxItems = function validateMaxItems(instance, schema2, options, ctx) {
-      if (!this.types.array(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!(instance.length <= schema2.maxItems)) {
-        result.addError({
-          name: "maxItems",
-          argument: schema2.maxItems,
-          message: "does not meet maximum length of " + schema2.maxItems
+    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
+      function adopt(value) {
+        return value instanceof P ? value : new P(function(resolve6) {
+          resolve6(value);
         });
       }
-      return result;
-    };
-    function testArrays(v, i, a) {
-      var j, len = a.length;
-      for (j = i + 1, len; j < len; j++) {
-        if (helpers.deepCompareStrict(v, a[j])) {
-          return false;
+      return new (P || (P = Promise))(function(resolve6, reject) {
+        function fulfilled(value) {
+          try {
+            step(generator.next(value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function rejected(value) {
+          try {
+            step(generator["throw"](value));
+          } catch (e) {
+            reject(e);
+          }
+        }
+        function step(result) {
+          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
         }
+        step((generator = generator.apply(thisArg, _arguments || [])).next());
+      });
+    };
+    Object.defineProperty(exports2, "__esModule", { value: true });
+    exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0;
+    var core14 = __importStar4(require_core());
+    var io6 = __importStar4(require_io());
+    var crypto = __importStar4(require("crypto"));
+    var fs13 = __importStar4(require("fs"));
+    var mm = __importStar4(require_manifest());
+    var os3 = __importStar4(require("os"));
+    var path12 = __importStar4(require("path"));
+    var httpm = __importStar4(require_lib5());
+    var semver8 = __importStar4(require_semver2());
+    var stream2 = __importStar4(require("stream"));
+    var util = __importStar4(require("util"));
+    var assert_1 = require("assert");
+    var exec_1 = require_exec();
+    var retry_helper_1 = require_retry_helper();
+    var HTTPError2 = class extends Error {
+      constructor(httpStatusCode) {
+        super(`Unexpected HTTP response: ${httpStatusCode}`);
+        this.httpStatusCode = httpStatusCode;
+        Object.setPrototypeOf(this, new.target.prototype);
       }
-      return true;
+    };
+    exports2.HTTPError = HTTPError2;
+    var IS_WINDOWS = process.platform === "win32";
+    var IS_MAC = process.platform === "darwin";
+    var userAgent = "actions/tool-cache";
+    function downloadTool2(url2, dest, auth, headers) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        dest = dest || path12.join(_getTempDirectory(), crypto.randomUUID());
+        yield io6.mkdirP(path12.dirname(dest));
+        core14.debug(`Downloading ${url2}`);
+        core14.debug(`Destination ${dest}`);
+        const maxAttempts = 3;
+        const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10);
+        const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20);
+        const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds);
+        return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () {
+          return yield downloadToolAttempt(url2, dest || "", auth, headers);
+        }), (err) => {
+          if (err instanceof HTTPError2 && err.httpStatusCode) {
+            if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) {
+              return false;
+            }
+          }
+          return true;
+        });
+      });
     }
-    validators.uniqueItems = function validateUniqueItems(instance, schema2, options, ctx) {
-      if (schema2.uniqueItems !== true) return;
-      if (!this.types.array(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!instance.every(testArrays)) {
-        result.addError({
-          name: "uniqueItems",
-          message: "contains duplicate item"
+    exports2.downloadTool = downloadTool2;
+    function downloadToolAttempt(url2, dest, auth, headers) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        if (fs13.existsSync(dest)) {
+          throw new Error(`Destination file path ${dest} already exists`);
+        }
+        const http = new httpm.HttpClient(userAgent, [], {
+          allowRetries: false
         });
-      }
-      return result;
-    };
-    validators.dependencies = function validateDependencies(instance, schema2, options, ctx) {
-      if (!this.types.object(instance)) return;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      for (var property in schema2.dependencies) {
-        if (instance[property] === void 0) {
-          continue;
+        if (auth) {
+          core14.debug("set auth");
+          if (headers === void 0) {
+            headers = {};
+          }
+          headers.authorization = auth;
         }
-        var dep = schema2.dependencies[property];
-        var childContext = ctx.makeChild(dep, property);
-        if (typeof dep == "string") {
-          dep = [dep];
+        const response = yield http.get(url2, headers);
+        if (response.message.statusCode !== 200) {
+          const err = new HTTPError2(response.message.statusCode);
+          core14.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
+          throw err;
         }
-        if (Array.isArray(dep)) {
-          dep.forEach(function(prop) {
-            if (instance[prop] === void 0) {
-              result.addError({
-                // FIXME there's two different "dependencies" errors here with slightly different outputs
-                // Can we make these the same? Or should we create different error types?
-                name: "dependencies",
-                argument: childContext.propertyPath,
-                message: "property " + prop + " not found, required by " + childContext.propertyPath
-              });
+        const pipeline = util.promisify(stream2.pipeline);
+        const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message);
+        const readStream = responseMessageFactory();
+        let succeeded = false;
+        try {
+          yield pipeline(readStream, fs13.createWriteStream(dest));
+          core14.debug("download complete");
+          succeeded = true;
+          return dest;
+        } finally {
+          if (!succeeded) {
+            core14.debug("download failed");
+            try {
+              yield io6.rmRF(dest);
+            } catch (err) {
+              core14.debug(`Failed to delete '${dest}'. ${err.message}`);
             }
-          });
-        } else {
-          var res = this.validateSchema(instance, dep, options, childContext);
-          if (result.instance !== res.instance) result.instance = res.instance;
-          if (res && res.errors.length) {
-            result.addError({
-              name: "dependencies",
-              argument: childContext.propertyPath,
-              message: "does not meet dependency required by " + childContext.propertyPath
-            });
-            result.importErrors(res);
           }
         }
-      }
-      return result;
-    };
-    validators["enum"] = function validateEnum(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
-      }
-      if (!Array.isArray(schema2["enum"])) {
-        throw new SchemaError("enum expects an array", schema2);
-      }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!schema2["enum"].some(helpers.deepCompareStrict.bind(null, instance))) {
-        result.addError({
-          name: "enum",
-          argument: schema2["enum"],
-          message: "is not one of enum values: " + schema2["enum"].map(String).join(",")
-        });
-      }
-      return result;
-    };
-    validators["const"] = function validateEnum(instance, schema2, options, ctx) {
-      if (instance === void 0) {
-        return null;
-      }
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (!helpers.deepCompareStrict(schema2["const"], instance)) {
-        result.addError({
-          name: "const",
-          argument: schema2["const"],
-          message: "does not exactly match expected constant: " + schema2["const"]
-        });
-      }
-      return result;
-    };
-    validators.not = validators.disallow = function validateNot(instance, schema2, options, ctx) {
-      var self2 = this;
-      if (instance === void 0) return null;
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      var notTypes = schema2.not || schema2.disallow;
-      if (!notTypes) return null;
-      if (!Array.isArray(notTypes)) notTypes = [notTypes];
-      notTypes.forEach(function(type2) {
-        if (self2.testType(instance, schema2, options, ctx, type2)) {
-          var id = type2 && (type2.$id || type2.id);
-          var schemaId = id || type2;
-          result.addError({
-            name: "not",
-            argument: schemaId,
-            message: "is of prohibited type " + schemaId
-          });
+      });
+    }
+    function extract7z(file, dest, _7zPath) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS");
+        (0, assert_1.ok)(file, 'parameter "file" is required');
+        dest = yield _createExtractFolder(dest);
+        const originalCwd = process.cwd();
+        process.chdir(dest);
+        if (_7zPath) {
+          try {
+            const logLevel = core14.isDebug() ? "-bb1" : "-bb0";
+            const args = [
+              "x",
+              logLevel,
+              "-bd",
+              "-sccUTF-8",
+              file
+            ];
+            const options = {
+              silent: true
+            };
+            yield (0, exec_1.exec)(`"${_7zPath}"`, args, options);
+          } finally {
+            process.chdir(originalCwd);
+          }
+        } else {
+          const escapedScript = path12.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, "");
+          const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, "");
+          const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, "");
+          const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`;
+          const args = [
+            "-NoLogo",
+            "-Sta",
+            "-NoProfile",
+            "-NonInteractive",
+            "-ExecutionPolicy",
+            "Unrestricted",
+            "-Command",
+            command
+          ];
+          const options = {
+            silent: true
+          };
+          try {
+            const powershellPath = yield io6.which("powershell", true);
+            yield (0, exec_1.exec)(`"${powershellPath}"`, args, options);
+          } finally {
+            process.chdir(originalCwd);
+          }
         }
+        return dest;
       });
-      return result;
-    };
-    module2.exports = attribute;
-  }
-});
-
-// node_modules/jsonschema/lib/scan.js
-var require_scan = __commonJS({
-  "node_modules/jsonschema/lib/scan.js"(exports2, module2) {
-    "use strict";
-    var urilib = require("url");
-    var helpers = require_helpers3();
-    module2.exports.SchemaScanResult = SchemaScanResult;
-    function SchemaScanResult(found, ref) {
-      this.id = found;
-      this.ref = ref;
     }
-    module2.exports.scan = function scan(base, schema2) {
-      function scanSchema(baseuri, schema3) {
-        if (!schema3 || typeof schema3 != "object") return;
-        if (schema3.$ref) {
-          var resolvedUri = urilib.resolve(baseuri, schema3.$ref);
-          ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0;
-          return;
+    exports2.extract7z = extract7z;
+    function extractTar2(file, dest, flags = "xz") {
+      return __awaiter4(this, void 0, void 0, function* () {
+        if (!file) {
+          throw new Error("parameter 'file' is required");
         }
-        var id = schema3.$id || schema3.id;
-        var ourBase = id ? urilib.resolve(baseuri, id) : baseuri;
-        if (ourBase) {
-          if (ourBase.indexOf("#") < 0) ourBase += "#";
-          if (found[ourBase]) {
-            if (!helpers.deepCompareStrict(found[ourBase], schema3)) {
-              throw new Error("Schema <" + ourBase + "> already exists with different definition");
-            }
-            return found[ourBase];
-          }
-          found[ourBase] = schema3;
-          if (ourBase[ourBase.length - 1] == "#") {
-            found[ourBase.substring(0, ourBase.length - 1)] = schema3;
+        dest = yield _createExtractFolder(dest);
+        core14.debug("Checking tar --version");
+        let versionOutput = "";
+        yield (0, exec_1.exec)("tar --version", [], {
+          ignoreReturnCode: true,
+          silent: true,
+          listeners: {
+            stdout: (data) => versionOutput += data.toString(),
+            stderr: (data) => versionOutput += data.toString()
           }
+        });
+        core14.debug(versionOutput.trim());
+        const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR");
+        let args;
+        if (flags instanceof Array) {
+          args = flags;
+        } else {
+          args = [flags];
         }
-        scanArray(ourBase + "/items", Array.isArray(schema3.items) ? schema3.items : [schema3.items]);
-        scanArray(ourBase + "/extends", Array.isArray(schema3.extends) ? schema3.extends : [schema3.extends]);
-        scanSchema(ourBase + "/additionalItems", schema3.additionalItems);
-        scanObject(ourBase + "/properties", schema3.properties);
-        scanSchema(ourBase + "/additionalProperties", schema3.additionalProperties);
-        scanObject(ourBase + "/definitions", schema3.definitions);
-        scanObject(ourBase + "/patternProperties", schema3.patternProperties);
-        scanObject(ourBase + "/dependencies", schema3.dependencies);
-        scanArray(ourBase + "/disallow", schema3.disallow);
-        scanArray(ourBase + "/allOf", schema3.allOf);
-        scanArray(ourBase + "/anyOf", schema3.anyOf);
-        scanArray(ourBase + "/oneOf", schema3.oneOf);
-        scanSchema(ourBase + "/not", schema3.not);
-      }
-      function scanArray(baseuri, schemas) {
-        if (!Array.isArray(schemas)) return;
-        for (var i = 0; i < schemas.length; i++) {
-          scanSchema(baseuri + "/" + i, schemas[i]);
+        if (core14.isDebug() && !flags.includes("v")) {
+          args.push("-v");
         }
-      }
-      function scanObject(baseuri, schemas) {
-        if (!schemas || typeof schemas != "object") return;
-        for (var p in schemas) {
-          scanSchema(baseuri + "/" + p, schemas[p]);
+        let destArg = dest;
+        let fileArg = file;
+        if (IS_WINDOWS && isGnuTar) {
+          args.push("--force-local");
+          destArg = dest.replace(/\\/g, "/");
+          fileArg = file.replace(/\\/g, "/");
         }
-      }
-      var found = {};
-      var ref = {};
-      scanSchema(base, schema2);
-      return new SchemaScanResult(found, ref);
-    };
-  }
-});
-
-// node_modules/jsonschema/lib/validator.js
-var require_validator2 = __commonJS({
-  "node_modules/jsonschema/lib/validator.js"(exports2, module2) {
-    "use strict";
-    var urilib = require("url");
-    var attribute = require_attribute();
-    var helpers = require_helpers3();
-    var scanSchema = require_scan().scan;
-    var ValidatorResult = helpers.ValidatorResult;
-    var ValidatorResultError = helpers.ValidatorResultError;
-    var SchemaError = helpers.SchemaError;
-    var SchemaContext = helpers.SchemaContext;
-    var anonymousBase = "/";
-    var Validator3 = function Validator4() {
-      this.customFormats = Object.create(Validator4.prototype.customFormats);
-      this.schemas = {};
-      this.unresolvedRefs = [];
-      this.types = Object.create(types);
-      this.attributes = Object.create(attribute.validators);
-    };
-    Validator3.prototype.customFormats = {};
-    Validator3.prototype.schemas = null;
-    Validator3.prototype.types = null;
-    Validator3.prototype.attributes = null;
-    Validator3.prototype.unresolvedRefs = null;
-    Validator3.prototype.addSchema = function addSchema(schema2, base) {
-      var self2 = this;
-      if (!schema2) {
-        return null;
-      }
-      var scan = scanSchema(base || anonymousBase, schema2);
-      var ourUri = base || schema2.$id || schema2.id;
-      for (var uri in scan.id) {
-        this.schemas[uri] = scan.id[uri];
-      }
-      for (var uri in scan.ref) {
-        this.unresolvedRefs.push(uri);
-      }
-      this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) {
-        return typeof self2.schemas[uri2] === "undefined";
+        if (isGnuTar) {
+          args.push("--warning=no-unknown-keyword");
+          args.push("--overwrite");
+        }
+        args.push("-C", destArg, "-f", fileArg);
+        yield (0, exec_1.exec)(`tar`, args);
+        return dest;
       });
-      return this.schemas[ourUri];
-    };
-    Validator3.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) {
-      if (!Array.isArray(schemas)) return;
-      for (var i = 0; i < schemas.length; i++) {
-        this.addSubSchema(baseuri, schemas[i]);
-      }
-    };
-    Validator3.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) {
-      if (!schemas || typeof schemas != "object") return;
-      for (var p in schemas) {
-        this.addSubSchema(baseuri, schemas[p]);
-      }
-    };
-    Validator3.prototype.setSchemas = function setSchemas(schemas) {
-      this.schemas = schemas;
-    };
-    Validator3.prototype.getSchema = function getSchema(urn) {
-      return this.schemas[urn];
-    };
-    Validator3.prototype.validate = function validate(instance, schema2, options, ctx) {
-      if (typeof schema2 !== "boolean" && typeof schema2 !== "object" || schema2 === null) {
-        throw new SchemaError("Expected `schema` to be an object or boolean");
-      }
-      if (!options) {
-        options = {};
-      }
-      var id = schema2.$id || schema2.id;
-      var base = urilib.resolve(options.base || anonymousBase, id || "");
-      if (!ctx) {
-        ctx = new SchemaContext(schema2, options, [], base, Object.create(this.schemas));
-        if (!ctx.schemas[base]) {
-          ctx.schemas[base] = schema2;
+    }
+    exports2.extractTar = extractTar2;
+    function extractXar(file, dest, flags = []) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS");
+        (0, assert_1.ok)(file, 'parameter "file" is required');
+        dest = yield _createExtractFolder(dest);
+        let args;
+        if (flags instanceof Array) {
+          args = flags;
+        } else {
+          args = [flags];
         }
-        var found = scanSchema(base, schema2);
-        for (var n in found.id) {
-          var sch = found.id[n];
-          ctx.schemas[n] = sch;
+        args.push("-x", "-C", dest, "-f", file);
+        if (core14.isDebug()) {
+          args.push("-v");
         }
-      }
-      if (options.required && instance === void 0) {
-        var result = new ValidatorResult(instance, schema2, options, ctx);
-        result.addError("is required, but is undefined");
-        return result;
-      }
-      var result = this.validateSchema(instance, schema2, options, ctx);
-      if (!result) {
-        throw new Error("Result undefined");
-      } else if (options.throwAll && result.errors.length) {
-        throw new ValidatorResultError(result);
-      }
-      return result;
-    };
-    function shouldResolve(schema2) {
-      var ref = typeof schema2 === "string" ? schema2 : schema2.$ref;
-      if (typeof ref == "string") return ref;
-      return false;
+        const xarPath = yield io6.which("xar", true);
+        yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args));
+        return dest;
+      });
     }
-    Validator3.prototype.validateSchema = function validateSchema(instance, schema2, options, ctx) {
-      var result = new ValidatorResult(instance, schema2, options, ctx);
-      if (typeof schema2 === "boolean") {
-        if (schema2 === true) {
-          schema2 = {};
-        } else if (schema2 === false) {
-          schema2 = { type: [] };
+    exports2.extractXar = extractXar;
+    function extractZip(file, dest) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        if (!file) {
+          throw new Error("parameter 'file' is required");
         }
-      } else if (!schema2) {
-        throw new Error("schema is undefined");
-      }
-      if (schema2["extends"]) {
-        if (Array.isArray(schema2["extends"])) {
-          var schemaobj = { schema: schema2, ctx };
-          schema2["extends"].forEach(this.schemaTraverser.bind(this, schemaobj));
-          schema2 = schemaobj.schema;
-          schemaobj.schema = null;
-          schemaobj.ctx = null;
-          schemaobj = null;
+        dest = yield _createExtractFolder(dest);
+        if (IS_WINDOWS) {
+          yield extractZipWin(file, dest);
         } else {
-          schema2 = helpers.deepMerge(schema2, this.superResolve(schema2["extends"], ctx));
+          yield extractZipNix(file, dest);
         }
-      }
-      var switchSchema = shouldResolve(schema2);
-      if (switchSchema) {
-        var resolved = this.resolve(schema2, switchSchema, ctx);
-        var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas);
-        return this.validateSchema(instance, resolved.subschema, options, subctx);
-      }
-      var skipAttributes = options && options.skipAttributes || [];
-      for (var key in schema2) {
-        if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) {
-          var validatorErr = null;
-          var validator = this.attributes[key];
-          if (validator) {
-            validatorErr = validator.call(this, instance, schema2, options, ctx);
-          } else if (options.allowUnknownAttributes === false) {
-            throw new SchemaError("Unsupported attribute: " + key, schema2);
-          }
-          if (validatorErr) {
-            result.importErrors(validatorErr);
-          }
+        return dest;
+      });
+    }
+    exports2.extractZip = extractZip;
+    function extractZipWin(file, dest) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, "");
+        const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, "");
+        const pwshPath = yield io6.which("pwsh", false);
+        if (pwshPath) {
+          const pwshCommand = [
+            `$ErrorActionPreference = 'Stop' ;`,
+            `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`,
+            `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`,
+            `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;`
+          ].join(" ");
+          const args = [
+            "-NoLogo",
+            "-NoProfile",
+            "-NonInteractive",
+            "-ExecutionPolicy",
+            "Unrestricted",
+            "-Command",
+            pwshCommand
+          ];
+          core14.debug(`Using pwsh at path: ${pwshPath}`);
+          yield (0, exec_1.exec)(`"${pwshPath}"`, args);
+        } else {
+          const powershellCommand = [
+            `$ErrorActionPreference = 'Stop' ;`,
+            `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`,
+            `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`,
+            `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`
+          ].join(" ");
+          const args = [
+            "-NoLogo",
+            "-Sta",
+            "-NoProfile",
+            "-NonInteractive",
+            "-ExecutionPolicy",
+            "Unrestricted",
+            "-Command",
+            powershellCommand
+          ];
+          const powershellPath = yield io6.which("powershell", true);
+          core14.debug(`Using powershell at path: ${powershellPath}`);
+          yield (0, exec_1.exec)(`"${powershellPath}"`, args);
         }
+      });
+    }
+    function extractZipNix(file, dest) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const unzipPath = yield io6.which("unzip", true);
+        const args = [file];
+        if (!core14.isDebug()) {
+          args.unshift("-q");
+        }
+        args.unshift("-o");
+        yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest });
+      });
+    }
+    function cacheDir(sourceDir, tool, version, arch2) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        version = semver8.clean(version) || version;
+        arch2 = arch2 || os3.arch();
+        core14.debug(`Caching tool ${tool} ${version} ${arch2}`);
+        core14.debug(`source dir: ${sourceDir}`);
+        if (!fs13.statSync(sourceDir).isDirectory()) {
+          throw new Error("sourceDir is not a directory");
+        }
+        const destPath = yield _createToolPath(tool, version, arch2);
+        for (const itemName of fs13.readdirSync(sourceDir)) {
+          const s = path12.join(sourceDir, itemName);
+          yield io6.cp(s, destPath, { recursive: true });
+        }
+        _completeToolPath(tool, version, arch2);
+        return destPath;
+      });
+    }
+    exports2.cacheDir = cacheDir;
+    function cacheFile(sourceFile, targetFile, tool, version, arch2) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        version = semver8.clean(version) || version;
+        arch2 = arch2 || os3.arch();
+        core14.debug(`Caching tool ${tool} ${version} ${arch2}`);
+        core14.debug(`source file: ${sourceFile}`);
+        if (!fs13.statSync(sourceFile).isFile()) {
+          throw new Error("sourceFile is not a file");
+        }
+        const destFolder = yield _createToolPath(tool, version, arch2);
+        const destPath = path12.join(destFolder, targetFile);
+        core14.debug(`destination file ${destPath}`);
+        yield io6.cp(sourceFile, destPath);
+        _completeToolPath(tool, version, arch2);
+        return destFolder;
+      });
+    }
+    exports2.cacheFile = cacheFile;
+    function find2(toolName, versionSpec, arch2) {
+      if (!toolName) {
+        throw new Error("toolName parameter is required");
       }
-      if (typeof options.rewrite == "function") {
-        var value = options.rewrite.call(this, instance, schema2, options, ctx);
-        result.instance = value;
-      }
-      return result;
-    };
-    Validator3.prototype.schemaTraverser = function schemaTraverser(schemaobj, s) {
-      schemaobj.schema = helpers.deepMerge(schemaobj.schema, this.superResolve(s, schemaobj.ctx));
-    };
-    Validator3.prototype.superResolve = function superResolve(schema2, ctx) {
-      var ref = shouldResolve(schema2);
-      if (ref) {
-        return this.resolve(schema2, ref, ctx).subschema;
-      }
-      return schema2;
-    };
-    Validator3.prototype.resolve = function resolve6(schema2, switchSchema, ctx) {
-      switchSchema = ctx.resolve(switchSchema);
-      if (ctx.schemas[switchSchema]) {
-        return { subschema: ctx.schemas[switchSchema], switchSchema };
-      }
-      var parsed = urilib.parse(switchSchema);
-      var fragment = parsed && parsed.hash;
-      var document2 = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length);
-      if (!document2 || !ctx.schemas[document2]) {
-        throw new SchemaError("no such schema <" + switchSchema + ">", schema2);
-      }
-      var subschema = helpers.objectGetPath(ctx.schemas[document2], fragment.substr(1));
-      if (subschema === void 0) {
-        throw new SchemaError("no such schema " + fragment + " located in <" + document2 + ">", schema2);
-      }
-      return { subschema, switchSchema };
-    };
-    Validator3.prototype.testType = function validateType(instance, schema2, options, ctx, type2) {
-      if (type2 === void 0) {
-        return;
-      } else if (type2 === null) {
-        throw new SchemaError('Unexpected null in "type" keyword');
-      }
-      if (typeof this.types[type2] == "function") {
-        return this.types[type2].call(this, instance);
-      }
-      if (type2 && typeof type2 == "object") {
-        var res = this.validateSchema(instance, type2, options, ctx);
-        return res === void 0 || !(res && res.errors.length);
+      if (!versionSpec) {
+        throw new Error("versionSpec parameter is required");
       }
-      return true;
-    };
-    var types = Validator3.prototype.types = {};
-    types.string = function testString(instance) {
-      return typeof instance == "string";
-    };
-    types.number = function testNumber(instance) {
-      return typeof instance == "number" && isFinite(instance);
-    };
-    types.integer = function testInteger(instance) {
-      return typeof instance == "number" && instance % 1 === 0;
-    };
-    types.boolean = function testBoolean(instance) {
-      return typeof instance == "boolean";
-    };
-    types.array = function testArray(instance) {
-      return Array.isArray(instance);
-    };
-    types["null"] = function testNull(instance) {
-      return instance === null;
-    };
-    types.date = function testDate(instance) {
-      return instance instanceof Date;
-    };
-    types.any = function testAny(instance) {
-      return true;
-    };
-    types.object = function testObject(instance) {
-      return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date);
-    };
-    module2.exports = Validator3;
-  }
-});
-
-// node_modules/jsonschema/lib/index.js
-var require_lib2 = __commonJS({
-  "node_modules/jsonschema/lib/index.js"(exports2, module2) {
-    "use strict";
-    var Validator3 = module2.exports.Validator = require_validator2();
-    module2.exports.ValidatorResult = require_helpers3().ValidatorResult;
-    module2.exports.ValidatorResultError = require_helpers3().ValidatorResultError;
-    module2.exports.ValidationError = require_helpers3().ValidationError;
-    module2.exports.SchemaError = require_helpers3().SchemaError;
-    module2.exports.SchemaScanResult = require_scan().SchemaScanResult;
-    module2.exports.scan = require_scan().scan;
-    module2.exports.validate = function(instance, schema2, options) {
-      var v = new Validator3();
-      return v.validate(instance, schema2, options);
-    };
-  }
-});
-
-// node_modules/@actions/tool-cache/lib/manifest.js
-var require_manifest = __commonJS({
-  "node_modules/@actions/tool-cache/lib/manifest.js"(exports2, module2) {
-    "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
+      arch2 = arch2 || os3.arch();
+      if (!isExplicitVersion(versionSpec)) {
+        const localVersions = findAllVersions2(toolName, arch2);
+        const match = evaluateVersions(localVersions, versionSpec);
+        versionSpec = match;
       }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
+      let toolPath = "";
+      if (versionSpec) {
+        versionSpec = semver8.clean(versionSpec) || "";
+        const cachePath = path12.join(_getCacheDirectory(), toolName, versionSpec, arch2);
+        core14.debug(`checking cache: ${cachePath}`);
+        if (fs13.existsSync(cachePath) && fs13.existsSync(`${cachePath}.complete`)) {
+          core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`);
+          toolPath = cachePath;
+        } else {
+          core14.debug("not found");
+        }
       }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
-        });
+      return toolPath;
+    }
+    exports2.find = find2;
+    function findAllVersions2(toolName, arch2) {
+      const versions = [];
+      arch2 = arch2 || os3.arch();
+      const toolPath = path12.join(_getCacheDirectory(), toolName);
+      if (fs13.existsSync(toolPath)) {
+        const children = fs13.readdirSync(toolPath);
+        for (const child of children) {
+          if (isExplicitVersion(child)) {
+            const fullPath = path12.join(toolPath, child, arch2 || "");
+            if (fs13.existsSync(fullPath) && fs13.existsSync(`${fullPath}.complete`)) {
+              versions.push(child);
+            }
+          }
+        }
       }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
+      return versions;
+    }
+    exports2.findAllVersions = findAllVersions2;
+    function getManifestFromRepo(owner, repo, auth, branch = "master") {
+      return __awaiter4(this, void 0, void 0, function* () {
+        let releases = [];
+        const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`;
+        const http = new httpm.HttpClient("tool-cache");
+        const headers = {};
+        if (auth) {
+          core14.debug("set auth");
+          headers.authorization = auth;
+        }
+        const response = yield http.getJson(treeUrl, headers);
+        if (!response.result) {
+          return releases;
+        }
+        let manifestUrl = "";
+        for (const item of response.result.tree) {
+          if (item.path === "versions-manifest.json") {
+            manifestUrl = item.url;
+            break;
           }
         }
-        function rejected(value) {
+        headers["accept"] = "application/vnd.github.VERSION.raw";
+        let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody();
+        if (versionsRaw) {
+          versionsRaw = versionsRaw.replace(/^\uFEFF/, "");
           try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
+            releases = JSON.parse(versionsRaw);
+          } catch (_a) {
+            core14.debug("Invalid json");
           }
         }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
-        }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
+        return releases;
       });
-    };
-    Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2._readLinuxVersionFile = exports2._getOsVersion = exports2._findMatch = void 0;
-    var semver8 = __importStar4(require_semver2());
-    var core_1 = require_core();
-    var os3 = require("os");
-    var cp = require("child_process");
-    var fs13 = require("fs");
-    function _findMatch(versionSpec, stable, candidates, archFilter) {
+    }
+    exports2.getManifestFromRepo = getManifestFromRepo;
+    function findFromManifest(versionSpec, stable, manifest, archFilter = os3.arch()) {
       return __awaiter4(this, void 0, void 0, function* () {
-        const platFilter = os3.platform();
-        let result;
-        let match;
-        let file;
-        for (const candidate of candidates) {
-          const version = candidate.version;
-          (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`);
-          if (semver8.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) {
-            file = candidate.files.find((item) => {
-              (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`);
-              let chk = item.arch === archFilter && item.platform === platFilter;
-              if (chk && item.platform_version) {
-                const osVersion = module2.exports._getOsVersion();
-                if (osVersion === item.platform_version) {
-                  chk = true;
-                } else {
-                  chk = semver8.satisfies(osVersion, item.platform_version);
-                }
-              }
-              return chk;
-            });
-            if (file) {
-              (0, core_1.debug)(`matched ${candidate.version}`);
-              match = candidate;
-              break;
-            }
-          }
-        }
-        if (match && file) {
-          result = Object.assign({}, match);
-          result.files = [file];
+        const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter);
+        return match;
+      });
+    }
+    exports2.findFromManifest = findFromManifest;
+    function _createExtractFolder(dest) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        if (!dest) {
+          dest = path12.join(_getTempDirectory(), crypto.randomUUID());
         }
-        return result;
+        yield io6.mkdirP(dest);
+        return dest;
       });
     }
-    exports2._findMatch = _findMatch;
-    function _getOsVersion() {
-      const plat = os3.platform();
+    function _createToolPath(tool, version, arch2) {
+      return __awaiter4(this, void 0, void 0, function* () {
+        const folderPath = path12.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || "");
+        core14.debug(`destination ${folderPath}`);
+        const markerPath = `${folderPath}.complete`;
+        yield io6.rmRF(folderPath);
+        yield io6.rmRF(markerPath);
+        yield io6.mkdirP(folderPath);
+        return folderPath;
+      });
+    }
+    function _completeToolPath(tool, version, arch2) {
+      const folderPath = path12.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || "");
+      const markerPath = `${folderPath}.complete`;
+      fs13.writeFileSync(markerPath, "");
+      core14.debug("finished caching tool");
+    }
+    function isExplicitVersion(versionSpec) {
+      const c = semver8.clean(versionSpec) || "";
+      core14.debug(`isExplicit: ${c}`);
+      const valid3 = semver8.valid(c) != null;
+      core14.debug(`explicit? ${valid3}`);
+      return valid3;
+    }
+    exports2.isExplicitVersion = isExplicitVersion;
+    function evaluateVersions(versions, versionSpec) {
       let version = "";
-      if (plat === "darwin") {
-        version = cp.execSync("sw_vers -productVersion").toString();
-      } else if (plat === "linux") {
-        const lsbContents = module2.exports._readLinuxVersionFile();
-        if (lsbContents) {
-          const lines = lsbContents.split("\n");
-          for (const line of lines) {
-            const parts = line.split("=");
-            if (parts.length === 2 && (parts[0].trim() === "VERSION_ID" || parts[0].trim() === "DISTRIB_RELEASE")) {
-              version = parts[1].trim().replace(/^"/, "").replace(/"$/, "");
-              break;
-            }
-          }
+      core14.debug(`evaluating ${versions.length} versions`);
+      versions = versions.sort((a, b) => {
+        if (semver8.gt(a, b)) {
+          return 1;
+        }
+        return -1;
+      });
+      for (let i = versions.length - 1; i >= 0; i--) {
+        const potential = versions[i];
+        const satisfied = semver8.satisfies(potential, versionSpec);
+        if (satisfied) {
+          version = potential;
+          break;
         }
       }
+      if (version) {
+        core14.debug(`matched: ${version}`);
+      } else {
+        core14.debug("match not found");
+      }
       return version;
     }
-    exports2._getOsVersion = _getOsVersion;
-    function _readLinuxVersionFile() {
-      const lsbReleaseFile = "/etc/lsb-release";
-      const osReleaseFile = "/etc/os-release";
-      let contents = "";
-      if (fs13.existsSync(lsbReleaseFile)) {
-        contents = fs13.readFileSync(lsbReleaseFile).toString();
-      } else if (fs13.existsSync(osReleaseFile)) {
-        contents = fs13.readFileSync(osReleaseFile).toString();
-      }
-      return contents;
+    exports2.evaluateVersions = evaluateVersions;
+    function _getCacheDirectory() {
+      const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || "";
+      (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined");
+      return cacheDirectory;
+    }
+    function _getTempDirectory() {
+      const tempDirectory = process.env["RUNNER_TEMP"] || "";
+      (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined");
+      return tempDirectory;
+    }
+    function _getGlobal(key, defaultValue) {
+      const value = global[key];
+      return value !== void 0 ? value : defaultValue;
+    }
+    function _unique(values) {
+      return Array.from(new Set(values));
     }
-    exports2._readLinuxVersionFile = _readLinuxVersionFile;
   }
 });
 
-// node_modules/@actions/tool-cache/lib/retry-helper.js
-var require_retry_helper = __commonJS({
-  "node_modules/@actions/tool-cache/lib/retry-helper.js"(exports2) {
+// node_modules/fast-deep-equal/index.js
+var require_fast_deep_equal = __commonJS({
+  "node_modules/fast-deep-equal/index.js"(exports2, module2) {
     "use strict";
-    var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      var desc = Object.getOwnPropertyDescriptor(m, k);
-      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-        desc = { enumerable: true, get: function() {
-          return m[k];
-        } };
-      }
-      Object.defineProperty(o, k2, desc);
-    }) : (function(o, m, k, k2) {
-      if (k2 === void 0) k2 = k;
-      o[k2] = m[k];
-    }));
-    var __setModuleDefault4 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
-      Object.defineProperty(o, "default", { enumerable: true, value: v });
-    }) : function(o, v) {
-      o["default"] = v;
-    });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
-    var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
-      function adopt(value) {
-        return value instanceof P ? value : new P(function(resolve6) {
-          resolve6(value);
-        });
-      }
-      return new (P || (P = Promise))(function(resolve6, reject) {
-        function fulfilled(value) {
-          try {
-            step(generator.next(value));
-          } catch (e) {
-            reject(e);
-          }
-        }
-        function rejected(value) {
-          try {
-            step(generator["throw"](value));
-          } catch (e) {
-            reject(e);
-          }
+    module2.exports = function equal(a, b) {
+      if (a === b) return true;
+      if (a && b && typeof a == "object" && typeof b == "object") {
+        if (a.constructor !== b.constructor) return false;
+        var length, i, keys;
+        if (Array.isArray(a)) {
+          length = a.length;
+          if (length != b.length) return false;
+          for (i = length; i-- !== 0; )
+            if (!equal(a[i], b[i])) return false;
+          return true;
         }
-        function step(result) {
-          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
+        if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
+        if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
+        if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
+        keys = Object.keys(a);
+        length = keys.length;
+        if (length !== Object.keys(b).length) return false;
+        for (i = length; i-- !== 0; )
+          if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
+        for (i = length; i-- !== 0; ) {
+          var key = keys[i];
+          if (!equal(a[key], b[key])) return false;
         }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-      });
+        return true;
+      }
+      return a !== a && b !== b;
     };
+  }
+});
+
+// node_modules/@actions/http-client/lib/proxy.js
+var require_proxy5 = __commonJS({
+  "node_modules/@actions/http-client/lib/proxy.js"(exports2) {
+    "use strict";
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.RetryHelper = void 0;
-    var core14 = __importStar4(require_core());
-    var RetryHelper = class {
-      constructor(maxAttempts, minSeconds, maxSeconds) {
-        if (maxAttempts < 1) {
-          throw new Error("max attempts should be greater than or equal to 1");
+    exports2.getProxyUrl = getProxyUrl;
+    exports2.checkBypass = checkBypass;
+    function getProxyUrl(reqUrl) {
+      const usingSsl = reqUrl.protocol === "https:";
+      if (checkBypass(reqUrl)) {
+        return void 0;
+      }
+      const proxyVar = (() => {
+        if (usingSsl) {
+          return process.env["https_proxy"] || process.env["HTTPS_PROXY"];
+        } else {
+          return process.env["http_proxy"] || process.env["HTTP_PROXY"];
         }
-        this.maxAttempts = maxAttempts;
-        this.minSeconds = Math.floor(minSeconds);
-        this.maxSeconds = Math.floor(maxSeconds);
-        if (this.minSeconds > this.maxSeconds) {
-          throw new Error("min seconds should be less than or equal to max seconds");
+      })();
+      if (proxyVar) {
+        try {
+          return new DecodedURL(proxyVar);
+        } catch (_a) {
+          if (!proxyVar.startsWith("http://") && !proxyVar.startsWith("https://"))
+            return new DecodedURL(`http://${proxyVar}`);
+        }
+      } else {
+        return void 0;
+      }
+    }
+    function checkBypass(reqUrl) {
+      if (!reqUrl.hostname) {
+        return false;
+      }
+      const reqHost = reqUrl.hostname;
+      if (isLoopbackAddress(reqHost)) {
+        return true;
+      }
+      const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || "";
+      if (!noProxy) {
+        return false;
+      }
+      let reqPort;
+      if (reqUrl.port) {
+        reqPort = Number(reqUrl.port);
+      } else if (reqUrl.protocol === "http:") {
+        reqPort = 80;
+      } else if (reqUrl.protocol === "https:") {
+        reqPort = 443;
+      }
+      const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+      if (typeof reqPort === "number") {
+        upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
+      }
+      for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) {
+        if (upperNoProxyItem === "*" || upperReqHosts.some((x) => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || upperNoProxyItem.startsWith(".") && x.endsWith(`${upperNoProxyItem}`))) {
+          return true;
         }
       }
-      execute(action, isRetryable) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          let attempt = 1;
-          while (attempt < this.maxAttempts) {
-            try {
-              return yield action();
-            } catch (err) {
-              if (isRetryable && !isRetryable(err)) {
-                throw err;
-              }
-              core14.info(err.message);
-            }
-            const seconds = this.getSleepAmount();
-            core14.info(`Waiting ${seconds} seconds before trying again`);
-            yield this.sleep(seconds);
-            attempt++;
-          }
-          return yield action();
-        });
+      return false;
+    }
+    function isLoopbackAddress(host) {
+      const hostLower = host.toLowerCase();
+      return hostLower === "localhost" || hostLower.startsWith("127.") || hostLower.startsWith("[::1]") || hostLower.startsWith("[0:0:0:0:0:0:0:1]");
+    }
+    var DecodedURL = class extends URL {
+      constructor(url2, base) {
+        super(url2, base);
+        this._decodedUsername = decodeURIComponent(super.username);
+        this._decodedPassword = decodeURIComponent(super.password);
       }
-      getSleepAmount() {
-        return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds;
+      get username() {
+        return this._decodedUsername;
       }
-      sleep(seconds) {
-        return __awaiter4(this, void 0, void 0, function* () {
-          return new Promise((resolve6) => setTimeout(resolve6, seconds * 1e3));
-        });
+      get password() {
+        return this._decodedPassword;
       }
     };
-    exports2.RetryHelper = RetryHelper;
   }
 });
 
-// node_modules/@actions/tool-cache/lib/tool-cache.js
-var require_tool_cache = __commonJS({
-  "node_modules/@actions/tool-cache/lib/tool-cache.js"(exports2) {
+// node_modules/@actions/http-client/lib/index.js
+var require_lib6 = __commonJS({
+  "node_modules/@actions/http-client/lib/index.js"(exports2) {
     "use strict";
     var __createBinding4 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
       if (k2 === void 0) k2 = k;
@@ -74975,15 +77842,25 @@ var require_tool_cache = __commonJS({
     }) : function(o, v) {
       o["default"] = v;
     });
-    var __importStar4 = exports2 && exports2.__importStar || function(mod) {
-      if (mod && mod.__esModule) return mod;
-      var result = {};
-      if (mod != null) {
-        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding4(result, mod, k);
-      }
-      __setModuleDefault4(result, mod);
-      return result;
-    };
+    var __importStar4 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
+      var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function(o2) {
+          var ar = [];
+          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
+          return ar;
+        };
+        return ownKeys(o);
+      };
+      return function(mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) {
+          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding4(result, mod, k[i]);
+        }
+        __setModuleDefault4(result, mod);
+        return result;
+      };
+    })();
     var __awaiter4 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
       function adopt(value) {
         return value instanceof P ? value : new P(function(resolve6) {
@@ -75012,523 +77889,616 @@ var require_tool_cache = __commonJS({
       });
     };
     Object.defineProperty(exports2, "__esModule", { value: true });
-    exports2.evaluateVersions = exports2.isExplicitVersion = exports2.findFromManifest = exports2.getManifestFromRepo = exports2.findAllVersions = exports2.find = exports2.cacheFile = exports2.cacheDir = exports2.extractZip = exports2.extractXar = exports2.extractTar = exports2.extract7z = exports2.downloadTool = exports2.HTTPError = void 0;
-    var core14 = __importStar4(require_core());
-    var io6 = __importStar4(require_io());
-    var crypto = __importStar4(require("crypto"));
-    var fs13 = __importStar4(require("fs"));
-    var mm = __importStar4(require_manifest());
-    var os3 = __importStar4(require("os"));
-    var path12 = __importStar4(require("path"));
-    var httpm = __importStar4(require_lib());
-    var semver8 = __importStar4(require_semver2());
-    var stream2 = __importStar4(require("stream"));
-    var util = __importStar4(require("util"));
-    var assert_1 = require("assert");
-    var exec_1 = require_exec();
-    var retry_helper_1 = require_retry_helper();
-    var HTTPError2 = class extends Error {
-      constructor(httpStatusCode) {
-        super(`Unexpected HTTP response: ${httpStatusCode}`);
-        this.httpStatusCode = httpStatusCode;
-        Object.setPrototypeOf(this, new.target.prototype);
+    exports2.HttpClient = exports2.HttpClientResponse = exports2.HttpClientError = exports2.MediaTypes = exports2.Headers = exports2.HttpCodes = void 0;
+    exports2.getProxyUrl = getProxyUrl;
+    exports2.isHttps = isHttps;
+    var http = __importStar4(require("http"));
+    var https2 = __importStar4(require("https"));
+    var pm = __importStar4(require_proxy5());
+    var tunnel = __importStar4(require_tunnel2());
+    var undici_1 = require_undici();
+    var HttpCodes;
+    (function(HttpCodes2) {
+      HttpCodes2[HttpCodes2["OK"] = 200] = "OK";
+      HttpCodes2[HttpCodes2["MultipleChoices"] = 300] = "MultipleChoices";
+      HttpCodes2[HttpCodes2["MovedPermanently"] = 301] = "MovedPermanently";
+      HttpCodes2[HttpCodes2["ResourceMoved"] = 302] = "ResourceMoved";
+      HttpCodes2[HttpCodes2["SeeOther"] = 303] = "SeeOther";
+      HttpCodes2[HttpCodes2["NotModified"] = 304] = "NotModified";
+      HttpCodes2[HttpCodes2["UseProxy"] = 305] = "UseProxy";
+      HttpCodes2[HttpCodes2["SwitchProxy"] = 306] = "SwitchProxy";
+      HttpCodes2[HttpCodes2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+      HttpCodes2[HttpCodes2["PermanentRedirect"] = 308] = "PermanentRedirect";
+      HttpCodes2[HttpCodes2["BadRequest"] = 400] = "BadRequest";
+      HttpCodes2[HttpCodes2["Unauthorized"] = 401] = "Unauthorized";
+      HttpCodes2[HttpCodes2["PaymentRequired"] = 402] = "PaymentRequired";
+      HttpCodes2[HttpCodes2["Forbidden"] = 403] = "Forbidden";
+      HttpCodes2[HttpCodes2["NotFound"] = 404] = "NotFound";
+      HttpCodes2[HttpCodes2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+      HttpCodes2[HttpCodes2["NotAcceptable"] = 406] = "NotAcceptable";
+      HttpCodes2[HttpCodes2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+      HttpCodes2[HttpCodes2["RequestTimeout"] = 408] = "RequestTimeout";
+      HttpCodes2[HttpCodes2["Conflict"] = 409] = "Conflict";
+      HttpCodes2[HttpCodes2["Gone"] = 410] = "Gone";
+      HttpCodes2[HttpCodes2["TooManyRequests"] = 429] = "TooManyRequests";
+      HttpCodes2[HttpCodes2["InternalServerError"] = 500] = "InternalServerError";
+      HttpCodes2[HttpCodes2["NotImplemented"] = 501] = "NotImplemented";
+      HttpCodes2[HttpCodes2["BadGateway"] = 502] = "BadGateway";
+      HttpCodes2[HttpCodes2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+      HttpCodes2[HttpCodes2["GatewayTimeout"] = 504] = "GatewayTimeout";
+    })(HttpCodes || (exports2.HttpCodes = HttpCodes = {}));
+    var Headers;
+    (function(Headers2) {
+      Headers2["Accept"] = "accept";
+      Headers2["ContentType"] = "content-type";
+    })(Headers || (exports2.Headers = Headers = {}));
+    var MediaTypes;
+    (function(MediaTypes2) {
+      MediaTypes2["ApplicationJson"] = "application/json";
+    })(MediaTypes || (exports2.MediaTypes = MediaTypes = {}));
+    function getProxyUrl(serverUrl) {
+      const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+      return proxyUrl ? proxyUrl.href : "";
+    }
+    var HttpRedirectCodes = [
+      HttpCodes.MovedPermanently,
+      HttpCodes.ResourceMoved,
+      HttpCodes.SeeOther,
+      HttpCodes.TemporaryRedirect,
+      HttpCodes.PermanentRedirect
+    ];
+    var HttpResponseRetryCodes = [
+      HttpCodes.BadGateway,
+      HttpCodes.ServiceUnavailable,
+      HttpCodes.GatewayTimeout
+    ];
+    var RetryableHttpVerbs = ["OPTIONS", "GET", "DELETE", "HEAD"];
+    var ExponentialBackoffCeiling = 10;
+    var ExponentialBackoffTimeSlice = 5;
+    var HttpClientError = class _HttpClientError extends Error {
+      constructor(message, statusCode) {
+        super(message);
+        this.name = "HttpClientError";
+        this.statusCode = statusCode;
+        Object.setPrototypeOf(this, _HttpClientError.prototype);
       }
     };
-    exports2.HTTPError = HTTPError2;
-    var IS_WINDOWS = process.platform === "win32";
-    var IS_MAC = process.platform === "darwin";
-    var userAgent = "actions/tool-cache";
-    function downloadTool2(url2, dest, auth, headers) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        dest = dest || path12.join(_getTempDirectory(), crypto.randomUUID());
-        yield io6.mkdirP(path12.dirname(dest));
-        core14.debug(`Downloading ${url2}`);
-        core14.debug(`Destination ${dest}`);
-        const maxAttempts = 3;
-        const minSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS", 10);
-        const maxSeconds = _getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS", 20);
-        const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds);
-        return yield retryHelper.execute(() => __awaiter4(this, void 0, void 0, function* () {
-          return yield downloadToolAttempt(url2, dest || "", auth, headers);
-        }), (err) => {
-          if (err instanceof HTTPError2 && err.httpStatusCode) {
-            if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) {
-              return false;
-            }
-          }
-          return true;
+    exports2.HttpClientError = HttpClientError;
+    var HttpClientResponse = class {
+      constructor(message) {
+        this.message = message;
+      }
+      readBody() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () {
+            let output = Buffer.alloc(0);
+            this.message.on("data", (chunk) => {
+              output = Buffer.concat([output, chunk]);
+            });
+            this.message.on("end", () => {
+              resolve6(output.toString());
+            });
+          }));
         });
-      });
-    }
-    exports2.downloadTool = downloadTool2;
-    function downloadToolAttempt(url2, dest, auth, headers) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        if (fs13.existsSync(dest)) {
-          throw new Error(`Destination file path ${dest} already exists`);
-        }
-        const http = new httpm.HttpClient(userAgent, [], {
-          allowRetries: false
+      }
+      readBodyBuffer() {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6) => __awaiter4(this, void 0, void 0, function* () {
+            const chunks = [];
+            this.message.on("data", (chunk) => {
+              chunks.push(chunk);
+            });
+            this.message.on("end", () => {
+              resolve6(Buffer.concat(chunks));
+            });
+          }));
         });
-        if (auth) {
-          core14.debug("set auth");
-          if (headers === void 0) {
-            headers = {};
+      }
+    };
+    exports2.HttpClientResponse = HttpClientResponse;
+    function isHttps(requestUrl) {
+      const parsedUrl = new URL(requestUrl);
+      return parsedUrl.protocol === "https:";
+    }
+    var HttpClient2 = class {
+      constructor(userAgent, handlers, requestOptions) {
+        this._ignoreSslError = false;
+        this._allowRedirects = true;
+        this._allowRedirectDowngrade = false;
+        this._maxRedirects = 50;
+        this._allowRetries = false;
+        this._maxRetries = 1;
+        this._keepAlive = false;
+        this._disposed = false;
+        this.userAgent = userAgent;
+        this.handlers = handlers || [];
+        this.requestOptions = requestOptions;
+        if (requestOptions) {
+          if (requestOptions.ignoreSslError != null) {
+            this._ignoreSslError = requestOptions.ignoreSslError;
           }
-          headers.authorization = auth;
-        }
-        const response = yield http.get(url2, headers);
-        if (response.message.statusCode !== 200) {
-          const err = new HTTPError2(response.message.statusCode);
-          core14.debug(`Failed to download from "${url2}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
-          throw err;
-        }
-        const pipeline = util.promisify(stream2.pipeline);
-        const responseMessageFactory = _getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY", () => response.message);
-        const readStream = responseMessageFactory();
-        let succeeded = false;
-        try {
-          yield pipeline(readStream, fs13.createWriteStream(dest));
-          core14.debug("download complete");
-          succeeded = true;
-          return dest;
-        } finally {
-          if (!succeeded) {
-            core14.debug("download failed");
-            try {
-              yield io6.rmRF(dest);
-            } catch (err) {
-              core14.debug(`Failed to delete '${dest}'. ${err.message}`);
-            }
+          this._socketTimeout = requestOptions.socketTimeout;
+          if (requestOptions.allowRedirects != null) {
+            this._allowRedirects = requestOptions.allowRedirects;
           }
-        }
-      });
-    }
-    function extract7z(file, dest, _7zPath) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        (0, assert_1.ok)(IS_WINDOWS, "extract7z() not supported on current OS");
-        (0, assert_1.ok)(file, 'parameter "file" is required');
-        dest = yield _createExtractFolder(dest);
-        const originalCwd = process.cwd();
-        process.chdir(dest);
-        if (_7zPath) {
-          try {
-            const logLevel = core14.isDebug() ? "-bb1" : "-bb0";
-            const args = [
-              "x",
-              logLevel,
-              "-bd",
-              "-sccUTF-8",
-              file
-            ];
-            const options = {
-              silent: true
-            };
-            yield (0, exec_1.exec)(`"${_7zPath}"`, args, options);
-          } finally {
-            process.chdir(originalCwd);
+          if (requestOptions.allowRedirectDowngrade != null) {
+            this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
           }
-        } else {
-          const escapedScript = path12.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, "");
-          const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, "");
-          const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, "");
-          const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`;
-          const args = [
-            "-NoLogo",
-            "-Sta",
-            "-NoProfile",
-            "-NonInteractive",
-            "-ExecutionPolicy",
-            "Unrestricted",
-            "-Command",
-            command
-          ];
-          const options = {
-            silent: true
-          };
-          try {
-            const powershellPath = yield io6.which("powershell", true);
-            yield (0, exec_1.exec)(`"${powershellPath}"`, args, options);
-          } finally {
-            process.chdir(originalCwd);
+          if (requestOptions.maxRedirects != null) {
+            this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+          }
+          if (requestOptions.keepAlive != null) {
+            this._keepAlive = requestOptions.keepAlive;
+          }
+          if (requestOptions.allowRetries != null) {
+            this._allowRetries = requestOptions.allowRetries;
+          }
+          if (requestOptions.maxRetries != null) {
+            this._maxRetries = requestOptions.maxRetries;
           }
         }
-        return dest;
-      });
-    }
-    exports2.extract7z = extract7z;
-    function extractTar2(file, dest, flags = "xz") {
-      return __awaiter4(this, void 0, void 0, function* () {
-        if (!file) {
-          throw new Error("parameter 'file' is required");
-        }
-        dest = yield _createExtractFolder(dest);
-        core14.debug("Checking tar --version");
-        let versionOutput = "";
-        yield (0, exec_1.exec)("tar --version", [], {
-          ignoreReturnCode: true,
-          silent: true,
-          listeners: {
-            stdout: (data) => versionOutput += data.toString(),
-            stderr: (data) => versionOutput += data.toString()
+      }
+      options(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("OPTIONS", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      get(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("GET", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      del(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("DELETE", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      post(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("POST", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      patch(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PATCH", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      put(requestUrl, data, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("PUT", requestUrl, data, additionalHeaders || {});
+        });
+      }
+      head(requestUrl, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request("HEAD", requestUrl, null, additionalHeaders || {});
+        });
+      }
+      sendStream(verb, requestUrl, stream2, additionalHeaders) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return this.request(verb, requestUrl, stream2, additionalHeaders);
+        });
+      }
+      /**
+       * Gets a typed object from an endpoint
+       * Be aware that not found returns a null.  Other errors (4xx, 5xx) reject the promise
+       */
+      getJson(requestUrl_1) {
+        return __awaiter4(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) {
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          const res = yield this.get(requestUrl, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      postJson(requestUrl_1, obj_1) {
+        return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
+          const res = yield this.post(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      putJson(requestUrl_1, obj_1) {
+        return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
+          const res = yield this.put(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      patchJson(requestUrl_1, obj_1) {
+        return __awaiter4(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
+          const data = JSON.stringify(obj, null, 2);
+          additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+          additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
+          const res = yield this.patch(requestUrl, data, additionalHeaders);
+          return this._processResponse(res, this.requestOptions);
+        });
+      }
+      /**
+       * Makes a raw http request.
+       * All other methods such as get, post, patch, and request ultimately call this.
+       * Prefer get, del, post and patch
+       */
+      request(verb, requestUrl, data, headers) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          if (this._disposed) {
+            throw new Error("Client has already been disposed.");
           }
+          const parsedUrl = new URL(requestUrl);
+          let info6 = this._prepareRequest(verb, parsedUrl, headers);
+          const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1;
+          let numTries = 0;
+          let response;
+          do {
+            response = yield this.requestRaw(info6, data);
+            if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
+              let authenticationHandler;
+              for (const handler of this.handlers) {
+                if (handler.canHandleAuthentication(response)) {
+                  authenticationHandler = handler;
+                  break;
+                }
+              }
+              if (authenticationHandler) {
+                return authenticationHandler.handleAuthentication(this, info6, data);
+              } else {
+                return response;
+              }
+            }
+            let redirectsRemaining = this._maxRedirects;
+            while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) {
+              const redirectUrl = response.message.headers["location"];
+              if (!redirectUrl) {
+                break;
+              }
+              const parsedRedirectUrl = new URL(redirectUrl);
+              if (parsedUrl.protocol === "https:" && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
+                throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
+              }
+              yield response.readBody();
+              if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+                for (const header in headers) {
+                  if (header.toLowerCase() === "authorization") {
+                    delete headers[header];
+                  }
+                }
+              }
+              info6 = this._prepareRequest(verb, parsedRedirectUrl, headers);
+              response = yield this.requestRaw(info6, data);
+              redirectsRemaining--;
+            }
+            if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+              return response;
+            }
+            numTries += 1;
+            if (numTries < maxTries) {
+              yield response.readBody();
+              yield this._performExponentialBackoff(numTries);
+            }
+          } while (numTries < maxTries);
+          return response;
         });
-        core14.debug(versionOutput.trim());
-        const isGnuTar = versionOutput.toUpperCase().includes("GNU TAR");
-        let args;
-        if (flags instanceof Array) {
-          args = flags;
-        } else {
-          args = [flags];
-        }
-        if (core14.isDebug() && !flags.includes("v")) {
-          args.push("-v");
-        }
-        let destArg = dest;
-        let fileArg = file;
-        if (IS_WINDOWS && isGnuTar) {
-          args.push("--force-local");
-          destArg = dest.replace(/\\/g, "/");
-          fileArg = file.replace(/\\/g, "/");
-        }
-        if (isGnuTar) {
-          args.push("--warning=no-unknown-keyword");
-          args.push("--overwrite");
-        }
-        args.push("-C", destArg, "-f", fileArg);
-        yield (0, exec_1.exec)(`tar`, args);
-        return dest;
-      });
-    }
-    exports2.extractTar = extractTar2;
-    function extractXar(file, dest, flags = []) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        (0, assert_1.ok)(IS_MAC, "extractXar() not supported on current OS");
-        (0, assert_1.ok)(file, 'parameter "file" is required');
-        dest = yield _createExtractFolder(dest);
-        let args;
-        if (flags instanceof Array) {
-          args = flags;
-        } else {
-          args = [flags];
+      }
+      /**
+       * Needs to be called if keepAlive is set to true in request options.
+       */
+      dispose() {
+        if (this._agent) {
+          this._agent.destroy();
         }
-        args.push("-x", "-C", dest, "-f", file);
-        if (core14.isDebug()) {
-          args.push("-v");
+        this._disposed = true;
+      }
+      /**
+       * Raw request.
+       * @param info
+       * @param data
+       */
+      requestRaw(info6, data) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6, reject) => {
+            function callbackForResult(err, res) {
+              if (err) {
+                reject(err);
+              } else if (!res) {
+                reject(new Error("Unknown error"));
+              } else {
+                resolve6(res);
+              }
+            }
+            this.requestRawWithCallback(info6, data, callbackForResult);
+          });
+        });
+      }
+      /**
+       * Raw request with callback.
+       * @param info
+       * @param data
+       * @param onResult
+       */
+      requestRawWithCallback(info6, data, onResult) {
+        if (typeof data === "string") {
+          if (!info6.options.headers) {
+            info6.options.headers = {};
+          }
+          info6.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8");
         }
-        const xarPath = yield io6.which("xar", true);
-        yield (0, exec_1.exec)(`"${xarPath}"`, _unique(args));
-        return dest;
-      });
-    }
-    exports2.extractXar = extractXar;
-    function extractZip(file, dest) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        if (!file) {
-          throw new Error("parameter 'file' is required");
+        let callbackCalled = false;
+        function handleResult(err, res) {
+          if (!callbackCalled) {
+            callbackCalled = true;
+            onResult(err, res);
+          }
         }
-        dest = yield _createExtractFolder(dest);
-        if (IS_WINDOWS) {
-          yield extractZipWin(file, dest);
-        } else {
-          yield extractZipNix(file, dest);
+        const req = info6.httpModule.request(info6.options, (msg) => {
+          const res = new HttpClientResponse(msg);
+          handleResult(void 0, res);
+        });
+        let socket;
+        req.on("socket", (sock) => {
+          socket = sock;
+        });
+        req.setTimeout(this._socketTimeout || 3 * 6e4, () => {
+          if (socket) {
+            socket.end();
+          }
+          handleResult(new Error(`Request timeout: ${info6.options.path}`));
+        });
+        req.on("error", function(err) {
+          handleResult(err);
+        });
+        if (data && typeof data === "string") {
+          req.write(data, "utf8");
         }
-        return dest;
-      });
-    }
-    exports2.extractZip = extractZip;
-    function extractZipWin(file, dest) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, "");
-        const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, "");
-        const pwshPath = yield io6.which("pwsh", false);
-        if (pwshPath) {
-          const pwshCommand = [
-            `$ErrorActionPreference = 'Stop' ;`,
-            `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`,
-            `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`,
-            `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;`
-          ].join(" ");
-          const args = [
-            "-NoLogo",
-            "-NoProfile",
-            "-NonInteractive",
-            "-ExecutionPolicy",
-            "Unrestricted",
-            "-Command",
-            pwshCommand
-          ];
-          core14.debug(`Using pwsh at path: ${pwshPath}`);
-          yield (0, exec_1.exec)(`"${pwshPath}"`, args);
+        if (data && typeof data !== "string") {
+          data.on("close", function() {
+            req.end();
+          });
+          data.pipe(req);
         } else {
-          const powershellCommand = [
-            `$ErrorActionPreference = 'Stop' ;`,
-            `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`,
-            `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`,
-            `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`
-          ].join(" ");
-          const args = [
-            "-NoLogo",
-            "-Sta",
-            "-NoProfile",
-            "-NonInteractive",
-            "-ExecutionPolicy",
-            "Unrestricted",
-            "-Command",
-            powershellCommand
-          ];
-          const powershellPath = yield io6.which("powershell", true);
-          core14.debug(`Using powershell at path: ${powershellPath}`);
-          yield (0, exec_1.exec)(`"${powershellPath}"`, args);
-        }
-      });
-    }
-    function extractZipNix(file, dest) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const unzipPath = yield io6.which("unzip", true);
-        const args = [file];
-        if (!core14.isDebug()) {
-          args.unshift("-q");
+          req.end();
         }
-        args.unshift("-o");
-        yield (0, exec_1.exec)(`"${unzipPath}"`, args, { cwd: dest });
-      });
-    }
-    function cacheDir(sourceDir, tool, version, arch2) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        version = semver8.clean(version) || version;
-        arch2 = arch2 || os3.arch();
-        core14.debug(`Caching tool ${tool} ${version} ${arch2}`);
-        core14.debug(`source dir: ${sourceDir}`);
-        if (!fs13.statSync(sourceDir).isDirectory()) {
-          throw new Error("sourceDir is not a directory");
+      }
+      /**
+       * Gets an http agent. This function is useful when you need an http agent that handles
+       * routing through a proxy server - depending upon the url and proxy environment variables.
+       * @param serverUrl  The server URL where the request will be sent. For example, https://api.github.com
+       */
+      getAgent(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        return this._getAgent(parsedUrl);
+      }
+      getAgentDispatcher(serverUrl) {
+        const parsedUrl = new URL(serverUrl);
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (!useProxy) {
+          return;
         }
-        const destPath = yield _createToolPath(tool, version, arch2);
-        for (const itemName of fs13.readdirSync(sourceDir)) {
-          const s = path12.join(sourceDir, itemName);
-          yield io6.cp(s, destPath, { recursive: true });
+        return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
+      }
+      _prepareRequest(method, requestUrl, headers) {
+        const info6 = {};
+        info6.parsedUrl = requestUrl;
+        const usingSsl = info6.parsedUrl.protocol === "https:";
+        info6.httpModule = usingSsl ? https2 : http;
+        const defaultPort = usingSsl ? 443 : 80;
+        info6.options = {};
+        info6.options.host = info6.parsedUrl.hostname;
+        info6.options.port = info6.parsedUrl.port ? parseInt(info6.parsedUrl.port) : defaultPort;
+        info6.options.path = (info6.parsedUrl.pathname || "") + (info6.parsedUrl.search || "");
+        info6.options.method = method;
+        info6.options.headers = this._mergeHeaders(headers);
+        if (this.userAgent != null) {
+          info6.options.headers["user-agent"] = this.userAgent;
         }
-        _completeToolPath(tool, version, arch2);
-        return destPath;
-      });
-    }
-    exports2.cacheDir = cacheDir;
-    function cacheFile(sourceFile, targetFile, tool, version, arch2) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        version = semver8.clean(version) || version;
-        arch2 = arch2 || os3.arch();
-        core14.debug(`Caching tool ${tool} ${version} ${arch2}`);
-        core14.debug(`source file: ${sourceFile}`);
-        if (!fs13.statSync(sourceFile).isFile()) {
-          throw new Error("sourceFile is not a file");
+        info6.options.agent = this._getAgent(info6.parsedUrl);
+        if (this.handlers) {
+          for (const handler of this.handlers) {
+            handler.prepareRequest(info6.options);
+          }
         }
-        const destFolder = yield _createToolPath(tool, version, arch2);
-        const destPath = path12.join(destFolder, targetFile);
-        core14.debug(`destination file ${destPath}`);
-        yield io6.cp(sourceFile, destPath);
-        _completeToolPath(tool, version, arch2);
-        return destFolder;
-      });
-    }
-    exports2.cacheFile = cacheFile;
-    function find2(toolName, versionSpec, arch2) {
-      if (!toolName) {
-        throw new Error("toolName parameter is required");
-      }
-      if (!versionSpec) {
-        throw new Error("versionSpec parameter is required");
+        return info6;
       }
-      arch2 = arch2 || os3.arch();
-      if (!isExplicitVersion(versionSpec)) {
-        const localVersions = findAllVersions2(toolName, arch2);
-        const match = evaluateVersions(localVersions, versionSpec);
-        versionSpec = match;
+      _mergeHeaders(headers) {
+        if (this.requestOptions && this.requestOptions.headers) {
+          return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
+        }
+        return lowercaseKeys(headers || {});
       }
-      let toolPath = "";
-      if (versionSpec) {
-        versionSpec = semver8.clean(versionSpec) || "";
-        const cachePath = path12.join(_getCacheDirectory(), toolName, versionSpec, arch2);
-        core14.debug(`checking cache: ${cachePath}`);
-        if (fs13.existsSync(cachePath) && fs13.existsSync(`${cachePath}.complete`)) {
-          core14.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`);
-          toolPath = cachePath;
-        } else {
-          core14.debug("not found");
+      /**
+       * Gets an existing header value or returns a default.
+       * Handles converting number header values to strings since HTTP headers must be strings.
+       * Note: This returns string | string[] since some headers can have multiple values.
+       * For headers that must always be a single string (like Content-Type), use the
+       * specialized _getExistingOrDefaultContentTypeHeader method instead.
+       */
+      _getExistingOrDefaultHeader(additionalHeaders, header, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          const headerValue = lowercaseKeys(this.requestOptions.headers)[header];
+          if (headerValue) {
+            clientHeader = typeof headerValue === "number" ? headerValue.toString() : headerValue;
+          }
+        }
+        const additionalValue = additionalHeaders[header];
+        if (additionalValue !== void 0) {
+          return typeof additionalValue === "number" ? additionalValue.toString() : additionalValue;
         }
+        if (clientHeader !== void 0) {
+          return clientHeader;
+        }
+        return _default2;
       }
-      return toolPath;
-    }
-    exports2.find = find2;
-    function findAllVersions2(toolName, arch2) {
-      const versions = [];
-      arch2 = arch2 || os3.arch();
-      const toolPath = path12.join(_getCacheDirectory(), toolName);
-      if (fs13.existsSync(toolPath)) {
-        const children = fs13.readdirSync(toolPath);
-        for (const child of children) {
-          if (isExplicitVersion(child)) {
-            const fullPath = path12.join(toolPath, child, arch2 || "");
-            if (fs13.existsSync(fullPath) && fs13.existsSync(`${fullPath}.complete`)) {
-              versions.push(child);
+      /**
+       * Specialized version of _getExistingOrDefaultHeader for Content-Type header.
+       * Always returns a single string (not an array) since Content-Type should be a single value.
+       * Converts arrays to comma-separated strings and numbers to strings to ensure type safety.
+       * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers
+       * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]).
+       */
+      _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default2) {
+        let clientHeader;
+        if (this.requestOptions && this.requestOptions.headers) {
+          const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType];
+          if (headerValue) {
+            if (typeof headerValue === "number") {
+              clientHeader = String(headerValue);
+            } else if (Array.isArray(headerValue)) {
+              clientHeader = headerValue.join(", ");
+            } else {
+              clientHeader = headerValue;
             }
           }
         }
+        const additionalValue = additionalHeaders[Headers.ContentType];
+        if (additionalValue !== void 0) {
+          if (typeof additionalValue === "number") {
+            return String(additionalValue);
+          } else if (Array.isArray(additionalValue)) {
+            return additionalValue.join(", ");
+          } else {
+            return additionalValue;
+          }
+        }
+        if (clientHeader !== void 0) {
+          return clientHeader;
+        }
+        return _default2;
       }
-      return versions;
-    }
-    exports2.findAllVersions = findAllVersions2;
-    function getManifestFromRepo(owner, repo, auth, branch = "master") {
-      return __awaiter4(this, void 0, void 0, function* () {
-        let releases = [];
-        const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`;
-        const http = new httpm.HttpClient("tool-cache");
-        const headers = {};
-        if (auth) {
-          core14.debug("set auth");
-          headers.authorization = auth;
+      _getAgent(parsedUrl) {
+        let agent;
+        const proxyUrl = pm.getProxyUrl(parsedUrl);
+        const useProxy = proxyUrl && proxyUrl.hostname;
+        if (this._keepAlive && useProxy) {
+          agent = this._proxyAgent;
         }
-        const response = yield http.getJson(treeUrl, headers);
-        if (!response.result) {
-          return releases;
+        if (!useProxy) {
+          agent = this._agent;
         }
-        let manifestUrl = "";
-        for (const item of response.result.tree) {
-          if (item.path === "versions-manifest.json") {
-            manifestUrl = item.url;
-            break;
-          }
+        if (agent) {
+          return agent;
         }
-        headers["accept"] = "application/vnd.github.VERSION.raw";
-        let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody();
-        if (versionsRaw) {
-          versionsRaw = versionsRaw.replace(/^\uFEFF/, "");
-          try {
-            releases = JSON.parse(versionsRaw);
-          } catch (_a) {
-            core14.debug("Invalid json");
-          }
+        const usingSsl = parsedUrl.protocol === "https:";
+        let maxSockets = 100;
+        if (this.requestOptions) {
+          maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
         }
-        return releases;
-      });
-    }
-    exports2.getManifestFromRepo = getManifestFromRepo;
-    function findFromManifest(versionSpec, stable, manifest, archFilter = os3.arch()) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter);
-        return match;
-      });
-    }
-    exports2.findFromManifest = findFromManifest;
-    function _createExtractFolder(dest) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        if (!dest) {
-          dest = path12.join(_getTempDirectory(), crypto.randomUUID());
+        if (proxyUrl && proxyUrl.hostname) {
+          const agentOptions = {
+            maxSockets,
+            keepAlive: this._keepAlive,
+            proxy: Object.assign(Object.assign({}, (proxyUrl.username || proxyUrl.password) && {
+              proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+            }), { host: proxyUrl.hostname, port: proxyUrl.port })
+          };
+          let tunnelAgent;
+          const overHttps = proxyUrl.protocol === "https:";
+          if (usingSsl) {
+            tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+          } else {
+            tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
+          }
+          agent = tunnelAgent(agentOptions);
+          this._proxyAgent = agent;
         }
-        yield io6.mkdirP(dest);
-        return dest;
-      });
-    }
-    function _createToolPath(tool, version, arch2) {
-      return __awaiter4(this, void 0, void 0, function* () {
-        const folderPath = path12.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || "");
-        core14.debug(`destination ${folderPath}`);
-        const markerPath = `${folderPath}.complete`;
-        yield io6.rmRF(folderPath);
-        yield io6.rmRF(markerPath);
-        yield io6.mkdirP(folderPath);
-        return folderPath;
-      });
-    }
-    function _completeToolPath(tool, version, arch2) {
-      const folderPath = path12.join(_getCacheDirectory(), tool, semver8.clean(version) || version, arch2 || "");
-      const markerPath = `${folderPath}.complete`;
-      fs13.writeFileSync(markerPath, "");
-      core14.debug("finished caching tool");
-    }
-    function isExplicitVersion(versionSpec) {
-      const c = semver8.clean(versionSpec) || "";
-      core14.debug(`isExplicit: ${c}`);
-      const valid3 = semver8.valid(c) != null;
-      core14.debug(`explicit? ${valid3}`);
-      return valid3;
-    }
-    exports2.isExplicitVersion = isExplicitVersion;
-    function evaluateVersions(versions, versionSpec) {
-      let version = "";
-      core14.debug(`evaluating ${versions.length} versions`);
-      versions = versions.sort((a, b) => {
-        if (semver8.gt(a, b)) {
-          return 1;
+        if (!agent) {
+          const options = { keepAlive: this._keepAlive, maxSockets };
+          agent = usingSsl ? new https2.Agent(options) : new http.Agent(options);
+          this._agent = agent;
         }
-        return -1;
-      });
-      for (let i = versions.length - 1; i >= 0; i--) {
-        const potential = versions[i];
-        const satisfied = semver8.satisfies(potential, versionSpec);
-        if (satisfied) {
-          version = potential;
-          break;
+        if (usingSsl && this._ignoreSslError) {
+          agent.options = Object.assign(agent.options || {}, {
+            rejectUnauthorized: false
+          });
         }
+        return agent;
       }
-      if (version) {
-        core14.debug(`matched: ${version}`);
-      } else {
-        core14.debug("match not found");
-      }
-      return version;
-    }
-    exports2.evaluateVersions = evaluateVersions;
-    function _getCacheDirectory() {
-      const cacheDirectory = process.env["RUNNER_TOOL_CACHE"] || "";
-      (0, assert_1.ok)(cacheDirectory, "Expected RUNNER_TOOL_CACHE to be defined");
-      return cacheDirectory;
-    }
-    function _getTempDirectory() {
-      const tempDirectory = process.env["RUNNER_TEMP"] || "";
-      (0, assert_1.ok)(tempDirectory, "Expected RUNNER_TEMP to be defined");
-      return tempDirectory;
-    }
-    function _getGlobal(key, defaultValue) {
-      const value = global[key];
-      return value !== void 0 ? value : defaultValue;
-    }
-    function _unique(values) {
-      return Array.from(new Set(values));
-    }
-  }
-});
-
-// node_modules/fast-deep-equal/index.js
-var require_fast_deep_equal = __commonJS({
-  "node_modules/fast-deep-equal/index.js"(exports2, module2) {
-    "use strict";
-    module2.exports = function equal(a, b) {
-      if (a === b) return true;
-      if (a && b && typeof a == "object" && typeof b == "object") {
-        if (a.constructor !== b.constructor) return false;
-        var length, i, keys;
-        if (Array.isArray(a)) {
-          length = a.length;
-          if (length != b.length) return false;
-          for (i = length; i-- !== 0; )
-            if (!equal(a[i], b[i])) return false;
-          return true;
+      _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+        let proxyAgent;
+        if (this._keepAlive) {
+          proxyAgent = this._proxyAgentDispatcher;
         }
-        if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
-        if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
-        if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
-        keys = Object.keys(a);
-        length = keys.length;
-        if (length !== Object.keys(b).length) return false;
-        for (i = length; i-- !== 0; )
-          if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
-        for (i = length; i-- !== 0; ) {
-          var key = keys[i];
-          if (!equal(a[key], b[key])) return false;
+        if (proxyAgent) {
+          return proxyAgent;
         }
-        return true;
+        const usingSsl = parsedUrl.protocol === "https:";
+        proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, (proxyUrl.username || proxyUrl.password) && {
+          token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString("base64")}`
+        }));
+        this._proxyAgentDispatcher = proxyAgent;
+        if (usingSsl && this._ignoreSslError) {
+          proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+            rejectUnauthorized: false
+          });
+        }
+        return proxyAgent;
+      }
+      _performExponentialBackoff(retryNumber) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+          const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+          return new Promise((resolve6) => setTimeout(() => resolve6(), ms));
+        });
+      }
+      _processResponse(res, options) {
+        return __awaiter4(this, void 0, void 0, function* () {
+          return new Promise((resolve6, reject) => __awaiter4(this, void 0, void 0, function* () {
+            const statusCode = res.message.statusCode || 0;
+            const response = {
+              statusCode,
+              result: null,
+              headers: {}
+            };
+            if (statusCode === HttpCodes.NotFound) {
+              resolve6(response);
+            }
+            function dateTimeDeserializer(key, value) {
+              if (typeof value === "string") {
+                const a = new Date(value);
+                if (!isNaN(a.valueOf())) {
+                  return a;
+                }
+              }
+              return value;
+            }
+            let obj;
+            let contents;
+            try {
+              contents = yield res.readBody();
+              if (contents && contents.length > 0) {
+                if (options && options.deserializeDates) {
+                  obj = JSON.parse(contents, dateTimeDeserializer);
+                } else {
+                  obj = JSON.parse(contents);
+                }
+                response.result = obj;
+              }
+              response.headers = res.message.headers;
+            } catch (err) {
+            }
+            if (statusCode > 299) {
+              let msg;
+              if (obj && obj.message) {
+                msg = obj.message;
+              } else if (contents && contents.length > 0) {
+                msg = contents;
+              } else {
+                msg = `Failed request: (${statusCode})`;
+              }
+              const err = new HttpClientError(msg, statusCode);
+              err.result = response.result;
+              reject(err);
+            } else {
+              resolve6(response);
+            }
+          }));
+        });
       }
-      return a !== a && b !== b;
     };
+    exports2.HttpClient = HttpClient2;
+    var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
   }
 });
 
@@ -83001,7 +85971,7 @@ var path6 = __toESM(require("path"));
 var core8 = __toESM(require_core());
 
 // src/config/db-config.ts
-var jsonschema = __toESM(require_lib2());
+var jsonschema = __toESM(require_lib4());
 var semver4 = __toESM(require_semver2());
 var PACK_IDENTIFIER_PATTERN = (function() {
   const alphaNumeric = "[a-z0-9]";
@@ -83289,7 +86259,7 @@ var path11 = __toESM(require("path"));
 var url = __toESM(require("url"));
 var import_zlib = __toESM(require("zlib"));
 var core12 = __toESM(require_core());
-var jsonschema2 = __toESM(require_lib2());
+var jsonschema2 = __toESM(require_lib4());
 
 // src/codeql.ts
 var fs10 = __toESM(require("fs"));
@@ -83762,7 +86732,7 @@ var os2 = __toESM(require("os"));
 var path7 = __toESM(require("path"));
 var import_perf_hooks = require("perf_hooks");
 var core10 = __toESM(require_core());
-var import_http_client = __toESM(require_lib());
+var import_http_client = __toESM(require_lib6());
 var toolcache2 = __toESM(require_tool_cache());
 var import_follow_redirects = __toESM(require_follow_redirects());
 var semver6 = __toESM(require_semver2());
diff --git a/package-lock.json b/package-lock.json
index 6720d605a9..0dd7b0f343 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -16,7 +16,7 @@
         "@actions/exec": "^1.1.1",
         "@actions/github": "^6.0.0",
         "@actions/glob": "^0.5.0",
-        "@actions/http-client": "^2.2.3",
+        "@actions/http-client": "^3.0.0",
         "@actions/io": "^1.1.3",
         "@actions/tool-cache": "^2.0.2",
         "@octokit/plugin-retry": "^6.0.0",
@@ -106,6 +106,26 @@
         "tmp-promise": "^3.0.2"
       }
     },
+    "node_modules/@actions/artifact-legacy/node_modules/@actions/http-client": {
+      "version": "2.2.3",
+      "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz",
+      "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==",
+      "license": "MIT",
+      "dependencies": {
+        "tunnel": "^0.0.6",
+        "undici": "^5.25.4"
+      }
+    },
+    "node_modules/@actions/artifact/node_modules/@actions/http-client": {
+      "version": "2.2.3",
+      "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz",
+      "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==",
+      "license": "MIT",
+      "dependencies": {
+        "tunnel": "^0.0.6",
+        "undici": "^5.25.4"
+      }
+    },
     "node_modules/@actions/artifact/node_modules/@octokit/endpoint": {
       "version": "9.0.6",
       "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz",
@@ -212,6 +232,16 @@
         "minimatch": "^3.0.4"
       }
     },
+    "node_modules/@actions/cache/node_modules/@actions/http-client": {
+      "version": "2.2.3",
+      "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz",
+      "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==",
+      "license": "MIT",
+      "dependencies": {
+        "tunnel": "^0.0.6",
+        "undici": "^5.25.4"
+      }
+    },
     "node_modules/@actions/cache/node_modules/semver": {
       "version": "6.3.1",
       "license": "ISC",
@@ -228,6 +258,16 @@
         "@actions/http-client": "^2.0.1"
       }
     },
+    "node_modules/@actions/core/node_modules/@actions/http-client": {
+      "version": "2.2.3",
+      "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz",
+      "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==",
+      "license": "MIT",
+      "dependencies": {
+        "tunnel": "^0.0.6",
+        "undici": "^5.25.4"
+      }
+    },
     "node_modules/@actions/exec": {
       "version": "1.1.1",
       "license": "MIT",
@@ -250,6 +290,16 @@
         "undici": "^5.28.5"
       }
     },
+    "node_modules/@actions/github/node_modules/@actions/http-client": {
+      "version": "2.2.3",
+      "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz",
+      "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==",
+      "license": "MIT",
+      "dependencies": {
+        "tunnel": "^0.0.6",
+        "undici": "^5.25.4"
+      }
+    },
     "node_modules/@actions/github/node_modules/@octokit/endpoint": {
       "version": "9.0.6",
       "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz",
@@ -366,12 +416,13 @@
       }
     },
     "node_modules/@actions/http-client": {
-      "version": "2.2.3",
-      "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz",
-      "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==",
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-3.0.0.tgz",
+      "integrity": "sha512-1s3tXAfVMSz9a4ZEBkXXRQD4QhY3+GAsWSbaYpeknPOKEeyRiU3lH+bHiLMZdo2x/fIeQ/hscL1wCkDLVM2DZQ==",
+      "license": "MIT",
       "dependencies": {
         "tunnel": "^0.0.6",
-        "undici": "^5.25.4"
+        "undici": "^5.28.5"
       }
     },
     "node_modules/@actions/io": {
@@ -391,6 +442,16 @@
         "semver": "^6.1.0"
       }
     },
+    "node_modules/@actions/tool-cache/node_modules/@actions/http-client": {
+      "version": "2.2.3",
+      "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz",
+      "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==",
+      "license": "MIT",
+      "dependencies": {
+        "tunnel": "^0.0.6",
+        "undici": "^5.25.4"
+      }
+    },
     "node_modules/@ava/typescript": {
       "version": "6.0.0",
       "resolved": "https://registry.npmjs.org/@ava/typescript/-/typescript-6.0.0.tgz",
diff --git a/package.json b/package.json
index 476685c4fb..bdc216eade 100644
--- a/package.json
+++ b/package.json
@@ -31,7 +31,7 @@
     "@actions/exec": "^1.1.1",
     "@actions/github": "^6.0.0",
     "@actions/glob": "^0.5.0",
-    "@actions/http-client": "^2.2.3",
+    "@actions/http-client": "^3.0.0",
     "@actions/io": "^1.1.3",
     "@actions/tool-cache": "^2.0.2",
     "@octokit/plugin-retry": "^6.0.0",